forked from BuilderIO/demo-editor
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshim.js.download
23 lines (21 loc) · 142 KB
/
shim.js.download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
!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]="d0068e6b-6db4-579b-bd13-7d2ce73ce7c2")}catch(e){}}();
(function(){"use strict";var Pl=Object.defineProperty;var Tl=(se,ue,Re)=>ue in se?Pl(se,ue,{enumerable:!0,configurable:!0,writable:!0,value:Re}):se[ue]=Re;var $=(se,ue,Re)=>(Tl(se,typeof ue!="symbol"?ue+"":ue,Re),Re);let se;const ue=new Uint8Array(16);function Re(){if(!se&&(se=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!se))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return se(ue)}const z=[];for(let e=0;e<256;++e)z.push((e+256).toString(16).slice(1));function Us(e,t=0){return z[e[t+0]]+z[e[t+1]]+z[e[t+2]]+z[e[t+3]]+"-"+z[e[t+4]]+z[e[t+5]]+"-"+z[e[t+6]]+z[e[t+7]]+"-"+z[e[t+8]]+z[e[t+9]]+"-"+z[e[t+10]]+z[e[t+11]]+z[e[t+12]]+z[e[t+13]]+z[e[t+14]]+z[e[t+15]]}const jr={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ze(e,t,n){if(jr.randomUUID&&!t&&!e)return jr.randomUUID();e=e||{};const r=e.random||(e.rng||Re)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(let i=0;i<16;++i)t[n+i]=r[i];return t}return Us(r)}const xs='.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}',As="360px",Cs=500;var be=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(be||{}),C=(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))(C||{});const Pt={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"}},Kr=()=>{try{return window.parent.Intercom}catch{return null}},Nr=[Object.freeze(Object.defineProperty({__proto__:null,disable:()=>{const e=Kr();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},enable:()=>{const e=Kr();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)}},Symbol.toStringTag,{value:"Module"}))];class Rs{static disable(){Nr.forEach(t=>t.disable())}static enable(){Nr.forEach(t=>t.enable())}}var Os=class extends Error{constructor(e,t,n){super(`Possible EventEmitter memory leak detected. ${n} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=n,this.name="MaxListenersExceededWarning"}},$r=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=$r.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,n){this.emit(e,t,n)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const n=e.indexOf(t);return n>-1&&e.splice(n,1),[]}_wrapOnceListener(e,t){const n=(...r)=>(this.removeListener(e,n),t.apply(this,r));return Object.defineProperty(n,"name",{value:t.name}),n}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const n=this._getListeners(e);return n.forEach(r=>{r.apply(this,t)}),n.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const n=this._getListeners(e).concat(t);if(this.events.set(e,n),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const r=new Os(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 n=this._getListeners(e);if(n.length>0){const r=[t].concat(n);this.events.set(e,r)}else this.events.set(e,n.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const n=this._getListeners(e);return n.length>0&&(this._removeListener(n,t),this.events.set(e,n),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)}},qr=$r;qr.defaultMaxListeners=10;const R=new qr,Tt=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),Ds=({"userleap-platform":e})=>e!=="web";class Vr{constructor(t){$(this,"storage");$(this,"tempStorage",{});$(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,n){this.isStorageAvailable?this.storage.setItem(t,n):this.tempStorage[t]=n}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 _e=new Vr("sessionStorage"),Z=new Vr("localStorage");class Ps{constructor(t){$(this,"payload");$(this,"promise");$(this,"reject",()=>{});$(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((n,r)=>{this.reject=r,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const Ts={RATELIMIT_RESET_DEFAULT:10};let Wr=!1,zr="",Bt=!1,Hr=!1,Mt=[];const Bs=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",bn=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(Hr=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",bn))},_n=(e="")=>{Wr=!0,zr=e};function Oe(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.28.1","x-ul-installation-method":Bs(e)};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 n=JSON.parse(e.mobileHeadersJSON);Object.assign(t,n)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t}const Gr=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const n=new Ps(t);return Mt.push(n),n.promise}},ke=async(e,t)=>{const{retries:n=0,shouldDropOnRateLimit:r=!1,shouldRetryRequest:i=!1,...s}=t,o={url:e,options:s,retries:n,shouldDropOnRateLimit:r};if(Bt&&!i)return Gr(o);const a={ok:!1,reportError:!1};if(Wr)return console.info(`UserLeap - ${zr}`),a;try{const l=await fetch(e,s);if(l.status===429)if(!Bt&&!r||i){Bt=!0;const u=l.headers.has("ratelimit-reset")?Number(l.headers.get("ratelimit-reset")):Ts.RATELIMIT_RESET_DEFAULT;return await Tt(u*1e3),ke(e,{...s,shouldDropOnRateLimit:r,shouldRetryRequest:!0})}else return Gr(o);if(Bt=!1,Mt.length&&(Mt.map(c=>{const u=c.payload;ke(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(p=>{c.resolveRequest(p)})}),Mt=[]),l.ok){if(l.status===249)return _n(),a;const c=await l.text();try{return c&&c!=="OK"&&(l.json=JSON.parse(c)),l}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${c}`)}}}return l}catch(l){const c=n+1;return c>5||Hr?{ok:!1,reportError:!1,error:l}:(await Tt(Math.pow(2,n)*1e3),ke(e,{...s,retries:c}))}},He={Error:1,Warn:2,Info:3,Debug:4};let kn=1e3,Ft=He.Debug,Ge=[];const Ms=e=>{const t=Object.entries(He).find(n=>n[1]===e);return(t==null?void 0:t[0])??""},Fs=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),js=(e,t)=>`${Fs(t)}:${e}`,Ks=()=>{Ge=Ge.filter(e=>e.level<=Ft)},Ns=()=>{Ge.length>kn&&Ge.shift()},jt=(e,t)=>{e>Ft||(Ge.push({level:e,line:js(t,new Date)}),Ns())},at=e=>{jt(He.Debug,e)},I=e=>{jt(He.Info,e)},En=e=>{jt(He.Warn,e)},Yr=e=>{jt(He.Error,e)},$s=()=>Ge.map(e=>e.line),qs=()=>new TextEncoder().encode($s().join(`
`)),Vs=async e=>{if(!e)return;const t=qs();return ke(e,{body:t,method:"PUT"})},Ws=(e,t)=>{e!==void 0&&(kn=e),t!==void 0&&(Ft=t),at(`Initializing logger with limit of ${kn} lines and ${Ms(Ft)} level`),Ks()};var Sn=(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))(Sn||{});class zs{constructor(t){$(this,"awaitingResolvers",[]);$(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 Jr=new zs(2),Hs=e=>Jr.setLimit(e),Gs=async e=>Jr.execute(async()=>{var r;I(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const t=await ke(e.uploadUrl,{body:e.data,method:"PUT"});I(`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}),Qr=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:i,responseGroupUuid:s,replayDuration:o,eventDigest:a},l=!1)=>{var u;if(!l&&!n&&!r){I(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${r}`);return}I(`Marking upload complete for survey: ${t}`);const c=await ke(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:o,eventDigest:a,userAgent:(u=window==null?void 0:window.navigator)==null?void 0:u.userAgent}),headers:i,shouldRetryRequest:!0});return I(`Done marking upload complete for survey: ${t}`),c},F=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,N=Object.keys,H=Array.isArray;function J(e,t){return typeof t!="object"||N(t).forEach(function(n){e[n]=t[n]}),e}typeof Promise>"u"||F.Promise||(F.Promise=Promise);const lt=Object.getPrototypeOf,Ys={}.hasOwnProperty;function ee(e,t){return Ys.call(e,t)}function Ye(e,t){typeof t=="function"&&(t=t(lt(e))),(typeof Reflect>"u"?N:Reflect.ownKeys)(t).forEach(n=>{de(e,n,t[n])})}const Xr=Object.defineProperty;function de(e,t,n,r){Xr(e,t,J(n&&ee(n,"get")&&typeof n.get=="function"?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},r))}function Je(e){return{from:function(t){return e.prototype=Object.create(t.prototype),de(e.prototype,"constructor",e),{extend:Ye.bind(null,e.prototype)}}}}const Js=Object.getOwnPropertyDescriptor;function Ln(e,t){let n;return Js(e,t)||(n=lt(e))&&Ln(n,t)}const Qs=[].slice;function Kt(e,t,n){return Qs.call(e,t,n)}function Zr(e,t){return t(e)}function ct(e){if(!e)throw new Error("Assertion Failed")}function ei(e){F.setImmediate?setImmediate(e):setTimeout(e,0)}function ti(e,t){return e.reduce((n,r,i)=>{var s=t(r,i);return s&&(n[s[0]]=s[1]),n},{})}function pe(e,t){if(typeof t=="string"&&ee(e,t))return e[t];if(!t)return e;if(typeof t!="string"){for(var n=[],r=0,i=t.length;r<i;++r){var s=pe(e,t[r]);n.push(s)}return n}var o=t.indexOf(".");if(o!==-1){var a=e[t.substr(0,o)];return a==null?void 0:pe(a,t.substr(o+1))}}function re(e,t,n){if(e&&t!==void 0&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if(typeof t!="string"&&"length"in t){ct(typeof n!="string"&&"length"in n);for(var r=0,i=t.length;r<i;++r)re(e,t[r],n[r])}else{var s=t.indexOf(".");if(s!==-1){var o=t.substr(0,s),a=t.substr(s+1);if(a==="")n===void 0?H(e)&&!isNaN(parseInt(o))?e.splice(o,1):delete e[o]:e[o]=n;else{var l=e[o];l&&ee(e,o)||(l=e[o]={}),re(l,a,n)}}else n===void 0?H(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}function ni(e){var t={};for(var n in e)ee(e,n)&&(t[n]=e[n]);return t}const Xs=[].concat;function ri(e){return Xs.apply([],e)}const ii="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(ri([8,16,32,64].map(e=>["Int","Uint","Float"].map(t=>t+e+"Array")))).filter(e=>F[e]),Zs=ii.map(e=>F[e]);ti(ii,e=>[e,!0]);let Ee=null;function ut(e){Ee=typeof WeakMap<"u"&&new WeakMap;const t=In(e);return Ee=null,t}function In(e){if(!e||typeof e!="object")return e;let t=Ee&&Ee.get(e);if(t)return t;if(H(e)){t=[],Ee&&Ee.set(e,t);for(var n=0,r=e.length;n<r;++n)t.push(In(e[n]))}else if(Zs.indexOf(e.constructor)>=0)t=e;else{const s=lt(e);for(var i in t=s===Object.prototype?{}:Object.create(s),Ee&&Ee.set(e,t),e)ee(e,i)&&(t[i]=In(e[i]))}return t}const{toString:eo}={};function Un(e){return eo.call(e).slice(8,-1)}const xn=typeof Symbol<"u"?Symbol.iterator:"@@iterator",to=typeof xn=="symbol"?function(e){var t;return e!=null&&(t=e[xn])&&t.apply(e)}:function(){return null},Qe={};function he(e){var t,n,r,i;if(arguments.length===1){if(H(e))return e.slice();if(this===Qe&&typeof e=="string")return[e];if(i=to(e)){for(n=[];!(r=i.next()).done;)n.push(r.value);return n}if(e==null)return[e];if(typeof(t=e.length)=="number"){for(n=new Array(t);t--;)n[t]=e[t];return n}return[e]}for(t=arguments.length,n=new Array(t);t--;)n[t]=arguments[t];return n}const An=typeof Symbol<"u"?e=>e[Symbol.toStringTag]==="AsyncFunction":()=>!1;var oe=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function si(e,t){oe=e,oi=t}var oi=()=>!0;const no=!new Error("").stack;function De(){if(no)try{throw De.arguments,new Error}catch(e){return e}return new Error}function Cn(e,t){var n=e.stack;return n?(t=t||0,n.indexOf(e.name)===0&&(t+=(e.name+e.message).split(`
`).length),n.split(`
`).slice(t).filter(oi).map(r=>`
`+r).join("")):""}var ai=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Rn=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ai),ro={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Xe(e,t){this._e=De(),this.name=e,this.message=t}function li(e,t){return e+". Errors: "+Object.keys(t).map(n=>t[n].toString()).filter((n,r,i)=>i.indexOf(n)===r).join(`
`)}function Nt(e,t,n,r){this._e=De(),this.failures=t,this.failedKeys=r,this.successCount=n,this.message=li(e,t)}function dt(e,t){this._e=De(),this.name="BulkError",this.failures=Object.keys(t).map(n=>t[n]),this.failuresByPos=t,this.message=li(e,t)}Je(Xe).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+Cn(this._e,2))}},toString:function(){return this.name+": "+this.message}}),Je(Nt).from(Xe),Je(dt).from(Xe);var On=Rn.reduce((e,t)=>(e[t]=t+"Error",e),{});const io=Xe;var x=Rn.reduce((e,t)=>{var n=t+"Error";function r(i,s){this._e=De(),this.name=n,i?typeof i=="string"?(this.message=`${i}${s?`
`+s:""}`,this.inner=s||null):typeof i=="object"&&(this.message=`${i.name} ${i.message}`,this.inner=i):(this.message=ro[t]||n,this.inner=null)}return Je(r).from(io),e[t]=r,e},{});x.Syntax=SyntaxError,x.Type=TypeError,x.Range=RangeError;var ci=ai.reduce((e,t)=>(e[t+"Error"]=x[t],e),{}),$t=Rn.reduce((e,t)=>(["Syntax","Type","Range"].indexOf(t)===-1&&(e[t+"Error"]=x[t]),e),{});function P(){}function pt(e){return e}function so(e,t){return e==null||e===pt?t:function(n){return t(e(n))}}function Pe(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function oo(e,t){return e===P?t:function(){var n=e.apply(this,arguments);n!==void 0&&(arguments[0]=n);var r=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var s=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?Pe(r,this.onsuccess):r),i&&(this.onerror=this.onerror?Pe(i,this.onerror):i),s!==void 0?s:n}}function ao(e,t){return e===P?t:function(){e.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?Pe(n,this.onsuccess):n),r&&(this.onerror=this.onerror?Pe(r,this.onerror):r)}}function lo(e,t){return e===P?t:function(n){var r=e.apply(this,arguments);J(n,r);var i=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var o=t.apply(this,arguments);return i&&(this.onsuccess=this.onsuccess?Pe(i,this.onsuccess):i),s&&(this.onerror=this.onerror?Pe(s,this.onerror):s),r===void 0?o===void 0?void 0:o:J(r,o)}}function co(e,t){return e===P?t:function(){return t.apply(this,arguments)!==!1&&e.apply(this,arguments)}}function Dn(e,t){return e===P?t:function(){var n=e.apply(this,arguments);if(n&&typeof n.then=="function"){for(var r=this,i=arguments.length,s=new Array(i);i--;)s[i]=arguments[i];return n.then(function(){return t.apply(r,s)})}return t.apply(this,arguments)}}$t.ModifyError=Nt,$t.DexieError=Xe,$t.BulkError=dt;var ht={};const ui=100,[Pn,qt,Tn]=typeof Promise>"u"?[]:(()=>{let e=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[e,lt(e),e];const t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,lt(t),e]})(),di=qt&&qt.then,Vt=Pn&&Pn.constructor,Bn=!!Tn;var Mn=!1,uo=Tn?()=>{Tn.then(Gt)}:F.setImmediate?setImmediate.bind(null,Gt):F.MutationObserver?()=>{var e=document.createElement("div");new MutationObserver(()=>{Gt(),e=null}).observe(e,{attributes:!0}),e.setAttribute("i","1")}:()=>{setTimeout(Gt,0)},ft=function(e,t){mt.push([e,t]),Wt&&(uo(),Wt=!1)},Fn=!0,Wt=!0,Te=[],zt=[],jn=null,Kn=pt,Ze={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:_i,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(e=>{try{_i(e[0],e[1])}catch{}})}},U=Ze,mt=[],Be=0,Ht=[];function L(e){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=P,this._lib=!1;var t=this._PSD=U;if(oe&&(this._stackHolder=De(),this._prev=null,this._numPrev=0),typeof e!="function"){if(e!==ht)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&$n(this,this._value))}this._state=null,this._value=null,++t.ref,hi(this,e)}const Nn={get:function(){var e=U,t=Qt;function n(r,i){var s=!e.global&&(e!==U||t!==Qt);const o=s&&!fe();var a=new L((l,c)=>{qn(this,new pi(Zt(r,e,s,o),Zt(i,e,s,o),l,c,e))});return oe&&yi(a,this),a}return n.prototype=ht,n},set:function(e){de(this,"then",e&&e.prototype===ht?Nn:{get:function(){return e},set:Nn.set})}};function pi(e,t,n,r,i){this.onFulfilled=typeof e=="function"?e:null,this.onRejected=typeof t=="function"?t:null,this.resolve=n,this.reject=r,this.psd=i}function hi(e,t){try{t(n=>{if(e._state===null){if(n===e)throw new TypeError("A promise cannot be resolved with itself.");var r=e._lib&&yt();n&&typeof n.then=="function"?hi(e,(i,s)=>{n instanceof L?n._then(i,s):n.then(i,s)}):(e._state=!0,e._value=n,fi(e)),r&>()}},$n.bind(null,e))}catch(n){$n(e,n)}}function $n(e,t){if(zt.push(t),e._state===null){var n=e._lib&&yt();t=Kn(t),e._state=!1,e._value=t,oe&&t!==null&&typeof t=="object"&&!t._promise&&function(r,i,s){try{r.apply(null,s)}catch(o){i&&i(o)}}(()=>{var r=Ln(t,"stack");t._promise=e,de(t,"stack",{get:()=>Mn?r&&(r.get?r.get.apply(t):r.value):e.stack})}),function(r){Te.some(i=>i._value===r._value)||Te.push(r)}(e),fi(e),n&>()}}function fi(e){var t=e._listeners;e._listeners=[];for(var n=0,r=t.length;n<r;++n)qn(e,t[n]);var i=e._PSD;--i.ref||i.finalize(),Be===0&&(++Be,ft(()=>{--Be==0&&Vn()},[]))}function qn(e,t){if(e._state!==null){var n=e._state?t.onFulfilled:t.onRejected;if(n===null)return(e._state?t.resolve:t.reject)(e._value);++t.psd.ref,++Be,ft(po,[n,e,t])}else e._listeners.push(t)}function po(e,t,n){try{jn=t;var r,i=t._value;t._state?r=e(i):(zt.length&&(zt=[]),r=e(i),zt.indexOf(i)===-1&&function(s){for(var o=Te.length;o;)if(Te[--o]._value===s._value)return void Te.splice(o,1)}(t)),n.resolve(r)}catch(s){n.reject(s)}finally{jn=null,--Be==0&&Vn(),--n.psd.ref||n.psd.finalize()}}function mi(e,t,n){if(t.length===n)return t;var r="";if(e._state===!1){var i,s,o=e._value;o!=null?(i=o.name||"Error",s=o.message||o,r=Cn(o,0)):(i=o,s=""),t.push(i+(s?": "+s:"")+r)}return oe&&((r=Cn(e._stackHolder,2))&&t.indexOf(r)===-1&&t.push(r),e._prev&&mi(e._prev,t,n)),t}function yi(e,t){var n=t?t._numPrev+1:0;n<100&&(e._prev=t,e._numPrev=n)}function Gt(){yt()&>()}function yt(){var e=Fn;return Fn=!1,Wt=!1,e}function gt(){var e,t,n;do for(;mt.length>0;)for(e=mt,mt=[],n=e.length,t=0;t<n;++t){var r=e[t];r[0].apply(null,r[1])}while(mt.length>0);Fn=!0,Wt=!0}function Vn(){var e=Te;Te=[],e.forEach(r=>{r._PSD.onunhandled.call(null,r._value,r)});for(var t=Ht.slice(0),n=t.length;n;)t[--n]()}function Yt(e){return new L(ht,!1,e)}function K(e,t){var n=U;return function(){var r=yt(),i=U;try{return Le(n,!0),e.apply(this,arguments)}catch(s){t&&t(s)}finally{Le(i,!1),r&>()}}}Ye(L.prototype,{then:Nn,_then:function(e,t){qn(this,new pi(null,null,e,t,U))},catch:function(e){if(arguments.length===1)return this.then(null,e);var t=arguments[0],n=arguments[1];return typeof t=="function"?this.then(null,r=>r instanceof t?n(r):Yt(r)):this.then(null,r=>r&&r.name===t?n(r):Yt(r))},finally:function(e){return this.then(t=>(e(),t),t=>(e(),Yt(t)))},stack:{get:function(){if(this._stack)return this._stack;try{Mn=!0;var e=mi(this,[],20).join(`
From previous: `);return this._state!==null&&(this._stack=e),e}finally{Mn=!1}}},timeout:function(e,t){return e<1/0?new L((n,r)=>{var i=setTimeout(()=>r(new x.Timeout(t)),e);this.then(n,r).finally(clearTimeout.bind(null,i))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&de(L.prototype,Symbol.toStringTag,"Dexie.Promise"),Ze.env=gi(),Ye(L,{all:function(){var e=he.apply(null,arguments).map(Xt);return new L(function(t,n){e.length===0&&t([]);var r=e.length;e.forEach((i,s)=>L.resolve(i).then(o=>{e[s]=o,--r||t(e)},n))})},resolve:e=>{if(e instanceof L)return e;if(e&&typeof e.then=="function")return new L((n,r)=>{e.then(n,r)});var t=new L(ht,!0,e);return yi(t,jn),t},reject:Yt,race:function(){var e=he.apply(null,arguments).map(Xt);return new L((t,n)=>{e.map(r=>L.resolve(r).then(t,n))})},PSD:{get:()=>U,set:e=>U=e},totalEchoes:{get:()=>Qt},newPSD:Se,usePSD:tt,scheduler:{get:()=>ft,set:e=>{ft=e}},rejectionMapper:{get:()=>Kn,set:e=>{Kn=e}},follow:(e,t)=>new L((n,r)=>Se((i,s)=>{var o=U;o.unhandleds=[],o.onunhandled=s,o.finalize=Pe(function(){(function(a){function l(){a(),Ht.splice(Ht.indexOf(l),1)}Ht.push(l),++Be,ft(()=>{--Be==0&&Vn()},[])})(()=>{this.unhandleds.length===0?i():s(this.unhandleds[0])})},o.finalize),e()},t,n,r))}),Vt&&(Vt.allSettled&&de(L,"allSettled",function(){const e=he.apply(null,arguments).map(Xt);return new L(t=>{e.length===0&&t([]);let n=e.length;const r=new Array(n);e.forEach((i,s)=>L.resolve(i).then(o=>r[s]={status:"fulfilled",value:o},o=>r[s]={status:"rejected",reason:o}).then(()=>--n||t(r)))})}),Vt.any&&typeof AggregateError<"u"&&de(L,"any",function(){const e=he.apply(null,arguments).map(Xt);return new L((t,n)=>{e.length===0&&n(new AggregateError([]));let r=e.length;const i=new Array(r);e.forEach((s,o)=>L.resolve(s).then(a=>t(a),a=>{i[o]=a,--r||n(new AggregateError(i))}))})}));const G={awaits:0,echoes:0,id:0};var ho=0,Jt=[],Wn=0,Qt=0,fo=0;function Se(e,t,n,r){var i=U,s=Object.create(i);s.parent=i,s.ref=0,s.global=!1,s.id=++fo;var o=Ze.env;s.env=Bn?{Promise:L,PromiseProp:{value:L,configurable:!0,writable:!0},all:L.all,race:L.race,allSettled:L.allSettled,any:L.any,resolve:L.resolve,reject:L.reject,nthen:vi(o.nthen,s),gthen:vi(o.gthen,s)}:{},t&&J(s,t),++i.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()};var a=tt(s,e,n,r);return s.ref===0&&s.finalize(),a}function et(){return G.id||(G.id=++ho),++G.awaits,G.echoes+=ui,G.id}function fe(){return!!G.awaits&&(--G.awaits==0&&(G.id=0),G.echoes=G.awaits*ui,!0)}function Xt(e){return G.echoes&&e&&e.constructor===Vt?(et(),e.then(t=>(fe(),t),t=>(fe(),q(t)))):e}function mo(e){++Qt,G.echoes&&--G.echoes!=0||(G.echoes=G.id=0),Jt.push(U),Le(e,!0)}function yo(){var e=Jt[Jt.length-1];Jt.pop(),Le(e,!1)}function Le(e,t){var n=U;if((t?!G.echoes||Wn++&&e===U:!Wn||--Wn&&e===U)||wi(t?mo.bind(null,e):yo),e!==U&&(U=e,n===Ze&&(Ze.env=gi()),Bn)){var r=Ze.env.Promise,i=e.env;qt.then=i.nthen,r.prototype.then=i.gthen,(n.global||e.global)&&(Object.defineProperty(F,"Promise",i.PromiseProp),r.all=i.all,r.race=i.race,r.resolve=i.resolve,r.reject=i.reject,i.allSettled&&(r.allSettled=i.allSettled),i.any&&(r.any=i.any))}}function gi(){var e=F.Promise;return Bn?{Promise:e,PromiseProp:Object.getOwnPropertyDescriptor(F,"Promise"),all:e.all,race:e.race,allSettled:e.allSettled,any:e.any,resolve:e.resolve,reject:e.reject,nthen:qt.then,gthen:e.prototype.then}:{}}function tt(e,t,n,r,i){var s=U;try{return Le(e,!0),t(n,r,i)}finally{Le(s,!1)}}function wi(e){di.call(Pn,e)}function Zt(e,t,n,r){return typeof e!="function"?e:function(){var i=U;n&&et(),Le(t,!0);try{return e.apply(this,arguments)}finally{Le(i,!1),r&&wi(fe)}}}function vi(e,t){return function(n,r){return e.call(this,Zt(n,t),Zt(r,t))}}(""+di).indexOf("[native code]")===-1&&(et=fe=P);const bi="unhandledrejection";function _i(e,t){var n;try{n=t.onuncatched(e)}catch{}if(n!==!1)try{var r,i={promise:t,reason:e};if(F.document&&document.createEvent?((r=document.createEvent("Event")).initEvent(bi,!0,!0),J(r,i)):F.CustomEvent&&J(r=new CustomEvent(bi,{detail:i}),i),r&&F.dispatchEvent&&(dispatchEvent(r),!F.PromiseRejectionEvent&&F.onunhandledrejection))try{F.onunhandledrejection(r)}catch{}oe&&r&&!r.defaultPrevented&&console.warn(`Unhandled rejection: ${e.stack||e}`)}catch{}}var q=L.reject;function zn(e,t,n,r){if(e.idbdb&&(e._state.openComplete||U.letThrough||e._vip)){var i=e._createTransaction(t,n,e._dbSchema);try{i.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===On.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>zn(e,t,n,r))):q(s)}return i._promise(t,(s,o)=>Se(()=>(U.trans=i,r(s,o,i)))).then(s=>i._completion.then(()=>s))}if(e._state.openComplete)return q(new x.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return q(new x.DatabaseClosed);e.open().catch(P)}return e._state.dbReadyPromise.then(()=>zn(e,t,n,r))}const ki="3.2.7",Me="",Hn=-1/0,me="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Ei="String expected.",wt=[],en=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),go=en,wo=en,Si=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),tn="__dbnames",Gn="readonly",Yn="readwrite";function Fe(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const Li={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function nn(e){return typeof e!="string"||/\./.test(e)?t=>t:t=>(t[e]===void 0&&e in t&&delete(t=ut(t))[e],t)}class vo{_trans(t,n,r){const i=this._tx||U.trans,s=this.name;function o(l,c,u){if(!u.schema[s])throw new x.NotFound("Table "+s+" not part of transaction");return n(u.idbtrans,u)}const a=yt();try{return i&&i.db===this.db?i===U.trans?i._promise(t,o,r):Se(()=>i._promise(t,o,r),{trans:i,transless:U.transless||U}):zn(this.db,t,[this.name],o)}finally{a&>()}}get(t,n){return t&&t.constructor===Object?this.where(t).first(n):this._trans("readonly",r=>this.core.get({trans:r,key:t}).then(i=>this.hook.reading.fire(i))).then(n)}where(t){if(typeof t=="string")return new this.db.WhereClause(this,t);if(H(t))return new this.db.WhereClause(this,`[${t.join("+")}]`);const n=N(t);if(n.length===1)return this.where(n[0]).equals(t[n[0]]);const r=this.schema.indexes.concat(this.schema.primKey).filter(c=>{if(c.compound&&n.every(u=>c.keyPath.indexOf(u)>=0)){for(let u=0;u<n.length;++u)if(n.indexOf(c.keyPath[u])===-1)return!1;return!0}return!1}).sort((c,u)=>c.keyPath.length-u.keyPath.length)[0];if(r&&this.db._maxKey!==Me){const c=r.keyPath.slice(0,n.length);return this.where(c).equals(c.map(u=>t[u]))}!r&&oe&&console.warn(`The query ${JSON.stringify(t)} on ${this.name} would benefit of a compound index [${n.join("+")}]`);const{idxByName:i}=this.schema,s=this.db._deps.indexedDB;function o(c,u){try{return s.cmp(c,u)===0}catch{return!1}}const[a,l]=n.reduce(([c,u],p)=>{const d=i[p],h=t[p];return[c||d,c||!d?Fe(u,d&&d.multi?g=>{const y=pe(g,p);return H(y)&&y.some(w=>o(h,w))}:g=>o(h,pe(g,p))):u]},[null,null]);return a?this.where(a.name).equals(t[a.keyPath]).filter(l):r?this.filter(l):this.where(n).equals("")}filter(t){return this.toCollection().and(t)}count(t){return this.toCollection().count(t)}offset(t){return this.toCollection().offset(t)}limit(t){return this.toCollection().limit(t)}each(t){return this.toCollection().each(t)}toArray(t){return this.toCollection().toArray(t)}toCollection(){return new this.db.Collection(new this.db.WhereClause(this))}orderBy(t){return new this.db.Collection(new this.db.WhereClause(this,H(t)?`[${t.join("+")}]`:t))}reverse(){return this.toCollection().reverse()}mapToClass(t){this.schema.mappedClass=t;const n=r=>{if(!r)return r;const i=Object.create(t.prototype);for(var s in r)if(ee(r,s))try{i[s]=r[s]}catch{}return i};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=n,this.hook("reading",n),t}defineClass(){return this.mapToClass(function(t){J(this,t)})}add(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=nn(i)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"add",keys:n!=null?[n]:null,values:[s]})).then(o=>o.numFailures?L.reject(o.failures[0]):o.lastResult).then(o=>{if(i)try{re(t,i,o)}catch{}return o})}update(t,n){if(typeof t!="object"||H(t))return this.where(":id").equals(t).modify(n);{const r=pe(t,this.schema.primKey.keyPath);if(r===void 0)return q(new x.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?N(n).forEach(i=>{re(t,i,n[i])}):n(t,{value:t,primKey:r})}catch{}return this.where(":id").equals(r).modify(n)}}put(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=nn(i)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"put",values:[s],keys:n!=null?[n]:null})).then(o=>o.numFailures?L.reject(o.failures[0]):o.lastResult).then(o=>{if(i)try{re(t,i,o)}catch{}return o})}delete(t){return this._trans("readwrite",n=>this.core.mutate({trans:n,type:"delete",keys:[t]})).then(n=>n.numFailures?L.reject(n.failures[0]):void 0)}clear(){return this._trans("readwrite",t=>this.core.mutate({trans:t,type:"deleteRange",range:Li})).then(t=>t.numFailures?L.reject(t.failures[0]):void 0)}bulkGet(t){return this._trans("readonly",n=>this.core.getMany({keys:t,trans:n}).then(r=>r.map(i=>this.hook.reading.fire(i))))}bulkAdd(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(nn(l)):t;return this.core.mutate({trans:o,type:"add",keys:i,values:u,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:g})=>{if(p===0)return s?d:h;throw new dt(`${this.name}.bulkAdd(): ${p} of ${c} operations failed`,g)})})}bulkPut(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(nn(l)):t;return this.core.mutate({trans:o,type:"put",keys:i,values:u,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:g})=>{if(p===0)return s?d:h;throw new dt(`${this.name}.bulkPut(): ${p} of ${c} operations failed`,g)})})}bulkDelete(t){const n=t.length;return this._trans("readwrite",r=>this.core.mutate({trans:r,type:"delete",keys:t})).then(({numFailures:r,lastResult:i,failures:s})=>{if(r===0)return i;throw new dt(`${this.name}.bulkDelete(): ${r} of ${n} operations failed`,s)})}}function vt(e){var t={},n=function(o,a){if(a){for(var l=arguments.length,c=new Array(l-1);--l;)c[l-1]=arguments[l];return t[o].subscribe.apply(null,c),e}if(typeof o=="string")return t[o]};n.addEventType=s;for(var r=1,i=arguments.length;r<i;++r)s(arguments[r]);return n;function s(o,a,l){if(typeof o!="object"){var c;a||(a=co),l||(l=P);var u={subscribers:[],fire:l,subscribe:function(p){u.subscribers.indexOf(p)===-1&&(u.subscribers.push(p),u.fire=a(u.fire,p))},unsubscribe:function(p){u.subscribers=u.subscribers.filter(function(d){return d!==p}),u.fire=u.subscribers.reduce(a,l)}};return t[o]=n[o]=u,u}N(c=o).forEach(function(p){var d=c[p];if(H(d))s(p,c[p][0],c[p][1]);else{if(d!=="asap")throw new x.InvalidArgument("Invalid event config");var h=s(p,pt,function(){for(var g=arguments.length,y=new Array(g);g--;)y[g]=arguments[g];h.subscribers.forEach(function(w){ei(function(){w.apply(null,y)})})})}})}}function bt(e,t){return Je(t).from({prototype:e}),t}function nt(e,t){return!(e.filter||e.algorithm||e.or)&&(t?e.justLimit:!e.replayFilter)}function Jn(e,t){e.filter=Fe(e.filter,t)}function Qn(e,t,n){var r=e.replayFilter;e.replayFilter=r?()=>Fe(r(),t()):t,e.justLimit=n&&!r}function rn(e,t){if(e.isPrimKey)return t.primaryKey;const n=t.getIndexByKeyPath(e.index);if(!n)throw new x.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function Ii(e,t,n){const r=rn(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:e.dir==="prev",unique:!!e.unique,query:{index:r,range:e.range}})}function sn(e,t,n,r){const i=e.replayFilter?Fe(e.filter,e.replayFilter()):e.filter;if(e.or){const s={},o=(a,l,c)=>{if(!i||i(l,c,d=>l.stop(d),d=>l.fail(d))){var u=l.primaryKey,p=""+u;p==="[object ArrayBuffer]"&&(p=""+new Uint8Array(u)),ee(s,p)||(s[p]=!0,t(a,l,c))}};return Promise.all([e.or._iterate(o,n),Ui(Ii(e,r,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Ui(Ii(e,r,n),Fe(e.algorithm,i),t,!e.keysOnly&&e.valueMapper)}function Ui(e,t,n,r){var i=K(r?(s,o,a)=>n(r(s),o,a):n);return e.then(s=>{if(s)return s.start(()=>{var o=()=>s.continue();t&&!t(s,a=>o=a,a=>{s.stop(a),o=P},a=>{s.fail(a),o=P})||i(s.value,s,a=>o=a),o()})})}function Q(e,t){try{const n=xi(e),r=xi(t);if(n!==r)return n==="Array"?1:r==="Array"?-1:n==="binary"?1:r==="binary"?-1:n==="string"?1:r==="string"?-1:n==="Date"?1:r!=="Date"?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:e<t?-1:0;case"binary":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c)if(i[c]!==s[c])return i[c]<s[c]?-1:1;return o===a?0:o<a?-1:1}(Ai(e),Ai(t));case"Array":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c){const u=Q(i[c],s[c]);if(u!==0)return u}return o===a?0:o<a?-1:1}(e,t)}}catch{}return NaN}function xi(e){const t=typeof e;if(t!=="object")return t;if(ArrayBuffer.isView(e))return"binary";const n=Un(e);return n==="ArrayBuffer"?"binary":n}function Ai(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}class bo{_read(t,n){var r=this._ctx;return r.error?r.table._trans(null,q.bind(null,r.error)):r.table._trans("readonly",t).then(n)}_write(t){var n=this._ctx;return n.error?n.table._trans(null,q.bind(null,n.error)):n.table._trans("readwrite",t,"locked")}_addAlgorithm(t){var n=this._ctx;n.algorithm=Fe(n.algorithm,t)}_iterate(t,n){return sn(this._ctx,t,n,this._ctx.table.core)}clone(t){var n=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return t&&J(r,t),n._ctx=r,n}raw(){return this._ctx.valueMapper=null,this}each(t){var n=this._ctx;return this._read(r=>sn(n,t,r,n.table.core))}count(t){return this._read(n=>{const r=this._ctx,i=r.table.core;if(nt(r,!0))return i.count({trans:n,query:{index:rn(r,i.schema),range:r.range}}).then(o=>Math.min(o,r.limit));var s=0;return sn(r,()=>(++s,!1),n,i).then(()=>s)}).then(t)}sortBy(t,n){const r=t.split(".").reverse(),i=r[0],s=r.length-1;function o(c,u){return u?o(c[r[u]],u-1):c[i]}var a=this._ctx.dir==="next"?1:-1;function l(c,u){var p=o(c,s),d=o(u,s);return p<d?-a:p>d?a:0}return this.toArray(function(c){return c.sort(l)}).then(n)}toArray(t){return this._read(n=>{var r=this._ctx;if(r.dir==="next"&&nt(r,!0)&&r.limit>0){const{valueMapper:i}=r,s=rn(r,r.table.core.schema);return r.table.core.query({trans:n,limit:r.limit,values:!0,query:{index:s,range:r.range}}).then(({result:o})=>i?o.map(i):o)}{const i=[];return sn(r,s=>i.push(s),n,r.table.core).then(()=>i)}},t)}offset(t){var n=this._ctx;return t<=0||(n.offset+=t,nt(n)?Qn(n,()=>{var r=t;return(i,s)=>r===0||(r===1?(--r,!1):(s(()=>{i.advance(r),r=0}),!1))}):Qn(n,()=>{var r=t;return()=>--r<0})),this}limit(t){return this._ctx.limit=Math.min(this._ctx.limit,t),Qn(this._ctx,()=>{var n=t;return function(r,i,s){return--n<=0&&i(s),n>=0}},!0),this}until(t,n){return Jn(this._ctx,function(r,i,s){return!t(r.value)||(i(s),n)}),this}first(t){return this.limit(1).toArray(function(n){return n[0]}).then(t)}last(t){return this.reverse().first(t)}filter(t){var n,r;return Jn(this._ctx,function(i){return t(i.value)}),n=this._ctx,r=t,n.isMatch=Fe(n.isMatch,r),this}and(t){return this.filter(t)}or(t){return new this.db.WhereClause(this._ctx.table,t,this)}reverse(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this}desc(){return this.reverse()}eachKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,i){t(i.key,i)})}eachUniqueKey(t){return this._ctx.unique="unique",this.eachKey(t)}eachPrimaryKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,i){t(i.primaryKey,i)})}keys(t){var n=this._ctx;n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.key)}).then(function(){return r}).then(t)}primaryKeys(t){var n=this._ctx;if(n.dir==="next"&&nt(n,!0)&&n.limit>0)return this._read(i=>{var s=rn(n,n.table.core.schema);return n.table.core.query({trans:i,values:!1,limit:n.limit,query:{index:s,range:n.range}})}).then(({result:i})=>i).then(t);n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.primaryKey)}).then(function(){return r}).then(t)}uniqueKeys(t){return this._ctx.unique="unique",this.keys(t)}firstKey(t){return this.limit(1).keys(function(n){return n[0]}).then(t)}lastKey(t){return this.reverse().firstKey(t)}distinct(){var t=this._ctx,n=t.index&&t.table.schema.idxByName[t.index];if(!n||!n.multi)return this;var r={};return Jn(this._ctx,function(i){var s=i.primaryKey.toString(),o=ee(r,s);return r[s]=!0,!o}),this}modify(t){var n=this._ctx;return this._write(r=>{var i;if(typeof t=="function")i=t;else{var s=N(t),o=s.length;i=function(y){for(var w=!1,f=0;f<o;++f){var m=s[f],b=t[m];pe(y,m)!==b&&(re(y,m,b),w=!0)}return w}}const a=n.table.core,{outbound:l,extractKey:c}=a.schema.primaryKey,u=this.db._options.modifyChunkSize||200,p=[];let d=0;const h=[],g=(y,w)=>{const{failures:f,numFailures:m}=w;d+=y-m;for(let b of N(f))p.push(f[b])};return this.clone().primaryKeys().then(y=>{const w=f=>{const m=Math.min(u,y.length-f);return a.getMany({trans:r,keys:y.slice(f,f+m),cache:"immutable"}).then(b=>{const v=[],E=[],S=l?[]:null,_=[];for(let k=0;k<m;++k){const B=b[k],D={value:ut(B),primKey:y[f+k]};i.call(D,D.value,D)!==!1&&(D.value==null?_.push(y[f+k]):l||Q(c(B),c(D.value))===0?(E.push(D.value),l&&S.push(y[f+k])):(_.push(y[f+k]),v.push(D.value)))}const A=nt(n)&&n.limit===1/0&&(typeof t!="function"||t===Xn)&&{index:n.index,range:n.range};return Promise.resolve(v.length>0&&a.mutate({trans:r,type:"add",values:v}).then(k=>{for(let B in k.failures)_.splice(parseInt(B),1);g(v.length,k)})).then(()=>(E.length>0||A&&typeof t=="object")&&a.mutate({trans:r,type:"put",keys:S,values:E,criteria:A,changeSpec:typeof t!="function"&&t}).then(k=>g(E.length,k))).then(()=>(_.length>0||A&&t===Xn)&&a.mutate({trans:r,type:"delete",keys:_,criteria:A}).then(k=>g(_.length,k))).then(()=>y.length>f+m&&w(f+u))})};return w(0).then(()=>{if(p.length>0)throw new Nt("Error modifying one or more objects",p,d,h);return y.length})})})}delete(){var t=this._ctx,n=t.range;return nt(t)&&(t.isPrimKey&&!wo||n.type===3)?this._write(r=>{const{primaryKey:i}=t.table.core.schema,s=n;return t.table.core.count({trans:r,query:{index:i,range:s}}).then(o=>t.table.core.mutate({trans:r,type:"deleteRange",range:s}).then(({failures:a,lastResult:l,results:c,numFailures:u})=>{if(u)throw new Nt("Could not delete some values",Object.keys(a).map(p=>a[p]),o-u);return o-u}))}):this.modify(Xn)}}const Xn=(e,t)=>t.value=null;function _o(e,t){return e<t?-1:e===t?0:1}function ko(e,t){return e>t?-1:e===t?0:1}function te(e,t,n){var r=e instanceof Ri?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function rt(e){return new e.Collection(e,()=>Ci("")).limit(0)}function Eo(e,t,n,r,i,s){for(var o=Math.min(e.length,r.length),a=-1,l=0;l<o;++l){var c=t[l];if(c!==r[l])return i(e[l],n[l])<0?e.substr(0,l)+n[l]+n.substr(l+1):i(e[l],r[l])<0?e.substr(0,l)+r[l]+n.substr(l+1):a>=0?e.substr(0,a)+t[a]+n.substr(a+1):null;i(e[l],c)<0&&(a=l)}return o<r.length&&s==="next"?e+n.substr(e.length):o<e.length&&s==="prev"?e.substr(0,n.length):a<0?null:e.substr(0,a)+r[a]+n.substr(a+1)}function on(e,t,n,r){var i,s,o,a,l,c,u,p=n.length;if(!n.every(y=>typeof y=="string"))return te(e,Ei);function d(y){i=function(f){return f==="next"?m=>m.toUpperCase():m=>m.toLowerCase()}(y),s=function(f){return f==="next"?m=>m.toLowerCase():m=>m.toUpperCase()}(y),o=y==="next"?_o:ko;var w=n.map(function(f){return{lower:s(f),upper:i(f)}}).sort(function(f,m){return o(f.lower,m.lower)});a=w.map(function(f){return f.upper}),l=w.map(function(f){return f.lower}),c=y,u=y==="next"?"":r}d("next");var h=new e.Collection(e,()=>Ie(a[0],l[p-1]+r));h._ondirectionchange=function(y){d(y)};var g=0;return h._addAlgorithm(function(y,w,f){var m=y.key;if(typeof m!="string")return!1;var b=s(m);if(t(b,l,g))return!0;for(var v=null,E=g;E<p;++E){var S=Eo(m,b,a[E],l[E],o,c);S===null&&v===null?g=E+1:(v===null||o(v,S)>0)&&(v=S)}return w(v!==null?function(){y.continue(v+u)}:f),!1}),h}function Ie(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Ci(e){return{type:1,lower:e,upper:e}}class Ri{get Collection(){return this._ctx.table.db.Collection}between(t,n,r,i){r=r!==!1,i=i===!0;try{return this._cmp(t,n)>0||this._cmp(t,n)===0&&(r||i)&&(!r||!i)?rt(this):new this.Collection(this,()=>Ie(t,n,!r,!i))}catch{return te(this,me)}}equals(t){return t==null?te(this,me):new this.Collection(this,()=>Ci(t))}above(t){return t==null?te(this,me):new this.Collection(this,()=>Ie(t,void 0,!0))}aboveOrEqual(t){return t==null?te(this,me):new this.Collection(this,()=>Ie(t,void 0,!1))}below(t){return t==null?te(this,me):new this.Collection(this,()=>Ie(void 0,t,!1,!0))}belowOrEqual(t){return t==null?te(this,me):new this.Collection(this,()=>Ie(void 0,t))}startsWith(t){return typeof t!="string"?te(this,Ei):this.between(t,t+Me,!0,!0)}startsWithIgnoreCase(t){return t===""?this.startsWith(t):on(this,(n,r)=>n.indexOf(r[0])===0,[t],Me)}equalsIgnoreCase(t){return on(this,(n,r)=>n===r[0],[t],"")}anyOfIgnoreCase(){var t=he.apply(Qe,arguments);return t.length===0?rt(this):on(this,(n,r)=>r.indexOf(n)!==-1,t,"")}startsWithAnyOfIgnoreCase(){var t=he.apply(Qe,arguments);return t.length===0?rt(this):on(this,(n,r)=>r.some(i=>n.indexOf(i)===0),t,Me)}anyOf(){const t=he.apply(Qe,arguments);let n=this._cmp;try{t.sort(n)}catch{return te(this,me)}if(t.length===0)return rt(this);const r=new this.Collection(this,()=>Ie(t[0],t[t.length-1]));r._ondirectionchange=s=>{n=s==="next"?this._ascending:this._descending,t.sort(n)};let i=0;return r._addAlgorithm((s,o,a)=>{const l=s.key;for(;n(l,t[i])>0;)if(++i,i===t.length)return o(a),!1;return n(l,t[i])===0||(o(()=>{s.continue(t[i])}),!1)}),r}notEqual(t){return this.inAnyRange([[Hn,t],[t,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const t=he.apply(Qe,arguments);if(t.length===0)return new this.Collection(this);try{t.sort(this._ascending)}catch{return te(this,me)}const n=t.reduce((r,i)=>r?r.concat([[r[r.length-1][1],i]]):[[Hn,i]],null);return n.push([t[t.length-1],this.db._maxKey]),this.inAnyRange(n,{includeLowers:!1,includeUppers:!1})}inAnyRange(t,n){const r=this._cmp,i=this._ascending,s=this._descending,o=this._min,a=this._max;if(t.length===0)return rt(this);if(!t.every(m=>m[0]!==void 0&&m[1]!==void 0&&i(m[0],m[1])<=0))return te(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",x.InvalidArgument);const l=!n||n.includeLowers!==!1,c=n&&n.includeUppers===!0;let u,p=i;function d(m,b){return p(m[0],b[0])}try{u=t.reduce(function(m,b){let v=0,E=m.length;for(;v<E;++v){const S=m[v];if(r(b[0],S[1])<0&&r(b[1],S[0])>0){S[0]=o(S[0],b[0]),S[1]=a(S[1],b[1]);break}}return v===E&&m.push(b),m},[]),u.sort(d)}catch{return te(this,me)}let h=0;const g=c?m=>i(m,u[h][1])>0:m=>i(m,u[h][1])>=0,y=l?m=>s(m,u[h][0])>0:m=>s(m,u[h][0])>=0;let w=g;const f=new this.Collection(this,()=>Ie(u[0][0],u[u.length-1][1],!l,!c));return f._ondirectionchange=m=>{m==="next"?(w=g,p=i):(w=y,p=s),u.sort(d)},f._addAlgorithm((m,b,v)=>{for(var E=m.key;w(E);)if(++h,h===u.length)return b(v),!1;return!!function(S){return!g(S)&&!y(S)}(E)||(this._cmp(E,u[h][1])===0||this._cmp(E,u[h][0])===0||b(()=>{p===i?m.continue(u[h][0]):m.continue(u[h][1])}),!1)}),f}startsWithAnyOf(){const t=he.apply(Qe,arguments);return t.every(n=>typeof n=="string")?t.length===0?rt(this):this.inAnyRange(t.map(n=>[n,n+Me])):te(this,"startsWithAnyOf() only works with strings")}}function ae(e){return K(function(t){return _t(t),e(t.target.error),!1})}function _t(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}const kt="storagemutated",Ue="x-storagemutated-1",xe=vt(null,kt);class So{_lock(){return ct(!U.global),++this._reculock,this._reculock!==1||U.global||(U.lockOwnerFor=this),this}_unlock(){if(ct(!U.global),--this._reculock==0)for(U.global||(U.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var t=this._blockedFuncs.shift();try{tt(t[1],t[0])}catch{}}return this}_locked(){return this._reculock&&U.lockOwnerFor!==this}create(t){if(!this.mode)return this;const n=this.db.idbdb,r=this.db._state.dbOpenError;if(ct(!this.idbtrans),!t&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new x.DatabaseClosed(r);case"MissingAPIError":throw new x.MissingAPI(r.message,r);default:throw new x.OpenFailed(r)}if(!this.active)throw new x.TransactionInactive;return ct(this._completion._state===null),(t=this.idbtrans=t||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):n.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}))).onerror=K(i=>{_t(i),this._reject(t.error)}),t.onabort=K(i=>{_t(i),this.active&&this._reject(new x.Abort(t.error)),this.active=!1,this.on("abort").fire(i)}),t.oncomplete=K(()=>{this.active=!1,this._resolve(),"mutatedParts"in t&&xe.storagemutated.fire(t.mutatedParts)}),this}_promise(t,n,r){if(t==="readwrite"&&this.mode!=="readwrite")return q(new x.ReadOnly("Transaction is readonly"));if(!this.active)return q(new x.TransactionInactive);if(this._locked())return new L((s,o)=>{this._blockedFuncs.push([()=>{this._promise(t,n,r).then(s,o)},U])});if(r)return Se(()=>{var s=new L((o,a)=>{this._lock();const l=n(o,a,this);l&&l.then&&l.then(o,a)});return s.finally(()=>this._unlock()),s._lib=!0,s});var i=new L((s,o)=>{var a=n(s,o,this);a&&a.then&&a.then(s,o)});return i._lib=!0,i}_root(){return this.parent?this.parent._root():this}waitFor(t){var n=this._root();const r=L.resolve(t);if(n._waitingFor)n._waitingFor=n._waitingFor.then(()=>r);else{n._waitingFor=r,n._waitingQueue=[];var i=n.idbtrans.objectStore(n.storeNames[0]);(function o(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(i.get(-1/0).onsuccess=o)})()}var s=n._waitingFor;return new L((o,a)=>{r.then(l=>n._waitingQueue.push(K(o.bind(null,l))),l=>n._waitingQueue.push(K(a.bind(null,l)))).finally(()=>{n._waitingFor===s&&(n._waitingFor=null)})})}abort(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new x.Abort))}table(t){const n=this._memoizedTables||(this._memoizedTables={});if(ee(n,t))return n[t];const r=this.schema[t];if(!r)throw new x.NotFound("Table "+t+" not part of transaction");const i=new this.db.Table(t,r,this);return i.core=this.db.core.table(t),n[t]=i,i}}function Zn(e,t,n,r,i,s,o){return{name:e,keyPath:t,unique:n,multi:r,auto:i,compound:s,src:(n&&!o?"&":"")+(r?"*":"")+(i?"++":"")+Oi(t)}}function Oi(e){return typeof e=="string"?e:e?"["+[].join.call(e,"+")+"]":""}function Di(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:ti(n,r=>[r.name,r])}}let Et=e=>{try{return e.only([[]]),Et=()=>[[]],[[]]}catch{return Et=()=>Me,Me}};function er(e){return e==null?()=>{}:typeof e=="string"?function(t){return t.split(".").length===1?r=>r[t]:r=>pe(r,t)}(e):t=>pe(t,e)}function Pi(e){return[].slice.call(e)}let Lo=0;function St(e){return e==null?":id":typeof e=="string"?e:`[${e.join("+")}]`}function Io(e,t,n){function r(l){if(l.type===3)return null;if(l.type===4)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:c,upper:u,lowerOpen:p,upperOpen:d}=l;return c===void 0?u===void 0?null:t.upperBound(u,!!d):u===void 0?t.lowerBound(c,!!p):t.bound(c,u,!!p,!!d)}const{schema:i,hasGetAll:s}=function(l,c){const u=Pi(l.objectStoreNames);return{schema:{name:l.name,tables:u.map(p=>c.objectStore(p)).map(p=>{const{keyPath:d,autoIncrement:h}=p,g=H(d),y=d==null,w={},f={name:p.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:g,keyPath:d,autoIncrement:h,unique:!0,extractKey:er(d)},indexes:Pi(p.indexNames).map(m=>p.index(m)).map(m=>{const{name:b,unique:v,multiEntry:E,keyPath:S}=m,_={name:b,compound:H(S),keyPath:S,unique:v,multiEntry:E,extractKey:er(S)};return w[St(S)]=_,_}),getIndexByKeyPath:m=>w[St(m)]};return w[":id"]=f.primaryKey,d!=null&&(w[St(d)]=f.primaryKey),f})},hasGetAll:u.length>0&&"getAll"in c.objectStore(u[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,n),o=i.tables.map(l=>function(c){const u=c.name;return{name:u,schema:c,mutate:function({trans:p,type:d,keys:h,values:g,range:y}){return new Promise((w,f)=>{w=K(w);const m=p.objectStore(u),b=m.keyPath==null,v=d==="put"||d==="add";if(!v&&d!=="delete"&&d!=="deleteRange")throw new Error("Invalid operation type: "+d);const{length:E}=h||g||{length:1};if(h&&g&&h.length!==g.length)throw new Error("Given keys array must have same length as given values array.");if(E===0)return w({numFailures:0,failures:{},results:[],lastResult:void 0});let S;const _=[],A=[];let k=0;const B=V=>{++k,_t(V)};if(d==="deleteRange"){if(y.type===4)return w({numFailures:k,failures:A,results:[],lastResult:void 0});y.type===3?_.push(S=m.clear()):_.push(S=m.delete(r(y)))}else{const[V,W]=v?b?[g,h]:[g,null]:[h,null];if(v)for(let j=0;j<E;++j)_.push(S=W&&W[j]!==void 0?m[d](V[j],W[j]):m[d](V[j])),S.onerror=B;else for(let j=0;j<E;++j)_.push(S=m[d](V[j])),S.onerror=B}const D=V=>{const W=V.target.result;_.forEach((j,ve)=>j.error!=null&&(A[ve]=j.error)),w({numFailures:k,failures:A,results:d==="delete"?h:_.map(j=>j.result),lastResult:W})};S.onerror=V=>{B(V),D(V)},S.onsuccess=D})},getMany:({trans:p,keys:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u),w=d.length,f=new Array(w);let m,b=0,v=0;const E=_=>{const A=_.target;f[A._pos]=A.result,++v===b&&h(f)},S=ae(g);for(let _=0;_<w;++_)d[_]!=null&&(m=y.get(d[_]),m._pos=_,m.onsuccess=E,m.onerror=S,++b);b===0&&h(f)}),get:({trans:p,key:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u).get(d);y.onsuccess=w=>h(w.target.result),y.onerror=ae(g)}),query:function(p){return d=>new Promise((h,g)=>{h=K(h);const{trans:y,values:w,limit:f,query:m}=d,b=f===1/0?void 0:f,{index:v,range:E}=m,S=y.objectStore(u),_=v.isPrimaryKey?S:S.index(v.name),A=r(E);if(f===0)return h({result:[]});if(p){const k=w?_.getAll(A,b):_.getAllKeys(A,b);k.onsuccess=B=>h({result:B.target.result}),k.onerror=ae(g)}else{let k=0;const B=w||!("openKeyCursor"in _)?_.openCursor(A):_.openKeyCursor(A),D=[];B.onsuccess=V=>{const W=B.result;return W?(D.push(w?W.value:W.primaryKey),++k===f?h({result:D}):void W.continue()):h({result:D})},B.onerror=ae(g)}})}(s),openCursor:function({trans:p,values:d,query:h,reverse:g,unique:y}){return new Promise((w,f)=>{w=K(w);const{index:m,range:b}=h,v=p.objectStore(u),E=m.isPrimaryKey?v:v.index(m.name),S=g?y?"prevunique":"prev":y?"nextunique":"next",_=d||!("openKeyCursor"in E)?E.openCursor(r(b),S):E.openKeyCursor(r(b),S);_.onerror=ae(f),_.onsuccess=K(A=>{const k=_.result;if(!k)return void w(null);k.___id=++Lo,k.done=!1;const B=k.continue.bind(k);let D=k.continuePrimaryKey;D&&(D=D.bind(k));const V=k.advance.bind(k),W=()=>{throw new Error("Cursor not stopped")};k.trans=p,k.stop=k.continue=k.continuePrimaryKey=k.advance=()=>{throw new Error("Cursor not started")},k.fail=K(f),k.next=function(){let j=1;return this.start(()=>j--?this.continue():this.stop()).then(()=>this)},k.start=j=>{const ve=new Promise((Y,We)=>{Y=K(Y),_.onerror=ae(We),k.fail=We,k.stop=Dt=>{k.stop=k.continue=k.continuePrimaryKey=k.advance=W,Y(Dt)}}),M=()=>{if(_.result)try{j()}catch(Y){k.fail(Y)}else k.done=!0,k.start=()=>{throw new Error("Cursor behind last entry")},k.stop()};return _.onsuccess=K(Y=>{_.onsuccess=M,M()}),k.continue=B,k.continuePrimaryKey=D,k.advance=V,M(),ve},w(k)},f)})},count({query:p,trans:d}){const{index:h,range:g}=p;return new Promise((y,w)=>{const f=d.objectStore(u),m=h.isPrimaryKey?f:f.index(h.name),b=r(g),v=b?m.count(b):m.count();v.onsuccess=K(E=>y(E.target.result)),v.onerror=ae(w)})}}}(l)),a={};return o.forEach(l=>a[l.name]=l),{stack:"dbcore",transaction:e.transaction.bind(e),table(l){if(!a[l])throw new Error(`Table '${l}' not found`);return a[l]},MIN_KEY:-1/0,MAX_KEY:Et(t),schema:i}}function tr({_novip:e},t){const n=t.db,r=function(i,s,{IDBKeyRange:o,indexedDB:a},l){return{dbcore:function(u,p){return p.reduce((d,{create:h})=>({...d,...h(d)}),u)}(Io(s,o,l),i.dbcore)}}(e._middlewares,n,e._deps,t);e.core=r.dbcore,e.tables.forEach(i=>{const s=i.name;e.core.schema.tables.some(o=>o.name===s)&&(i.core=e.core.table(s),e[s]instanceof e.Table&&(e[s].core=i.core))})}function an({_novip:e},t,n,r){n.forEach(i=>{const s=r[i];t.forEach(o=>{const a=Ln(o,i);(!a||"value"in a&&a.value===void 0)&&(o===e.Transaction.prototype||o instanceof e.Transaction?de(o,i,{get(){return this.table(i)},set(l){Xr(this,i,{value:l,writable:!0,configurable:!0,enumerable:!0})}}):o[i]=new e.Table(i,s))})})}function nr({_novip:e},t){t.forEach(n=>{for(let r in n)n[r]instanceof e.Table&&delete n[r]})}function Uo(e,t){return e._cfg.version-t._cfg.version}function xo(e,t,n,r){const i=e._dbSchema,s=e._createTransaction("readwrite",e._storeNames,i);s.create(n),s._completion.catch(r);const o=s._reject.bind(s),a=U.transless||U;Se(()=>{U.trans=s,U.transless=a,t===0?(N(i).forEach(l=>{rr(n,l,i[l].primKey,i[l].indexes)}),tr(e,n),L.follow(()=>e.on.populate.fire(s)).catch(o)):function({_novip:l},c,u,p){const d=[],h=l._versions;let g=l._dbSchema=sr(l,l.idbdb,p),y=!1;const w=h.filter(m=>m._cfg.version>=c);function f(){return d.length?L.resolve(d.shift()(u.idbtrans)).then(f):L.resolve()}return w.forEach(m=>{d.push(()=>{const b=g,v=m._cfg.dbschema;or(l,b,p),or(l,v,p),g=l._dbSchema=v;const E=Ti(b,v);E.add.forEach(_=>{rr(p,_[0],_[1].primKey,_[1].indexes)}),E.change.forEach(_=>{if(_.recreate)throw new x.Upgrade("Not yet support for changing primary key");{const A=p.objectStore(_.name);_.add.forEach(k=>ir(A,k)),_.change.forEach(k=>{A.deleteIndex(k.name),ir(A,k)}),_.del.forEach(k=>A.deleteIndex(k))}});const S=m._cfg.contentUpgrade;if(S&&m._cfg.version>c){tr(l,p),u._memoizedTables={},y=!0;let _=ni(v);E.del.forEach(D=>{_[D]=b[D]}),nr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],N(_),_),u.schema=_;const A=An(S);let k;A&&et();const B=L.follow(()=>{if(k=S(u),k&&A){var D=fe.bind(null,null);k.then(D,D)}});return k&&typeof k.then=="function"?L.resolve(k):B.then(()=>k)}}),d.push(b=>{(!y||!go)&&function(v,E){[].slice.call(E.db.objectStoreNames).forEach(S=>v[S]==null&&E.db.deleteObjectStore(S))}(m._cfg.dbschema,b),nr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),u.schema=l._dbSchema})}),f().then(()=>{var m,b;b=p,N(m=g).forEach(v=>{b.db.objectStoreNames.contains(v)||rr(b,v,m[v].primKey,m[v].indexes)})})}(e,t,s,n).catch(o)})}function Ti(e,t){const n={del:[],add:[],change:[]};let r;for(r in e)t[r]||n.del.push(r);for(r in t){const i=e[r],s=t[r];if(i){const o={name:r,def:s,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(s.primKey.keyPath||"")||i.primKey.auto!==s.primKey.auto&&!en)o.recreate=!0,n.change.push(o);else{const a=i.idxByName,l=s.idxByName;let c;for(c in a)l[c]||o.del.push(c);for(c in l){const u=a[c],p=l[c];u?u.src!==p.src&&o.change.push(p):o.add.push(p)}(o.del.length>0||o.add.length>0||o.change.length>0)&&n.change.push(o)}}else n.add.push([r,s])}return n}function rr(e,t,n,r){const i=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach(s=>ir(i,s)),i}function ir(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function sr(e,t,n){const r={};return Kt(t.objectStoreNames,0).forEach(i=>{const s=n.objectStore(i);let o=s.keyPath;const a=Zn(Oi(o),o||"",!1,!1,!!s.autoIncrement,o&&typeof o!="string",!0),l=[];for(let u=0;u<s.indexNames.length;++u){const p=s.index(s.indexNames[u]);o=p.keyPath;var c=Zn(p.name,o,!!p.unique,!!p.multiEntry,!1,o&&typeof o!="string",!1);l.push(c)}r[i]=Di(i,a,l)}),r}function or({_novip:e},t,n){const r=n.db.objectStoreNames;for(let i=0;i<r.length;++i){const s=r[i],o=n.objectStore(s);e._hasGetAll="getAll"in o;for(let a=0;a<o.indexNames.length;++a){const l=o.indexNames[a],c=o.index(l).keyPath,u=typeof c=="string"?c:"["+Kt(c).join("+")+"]";if(t[s]){const p=t[s].idxByName[u];p&&(p.name=l,delete t[s].idxByName[u],t[s].idxByName[l]=p)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&F.WorkerGlobalScope&&F instanceof F.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}class Ao{_parseStoresSpec(t,n){N(t).forEach(r=>{if(t[r]!==null){var i=t[r].split(",").map((o,a)=>{const l=(o=o.trim()).replace(/([&*]|\+\+)/g,""),c=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return Zn(l,c||null,/\&/.test(o),/\*/.test(o),/\+\+/.test(o),H(c),a===0)}),s=i.shift();if(s.multi)throw new x.Schema("Primary key cannot be multi-valued");i.forEach(o=>{if(o.auto)throw new x.Schema("Only primary key can be marked as autoIncrement (++)");if(!o.keyPath)throw new x.Schema("Index must have a name and cannot be an empty string")}),n[r]=Di(r,s,i)}})}stores(t){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?J(this._cfg.storesSource,t):t;const r=n._versions,i={};let s={};return r.forEach(o=>{J(i,o._cfg.storesSource),s=o._cfg.dbschema={},o._parseStoresSpec(i,s)}),n._dbSchema=s,nr(n,[n._allTables,n,n.Transaction.prototype]),an(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],N(s),s),n._storeNames=N(s),this}upgrade(t){return this._cfg.contentUpgrade=Dn(this._cfg.contentUpgrade||P,t),this}}function ar(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new je(tn,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function lr(e){return e&&typeof e.databases=="function"}function cr(e){return Se(function(){return U.letThrough=!0,e()})}function Co(){var e;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(t){var n=function(){return indexedDB.databases().finally(t)};e=setInterval(n,100),n()}).finally(function(){return clearInterval(e)}):Promise.resolve()}function Ro(e){const t=e._state,{indexedDB:n}=e._deps;if(t.isBeingOpened||e.idbdb)return t.dbReadyPromise.then(()=>t.dbOpenError?q(t.dbOpenError):e);oe&&(t.openCanceller._stackHolder=De()),t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;const r=t.openCanceller;function i(){if(t.openCanceller!==r)throw new x.DatabaseClosed("db.open() was cancelled")}let s=t.dbReadyResolve,o=null,a=!1;const l=()=>new L((c,u)=>{if(i(),!n)throw new x.MissingAPI;const p=e.name,d=t.autoSchema?n.open(p):n.open(p,Math.round(10*e.verno));if(!d)throw new x.MissingAPI;d.onerror=ae(u),d.onblocked=K(e._fireOnBlocked),d.onupgradeneeded=K(h=>{if(o=d.transaction,t.autoSchema&&!e._options.allowEmptyDB){d.onerror=_t,o.abort(),d.result.close();const y=n.deleteDatabase(p);y.onsuccess=y.onerror=K(()=>{u(new x.NoSuchDatabase(`Database ${p} doesnt exist`))})}else{o.onerror=ae(u);var g=h.oldVersion>Math.pow(2,62)?0:h.oldVersion;a=g<1,e._novip.idbdb=d.result,xo(e,g/10,o,u)}},u),d.onsuccess=K(()=>{o=null;const h=e._novip.idbdb=d.result,g=Kt(h.objectStoreNames);if(g.length>0)try{const w=h.transaction((y=g).length===1?y[0]:y,"readonly");t.autoSchema?function({_novip:f},m,b){f.verno=m.version/10;const v=f._dbSchema=sr(0,m,b);f._storeNames=Kt(m.objectStoreNames,0),an(f,[f._allTables],N(v),v)}(e,h,w):(or(e,e._dbSchema,w),function(f,m){const b=Ti(sr(0,f.idbdb,m),f._dbSchema);return!(b.add.length||b.change.some(v=>v.add.length||v.change.length))}(e,w)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),tr(e,w)}catch{}var y;wt.push(e),h.onversionchange=K(w=>{t.vcFired=!0,e.on("versionchange").fire(w)}),h.onclose=K(w=>{e.on("close").fire(w)}),a&&function({indexedDB:w,IDBKeyRange:f},m){!lr(w)&&m!==tn&&ar(w,f).put({name:m}).catch(P)}(e._deps,p),c()},u)}).catch(c=>c&&c.name==="UnknownError"&&t.PR1398_maxLoop>0?(t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):L.reject(c));return L.race([r,(typeof navigator>"u"?L.resolve():Co()).then(l)]).then(()=>(i(),t.onReadyBeingFired=[],L.resolve(cr(()=>e.on.ready.fire(e.vip))).then(function c(){if(t.onReadyBeingFired.length>0){let u=t.onReadyBeingFired.reduce(Dn,P);return t.onReadyBeingFired=[],L.resolve(cr(()=>u(e.vip))).then(c)}}))).finally(()=>{t.onReadyBeingFired=null,t.isBeingOpened=!1}).then(()=>e).catch(c=>{t.dbOpenError=c;try{o&&o.abort()}catch{}return r===t.openCanceller&&e._close(),q(c)}).finally(()=>{t.openComplete=!0,s()})}function ur(e){var t=s=>e.next(s),n=i(t),r=i(s=>e.throw(s));function i(s){return o=>{var a=s(o),l=a.value;return a.done?l:l&&typeof l.then=="function"?l.then(n,r):H(l)?Promise.all(l).then(n,r):n(l)}}return i(t)()}function Oo(e,t,n){var r=arguments.length;if(r<2)throw new x.InvalidArgument("Too few arguments");for(var i=new Array(r-1);--r;)i[r-1]=arguments[r];return n=i.pop(),[e,ri(i),n]}function Bi(e,t,n,r,i){return L.resolve().then(()=>{const s=U.transless||U,o=e._createTransaction(t,n,e._dbSchema,r),a={trans:o,transless:s};if(r)o.idbtrans=r.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(p){return p.name===On.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>Bi(e,t,n,null,i))):q(p)}const l=An(i);let c;l&&et();const u=L.follow(()=>{if(c=i.call(o,o),c)if(l){var p=fe.bind(null,null);c.then(p,p)}else typeof c.next=="function"&&typeof c.throw=="function"&&(c=ur(c))},a);return(c&&typeof c.then=="function"?L.resolve(c).then(p=>o.active?p:q(new x.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):u.then(()=>c)).then(p=>(r&&o._resolve(),o._completion.then(()=>p))).catch(p=>(o._reject(p),q(p)))})}function ln(e,t,n){const r=H(e)?e.slice():[e];for(let i=0;i<n;++i)r.push(t);return r}const Do={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(e){return{...e,table(t){const n=e.table(t),{schema:r}=n,i={},s=[];function o(u,p,d){const h=St(u),g=i[h]=i[h]||[],y=u==null?0:typeof u=="string"?1:u.length,w=p>0,f={...d,isVirtual:w,keyTail:p,keyLength:y,extractKey:er(u),unique:!w&&d.unique};return g.push(f),f.isPrimaryKey||s.push(f),y>1&&o(y===2?u[0]:u.slice(0,y-1),p+1,d),g.sort((m,b)=>m.keyTail-b.keyTail),f}const a=o(r.primaryKey.keyPath,0,r.primaryKey);i[":id"]=[a];for(const u of r.indexes)o(u.keyPath,0,u);function l(u){const p=u.query.index;return p.isVirtual?{...u,query:{index:p,range:(d=u.query.range,h=p.keyTail,{type:d.type===1?2:d.type,lower:ln(d.lower,d.lowerOpen?e.MAX_KEY:e.MIN_KEY,h),lowerOpen:!0,upper:ln(d.upper,d.upperOpen?e.MIN_KEY:e.MAX_KEY,h),upperOpen:!0})}}:u;var d,h}return{...n,schema:{...r,primaryKey:a,indexes:s,getIndexByKeyPath:function(u){const p=i[St(u)];return p&&p[0]}},count:u=>n.count(l(u)),query:u=>n.query(l(u)),openCursor(u){const{keyTail:p,isVirtual:d,keyLength:h}=u.query.index;return d?n.openCursor(l(u)).then(g=>g&&function(y){return Object.create(y,{continue:{value:function(f){f!=null?y.continue(ln(f,u.reverse?e.MAX_KEY:e.MIN_KEY,p)):u.unique?y.continue(y.key.slice(0,h).concat(u.reverse?e.MIN_KEY:e.MAX_KEY,p)):y.continue()}},continuePrimaryKey:{value(f,m){y.continuePrimaryKey(ln(f,e.MAX_KEY,p),m)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const f=y.key;return h===1?f[0]:f.slice(0,h)}},value:{get:()=>y.value}})}(g)):n.openCursor(u)}}}}}};function dr(e,t,n,r){return n=n||{},r=r||"",N(e).forEach(i=>{if(ee(t,i)){var s=e[i],o=t[i];if(typeof s=="object"&&typeof o=="object"&&s&&o){const a=Un(s);a!==Un(o)?n[r+i]=t[i]:a==="Object"?dr(s,o,n,r+i+"."):s!==o&&(n[r+i]=t[i])}else s!==o&&(n[r+i]=t[i])}else n[r+i]=void 0}),N(t).forEach(i=>{ee(e,i)||(n[r+i]=t[i])}),n}const Po={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:r}=n.schema;return{...n,mutate(s){const o=U.trans,{deleting:a,creating:l,updating:c}=o.table(t).hook;switch(s.type){case"add":if(l.fire===P)break;return o._promise("readwrite",()=>u(s),!0);case"put":if(l.fire===P&&c.fire===P)break;return o._promise("readwrite",()=>u(s),!0);case"delete":if(a.fire===P)break;return o._promise("readwrite",()=>u(s),!0);case"deleteRange":if(a.fire===P)break;return o._promise("readwrite",()=>function(d){return p(d.trans,d.range,1e4)}(s),!0)}return n.mutate(s);function u(d){const h=U.trans,g=d.keys||function(y,w){return w.type==="delete"?w.keys:w.keys||w.values.map(y.extractKey)}(r,d);if(!g)throw new Error("Keys missing");return(d=d.type==="add"||d.type==="put"?{...d,keys:g}:{...d}).type!=="delete"&&(d.values=[...d.values]),d.keys&&(d.keys=[...d.keys]),function(y,w,f){return w.type==="add"?Promise.resolve([]):y.getMany({trans:w.trans,keys:f,cache:"immutable"})}(n,d,g).then(y=>{const w=g.map((f,m)=>{const b=y[m],v={onerror:null,onsuccess:null};if(d.type==="delete")a.fire.call(v,f,b,h);else if(d.type==="add"||b===void 0){const E=l.fire.call(v,f,d.values[m],h);f==null&&E!=null&&(f=E,d.keys[m]=f,r.outbound||re(d.values[m],r.keyPath,f))}else{const E=dr(b,d.values[m]),S=c.fire.call(v,E,f,b,h);if(S){const _=d.values[m];Object.keys(S).forEach(A=>{ee(_,A)?_[A]=S[A]:re(_,A,S[A])})}}return v});return n.mutate(d).then(({failures:f,results:m,numFailures:b,lastResult:v})=>{for(let E=0;E<g.length;++E){const S=m?m[E]:g[E],_=w[E];S==null?_.onerror&&_.onerror(f[E]):_.onsuccess&&_.onsuccess(d.type==="put"&&y[E]?d.values[E]:S)}return{failures:f,results:m,numFailures:b,lastResult:v}}).catch(f=>(w.forEach(m=>m.onerror&&m.onerror(f)),Promise.reject(f)))})}function p(d,h,g){return n.query({trans:d,values:!1,query:{index:r,range:h},limit:g}).then(({result:y})=>u({type:"delete",keys:y,trans:d}).then(w=>w.numFailures>0?Promise.reject(w.failures[0]):y.length<g?{failures:[],numFailures:0,lastResult:void 0}:p(d,{...h,lower:y[y.length-1],lowerOpen:!0},g)))}}}}})};function Mi(e,t,n){try{if(!t||t.keys.length<e.length)return null;const r=[];for(let i=0,s=0;i<t.keys.length&&s<e.length;++i)Q(t.keys[i],e[s])===0&&(r.push(n?ut(t.values[i]):t.values[i]),++s);return r.length===e.length?r:null}catch{return null}}const To={stack:"dbcore",level:-1,create:e=>({table:t=>{const n=e.table(t);return{...n,getMany:r=>{if(!r.cache)return n.getMany(r);const i=Mi(r.keys,r.trans._cache,r.cache==="clone");return i?L.resolve(i):n.getMany(r).then(s=>(r.trans._cache={keys:r.keys,values:r.cache==="clone"?ut(s):s},s))},mutate:r=>(r.type!=="add"&&(r.trans._cache=null),n.mutate(r))}}})};function pr(e){return!("from"in e)}const ye=function(e,t){if(!this){const n=new ye;return e&&"d"in e&&J(n,e),n}J(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function Lt(e,t,n){const r=Q(t,n);if(isNaN(r))return;if(r>0)throw RangeError();if(pr(e))return J(e,{from:t,to:n,d:1});const i=e.l,s=e.r;if(Q(n,e.from)<0)return i?Lt(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Fi(e);if(Q(t,e.to)>0)return s?Lt(s,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Fi(e);Q(t,e.from)<0&&(e.from=t,e.l=null,e.d=s?s.d+1:1),Q(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const o=!e.r;i&&!e.l&&cn(e,i),s&&o&&cn(e,s)}function cn(e,t){pr(t)||function n(r,{from:i,to:s,l:o,r:a}){Lt(r,i,s),o&&n(r,o),a&&n(r,a)}(e,t)}function Bo(e,t){const n=hr(t);let r=n.next();if(r.done)return!1;let i=r.value;const s=hr(e);let o=s.next(i.from),a=o.value;for(;!r.done&&!o.done;){if(Q(a.from,i.to)<=0&&Q(a.to,i.from)>=0)return!0;Q(i.from,a.from)<0?i=(r=n.next(a.from)).value:a=(o=s.next(i.from)).value}return!1}function hr(e){let t=pr(e)?null:{s:0,n:e};return{next(n){const r=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,r)for(;t.n.l&&Q(n,t.n.from)<0;)t={up:t,n:t.n.l,s:1};else for(;t.n.l;)t={up:t,n:t.n.l,s:1};case 1:if(t.s=2,!r||Q(n,t.n.to)<=0)return{value:t.n,done:!1};case 2:if(t.n.r){t.s=3,t={up:t,n:t.n.r,s:0};continue}case 3:t=t.up}return{done:!0}}}}function Fi(e){var t,n;const r=(((t=e.r)===null||t===void 0?void 0:t.d)||0)-(((n=e.l)===null||n===void 0?void 0:n.d)||0),i=r>1?"r":r<-1?"l":"";if(i){const s=i==="r"?"l":"r",o={...e},a=e[i];e.from=a.from,e.to=a.to,e[i]=a[i],o[i]=a[s],e[s]=o,o.d=ji(o)}e.d=ji(e)}function ji({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}Ye(ye.prototype,{add(e){return cn(this,e),this},addKey(e){return Lt(this,e,e),this},addKeys(e){return e.forEach(t=>Lt(this,t,t)),this},[xn](){return hr(this)}});const Mo={stack:"dbcore",level:0,create:e=>{const t=e.schema.name,n=new ye(e.MIN_KEY,e.MAX_KEY);return{...e,table:r=>{const i=e.table(r),{schema:s}=i,{primaryKey:o}=s,{extractKey:a,outbound:l}=o,c={...i,mutate:d=>{const h=d.trans,g=h.mutatedParts||(h.mutatedParts={}),y=S=>{const _=`idb://${t}/${r}/${S}`;return g[_]||(g[_]=new ye)},w=y(""),f=y(":dels"),{type:m}=d;let[b,v]=d.type==="deleteRange"?[d.range]:d.type==="delete"?[d.keys]:d.values.length<50?[[],d.values]:[];const E=d.trans._cache;return i.mutate(d).then(S=>{if(H(b)){m!=="delete"&&(b=S.results),w.addKeys(b);const _=Mi(b,E);_||m==="add"||f.addKeys(b),(_||v)&&function(A,k,B,D){function V(W){const j=A(W.name||"");function ve(Y){return Y!=null?W.extractKey(Y):null}const M=Y=>W.multiEntry&&H(Y)?Y.forEach(We=>j.addKey(We)):j.addKey(Y);(B||D).forEach((Y,We)=>{const Dt=B&&ve(B[We]),Fr=D&&ve(D[We]);Q(Dt,Fr)!==0&&(Dt!=null&&M(Dt),Fr!=null&&M(Fr))})}k.indexes.forEach(V)}(y,s,_,v)}else if(b){const _={from:b.lower,to:b.upper};f.add(_),w.add(_)}else w.add(n),f.add(n),s.indexes.forEach(_=>y(_.name).add(n));return S})}},u=({query:{index:d,range:h}})=>{var g,y;return[d,new ye((g=h.lower)!==null&&g!==void 0?g:e.MIN_KEY,(y=h.upper)!==null&&y!==void 0?y:e.MAX_KEY)]},p={get:d=>[o,new ye(d.key)],getMany:d=>[o,new ye().addKeys(d.keys)],count:u,query:u,openCursor:u};return N(p).forEach(d=>{c[d]=function(h){const{subscr:g}=U;if(g){const y=v=>{const E=`idb://${t}/${r}/${v}`;return g[E]||(g[E]=new ye)},w=y(""),f=y(":dels"),[m,b]=p[d](h);if(y(m.name||"").add(b),!m.isPrimaryKey){if(d!=="count"){const v=d==="query"&&l&&h.values&&i.query({...h,values:!1});return i[d].apply(this,arguments).then(E=>{if(d==="query"){if(l&&h.values)return v.then(({result:_})=>(w.addKeys(_),E));const S=h.values?E.result.map(a):E.result;h.values?w.addKeys(S):f.addKeys(S)}else if(d==="openCursor"){const S=E,_=h.values;return S&&Object.create(S,{key:{get:()=>(f.addKey(S.primaryKey),S.key)},primaryKey:{get(){const A=S.primaryKey;return f.addKey(A),A}},value:{get:()=>(_&&w.addKey(S.primaryKey),S.value)}})}return E})}f.add(n)}}return i[d].apply(this,arguments)}}),c}}}};class je{constructor(t,n){this._middlewares={},this.verno=0;const r=je.dependencies;this._options=n={addons:je.addons,autoOpen:!0,indexedDB:r.indexedDB,IDBKeyRange:r.IDBKeyRange,...n},this._deps={indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange};const{addons:i}=n;this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;const s={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:P,dbReadyPromise:null,cancelOpen:P,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var o;s.dbReadyPromise=new L(a=>{s.dbReadyResolve=a}),s.openCanceller=new L((a,l)=>{s.cancelOpen=l}),this._state=s,this.name=t,this.on=vt(this,"populate","blocked","versionchange","close",{ready:[Dn,P]}),this.on.ready.subscribe=Zr(this.on.ready.subscribe,a=>(l,c)=>{je.vip(()=>{const u=this._state;if(u.openComplete)u.dbOpenError||L.resolve().then(l),c&&a(l);else if(u.onReadyBeingFired)u.onReadyBeingFired.push(l),c&&a(l);else{a(l);const p=this;c||a(function d(){p.on.ready.unsubscribe(l),p.on.ready.unsubscribe(d)})}})}),this.Collection=(o=this,bt(bo.prototype,function(a,l){this.db=o;let c=Li,u=null;if(l)try{c=l()}catch(g){u=g}const p=a._ctx,d=p.table,h=d.hook.reading.fire;this._ctx={table:d,index:p.index,isPrimKey:!p.index||d.schema.primKey.keyPath&&p.index===d.schema.primKey.name,range:c,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:u,or:p.or,valueMapper:h!==pt?h:null}})),this.Table=function(a){return bt(vo.prototype,function(l,c,u){this.db=a,this._tx=u,this.name=l,this.schema=c,this.hook=a._allTables[l]?a._allTables[l].hook:vt(null,{creating:[oo,P],reading:[so,pt],updating:[lo,P],deleting:[ao,P]})})}(this),this.Transaction=function(a){return bt(So.prototype,function(l,c,u,p,d){this.db=a,this.mode=l,this.storeNames=c,this.schema=u,this.chromeTransactionDurability=p,this.idbtrans=null,this.on=vt(this,"complete","error","abort"),this.parent=d||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new L((h,g)=>{this._resolve=h,this._reject=g}),this._completion.then(()=>{this.active=!1,this.on.complete.fire()},h=>{var g=this.active;return this.active=!1,this.on.error.fire(h),this.parent?this.parent._reject(h):g&&this.idbtrans&&this.idbtrans.abort(),q(h)})})}(this),this.Version=function(a){return bt(Ao.prototype,function(l){this.db=a,this._cfg={version:l,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})}(this),this.WhereClause=function(a){return bt(Ri.prototype,function(l,c,u){this.db=a,this._ctx={table:l,index:c===":id"?null:c,or:u};const p=a._deps.indexedDB;if(!p)throw new x.MissingAPI;this._cmp=this._ascending=p.cmp.bind(p),this._descending=(d,h)=>p.cmp(h,d),this._max=(d,h)=>p.cmp(d,h)>0?d:h,this._min=(d,h)=>p.cmp(d,h)<0?d:h,this._IDBKeyRange=a._deps.IDBKeyRange})}(this),this.on("versionchange",a=>{a.newVersion>0?console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`):console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`),this.close()}),this.on("blocked",a=>{!a.newVersion||a.newVersion<a.oldVersion?console.warn(`Dexie.delete('${this.name}') was blocked`):console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${a.oldVersion/10}`)}),this._maxKey=Et(n.IDBKeyRange),this._createTransaction=(a,l,c,u)=>new this.Transaction(a,l,c,this._options.chromeTransactionDurability,u),this._fireOnBlocked=a=>{this.on("blocked").fire(a),wt.filter(l=>l.name===this.name&&l!==this&&!l._state.vcFired).map(l=>l.on("versionchange").fire(a))},this.use(Do),this.use(Po),this.use(Mo),this.use(To),this.vip=Object.create(this,{_vip:{value:!0}}),i.forEach(a=>a(this))}version(t){if(isNaN(t)||t<.1)throw new x.Type("Given version is not a positive number");if(t=Math.round(10*t)/10,this.idbdb||this._state.isBeingOpened)throw new x.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,t);const n=this._versions;var r=n.filter(i=>i._cfg.version===t)[0];return r||(r=new this.Version(t),n.push(r),n.sort(Uo),r.stores({}),this._state.autoSchema=!1,r)}_whenReady(t){return this.idbdb&&(this._state.openComplete||U.letThrough||this._vip)?t():new L((n,r)=>{if(this._state.openComplete)return r(new x.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void r(new x.DatabaseClosed);this.open().catch(P)}this._state.dbReadyPromise.then(n,r)}).then(t)}use({stack:t,create:n,level:r,name:i}){i&&this.unuse({stack:t,name:i});const s=this._middlewares[t]||(this._middlewares[t]=[]);return s.push({stack:t,create:n,level:r??10,name:i}),s.sort((o,a)=>o.level-a.level),this}unuse({stack:t,name:n,create:r}){return t&&this._middlewares[t]&&(this._middlewares[t]=this._middlewares[t].filter(i=>r?i.create!==r:!!n&&i.name!==n)),this}open(){return Ro(this)}_close(){const t=this._state,n=wt.indexOf(this);if(n>=0&&wt.splice(n,1),this.idbdb){try{this.idbdb.close()}catch{}this._novip.idbdb=null}t.dbReadyPromise=new L(r=>{t.dbReadyResolve=r}),t.openCanceller=new L((r,i)=>{t.cancelOpen=i})}close(){this._close();const t=this._state;this._options.autoOpen=!1,t.dbOpenError=new x.DatabaseClosed,t.isBeingOpened&&t.cancelOpen(t.dbOpenError)}delete(){const t=arguments.length>0,n=this._state;return new L((r,i)=>{const s=()=>{this.close();var o=this._deps.indexedDB.deleteDatabase(this.name);o.onsuccess=K(()=>{(function({indexedDB:a,IDBKeyRange:l},c){!lr(a)&&c!==tn&&ar(a,l).delete(c).catch(P)})(this._deps,this.name),r()}),o.onerror=ae(i),o.onblocked=this._fireOnBlocked};if(t)throw new x.InvalidArgument("Arguments not allowed in db.delete()");n.isBeingOpened?n.dbReadyPromise.then(s):s()})}backendDB(){return this.idbdb}isOpen(){return this.idbdb!==null}hasBeenClosed(){const t=this._state.dbOpenError;return t&&t.name==="DatabaseClosed"}hasFailed(){return this._state.dbOpenError!==null}dynamicallyOpened(){return this._state.autoSchema}get tables(){return N(this._allTables).map(t=>this._allTables[t])}transaction(){const t=Oo.apply(this,arguments);return this._transaction.apply(this,t)}_transaction(t,n,r){let i=U.trans;i&&i.db===this&&t.indexOf("!")===-1||(i=null);const s=t.indexOf("?")!==-1;let o,a;t=t.replace("!","").replace("?","");try{if(a=n.map(c=>{var u=c instanceof this.Table?c.name:c;if(typeof u!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return u}),t=="r"||t===Gn)o=Gn;else{if(t!="rw"&&t!=Yn)throw new x.InvalidArgument("Invalid transaction mode: "+t);o=Yn}if(i){if(i.mode===Gn&&o===Yn){if(!s)throw new x.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&a.forEach(c=>{if(i&&i.storeNames.indexOf(c)===-1){if(!s)throw new x.SubTransaction("Table "+c+" not included in parent transaction.");i=null}}),s&&i&&!i.active&&(i=null)}}catch(c){return i?i._promise(null,(u,p)=>{p(c)}):q(c)}const l=Bi.bind(null,this,o,a,i,r);return i?i._promise(o,l,"lock"):U.trans?tt(U.transless,()=>this._whenReady(l)):this._whenReady(l)}table(t){if(!ee(this._allTables,t))throw new x.InvalidTable(`Table ${t} does not exist`);return this._allTables[t]}}const Fo=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable";class jo{constructor(t){this._subscribe=t}subscribe(t,n,r){return this._subscribe(t&&typeof t!="function"?t:{next:t,error:n,complete:r})}[Fo](){return this}}function Ki(e,t){return N(t).forEach(n=>{cn(e[n]||(e[n]=new ye),t[n])}),e}function Ko(e){let t,n=!1;const r=new jo(i=>{const s=An(e);let o=!1,a={},l={};const c={get closed(){return o},unsubscribe:()=>{o=!0,xe.storagemutated.unsubscribe(h)}};i.start&&i.start(c);let u=!1,p=!1;function d(){return N(l).some(y=>a[y]&&Bo(a[y],l[y]))}const h=y=>{Ki(a,y),d()&&g()},g=()=>{if(u||o)return;a={};const y={},w=function(f){s&&et();const m=()=>Se(e,{subscr:f,trans:null}),b=U.trans?tt(U.transless,m):m();return s&&b.then(fe,fe),b}(y);p||(xe(kt,h),p=!0),u=!0,Promise.resolve(w).then(f=>{n=!0,t=f,u=!1,o||(d()?g():(a={},l=y,i.next&&i.next(f)))},f=>{u=!1,n=!1,i.error&&i.error(f),c.unsubscribe()})};return g(),c});return r.hasValue=()=>n,r.getValue=()=>t,r}let fr;try{fr={indexedDB:F.indexedDB||F.mozIndexedDB||F.webkitIndexedDB||F.msIndexedDB,IDBKeyRange:F.IDBKeyRange||F.webkitIDBKeyRange}}catch{fr={indexedDB:null,IDBKeyRange:null}}const Ke=je;function un(e){let t=ge;try{ge=!0,xe.storagemutated.fire(e)}finally{ge=t}}Ye(Ke,{...$t,delete:e=>new Ke(e,{addons:[]}).delete(),exists:e=>new Ke(e,{addons:[]}).open().then(t=>(t.close(),!0)).catch("NoSuchDatabaseError",()=>!1),getDatabaseNames(e){try{return function({indexedDB:t,IDBKeyRange:n}){return lr(t)?Promise.resolve(t.databases()).then(r=>r.map(i=>i.name).filter(i=>i!==tn)):ar(t,n).toCollection().primaryKeys()}(Ke.dependencies).then(e)}catch{return q(new x.MissingAPI)}},defineClass:()=>function(e){J(this,e)},ignoreTransaction:e=>U.trans?tt(U.transless,e):e(),vip:cr,async:function(e){return function(){try{var t=ur(e.apply(this,arguments));return t&&typeof t.then=="function"?t:L.resolve(t)}catch(n){return q(n)}}},spawn:function(e,t,n){try{var r=ur(e.apply(n,t||[]));return r&&typeof r.then=="function"?r:L.resolve(r)}catch(i){return q(i)}},currentTransaction:{get:()=>U.trans||null},waitFor:function(e,t){const n=L.resolve(typeof e=="function"?Ke.ignoreTransaction(e):e).timeout(t||6e4);return U.trans?U.trans.waitFor(n):n},Promise:L,debug:{get:()=>oe,set:e=>{si(e,e==="dexie"?()=>!0:Si)}},derive:Je,extend:J,props:Ye,override:Zr,Events:vt,on:xe,liveQuery:Ko,extendObservabilitySet:Ki,getByKeyPath:pe,setByKeyPath:re,delByKeyPath:function(e,t){typeof t=="string"?re(e,t,void 0):"length"in t&&[].map.call(t,function(n){re(e,n,void 0)})},shallowClone:ni,deepClone:ut,getObjectDiff:dr,cmp:Q,asap:ei,minKey:Hn,addons:[],connections:wt,errnames:On,dependencies:fr,semVer:ki,version:ki.split(".").map(e=>parseInt(e)).reduce((e,t,n)=>e+t/Math.pow(10,2*n))}),Ke.maxKey=Et(Ke.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(xe(kt,e=>{if(!ge){let t;en?(t=document.createEvent("CustomEvent"),t.initCustomEvent(Ue,!0,!0,e)):t=new CustomEvent(Ue,{detail:e}),ge=!0,dispatchEvent(t),ge=!1}}),addEventListener(Ue,({detail:e})=>{ge||un(e)}));let ge=!1;if(typeof BroadcastChannel<"u"){const e=new BroadcastChannel(Ue);typeof e.unref=="function"&&e.unref(),xe(kt,t=>{ge||e.postMessage(t)}),e.onmessage=t=>{t.data&&un(t.data)}}else if(typeof self<"u"&&typeof navigator<"u"){xe(kt,t=>{try{ge||(typeof localStorage<"u"&&localStorage.setItem(Ue,JSON.stringify({trig:Math.random(),changedParts:t})),typeof self.clients=="object"&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(n=>n.postMessage({type:Ue,changedParts:t})))}catch{}}),typeof addEventListener<"u"&&addEventListener("storage",t=>{if(t.key===Ue){const n=JSON.parse(t.newValue);n&&un(n.changedParts)}});const e=self.document&&navigator.serviceWorker;e&&e.addEventListener("message",function({data:t}){t&&t.type===Ue&&un(t.changedParts)})}L.rejectionMapper=function(e,t){if(!e||e instanceof Xe||e instanceof TypeError||e instanceof SyntaxError||!e.name||!ci[e.name])return e;var n=new ci[e.name](t||e.message,e);return"stack"in e&&de(n,"stack",{get:function(){return this.inner.stack}}),n},si(oe,Si);let Ni=!0,mr=!1;const No=()=>Ni=!1,$o=()=>mr=!0,qo=["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"];let It={},yr;class Vo{constructor(t){$(this,"_values",[]);$(this,"_isWebMetric");this.name=t,this._isWebMetric=qo.includes(this.name)}report(t){if(Ni&&this._values.push({time:Date.now(),value:t}),mr||!this._isWebMetric)return;const n=this.findExceededThreshold(t);n&&yr&&yr(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=It[this.name];if(n)return n.find(r=>this.valueExceedsThreshold(t,r))}valueExceedsThreshold(t,n){return n.type==="max"?t>n.value:n.type==="min"?t<n.value:!1}}const Wo=(e,t)=>{It={},mr=!1,e==null||e.forEach(n=>{var r;n.metric in It||(It[n.metric]=[]),(r=It[n.metric])==null||r.push(n)}),yr=t},Ut={},dn=e=>{const t=new Vo(e);return Ut[e]=t,t},$i=(e,t)=>{let n=Ut[e];return n||(n=dn(e)),n.report(t)},zo=async e=>{const t=Object.values(Ut).map(n=>({name:n.name,values:n.collect()}));if(t.some(n=>n.values.length))try{await e(JSON.stringify(t))}catch(n){En(`Error posting metrics: ${n}`)}},Ho=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{zo(t)},e*1e3):No()},qi=async(e,t)=>{const n=performance.now();try{await e()}finally{const r=performance.now()-n;let i=Ut[t];i||(i=dn(t)),i.report(r/1e3)}},Vi=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let i=Ut[t];i||(i=dn(t)),i.report(r/1e3)}},Go=30,Wi=()=>{_e.setItem("sprig.disableReplayRecording","disabled")},Ne=()=>!!_e.getItem("sprig.disableReplayRecording"),Yo=["did not allow mutations","called in an invalid security context"],Jo=e=>{if(!e)return!0;for(const t of Yo)if(e.toLowerCase().includes(t))return!1;return!0},Qo=(e,t,{reportError:n=!0,extraInfo:r})=>{Ne()||t instanceof Error&&(Wi(),Jo(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),Zo()))},Xo=async(e,t,{reportError:n}={reportError:!0})=>{var i;let r;try{if(n&&((i=window.navigator.storage)!=null&&i.estimate)){const{quota:s,usage:o}=await window.navigator.storage.estimate();r={availableSpaceInMB:s&&o?(s-o)/(1024*1024):void 0,quota:s,usage:o}}}catch(s){window.UserLeap.reportError("Error getting storage estimate",s,{originalMessage:e,originalError:t})}Qo(e,t,{reportError:n,extraInfo:r})},X=(()=>{const e=_e.getItem("sprig.sessionId");if(e)return I(`Found saved session id: ${e}`),_e.removeItem("sprig.sessionId"),e;const t=ze();return I(`Generating new uuid: ${t}`),t})();window.addEventListener("beforeunload",()=>{I(`Before page unload saving session id: ${X}`),_e.setItem("sprig.sessionId",X)});const Zo=async()=>{O.transaction("rw",O.events,O.chunkUploads,O.pendingCaptures,()=>{O.events.clear(),O.chunkUploads.clear(),O.pendingCaptures.clear()}).catch(()=>{})},gr=(e,t,n=()=>!0)=>O.table(t).where("timestamp").below(e).and(n).delete(),ea=async(e,t)=>{let n=[];return await qi(async()=>{n=await O.events.where("[sessionId+timestamp]").between([X,e],[X,t??Date.now()]).toArray()},"sdk_replay_get_events_between_seconds"),n},ta=(e,t,n)=>{const r=new Date,i=r.setMinutes(r.getMinutes()+(n??Go));return O.events.where("[sessionId+timestamp]").between([X,e],[X,t]).modify({expiredAt:i})},na=e=>O.chunkUploads.add({...e,sessionId:e.sessionId??X}),ra=(e,t)=>O.chunkUploads.update(e,{data:null,etag:t,status:"UploadComplete"}),ia=({status:e,uploadId:t})=>t?O.chunkUploads.where({uploadId:t,status:e}).toArray():O.chunkUploads.where({sessionId:X,status:e}).toArray(),sa=e=>O.chunkUploads.where({uploadId:e,status:"UploadComplete"}).toArray(),oa=e=>O.chunkUploads.where({uploadId:e,status:"UploadComplete"}).delete(),aa=e=>O.pendingCaptures.add({...e,sessionId:e.sessionId??X,canUpload:!1}),la=()=>O.pendingCaptures.where("sessionId").equals(X).and(e=>e.targetTimestamp<Date.now()).toArray(),ca=()=>O.pendingCaptures.where("sessionId").equals(X).toArray(),ua=e=>O.pendingCaptures.where("sessionId").equals(X).and(t=>t.captureParams.responseGroupId===e).modify({canUpload:!0}),da=async e=>{var t;if((t=window.navigator.storage)!=null&&t.estimate){const{quota:n,usage:r}=await window.navigator.storage.estimate();if(n&&r&&(n-r)/1073741824<e)return!1}return!0};class pa extends je{constructor(){super("replayStorage",{autoOpen:!1});$(this,"events");$(this,"chunkUploads");$(this,"pendingCaptures")}}const O=new pa;O.version(1).stores({events:"uuid, timestamp, [sessionId+timestamp]",chunkUploads:"uuid, timestamp, [sessionId+status], [uploadId+status], [sessionId+status+uploadId]",pendingCaptures:"uuid, timestamp, [sessionId+targetTimestamp]"}),O.open().catch(e=>{Yr(`Error opening replay storage: ${JSON.stringify(e)}`),Wi()});const ha=async(e,t,n)=>new Promise((r,i)=>{const s=e.createElement("script");s.src=t,s.onload=r,s.onerror=i,n&&(s.nonce=n),e.head.appendChild(s)});let zi=1,wr=5e3,pn=6e4;const fa=5,Hi=1e3,Gi=30,hn=Gi+fa,ma="sprig.pendingCount";let vr,br,Yi,Ji=Date.now(),fn=!1,mn;const ya=async(e,t,n,r=2,i)=>{await it(async()=>{if(Ne()){I("Not initializing replay because recording is disabled");return}if(!t){I("Not initializing replay because config didn't specify maxReplayDurationSeconds");return}if(i!=null&&i.minAvailableGb&&(zi=i.minAvailableGb),!await da(zi)){En("Minimum storage not available");return}I("Initializing replay"),i!=null&&i.minDuration&&(wr=i.minDuration),i!=null&&i.batchDuration&&(pn=i.batchDuration),Hs(r),Sa(),ba(t+hn,30*60,t+hn),_a(),window.rrwebRecord||(I("Loading recording script"),await ha(e,"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.6.min.js",n),I("Recording script finished loading"));const s=window.rrwebRecord;if(!s){En("Record script failed to set global function");return}let o=!0,a=0;mn=s({checkoutEveryNms:Gi*1e3,sampling:{input:"last",scroll:250,media:800},emit:(l,c)=>{if(Ne())return;if(Ji=Date.now(),c&&l.type===Sn.Meta)a=performance.now();else if(c&&a&&l.type===Sn.FullSnapshot){const p=performance.now()-a;$i("sdk_replay_snapshot_seconds",p/1e3)}const u=o||!!c;o=!1,ga({uuid:ze(),event:JSON.stringify(l),isValidStart:u,timestamp:Date.now()})},...i}),fn=!0,br||(br=window.setInterval(()=>{Date.now()-Ji>Hi&&we("Sprig_Noop",{})},Hi)),R.on("survey.complete",l=>{Ra({id:l,userAgent:window.navigator.userAgent})})},"Error initializing replay")};let _r=!1,kr=[];const ga=e=>{kr.push(e),_r||va()},wa=e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??X}));if(t.length!==0)return O.transaction("rw",O.events,()=>{O.events.bulkAdd(t)}).catch(n=>{st("Error storing replay events",n)})},va=()=>{_r=!0,setTimeout(async()=>{if(Ne())return;const e=kr;kr=[],_r=!1,Vi(async()=>{await wa(e)},"sdk_replay_add_event_batch_seconds")},500)},ba=(e=6*60,t=30*60,n=4*60)=>{vr=window.setInterval(()=>{const r=Date.now();Ne()||(at(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),qi(()=>O.transaction("rw!",O.events,O.chunkUploads,O.pendingCaptures,()=>{gr(r-e*1e3,"events",i=>i.expiredAt===void 0||i.expiredAt<r-e*1e3),gr(r-t*1e3,"chunkUploads"),gr(r-n*1e3,"pendingCaptures",i=>i.canUpload===void 0||i.canUpload===!1)}).catch(i=>{clearInterval(vr),st("Error deleting table rows",i)}),"sdk_replay_cleanup_seconds"),I("Cleanup complete"))},30*1e3)},_a=(e=5)=>{Yi=window.setInterval(async()=>{it(async()=>{const t=parseInt($e??"0");if(t===0)return;const n=await la();n!=null&&n.length&&(await Promise.all(n.map(async r=>(await O.pendingCaptures.delete(r.uuid),ts(r.captureParams,r.canUpload)))),$e=(t-n.length).toString(),_e.setItem(ma,$e))},"Error initiating pending captures")},e*1e3)},ka=async(e,t,n,r,i)=>{const s=Math.min(e+i,n),o=`from: ${new Date(e).toLocaleTimeString()} to ${new Date(s).toLocaleTimeString()}`;I(`Getting event batch ${o}`);const a=await ea(e,s);if(!(a!=null&&a.length))return I(`No events found ${o}`),{validStartFound:r,events:[]};if(!r){I(`Searching for valid start in ${a.length} events ${o}`);let l=-1;if(a==null||a.forEach((u,p)=>{if(!u.isValidStart)return;const d=u.timestamp<=t;(l<0||d)&&(l=p)}),l<0)return I(`No valid start found in ${a.length} events ${o}`),{validStartFound:r,events:[]};const c=a[l].timestamp;return I(`Found valid start at: ${new Date(c).toLocaleTimeString()} in events ${o}`),{validStartFound:!0,events:a==null?void 0:a.slice(l)}}return{validStartFound:r,events:a}},Ea=(e,t,n)=>{const r=e.length,i=t*1024*1024,s=Math.ceil(r/n),o=Math.max(i,s);I(`Total file bytes: ${r} / target chunk size: ${o}`);const a=[];let l=0;for(;l<r;)a.push(e.slice(l,l+o)),l+=o;return a},Qi=e=>Promise.all(e.map(async t=>{const n=await Gs(t);return await ra(t.uuid,n),t.uploadId})),Xi=async e=>{I(`Marking upload complete if finished: ${e}`);const t=await sa(e);if(!(t!=null&&t.length)){I(`No finished chunks found for upload: ${e}`);return}const n=t.reduce((s,o)=>(s.find(a=>a.chunkIndex===o.chunkIndex)||s.push(o),s),[]);n.sort((s,o)=>s.chunkIndex-o.chunkIndex);const r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),i=n[0];await Qr({apiUrl:i.apiUrl,surveyId:i.surveyId,uploadId:e,responseGroupUuid:i.responseGroupId,etags:r,headers:i.completeUploadHeaders,replayDuration:i.replayDuration}),I(`Cleaning up chunks for ${e}`),await oa(e),I(`Done cleaning up chunks for ${e}`)},Sa=async()=>{it(async()=>{const e=await ia({status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await Qi(e);I(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return Xi(n)}))},"Error uploading unfinished chunks")},La=async(e,t)=>{await Qi(t),I(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>Xi(n)))},Ia=e=>{let t=0;e.forEach(i=>{t+=i.length});const n=new Uint8Array(t);let r=0;return e.forEach(i=>{n.set(i,r),r+=i.length}),n},Zi=async(e,t,n)=>{const r=new TextEncoder;let i=null,s=null,o=null,a=!1,l=!1,[c,u]=[0,0];const p=e-hn*1e3,d=[];let h=[];I(`Getting events between ${new Date(e).toLocaleTimeString()} and ${new Date(t).toLocaleTimeString()}`),I(`Using batch duration: ${pn}ms`);for(let y=p;y<t;y+=pn){if({validStartFound:l,events:h}=await ka(y,e,t,l,pn),!(h!=null&&h.length)){I("No events found");continue}c===0&&(c=h[0].timestamp),u=h[h.length-1].timestamp,I(`Last event time in batch: ${new Date(u).toLocaleTimeString()}`);const w=`${a?",":"["}${h.map(m=>m.event).join(",")}`,f=r.encode(w);n&&s===null&&(at("Attempting compression"),o=new window.CompressionStream("gzip"),s=o.writable.getWriter()),Vi(()=>{n&&s?s.write(f):d.push(f)},"sdk_replay_compression_seconds"),a=!0}if(u-c<wr)return I(`Replay duration is shorter than minimum of ${wr}ms / Start:${c} / End:${u}`),null;const g=r.encode("]");return at("Writing final close brace"),s&&o?(s.write(g),s.close(),i=new Uint8Array(await new Response(o.readable).arrayBuffer())):(d.push(g),i=Ia(d)),I("Finished generating file data"),i},Ua=async(e,t)=>{const n=window.CompressionStream!==void 0;let r=null;const i=t??Date.now(),s=i-e;try{r=await Zi(s,i,n)}catch(o){o instanceof Error&&window.UserLeap.reportError("Error compressing replay",o),n&&it(async()=>{await Zi(s,i,!1)},"fileData fallback failed")}return r},es=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:i,completeUploadHeaders:s,replayParams:o,triggerTimestamp:a}=e,l=await Ua(o.replayDurationSeconds*1e3,a);if(l!=null&&l.length)I(`Found file data for survey: ${t}`);else{I(`File data is empty for survey: ${t}`);return}const c=Ea(l,o.minimumChunkSizeMb,o.signedUrls.length);I(`Got ${c.length} chunks for survey: ${t}`);const u=await Promise.all(c.map(async(p,d)=>{const h=ze(),g={apiUrl:i,chunkIndex:d+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:a,totalChunks:c.length,data:p,uploadId:o.uploadId,uploadUrl:o.signedUrls[d].url,uuid:h,visitorId:r};return I(`Recording chunk upload: ${JSON.stringify({index:g.chunkIndex,surveyId:g.surveyId,uploadId:g.uploadId,size:p.length,id:h},null,2)}`),await na(g),I(`Done creating chunk upload: ${h}`),g}));I(`All chunk records created. Beginning upload for survey: ${t}`),await La([o.uploadId],u)},ts=async(e,t)=>{if(I(`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)}`),Ne()){I(`Replay recording is disabled: ${e.surveyId}`);return}I(`Replay recording enabled: ${e.surveyId}`);const{isStandalone:n,replayParams:r,triggerTimestamp:i,responseGroupId:s}=e,o=async()=>{setTimeout(()=>R.removeListener(C.QuestionAnswered,o),0),it(async()=>{r.replayDurationType==="before"?await es(e):await ua(s)},"Error in schedule/capture callback")};it(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){n||(I("Attaching QuestionAnswered listener for non-standalone replay"),R.on(C.QuestionAnswered,o)),I(`Scheduling capture for replay of type: ${r.replayDurationType}`),await xa(e);return}if(n||t)I(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${n} / canUpload? ${t}`),await es(e);else{const a=hn+r.replayDurationSeconds,l=i-a*1e3,c=i;I(`Setting expiry minutes to ${r.expirationTimeLimitMinutes} for events from ${new Date(l).toLocaleTimeString()} to ${new Date(c).toLocaleTimeString()}`),await ta(l,c,r.expirationTimeLimitMinutes),I("Attaching QuestionAnswered listener"),R.on(C.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},ns=()=>{if(Ne()){at("Not clearing user data, replay is disabled");return}return O.transaction("rw",O.events,O.pendingCaptures,()=>{O.events.where("sessionId").equals(X).delete(),O.pendingCaptures.where("sessionId").equals(X).delete()}).catch(e=>{st("Error clearing session event data",e)})};let $e=_e.getItem("sprig.pendingCount");const xa=async e=>{I(`Scheduling replay capture: ${JSON.stringify(e)}`);const{surveyId:t}=e,n=await ca(),r=n==null?void 0:n.filter(o=>o.captureParams.surveyId===t);if(r!=null&&r.length){I(`Pending capture exists for survey: ${t}`);return}const i={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(i.replayParams.replayDurationSeconds*=2),i.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;return i.triggerTimestamp=s,$e=$e?(parseInt($e)+1).toString():"1",_e.setItem("sprig.pendingCount",$e),aa({uuid:ze(),targetTimestamp:s,timestamp:Date.now(),captureParams:i})},we=(e,t)=>{var n,r;if(fn)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(i){st("Error recording custom event",i)}},it=async(e,t)=>{try{await e()}catch(n){st(t,n)}},rs=e=>{e.description&&(e.description=Er(e.description)),we("Sprig_PageView",e)},Aa=e=>{we("Sprig_TrackEvent",e)},Ca=e=>{we("Sprig_ShowSurvey",e)},Ra=e=>{we("Sprig_SubmitSurvey",e)},Oa=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Er(e.elementAttributes.text)),we("Sprig_Click",e)},Da=e=>{we("Sprig_Refresh",e)},Pa=e=>{e.currentPageTitle&&(e.currentPageTitle=Er(e.currentPageTitle)),we("Sprig_BackForward",e)},Ta=e=>{we("Sprig_Keystroke",e)},st=(e,t,{reportError:n}={reportError:!0})=>(mn&&(mn(),mn=void 0),fn=!1,[vr,br,Yi].forEach(r=>{r&&clearInterval(r)}),Yr(`${e} - ${JSON.stringify(t)}`),Xo(e,t,{reportError:n})),is=()=>fn,Er=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),ss="ul-view-sdk-script",Ba=["ios","android"],Ae="visitors",Ce="environments",os=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 yn(e,t){const{matchType:n,pattern:r}=e,i=n?os[n]:os.legacy;let s=!1;try{s=i(r,t)}catch(o){const a=`[Sprig] (ERR-445) Failed to check url match with pattern ${r}`;o instanceof Error&&(console.warn(a,o),o.stack=JSON.stringify(e),window.UserLeap.reportError(a,o))}return s}async function le(e,t){var s,o,a;const{shouldDropOnRateLimit:n,...r}=t;r.headers=Object.assign(Oe(window.UserLeap),r.headers);const i=await ke(e,{...r,shouldDropOnRateLimit:n});if(i.ok){const l=(s=i.headers)==null?void 0:s.get("Authorization"),c=l?l.split(" "):void 0,u=c&&c.length===2?c[1]:void 0,p=(o=i.headers)==null?void 0:o.get("x-ul-visitor-id");u&&p&&(p!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(ne("token",u),ne("vid",p),R.emit(C.VisitorIDUpdated,{visitorId:p}),window.UserLeap.token=u,window.UserLeap.visitorId=p)}return(a=i.json)!=null&&a.logMessage&&console.warn(`[Sprig] ${i.json.logMessage}`),i}function ne(e,t){const n=Z.getItem("userleap.ids");let r={};if(n)try{r=JSON.parse(n)}catch(s){s instanceof Error&&(s.stack=n,window.UserLeap.reportError("Failed to parse local storage credentials",s)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",s)}let i=r[window.UserLeap.envId];i?i[e]=t:i={[e]:t},r[window.UserLeap.envId]=i;try{Z.setItem("userleap.ids",JSON.stringify(r))}catch(s){s instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${s.message}`)}}function Sr(){return window.previewMode?"0":window.UserLeap.visitorId??""}function ie(e,t,n){const r=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(i=>{r.push(i),i===Ce?r.push(window.UserLeap.envId):i===Ae&&r.push(Sr())}),n&&r.push(n),r.join("/")}const xt=async e=>{var j,ve;const{context:t,forceBrandedLogo:n,endCard:r,isFeedback:i=!1,locale:s,productConfig:o,questions:a,responseGroupUid:l,surveyId:c,uuid:u,vid:p,sessionReplay:d,studyType:h}=e,g=Oe(window.UserLeap),y=Ir(g),w=Lr(g);if(I(`Attempting to display survey: ${c}`),d&&(I("Survey has replay attached"),y?R.emit(C.ReplayCapture,{responseGroupUid:l,hasQuestions:!!(a!=null&&a.length),surveyId:c,uploadId:d.uploadId,replayType:d.replayDurationType??"before",seconds:d.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:ze(),mediaType:"screen",questionId:1,responseGroupUid:l,surveyId:c,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}}):ts({responseGroupId:l,surveyId:c,visitorId:p,replayParams:d,completeUploadHeaders:g,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:a.length===0})),p==null||!(a!=null&&a.length))return I(`Not displaying survey: vid: ${p} / questions: ${a}`),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){I("Already displaying a survey");const M="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(M),{success:!1,message:M,surveyState:"no survey"}}if(p!==window.UserLeap.visitorId&&u!==window.UserLeap.visitorId&&!window.previewMode){const M="Attempted to display survey to a different visitor";return I(M),window.UserLeap.reportError("DisplaySurvey",new Error(M)),{success:!1,message:M,surveyState:"no survey"}}I(`Showing survey: ${c}`),Ca({id:c,userAgent:window.navigator.userAgent}),Rs.disable(),R.emit(C.SurveyWillPresent,{name:C.SurveyWillPresent,"survey.id":c});let f,m=document.createElement("div"),b,v,E;const S=M=>{const{"view.version":Y}=M;Y!==g["x-ul-sdk-version"]&&cs(),R.removeListener("verify.view.version",S)};R.on("verify.view.version",S),window.UserLeap.useMobileStyling=w,Ds(g)?(f="ul-direct-embeded-frame",b=document.head,v=window,E=!1,y&&(ls(),m.id=f,window.UserLeap.container.appendChild(m),us(),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":c}))):{frameId:f,contentWinDocHead:b,contentWindow:v,hasOverlay:E,iframe:m}=Na({productConfig:o,useMobileStyling:w,surveyId:c,isFeedback:i}),window.UserLeap.frameId=f;const _=M=>{R.once(C.CloseSurveyOnOverlayClick,M)},A={apiURL:window.UserLeap._API_URL,cards:a,configureExitOnOverlayClick:_,context:t,endCard:r,envId:window.UserLeap.envId,eventEmitFn:R.emit.bind(R),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:n,frame:m,headers:g,locale:s,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:Z.getItem("sprig.previewKey"),productConfig:{framePosition:o==null?void 0:o.framePosition,desktopDisplay:o==null?void 0:o.desktopDisplay,placement:o==null?void 0:o.placement},responseGroupUid:l,startingQuestionIdx:(j=window.UserLeap.config)==null?void 0:j.startingQuestionIdx,studyType:h,styleNonce:window.UserLeap.styleNonce,surveyId:c,tabTitle:document.title,ulEvents:Pt,useMobileStyling:w,userId:u,viewDocument:v==null?void 0:v.document,viewWindow:v,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(ve=window.UserLeap._config)!=null&&ve.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null}),A.customStyles=o==null?void 0:o.customStyles,v&&(v.__cfg=A);function k(){const M=document.createElement("script");return window.UserLeap.nonce&&M.setAttribute("nonce",window.UserLeap.nonce),M.id=ss,M}const B=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:A.path,D=document.getElementById(ss);D&&D.remove();const V=k(),W=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(A.installationMethod==="web-npm"||A.installationMethod==="web-npm-bundled"){const{default:M}=await import("../view/view.tsx");M.configure(A),E&&window.UserLeap.container&&W()}else B&&(V.src=B,E&&V.addEventListener("load",()=>{window.UserLeap.container&&W()}),v==null||v.addEventListener("error",M=>{M.target instanceof HTMLScriptElement&&M.target.src===B&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));return b==null||b.appendChild(V),{success:!0,surveyState:"ready",surveyId:c,responseGroupUid:l}};function Lr(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 Ir(e)||t>10&&t<Cs}function Ir(e){return Ba.includes(e["userleap-platform"])}const as="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 Ma="rgba(255,255,255, 0.95)",Fa="rgba(0,0,0,0.9)",Ur="0px",ls=e=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className="ul-container";const t=ps();e&&t&&!window.UserLeap.useMobileStyling?t.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},cs=(e,t)=>{var r;qa();const n=window.UserLeap.container;if(n)try{(r=n.parentNode)==null||r.removeChild(n),window.UserLeap.container=null,ne("trackStartUrl",null),R.emit(C.SurveyLifeCycle,{state:"dismissed"}),R.emit(C.SurveyClosed,{name:C.SurveyClosed,initiator:e,studyType:t})}catch(i){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),i instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",i)}},us=()=>{R.once(C.SurveyWillClose,({initiator:e,studyType:t})=>{R.removeAllListeners(C.CloseSurveyOnOverlayClick),cs(e,t)})},ja=(e,t)=>{const r={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},i=t?e.overlayStyleMobile:e.overlayStyle;r["background-color"]=i==="light"?Ma:Fa,t||(r.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,r)},Ka=(e,t,n,r)=>{var u,p;const i={position:"fixed",bottom:"0px",right:Ur,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%"},s=Object.assign({},t,window.UserLeap),{desktopDisplay:o}=t||{},a=o==="center-modal";a&&(s.framePosition="center");let l,c=!1;if(n)(u=window.UserLeap.windowDimensions)!=null&&u.width?i.width=`${window.UserLeap.windowDimensions.width}px`:i.width="100%",(p=window.UserLeap.windowDimensions)!=null&&p.height?i.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?i.maxHeight=window.UserLeap.maxHeight:i.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(s.overlayStyleMobile)&&(c=!0);else{i.width=As,i.maxHeight=window.UserLeap.maxHeight||"66vh";const d=()=>{c=!0,l={margin:"auto",position:"static"}};if(r)a?d():l={position:"relative",height:"300px"};else switch(s.framePosition){case"bottomLeft":l={left:Ur};break;case"topLeft":l={left:Ur,top:0};break;case"topRight":l={top:0};break;case"center":d();break}}return c&&ja(s,n),Object.assign(e.style,i,l),c},Na=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:r})=>{var p,d;const i=as,s=r&&e.desktopDisplay==="slider";ls(s),$a();const o=document.createElement("iframe");o.id=i,o.setAttribute("title","Sprig User Feedback Dialog");const a=Ka(o,e,t,r);us(),o.setHeight=h=>{parseInt(o.style.height)!=h&&(o.style.height=`${h}px`,R.emit(C.SurveyHeight,{name:C.SurveyHeight,contentFrameHeight:h}))};let l=!1;o.setWidth=h=>{(parseInt(o.style.width)!=h||!l)&&(l=!0,o.style.width=`${h}px`,R.emit(C.SurveyWidth,{name:C.SurveyWidth,contentFrameWidth:h}))},(p=window.UserLeap.container)==null||p.appendChild(o),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{R.emit(C.CloseSurveyOnOverlayClick)}),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":n});const c=(d=o.contentWindow)==null?void 0:d.document;if(c&&(c.open("text/html","replace"),c.write("<!doctype html><head></head><body></body></html>"),c.close(),!t)){const h=c.body;h.style.display="flex",h.style.alignItems="center"}const u=c==null?void 0:c.head;return{frameId:i,contentWinDocHead:u,contentWindow:o.contentWindow,hasOverlay:a,iframe:o}},ds={[C.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},$a=()=>{Object.entries(ds).forEach(([e,t])=>{R.on(e,t)})},qa=()=>{Object.entries(ds).forEach(([e,t])=>{R.off(e,t)})},ps=()=>T,ot=()=>document.getElementById("sprig-feedback-container"),xr=()=>document.getElementById("sprig-feedback-loading-animation"),Va=()=>{if(xr())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=`
<div class="ul-loading-spinner">
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
<div class="fourth"></div>
</div>
`,e},hs=()=>!!document.getElementById(as);let Ar=!1,T=null,ce=null,Cr=!1,At=null,qe=null;const Wa=["bottom-left","bottom-right","center-left","center-right"],za=e=>{if(ot()||!Wa.includes(e))return;const[t,n]=e.split("-"),r=document.createElement("div");r.id="sprig-feedback-container",r.classList.add(`sprig-feedback-container-${n}`,`sprig-feedback-container-${t}`),document.body.appendChild(r)},gn=()=>{var t;const e=window.UserLeap.container;return((t=e==null?void 0:e.parentElement)==null?void 0:t.id)==="sprig-feedback-loading-container"},fs=()=>document.getElementById("sprig-feedback-error-container"),ms=()=>{if(!T)return 0;const e=T==null?void 0:T.clientWidth,t=window.getComputedStyle(T),n=parseInt(t.borderRightWidth||"0"),r=parseInt(t.borderLeftWidth||"0");return e+n+r},wn=e=>{const t=ot();t&&(qe!=null&&qe.endsWith("right")?t.style.right=`${e}px`:qe!=null&&qe.endsWith("left")&&(t.style.left=`${e}px`))},Rr=()=>{if(T&&(gn()||fs())){R.off(C.SurveyAppeared,Ct),Or();const e=ms();return wn(-e),!0}return!1},Ct=()=>{if(!T||!ce)return;const e=xr();e&&e.remove(),T.style.height="auto",T.style.width="auto",ce.disabled=!1,Cr=!1},Or=()=>{if(!T)return;if(!xr()){const t=Va();t&&(T.style.height="300px",T.style.width="360px",T.appendChild(t))}},ys=()=>{!T||!ce||(wn(0),ce.disabled=!0,Cr=!0)},Ha=async e=>{const t=await le(ie("1",[Ae],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},gs=async(e,t)=>{const{buttonTheme:n,eventId:r,placement:i,desktopDisplay:s,feedbackLabel:o,surveyUuid:a,surveyId:l}=e;let c=ot();if(c){if(!t&&r===At)return;c.remove(),R.off(Pt.SURVEY_FADING_OUT,Rr)}if(At=r,!document.getElementById("sprig-feedback-style")){const{head:w}=document,f=document.createElement("style");f.id="sprig-feedback-style",f.textContent=xs,f.nonce=window.UserLeap.styleNonce,w.appendChild(f)}Ar=s==="center-modal",qe=i;const[p,d]=i.split("-");za(i),c=ot(),ce=document.createElement("button");const h=document.createElement("div");h.className="sprig-feedback-button-label",h.innerText=o,ce.appendChild(h),ce.id="sprig-feedback-button",ce.classList.add(`sprig-feedback-button-${d}`,`sprig-feedback-button-${p}`,`sprig-feedback-button-${n}`,"fade-in-transition"),R.on(Pt.SURVEY_FADING_OUT,Rr),ce.addEventListener("click",async()=>{const w=document.getElementById("sprig-feedback-error-container");if(hs()||fs()){if(Rr()){R.emit(C.SurveyWillClose,{name:C.SurveyWillClose,initiator:be.FeedbackClosed,studyType:"feedbackButton"});const v=ot();w&&v&&(v.remove(),At=null,T=null)}return}const f=Oe(window.UserLeap);if(!Lr(f)&&!Cr&&ys(),t){T&&T.classList.add("sprig-feedback-loading-container-previews"),await xt(t),Ct();return}const b=await Ha(a);if(b)R.once(C.SurveyAppeared,Ct),xt({...b,studyType:"feedbackButton"});else if(T){const v=Ya();T.appendChild(v),Ct(),T.style.height="300px",T.style.width="360px"}}),c==null||c.appendChild(ce),R.emit(C.FeedbackButtonLoaded,{name:C.FeedbackButtonLoaded,"survey.id":l});const{useMobileStyling:g,_config:{border:y}}=window.UserLeap;if(!Ar&&!g){const w=document.createElement("div");w.id="sprig-feedback-loading-container",w.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${d}`,w.style.setProperty("--feedback-border",y),T=w,Or(),c==null||c.appendChild(w);const f=ms();wn(-f)}else Ar&&wn(0);window.UserLeap._config.isOnQuestionsTab&&t&&!gn()&&T&&(ys(),Or(),T&&T.classList.add("sprig-feedback-loading-container-previews"),xt(t),Ct())},Ga=e=>{if(gn())return;const t=ot();if(!t)return;const{pageUrlEvents:n}=window.UserLeap._config,r=n==null?void 0:n.find(s=>s.id===At);if(!r)return;yn(r,e)||(t.remove(),At=null,T=null)},Ya=()=>{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">
<circle cx="20" cy="20" r="14.5" stroke="#B0B5B7" stroke-width="3"/>
<path d="M20 12L20 21.6" stroke="#B0B5B7" stroke-width="3" stroke-linecap="round"/>
<circle cx="19.9984" cy="27.6" r="1.6" fill="#B0B5B7"/>
</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},Ja="!launch_darkly_";class Qa{constructor(){$(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[`${Ja}${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 Dr=new Qa;Object.freeze(Dr);const Xa="!optimizely_experiments_";class Za{constructor(){$(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:r}=t;try{return n&&Object.keys(this._optimizelyData).map(i=>{delete this._optimizelyData[i]}),r&&r.map(i=>{const{id:s,variation:o}=i,a=this.transformExperimentId(s);o&&typeof o=="string"&&(this._optimizelyData[a]=o)}),!0}catch(i){return i instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",i),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return Xa+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 r=Object.keys(n).map(i=>{var s,o;return(s=n[i].variation)!=null&&s.name?{id:i,variation:(o=n[i].variation)==null?void 0:o.name}:{id:i,variation:"Original"}});return this.setOptimizelyExperiment({experiments:r},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const vn=new Za;Object.freeze(vn);class el{constructor(t,n){$(this,"paused");$(this,"queue");$(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let r=0;r<n;r++)this.push(t[r])}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),r=t[0],i=this.ul[r];i instanceof Function?i.apply(this.ul,n):r&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",r)}}perform(t){if(this.paused){let n=()=>{};const r=new Promise(function(i){n=function(){i(t())}});return this.queue.push(n),r}else return t()}empty(){this.queue.length=0}}const tl=1,ws=e=>e instanceof HTMLElement||e instanceof SVGElement,nl=(e,t,n)=>{const r=e.createElement("style");n&&(r.nonce=n),r.textContent=t,r.id="ul-custom-style",e.head.appendChild(r)},rl=e=>{const t=e.querySelector(".ul-card__container");let n=600,r=360;if(t){n=t.scrollHeight;const i=getComputedStyle(t),s=parseFloat(i.marginTop)+parseFloat(i.marginBottom),o=parseFloat(i.borderTopWidth)+parseFloat(i.borderBottomWidth);n+=s+o;const a=t.querySelector(".ul-card--matrix_grid");r=a?a.scrollWidth:t.scrollWidth;const l=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),c=parseFloat(i.marginLeft)+parseFloat(i.marginRight),u=parseFloat(i.borderLeftWidth)+parseFloat(i.borderRightWidth);r+=c+u+l}return[n+tl,r]},Pr=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>Pr(e,t),e):setTimeout(()=>{const r=performance.now()-n;t.report(r/1e3),setTimeout(()=>Pr(e,t),e)},0)},il=(e=1e3)=>{const t=dn("sdk_event_queue_latency_seconds");Pr(e,t)},sl=({webMetricsEnabled:e,reportingIntervalSeconds:t,thresholds:n,postMetrics:r})=>{Wo(n,(i,s)=>{if(is()){const o=`Value: ${i} on ${s.metric} violated threshold of ${s.type} ${s.value}`;st("Threshold violated",new Error(o),{reportError:!1}),$o()}}),Ho({reportingIntervalSeconds:t,postMetrics:r}),e&&il()},Tr={capture:!0},ol=["a","button","input","option","li","link"],al=["Escape","Enter","Backspace","F5","Tab"],ll=["label","type","role","title","placeholder","errormessage","valuetext","href"],vs="aria-",cl=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},bs=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=cl(e);for(const i of e.attributes){let s=i.name;const o=i.value;s.startsWith(vs)&&(s=s.substring(vs.length)),ll.includes(s)&&(n[s]=o)}return n},ul=e=>{var i;if(!e)return{};const n={...bs(e)},r=e.parentElement;if(r&&ol.includes((i=r.tagName)==null?void 0:i.toLowerCase())){const s=bs(r);Object.assign(n,s)}return n},_s=(e,t)=>{Oa({x:t.x,y:t.y,type:e,elementAttributes:ul(t.target)})},dl=e=>t=>_s(e,t),pl=e=>{al.includes(e.key)&&Ta({key:e.key})},hl=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&Da({url:window.location.href,currentPageTitle:document.title})},fl=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&Pa({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},ml=()=>{window.addEventListener("click",dl("left_click"),Tr),window.addEventListener("mousedown",e=>{e.button===2&&_s("right_click",e)},Tr),window.addEventListener("keydown",pl,Tr),hl(),fl()},yl={test:"test"},gl=["popState","pushState","replaceState"],Rt="!email",Br="pageUrl";function wl(e,t){const{pageUrlEvents:n,interactiveEvents:r,dismissOnPageChange:i}=window.UserLeap._config;if(!i)return!0;const s=[];n&&n.length&&s.push(...n),r&&r.length&&s.push(...r);const o=e&&s.find(a=>a.id===e);return o?yn(o,window.location.href):t===window.location.href}function Ot(e){const{pageUrlEvents:t,interactiveEvents:n,dismissOnPageChange:r,platform:i}=window.UserLeap._config;if(i&&i!=="web")return;const s=Ve("trackStartUrl"),o=s?String(s):null;t&&Ls(window.location.href),n&&(Es(),vl()),ps()&&Ga(window.location.href),!gn()&&r&&o&&o!==window.location.href&&e&&gl.includes(e.type)&&window.UserLeap("dismissActiveSurvey",be.PageChange)}const ks={capture:!0},vl=()=>{const t=window.UserLeap._config.interactiveEvents.filter(r=>yn(r,window.location.href)).map(r=>{const{name:i,properties:s}=r,{selector:o,innerText:a}=s;return o?l=>{if(ws(l.target))try{l.target.closest(o)&&window.UserLeap("track",i)}catch{}return!1}:l=>(ws(l.target)&&l.target.innerText===a&&window.UserLeap("track",i),!1)}),n=r=>t.forEach(i=>i(r));window.UserLeap._config.interactiveEventsHandler=n,window.addEventListener("click",n,ks)},Es=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,ks),delete window.UserLeap._config.interactiveEventsHandler};function bl(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,Ot,!0))}function _l(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,Ot,!0)),window.UserLeap._config.interactiveEvents&&Es()}function kl(e,t){let n=ie("1",[Ce],"questions?");return e!=null&&(n+=`&vid=${e}`),t&&(t.surveyId&&(n+=`&surveyid=${t.surveyId}`),t.surveyTemplateId&&(n+=`&surveytemplateid=${t.surveyTemplateId}`),t.previewLanguage&&(n+=`&previewLanguage=${encodeURIComponent(t.previewLanguage)}`),t.useMobileStyling&&(n+=`&isMobile=${t.useMobileStyling}`)),n}function Ve(e){const t=Z.getItem("userleap.ids");if(t)try{const r=JSON.parse(t)[window.UserLeap.envId];return r&&r[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 Ss(){window.previewMode||(window.UserLeap.visitorId=ze(),I(`Generating new vid: ${window.UserLeap.visitorId}`),ne("vid",window.UserLeap.visitorId),R.emit(C.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}))}function Ls(e,t,n){var u;if(e.endsWith("mock_snippet.html"))return;I(`Tracking page view: ${e}`);const r=window.UserLeap._config.pageUrlEvents;let i=!1;if(r&&r.length)for(let p=0;p<r.length&&(i=yn(r[p],e),!i);p++);if(!i)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",e);const s=10,o=1;let a=[];const l={viewedAt:Date.now(),location:e},c=Z.getItem("userleap.pageviews");try{if(a=c?JSON.parse(c):[],Array.isArray(a)||(a=[]),a.length>0){const p=a[a.length-1],d=(Date.now()-p.viewedAt)/1e3;if(p.location!=e&&d>o){const h=(u=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:u.getAttribute("content");rs({...h&&{description:h},url:e,referrer:document.referrer,pageTitle:document.title})}(p.location!=e&&d>o||d>s)&&(window.UserLeap._queue.push(["track",Br,t,{url:e},n]),a.push(l))}else window.UserLeap._queue.push(["track",Br,t,{url:e},n]),a.push(l),rs({url:e});a.length>5&&a.splice(0,a.length-5),Z.setItem("userleap.pageviews",JSON.stringify(a))}catch(p){p instanceof Error&&window.UserLeap.reportError("trackPageView",p,{pageViewsStorage:c}),console.warn("[Sprig] (ERR-425) Failed to update page views in local storage")}}function El(){const e="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in e&&(e.pushState=(t=>function(...r){const i=t.apply(this,r),s=new Event("pushState");return window.dispatchEvent(s),Ot(s),i})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...r){const i=t.apply(this,r),s=new Event("replaceState");return window.dispatchEvent(s),Ot(s),i})(e.replaceState)),bl()}async function Mr(e,t){const n=Sr();e&&!t&&(window.UserLeap._config.mode=yl.test);const r=Oe(window.UserLeap),i=Lr(r),s=await le(kl(n,{...e,previewLanguage:window.UserLeap._config.previewLanguage,useMobileStyling:i}),{shouldDropOnRateLimit:!0});if(!s.ok)return s.reportError&&s.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",s.error),window.UserLeap.reportError("getQuestions",s.error)),{success:!1,surveyState:"no survey"};if(s.json.delay&&await Tt(s.json.delay),s.json.isFeedback){const{feedbackLabel:o,productConfig:a,surveyUuid:l}=s.json,{buttonTheme:c,placement:u,desktopDisplay:p}=a,d={buttonTheme:c,desktopDisplay:p,eventId:0,feedbackLabel:o,placement:u,surveyUuid:l,surveyId:e==null?void 0:e.surveyId};gs(d,s.json)}else return xt(s.json)}function Sl(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const r=e[t];e[t]=e[n],e[n]=r}}function Ll(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:r}=e;t&&Sl(t),(t||n||r)&&(El(),Ot())}async function Il(e,t){var r,i;let n=!0;return t&&((r=e==null?void 0:e.json)!=null&&r.surveyId)&&(window.UserLeap.delayingSurvey=!0,n=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!n)?!1:((i=e==null?void 0:e.json)!=null&&i.delay&&(window.UserLeap.delayingSurvey=!0,await Tt(e.json.delay),window.UserLeap.delayingSurvey=!1),n)}const Ul=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var w,f,m,b;const{userId:i,anonymousId:s,metadata:o={},properties:a,showSurveyCallback:l}=r;let{eventName:c}=r;if(window.UserLeap.debugMode&&c!==Br&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const u=Z.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!i){const v="[Sprig] - Skipping tracking without userId";return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}if(!c||c.trim().length===0){c=c?String(c):"";const v="[Sprig] - Invalid event name "+c;return console.warn(v),{success:!1,message:v,surveyState:"no survey"}}const p=window.location.href;if(o.url||(o.url=p),ne("trackStartUrl",p),(f=(w=window.UserLeap)==null?void 0:w._config)!=null&&f.optimizelyEnabled){const v=Oe(window.UserLeap);Ir(v)||vn.getAndSetWebOptimizelyExperiments(),o.optimizelyExperiments=Object.assign({},vn.getAllOptimizelyExperiments())}(b=(m=window.UserLeap)==null?void 0:m._config)!=null&&b.launchDarklyEnabled&&(o.launchDarklyFlags=Dr.getAllLaunchDarklyVariations()),i&&(window.UserLeap.userId=i),s&&(window.UserLeap.partnerAnonymousId=s),a&&(o.eventProperties=a),Aa({name:c,url:o.url}),I(`Tracking event: ${c}`);const d=window.UserLeap.delayingSurvey||hs()?await le(ie("1",[Ae],"events/batch"),{body:JSON.stringify({events:[{event:c,metadata:o}],previewKey:u}),method:"POST",shouldDropOnRateLimit:!0}):await le(ie("1",[Ae],"events"),{body:JSON.stringify({event:c,metadata:o,previewKey:u}),method:"POST",shouldDropOnRateLimit:!0});if(!d.ok){const v="[Sprig] (ERR-421) Failed to track event";return d.reportError&&(console.warn(v,d.error),d.error&&window.UserLeap.reportError("track",d.error)),{success:!1,message:v,error:d.error,surveyState:"no survey"}}i&&ne("uid",i),s&&ne("aid",s);const h=d.json;return h.invalidPreviewKey&&Z.removeItem("sprig.previewKey"),!!(h!=null&&h.feedbackButton)&&gs(h.feedbackButton),await Il(d,l)?wl(h.eventId,p)?xt(h):{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={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",be.Override),Mr({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",be.Override),Mr({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",be.Override),Mr({surveyId:r},!1)},previewSurvey(r){n._previewSurvey(r)},reviewSurvey(r){n._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=be.API){R.emit(C.SurveyWillClose,{name:C.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 c="[Sprig] - Disregarding empty payload provided";return console.warn(c),{success:!1,message:c}}const{userId:i,anonymousId:s,attributes:o}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!i){const c="[Sprig] - Skipping tracking without userId";return console.warn(c),{success:!1,message:c}}if(!o&&(!i||window.UserLeap.userId===i)&&(!s||window.UserLeap.partnerAnonymousId===s))return{success:!0};const a={};i&&(a.userId=window.UserLeap.userId=i),s&&(a.partnerAnonymousId=window.UserLeap.partnerAnonymousId=s);let l;return o?(o.email&&!Object.prototype.hasOwnProperty.call(o,Rt)&&(o[Rt]=o.email,delete o.email),I(`Setting attributes: ${JSON.stringify(o)}`),l=await le(ie("1",[Ce,Ae],"attributes"),{body:JSON.stringify(o),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 le(ie("1",[Ce,Ae]),{body:JSON.stringify(a),method:"PUT"}),o&&o[Rt]&&(window.UserLeap.email=o[Rt]),l.ok&&(i&&ne("uid",i),s&&ne("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 le(ie("1",[Ce,Ae],"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){R.on(C.SurveyLifeCycle,r)},async removeSurveyListener(r){R.removeListener(C.SurveyLifeCycle,r)},async addListener(r,i){R.on(r,i)},async removeListener(r,i){R.removeListener(r,i)},async removeAllListeners(){R.removeAllListeners()},setPreviewKey(r){!r||typeof r!="string"||Z.isStorageAvailable&&r&&Z.setItem("sprig.previewKey",r)},async setUserId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",r),r==null){const o=`[Sprig] - Invalid userId ${r}`;return console.warn(o),{success:!1,message:o}}if(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const i=window.UserLeap.visitorId,s=await le(ie("1",[Ce,Ae]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!s.ok){s.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",s.error),s.error&&window.UserLeap.reportError("setUserId",s.error));return}i!==window.UserLeap.visitorId&&ns(),ne("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,ne("aid",r),{success:!0}},async track(r,i,s={},o=void 0){return t({eventName:r,properties:i,metadata:s,showSurveyCallback:o})},async identifyAndTrack(r){return await t(r)},trackPageView(r,i=void 0,s=void 0){Ls(r,i,s)},applyStyles(r){if(window.UserLeap.customStyles=r,window.UserLeap.container){const i=window.UserLeap.container.children[0].contentDocument;if(i){const s=i.getElementById("ul-custom-style");s?s.textContent=r:nl(i,r,window.UserLeap.styleNonce)}}},setWindowDimensions(r,i){var l,c;const s=typeof r=="string"?parseInt(r,10):r,o=typeof i=="string"?parseInt(i,10):i;if(!isNaN(s)&&!isNaN(o)&&(window.UserLeap.windowDimensions={width:s,height:o}),!window.UserLeap.frameId)return;const a=document.getElementById(window.UserLeap.frameId);a&&(window.UserLeap.useMobileStyling&&((l=window.UserLeap.windowDimensions)!=null&&l.width&&(a.style.width=`${window.UserLeap.windowDimensions.width}px`),(c=window.UserLeap.windowDimensions)!=null&&c.height&&(a.style.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`),a.contentDocument&&(a.style.height=String(rl(a.contentDocument)[0])+"px")),R.emit(C.SurveyDimensions,{name:C.SurveyDimensions,contentFrameWidth:a.clientWidth,contentFrameHeight:a.clientHeight}))},logoutUser(){window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),I(`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,Z.removeItem("userleap.ids"),Z.removeItem("userleap.pageviews"),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),Ss(),ns(),window.UserLeap._queue.unpause()},teardown(){_l(),window.UserLeap("dismissActiveSurvey",be.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,i=!0){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const a=typeof r=="string"?JSON.parse(r):r;vn.setOptimizelyExperiment(a,i)}catch(a){console.warn("[Sprig] Error with integrating Optimizely data"),a instanceof Error&&window.UserLeap.reportError("integrateOptimizely",a)}},integrateOptimizelyClient(r){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const i=({experiment:a,variation:l})=>{const c={experiments:[{id:a.id,variation:l.key}]};window.UserLeap("integrateOptimizely",c,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",i)},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}Dr.setLDFlagsVariations(r)},setVisitorAttribute(r,i){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),n.setAttribute(r,i)},async setEmail(r){return n.setAttribute(Rt,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),n.setEmail(r)},async _generateVideoUploadUrl(r){return Rl(r)},_reportMetric(r,i){$i(r,i)},async _completeSessionReplay({surveyId:r,responseGroupUuid:i,eventDigest:s}){if(!r||!i)return!1;const o=window.UserLeap._API_URL;try{const a=await Qr({surveyId:r,responseGroupUuid:i,eventDigest:s,apiUrl:o,headers:Oe(window.UserLeap)},!0);return!(a!=null&&a.error)}catch(a){return console.warn("[Sprig] Error with completing session replay"),a instanceof Error&&window.UserLeap.reportError("completeSessionReplay",a),!1}}};Object.assign(window.UserLeap,n)};async function xl(e){const t=Oe(window.UserLeap);document.addEventListener("securitypolicyviolation",bn);const n=await ke(ie("1",[Ce],"config"),{headers:t}),r="TypeError";if(window.UserLeap.error=n.error,!n.ok&&n.error&&n.error.name===r?(window.UserLeap._API_URL="https://api.sprig.com",window.UserLeap.reportError("sprigDomainRequest",n.error)):document.removeEventListener("securitypolicyviolation",bn),!n.ok)return n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),_n("Disabled: failed to fetch configuration"),e;const i=n.json;return i!=null&&i.disabled?(_n(`Disabled: ${i.disabled}`),{disabled:i.disabled}):Object.assign({},i,e)}const Al=e=>typeof e=="object"&&e&&"inner"in e&&!!e.inner&&typeof e.inner=="object";async function Cl(e,t,n={}){var p,d;const r=window.__cfg&&window.__cfg.mode,i=Sr(),s=window.UserLeap.envId,o=window.document.documentElement,a=Al(t)?{inner:{message:(p=t.inner)==null?void 0:p.message,stack:(d=t.inner)==null?void 0:d.stack}}:{},l={mode:r,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:o.clientWidth,clientHeight:o.clientHeight,location:window.location.href,language:window.navigator.language,...n,...a},c={action:e,err:{message:t.message,stack:t.stack},meta:l,vid:i,envId:s},u=await le(ie("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(c),shouldDropOnRateLimit:!0});if(!u.ok)console.warn("[Sprig] (ERR-444) Failed to report error to API",t);else{const{presignedUrl:h}=u.json;Vs(h)}}async function Rl(e){var n;if(!e)return;const t=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const r=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(r.ok){const i=await r.json();return(n=i==null?void 0:i.upload)==null?void 0:n.url}else return null}catch(r){console.warn("[Sprig] Error with generating video upload url"),r instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",r)}}function Ol(e={}){const t=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";window.UserLeap.UPDATES=Pt,window.UserLeap("setPreviewKey",t);async function n(){if(window.UserLeap.loaded)return;if(I("Loading sprig on page load"),window.UserLeap.reportError=Cl,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 a in window.UserLeap._config)window.UserLeap[a]=window.UserLeap._config[a];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 a=Ve("sampled");if(a===null&&(a=Math.random()<r,ne("sampled",a)),!a)return}else Ve("sampled")!==null&&ne("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const i=[...window.UserLeap._queue];window.UserLeap._queue=new el(window.UserLeap,[]),window.UserLeap._queue.pause();for(let a=0;a<i.length;a++)window.UserLeap._queue.push(i[a]);const s=Ve("token");s?(window.UserLeap.token=s,window.UserLeap.visitorId=Ve("vid"),window.UserLeap.userId=Ve("uid"),window.UserLeap.partnerAnonymousId=Ve("aid")):(Z.removeItem("userleap.ids"),Ss());const o=await xl(e);sl({webMetricsEnabled:o.metricsReportingEnabled,reportingIntervalSeconds:o.metricsReportingEnabled||o.mobileMetricsReportingEnabled?o.metricsReportingIntervalSeconds:0,thresholds:o.metricThresholds,postMetrics:async a=>{await le(ie("1",[Ce],"metrics"),{body:a,method:"POST",headers:{"x-ul-replay-enabled":`${is()}`},shouldDropOnRateLimit:!0})}}),ya(window.document,o.maxReplayDurationSeconds,window.UserLeap.replayNonce,window.UserLeap.maxInflightReplayRequests,o.replaySettings).then(()=>{ml()}),Ws(o.logBufferLimit,o.logLevel),Ul(o),await Ll(o),window.UserLeap._queue.unpause(),R.emit(C.SDKReady,{mobileMetricsReportingEnabled:!!o.mobileMetricsReportingEnabled,metricsReportingInterval:o.metricsReportingIntervalSeconds||0,metricsThresholds:o.metricThresholds||[],maxMobileReplayDurationSeconds:o.maxMobileReplayDurationSeconds,mobileReplaySettings:o.mobileReplaySettings}),R.emit(C.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}const Dl="sprig-web-view-sdk";let Is;Is={path:`https://cdn.sprig.com/${Dl}-v2.28.1.js`},Ol(Is)})();
//# debugId=d0068e6b-6db4-579b-bd13-7d2ce73ce7c2