@sesamy/sesamy-js 1.35.4 → 1.35.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,8 +31,8 @@
31
31
  *
32
32
  * Please keep this comment intact in order to properly abide by the MIT License.
33
33
  *
34
- **/var __webpack_require__={d:($e,De)=>{for(var Fe in De)__webpack_require__.o(De,Fe)&&!__webpack_require__.o($e,Fe)&&Object.defineProperty($e,Fe,{enumerable:!0,get:De[Fe]})},o:($e,De)=>Object.prototype.hasOwnProperty.call($e,De)},__webpack_exports__={};__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__,k:()=>detectIncognito});var __awaiter=function($e,De,Fe,Be){return new(Fe||(Fe=Promise))(function(He,Ke){function Ge(Xe){try{Ze(Be.next(Xe))}catch(Je){Ke(Je)}}function We(Xe){try{Ze(Be.throw(Xe))}catch(Je){Ke(Je)}}function Ze(Xe){var Je;Xe.done?He(Xe.value):(Je=Xe.value,Je instanceof Fe?Je:new Fe(function(Ye){Ye(Je)})).then(Ge,We)}Ze((Be=Be.apply($e,[])).next())})},__generator=function($e,De){var Fe,Be,He,Ke,Ge={label:0,sent:function(){if(1&He[0])throw He[1];return He[1]},trys:[],ops:[]};return Ke={next:We(0),throw:We(1),return:We(2)},typeof Symbol=="function"&&(Ke[Symbol.iterator]=function(){return this}),Ke;function We(Ze){return function(Xe){return function(Je){if(Fe)throw new TypeError("Generator is already executing.");for(;Ke&&(Ke=0,Je[0]&&(Ge=0)),Ge;)try{if(Fe=1,Be&&(He=2&Je[0]?Be.return:Je[0]?Be.throw||((He=Be.return)&&He.call(Be),0):Be.next)&&!(He=He.call(Be,Je[1])).done)return He;switch(Be=0,He&&(Je=[2&Je[0],He.value]),Je[0]){case 0:case 1:He=Je;break;case 4:return Ge.label++,{value:Je[1],done:!1};case 5:Ge.label++,Be=Je[1],Je=[0];continue;case 7:Je=Ge.ops.pop(),Ge.trys.pop();continue;default:if(He=Ge.trys,!((He=He.length>0&&He[He.length-1])||Je[0]!==6&&Je[0]!==2)){Ge=0;continue}if(Je[0]===3&&(!He||Je[1]>He[0]&&Je[1]<He[3])){Ge.label=Je[1];break}if(Je[0]===6&&Ge.label<He[1]){Ge.label=He[1],He=Je;break}if(He&&Ge.label<He[2]){Ge.label=He[2],Ge.ops.push(Je);break}He[2]&&Ge.ops.pop(),Ge.trys.pop();continue}Je=De.call($e,Ge)}catch(Ye){Je=[6,Ye],Be=0}finally{Fe=He=0}if(5&Je[0])throw Je[1];return{value:Je[0]?Je[1]:void 0,done:!0}}([Ze,Xe])}}};function detectIncognito(){return __awaiter(this,void 0,Promise,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,new Promise(function(resolve,reject){var browserName="Unknown";function __callback($e){resolve({isPrivate:$e,browserName})}function identifyChromium(){var $e=navigator.userAgent;return $e.match(/Chrome/)?navigator.brave!==void 0?"Brave":$e.match(/Edg/)?"Edge":$e.match(/OPR/)?"Opera":"Chrome":"Chromium"}function assertEvalToString($e){return $e===eval.toString().length}function feid(){var toFixedEngineID=0;try{eval("(-1).toFixed(-1);")}catch($e){toFixedEngineID=$e.message.length}return toFixedEngineID}function isSafari(){return feid()===44}function isChrome(){return feid()===51}function isFirefox(){return feid()===25}function isMSIE(){return navigator.msSaveBlob!==void 0&&assertEvalToString(39)}function newSafariTest(){var $e=String(Math.random());try{window.indexedDB.open($e,1).onupgradeneeded=function(De){var Fe,Be,He=(Fe=De.target)===null||Fe===void 0?void 0:Fe.result;try{He.createObjectStore("test",{autoIncrement:!0}).put(new Blob),__callback(!1)}catch(Ge){var Ke=Ge;return Ge instanceof Error&&(Ke=(Be=Ge.message)!==null&&Be!==void 0?Be:Ge),typeof Ke!="string"?void __callback(!1):void __callback(Ke.includes("BlobURLs are not yet supported"))}finally{He.close(),window.indexedDB.deleteDatabase($e)}}}catch{__callback(!1)}}function oldSafariTest(){var $e=window.openDatabase,De=window.localStorage;try{$e(null,null,null,null)}catch{return void __callback(!0)}try{De.setItem("test","1"),De.removeItem("test")}catch{return void __callback(!0)}__callback(!1)}function safariPrivateTest(){navigator.maxTouchPoints!==void 0?newSafariTest():oldSafariTest()}function getQuotaLimit(){var $e=window;return $e.performance!==void 0&&$e.performance.memory!==void 0&&$e.performance.memory.jsHeapSizeLimit!==void 0?performance.memory.jsHeapSizeLimit:1073741824}function storageQuotaChromePrivateTest(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function($e,De){__callback(Math.round(De/1048576)<2*Math.round(getQuotaLimit()/1048576))},function($e){reject(new Error("detectIncognito somehow failed to query storage quota: "+$e.message))})}function oldChromePrivateTest(){(0,window.webkitRequestFileSystem)(0,1,function(){__callback(!1)},function(){__callback(!0)})}function chromePrivateTest(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?storageQuotaChromePrivateTest():oldChromePrivateTest()}function firefoxPrivateTest(){__callback(navigator.serviceWorker===void 0)}function msiePrivateTest(){__callback(window.indexedDB===void 0)}function main(){isSafari()?(browserName="Safari",safariPrivateTest()):isChrome()?(browserName=identifyChromium(),chromePrivateTest()):isFirefox()?(browserName="Firefox",firefoxPrivateTest()):isMSIE()?(browserName="Internet Explorer",msiePrivateTest()):reject(new Error("detectIncognito cannot determine the browser"))}main()})];case 1:return[2,_a.sent()]}})})}typeof window<"u"&&(window.detectIncognito=detectIncognito);const __WEBPACK_DEFAULT_EXPORT__=detectIncognito;__webpack_exports__.A;var __webpack_exports__detectIncognito=__webpack_exports__.k;async function isIncognito(){try{const{isPrivate:$e}=await __webpack_exports__detectIncognito();return $e}catch{return!1}}function isBrowser(){return typeof window<"u"}const STORAGE_KEY="sesamyFlags";async function saveFlags($e){try{localStorage.setItem(STORAGE_KEY,JSON.stringify($e))}catch{log("Failed to save flags to localStorage")}}async function setFlag($e,De){const Fe=await listFlags();Fe[$e]=De,await saveFlags(Fe)}async function getFlag($e){return(await listFlags())[$e]}async function deleteFlag($e){const De=await listFlags();$e in De&&(delete De[$e],await saveFlags(De))}async function listFlags(){try{const $e=localStorage.getItem(STORAGE_KEY);return $e?JSON.parse($e):{}}catch{return{}}}let auth0Client,organization,initialized=!1,loginInProgress=!1;isBrowser()&&window.addEventListener("pageshow",()=>{loginInProgress=!1});const ACCESS_TOKEN_KEY="sesamyAccessToken",REFRESH_TOKEN_KEY="sesamyRefreshToken";async function waitForInit(){return initialized?!0:new Promise(($e,De)=>{const Fe=setTimeout(()=>{initialized?$e(!0):De(new Error("Initialization failed: Timeout"))},2e3);window.addEventListener(Events.AUTH_INITIALIZED,()=>{clearTimeout(Fe),$e(!0)})})}async function refreshLocalAccessToken($e){if(!$e)return null;const De=localStorage.getItem(REFRESH_TOKEN_KEY);if(!De)return log("No refresh token found in localstorage"),null;const Fe=new URLSearchParams;Fe.set("client_id",$e.iss),Fe.set("refresh_token",De),Fe.set("grant_type","refresh_token");const Be=new URL($e.iss);Be.pathname="/oauth/token",Be.searchParams.set("user_id",$e.sub);try{const He=await fetch(Be.href,{body:Fe.toString(),method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!He.ok)throw localStorage.removeItem(REFRESH_TOKEN_KEY),new Error("Renew token failed");const Ke=await He.json();return localStorage.setItem(REFRESH_TOKEN_KEY,Ke.refresh_token),localStorage.setItem(ACCESS_TOKEN_KEY,Ke.access_token),Ke.access_token}catch{logout()}}async function getLocalStorageAccessToken(){const $e=localStorage.getItem(ACCESS_TOKEN_KEY);if(!$e)return null;const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3){const Fe=await refreshLocalAccessToken(De);if(Fe)return Fe;localStorage.removeItem(ACCESS_TOKEN_KEY)}return $e}function getTopLevelDomain($e){try{const De=new URL($e).hostname,Fe=De.split(".");return Fe.length>1?Fe.slice(-2).join("."):De}catch{return null}}async function init$3($e){if($e.enabled===!1)return;organization=$e.organization;const Be={domain:await getFlag("newAuth")&&$e.domain?$e.domain:getBaseUrl("token",$e.environment),clientId:$e.clientId,useCookiesForTransactions:!0};if(getTopLevelDomain(window.location.href)!==getTopLevelDomain(getBaseUrl("auth",$e.environment))&&(Be.cacheLocation="localstorage",Be.useRefreshTokens=!0),auth0Client=await oe$1(Be),window.location.search.includes("code=")){log("Code found in URL, handling redirect");try{const Ge=await auth0Client.handleRedirectCallback();log(`Login result: ${JSON.stringify(Ge)}`);const We=await auth0Client.getUser();if(!We)throw log("No user found"),new Error("No user found");log(`User found ${JSON.stringify(We)}`),triggerEvent(Events.AUTHENTICATED,We),log("Rewrite url")}catch(Ge){alert("There was an error logging in"),console.error(Ge)}const He=new URL(location.href),Ke=He.searchParams;Ke.delete("code"),Ke.delete("state"),He.search=Ke.toString(),window.history.replaceState({},document.title,He.toString())}initialized=!0,triggerEvent(Events.AUTH_INITIALIZED,{})}async function isAuthenticated(){return await waitForInit(),await getLocalStorageAccessToken()?!0:auth0Client?auth0Client.isAuthenticated():!1}async function getUser(){return await waitForInit(),await getLocalStorageAccessToken()?(log("Using local user"),{sub:"local",name:"Local User"}):auth0Client?auth0Client.getUser():null}async function loginWithRedirect($e){if(loginInProgress){log("Login already in progress");return}if(loginInProgress=!0,await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),!auth0Client)throw new Error("Auth0 client not initialized");const De=($e==null?void 0:$e.authorizationParams)||{};return await isIncognito()&&navigator.userAgent.includes("Safari")&&navigator.userAgent.includes("iPhone")&&sessionStorage.setItem(SESMAY_CONTENT_RELOAD_KEY,"true"),auth0Client.loginWithRedirect({...$e,authorizationParams:{organization,redirect_uri:window.location.href,ui_locales:getLanguage(),...De}})}async function getTokenSilently($e=!0,De=!1){await waitForInit();const Fe=await getLocalStorageAccessToken();if(Fe)return Fe;try{if(!auth0Client)return log("Auth client not initialized"),null;let Be=await auth0Client.getTokenSilently();const He=getPayloadFromJwt(Be);return De&&(He!=null&&He.exp)&&He.exp+3600<new Date().getTime()/1e3&&(Be=await auth0Client.getTokenSilently({cacheMode:De?"off":"on"})),Be}catch(Be){const He=Be;if(log(`Failed to get token silently: ${He.message}`),He.message==="Invalid refresh token"&&await logout(),$e)throw Be;return null}}async function logout($e={}){if(await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),triggerEvent(Events.LOGOUT,{}),!!auth0Client)return log(`Logout with options: ${JSON.stringify($e)}`),auth0Client.logout({...$e,logoutParams:{returnTo:window.location.href,...$e.logoutParams}})}function getPayloadFromJwt($e){const De=$e.split(".");if(De.length!==3)return null;const Be=De[1].replace(/-/g,"+").replace(/_/g,"/"),He=decodeURIComponent(atob(Be).split("").map(function(Ke){return"%"+("00"+Ke.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(He)}async function setToken($e){const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3)throw new Error("Invalid token");log("Set token"),localStorage.setItem(ACCESS_TOKEN_KEY,$e),triggerEvent(Events.AUTHENTICATED,De)}const defaultSkip=($e,De)=>De.skipDedupe||De.method!=="GET",defaultKey=($e,De)=>De.method+"@"+$e,defaultResolver=$e=>$e.clone(),dedupe=({skip:$e=defaultSkip,key:De=defaultKey,resolver:Fe=defaultResolver}={})=>{const Be=new Map;return He=>(Ke,Ge)=>{if($e(Ke,Ge))return He(Ke,Ge);const We=De(Ke,Ge);if(!Be.has(We))Be.set(We,[]);else return new Promise((Ze,Xe)=>{Be.get(We).push([Ze,Xe])});try{return He(Ke,Ge).then(Ze=>(Be.get(We).forEach(([Xe])=>Xe(Fe(Ze))),Be.delete(We),Ze)).catch(Ze=>{throw Be.get(We).forEach(([,Xe])=>Xe(Ze)),Be.delete(We),Ze})}catch(Ze){return Be.delete(We),Promise.reject(Ze)}}},defaultDelayRamp=($e,De)=>$e*De,defaultUntil=$e=>$e&&$e.ok,retry=({delayTimer:$e=500,delayRamp:De=defaultDelayRamp,maxAttempts:Fe=10,until:Be=defaultUntil,onRetry:He=null,retryOnNetworkError:Ke=!1,resolveWithLatestResponse:Ge=!1,skip:We}={})=>Ze=>(Xe,Je)=>{let Ye=0;if(We&&We(Xe,Je))return Ze(Xe,Je);const Qe=(et,tt)=>Promise.resolve(Be(et,tt)).then(ct=>ct?et&&Ge?et:tt?Promise.reject(tt):et:(Ye++,!Fe||Ye<=Fe?new Promise(at=>{const ft=De($e,Ye);setTimeout(()=>{typeof He=="function"?Promise.resolve(He({response:et,error:tt,url:Xe,options:Je})).then((ut={})=>{var ot,rt;at(Ze((ot=ut&&ut.url)!==null&&ot!==void 0?ot:Xe,(rt=ut&&ut.options)!==null&&rt!==void 0?rt:Je))}):at(Ze(Xe,Je))},ft)}).then(Qe).catch(at=>{if(!Ke)throw at;return Qe(null,at)}):et&&Ge?et:Promise.reject(tt||new Error("Number of attempts exceeded."))));return Ze(Xe,Je).then(Qe).catch(et=>{if(!Ke)throw et;return Qe(null,et)})},JSON_MIME="application/json",CONTENT_TYPE_HEADER="Content-Type",FETCH_ERROR=Symbol(),CATCHER_FALLBACK=Symbol();function extractContentType($e={}){var De;return(De=Object.entries($e).find(([Fe])=>Fe.toLowerCase()===CONTENT_TYPE_HEADER.toLowerCase()))===null||De===void 0?void 0:De[1]}function isLikelyJsonMime($e){return/^application\/.*json.*/.test($e)}const mix=function($e,De,Fe=!1){return Object.entries(De).reduce((Be,[He,Ke])=>{const Ge=$e[He];return Array.isArray(Ge)&&Array.isArray(Ke)?Be[He]=Fe?[...Ge,...Ke]:Ke:typeof Ge=="object"&&typeof Ke=="object"?Be[He]=mix(Ge,Ke,Fe):Be[He]=Ke,Be},{...$e})},config={options:{},errorType:"text",polyfills:{},polyfill($e,De=!0,Fe=!1,...Be){const He=this.polyfills[$e]||(typeof self<"u"?self[$e]:null)||(typeof global<"u"?global[$e]:null);if(De&&!He)throw new Error($e+" is not defined");return Fe&&He?new He(...Be):He}};function setOptions($e,De=!1){config.options=De?$e:mix(config.options,$e)}function setPolyfills($e,De=!1){config.polyfills=De?$e:mix(config.polyfills,$e)}function setErrorType($e){config.errorType=$e}const middlewareHelper=$e=>De=>$e.reduceRight((Fe,Be)=>Be(Fe),De)||De;class WretchError extends Error{}const resolver=$e=>{const De=Object.create(null);$e=$e._addons.reduce((ot,rt)=>rt.beforeRequest&&rt.beforeRequest(ot,$e._options,De)||ot,$e);const{_url:Fe,_options:Be,_config:He,_catchers:Ke,_resolvers:Ge,_middlewares:We,_addons:Ze}=$e,Xe=new Map(Ke),Je=mix(He.options,Be);let Ye=Fe;const Qe=middlewareHelper(We)((ot,rt)=>(Ye=ot,He.polyfill("fetch")(ot,rt)))(Fe,Je),et=new Error,tt=Qe.catch(ot=>{throw{[FETCH_ERROR]:ot}}).then(ot=>{var rt;if(!ot.ok){const lt=new WretchError;if(lt.cause=et,lt.stack=lt.stack+`
35
- CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque")throw lt;const pt=He.errorType==="json"||((rt=ot.headers.get("Content-Type"))===null||rt===void 0?void 0:rt.split(";")[0])==="application/json";return(He.errorType?pt?ot.text():ot[He.errorType]():Promise.resolve(ot.body)).then(vt=>{throw lt.message=typeof vt=="string"?vt:ot.statusText,vt&&(pt&&typeof vt=="string"?(lt.text=vt,lt.json=JSON.parse(vt)):lt[He.errorType]=vt),lt})}return ot}),ct=ot=>ot.catch(rt=>{const lt=Object.prototype.hasOwnProperty.call(rt,FETCH_ERROR),pt=lt?rt[FETCH_ERROR]:rt,gt=(pt==null?void 0:pt.status)&&Xe.get(pt.status)||Xe.get(pt==null?void 0:pt.name)||lt&&Xe.has(FETCH_ERROR)&&Xe.get(FETCH_ERROR);if(gt)return gt(pt,$e);const vt=Xe.get(CATCHER_FALLBACK);if(vt)return vt(pt,$e);throw pt}),at=ot=>rt=>ct(ot?tt.then(lt=>lt&&lt[ot]()).then(lt=>rt?rt(lt):lt):tt.then(lt=>rt?rt(lt):lt)),ft={_wretchReq:$e,_fetchReq:Qe,_sharedState:De,res:at(null),json:at("json"),blob:at("blob"),formData:at("formData"),arrayBuffer:at("arrayBuffer"),text:at("text"),error(ot,rt){return Xe.set(ot,rt),this},badRequest(ot){return this.error(400,ot)},unauthorized(ot){return this.error(401,ot)},forbidden(ot){return this.error(403,ot)},notFound(ot){return this.error(404,ot)},timeout(ot){return this.error(408,ot)},internalError(ot){return this.error(500,ot)},fetchError(ot){return this.error(FETCH_ERROR,ot)}},ut=Ze.reduce((ot,rt)=>({...ot,...typeof rt.resolver=="function"?rt.resolver(ot):rt.resolver}),ft);return Ge.reduce((ot,rt)=>rt(ot,$e),ut)},core={_url:"",_options:{},_config:config,_catchers:new Map,_resolvers:[],_deferred:[],_middlewares:[],_addons:[],addon($e){return{...this,_addons:[...this._addons,$e],...$e.wretch}},errorType($e){return{...this,_config:{...this._config,errorType:$e}}},polyfills($e,De=!1){return{...this,_config:{...this._config,polyfills:De?$e:mix(this._config.polyfills,$e)}}},url($e,De=!1){if(De)return{...this,_url:$e};const Fe=this._url.split("?");return{...this,_url:Fe.length>1?Fe[0]+$e+"?"+Fe[1]:this._url+$e}},options($e,De=!1){return{...this,_options:De?$e:mix(this._options,$e)}},headers($e){const De=$e?Array.isArray($e)?Object.fromEntries($e):"entries"in $e?Object.fromEntries($e.entries()):$e:{};return{...this,_options:mix(this._options,{headers:De})}},accept($e){return this.headers({Accept:$e})},content($e){return this.headers({[CONTENT_TYPE_HEADER]:$e})},auth($e){return this.headers({Authorization:$e})},catcher($e,De){const Fe=new Map(this._catchers);return Fe.set($e,De),{...this,_catchers:Fe}},catcherFallback($e){return this.catcher(CATCHER_FALLBACK,$e)},resolve($e,De=!1){return{...this,_resolvers:De?[$e]:[...this._resolvers,$e]}},defer($e,De=!1){return{...this,_deferred:De?[$e]:[...this._deferred,$e]}},middlewares($e,De=!1){return{...this,_middlewares:De?$e:[...this._middlewares,...$e]}},fetch($e=this._options.method,De="",Fe=null){let Be=this.url(De).options({method:$e});const He=extractContentType(Be._options.headers),Ke=this._config.polyfill("FormData",!1),Ge=typeof Fe=="object"&&!(Ke&&Fe instanceof Ke)&&(!Be._options.headers||!He||isLikelyJsonMime(He));return Be=Fe?Ge?Be.json(Fe,He):Be.body(Fe):Be,resolver(Be._deferred.reduce((We,Ze)=>Ze(We,We._url,We._options),Be))},get($e=""){return this.fetch("GET",$e)},delete($e=""){return this.fetch("DELETE",$e)},put($e,De=""){return this.fetch("PUT",De,$e)},post($e,De=""){return this.fetch("POST",De,$e)},patch($e,De=""){return this.fetch("PATCH",De,$e)},head($e=""){return this.fetch("HEAD",$e)},opts($e=""){return this.fetch("OPTIONS",$e)},body($e){return{...this,_options:{...this._options,body:$e}}},json($e,De){const Fe=extractContentType(this._options.headers);return this.content(De||isLikelyJsonMime(Fe)&&Fe||JSON_MIME).body(JSON.stringify($e))}};function factory($e="",De={}){return{...core,_url:$e,_options:De}}factory.default=factory;factory.options=setOptions;factory.errorType=setErrorType;factory.polyfills=setPolyfills;factory.WretchError=WretchError;function clearCache(){return sessionStorage.removeItem(CACHE_TIMESTAMP_KEY),log("Cache cleared"),triggerEvent(Events.CLEAR_CACHE,{}),"Cache cleared"}function isValidHttpUrl($e){let De;try{De=new URL($e)}catch{return!1}return De.protocol==="http:"||De.protocol==="https:"}function decodeItemSrc($e,De){if(isValidHttpUrl($e))return{itemSrc:$e};const[Fe,Be,He]=$e.split(":");return{sku:`${Fe}:${Be}`,purchaseOption:De||He}}function removeTrailingSlash($e){return $e.endsWith("/")?$e.slice(0,-1):$e}function compareUrlWithoutHash($e,De){if(!isValidHttpUrl($e)||!isValidHttpUrl(De))return!1;const Fe=new URL($e),Be=new URL(De);return Fe.origin===Be.origin&&removeTrailingSlash(Fe.pathname)===removeTrailingSlash(Be.pathname)}function generateCheckoutLink($e,De,Fe){const Be=new URL(`${getBaseUrl("checkout3",$e.environment)}`);if(De.language&&Be.searchParams.set("lang",De.language),De.sku)Be.searchParams.set("sku",De.sku),De.purchaseOptionId&&Be.searchParams.set("po-id",De.purchaseOptionId);else if(De.itemSrc){const{sku:We,purchaseOption:Ze,itemSrc:Xe}=decodeItemSrc(De.itemSrc,De.purchaseOptionId);Xe&&Be.searchParams.set("url",Xe),We&&Be.searchParams.set("sku",We),Ze&&Be.searchParams.set("po-id",Ze)}De.email&&Be.searchParams.set("email",De.email),De.business&&Be.searchParams.set("business","true"),De.currency&&Be.searchParams.set("currency",De.currency),De.price&&Be.searchParams.set("price",De.price.toString()),De.discountCode&&Be.searchParams.set("discount-code",De.discountCode),De.attributionItemSrc?Be.searchParams.set("itemSrc",De.attributionItemSrc):Fe.itemSrc&&Be.searchParams.set("itemSrc",Fe.itemSrc),De.attributionPublisherContentId?Be.searchParams.set("publisherContentId",De.attributionPublisherContentId):Fe.publisherContentId&&Be.searchParams.set("publisherContentId",Fe.publisherContentId),De.utmSource?Be.searchParams.set("utm_source",De.utmSource):Fe.utmSource&&Be.searchParams.set("utm_source",Fe.utmSource),De.utmMedium?Be.searchParams.set("utm_medium",De.utmMedium):Fe.utmMedium&&Be.searchParams.set("utm_medium",Fe.utmMedium),De.utmCampaign?Be.searchParams.set("utm_campaign",De.utmCampaign):Fe.utmCampaign&&Be.searchParams.set("utm_campaign",Fe.utmCampaign),De.utmTerm?Be.searchParams.set("utm_term",De.utmTerm):Fe.utmTerm&&Be.searchParams.set("utm_term",Fe.utmTerm),De.utmContent?Be.searchParams.set("utm_content",De.utmContent):Fe.utmContent&&Be.searchParams.set("utm_content",Fe.utmContent);const He=["_ga","_gid","_fbp","_fbc"];document.cookie.split(";").map(We=>{const[Ze,Xe]=We.trim().split("=");return{key:Ze,value:Xe}}).filter(We=>He.some(Ze=>Ze===We.key)).forEach(We=>{Be.searchParams.append(We.key,We.value)});const Ge=new URL(De.redirectUrl||window.location.href);return Ge.searchParams.set("force-refetch-entitlements","true"),De.itemSrc&&Ge.searchParams.set("sesamy-purchase",De.itemSrc),Be.searchParams.set("redirect-url",Ge.toString()),De.paymentMethodsFilter&&Be.searchParams.set("paymentmethods-filter",De.paymentMethodsFilter.flatMap(({provider:We,methods:Ze})=>Ze?Ze.map(Xe=>`${We}|${Xe}`):We).join(",")),Be}const SIGNED_URL_KEY="sesamySignedURLs";function getSignedLinks(){const $e=sessionStorage.getItem(SIGNED_URL_KEY);return $e?JSON.parse($e):[]}function addSignedLink($e){const De=getSignedLinks();De.push($e),log(`Adding signed URL: ${$e}`),sessionStorage.setItem(SIGNED_URL_KEY,JSON.stringify(De))}function removeUndefinedValues($e){const De={};return Object.keys($e).forEach(Fe=>{const Be=$e[Fe];Be!=null&&(De[Fe]=Be.toString())}),De}const ATTRIBUTION_KEY="sesamyAttribution";function parseFromSessionStorage($e){const De=sessionStorage.getItem($e);if(!De)return null;try{return JSON.parse(De).value}catch{return console.error(`Failed to parse ${$e}`),null}}function resetUtmTags($e){return Object.keys($e).find(De=>De.startsWith("utm_"))?{utmSource:void 0,utmMedium:void 0,utmCampaign:void 0,...$e}:$e}function getAttribution(){return parseFromSessionStorage(ATTRIBUTION_KEY)||{}}function setAttribution($e){if($e===null)sessionStorage.removeItem(ATTRIBUTION_KEY);else{log(`Setting attribution ${JSON.stringify($e)}`);const De=getAttribution()??{},Fe=removeUndefinedValues({...De,...resetUtmTags($e)});sessionStorage.setItem(ATTRIBUTION_KEY,JSON.stringify({value:Fe}))}}function createApi($e){const De=getBaseUrl("api2",$e.environment),Fe=st=>async(dt,$t)=>{let Ct=sessionStorage.getItem(CACHE_TIMESTAMP_KEY);Ct||(Ct=Date.now().toString(),sessionStorage.setItem(CACHE_TIMESTAMP_KEY,Ct));const _t={...$t,headers:{...$t.headers,"Cache-Timestamp":Ct}};return st(dt,_t)},Be=(st=!0)=>dt=>async($t,Ct)=>{let _t=null;if(_t=await getTokenSilently(st),!_t){if(st)throw new Error("No access token available");return dt($t,Ct)}const Mt={...Ct,headers:{...Ct.headers,..._t?{Authorization:`Bearer ${_t}`}:{}}};return dt($t,Mt)},He=st=>(dt,$t)=>{if($t.headers.Authorization)return st(dt,$t);const Ct=localStorage.getItem("__anon_id"),_t=btoa(`${$e.clientId}|${Ct}:`),Mt={...$t,headers:{...$t.headers,Authorization:`Basic ${_t}`}};return st(dt,Mt)},Ke=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(),dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]),Ge=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(!1),He,dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]);async function We(st={}){const{waitForEntitlementAfter:dt,includeSignedLinks:$t=!0}=st,Ct=dt?`?wait-for-entitlement-after=${dt.toISOString()}`:"",_t=await isAuthenticated()?await Ke.get(`/entitlements${Ct}`).json():[];return $t&&_t.push(...getSignedLinks()),_t}async function Ze(st,dt=[]){const $t=await We();return $t==null?void 0:$t.find(_t=>{const{sku:Mt,purchaseOption:Ht}=decodeItemSrc(st);let Gt="sku"in _t&&Mt===_t.sku;Gt&&Ht&&"purchaseOptionId"in _t&&(Gt=Ht===_t.purchaseOptionId);const tr=compareUrlWithoutHash(st,_t.url),rr=dt.some(nr=>compareUrlWithoutHash(nr,_t.url));return Gt||tr||rr})}async function Xe(st){const dt=await Ke.get("/entitlements").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function Je(st){return Ke.get(`/entitlements/${encodeURIComponent(st)}/access`).json()}async function Ye(st,dt,$t){const Ct=new URL(getBaseUrl("api2",$e.environment));return Ct.pathname="/proxy",Ct.searchParams.set("url",dt),$t&&Ct.searchParams.set("selector",$t),factory(Ct.toString()).headers({Authorization:`Bearer ${st}`}).get().text()}async function Qe(st){return await isAuthenticated()?await Ke.get(`/fulfillments?sku=${encodeURIComponent(st)}`).json():[]}async function et(){return Ke.get("/contracts").json()}async function tt(st){const dt=await Ke.get("/contracts").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ct(st){const dt=await Ke.post({},`/contracts/${encodeURIComponent(st)}/cancel`).res();return clearCache(),dt.ok}async function at(){return console.warn("getSubscriptions is deprecated, use getContracts instead"),Ke.get("/subscriptions").json()}async function ft(){return Ke.get("/bills").json()}async function ut(st){const dt=await Ke.get("/bills").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ot(){return Ke.get("/transactions").json()}async function rt(st){const dt=await Ke.get("/transactions").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function lt(st,dt){const $t=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).put(dt).json();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),$t}async function pt(st){const dt=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function gt(st){return(await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).get().json())[st]}async function vt(){return await Ke.url("/user-metadata").get().json()}async function Et(){return await Ke.url("/tags").get().json()}async function Pt(st){const dt=await Ke.url(`/tags/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function Nt(st){const dt=await Ke.url("/tags").post(encodeURIComponent(st)).res();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),dt.ok}async function yt(st){return(await Ge.url("/tallies").get().json())[st]}async function It(){return await Ge.url("/tallies").get().json()}async function Rt(st){const dt=await Ge.url(`/tallies/${st}`).delete().res();return clearCache(),dt.ok}async function mt(st,dt){return await Ge.url(`/tallies/${encodeURIComponent(st)}/push`).post(dt).json()}async function At(st){return await Ke.url(`/products/${encodeURIComponent(st)}`).get().json()}async function Ut(){return await getTokenSilently(!1)?await Ke.url("/profile").get().json():null}async function xt(st){const dt=await Ke.url("/profile").patch(st).res();return clearCache(),dt.ok}async function nt(){return await Ke.url("/payment-issues").get().json()}async function it(){return(await Ke.url("/profile/spotify-link").get().json()).isSpotifyLinked}async function ht(){return(await Ke.url("/profile/unlink-spotify").post().res()).ok}async function St(st){const dt=await getTokenSilently(!1);if(!dt)throw new Error("No access token available");const $t=new URL(`${getBaseUrl("access-sync",$e.environment)}/spotify/sesamy-callback`);$t.searchParams.set("access_token",dt),$t.searchParams.set("state",st),window.location.href=$t.toString()}async function bt(st){const dt=await Ke.url(`/products/${encodeURIComponent(st)}/auto-onboard`).post().json();return dt.length&&clearCache(),dt}async function wt(st,dt=3600){const{shortlink:$t}=await factory(SHORTLINK_URL).post({url:st,ttl:dt}).json();return $t}async function kt(st){const dt=await getTokenSilently(!1,!0);let $t;const Ct=st.language||getLanguage(),_t=getAttribution();switch(st.target){case"account":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-payment":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/change-payment-method`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-plan":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/edit-plan`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"consume":$t=new URL(`${getBaseUrl("consume",$e.environment)}/${encodeURIComponent(st.language||Ct)}/@${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.sku)}`),st.episodeId?$t.href+=`/${st.episodeId}`:$t.href+="/listen",$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"checkout":$t=generateCheckoutLink($e,{language:Ct,...st},_t);break;default:throw new Error("Invalid target")}return dt&&($t.hash=`#access_token=${dt}`),st.shorten?wt($t.href,st.ttl):$t.href}async function Tt(st){const dt=getAttribution(),$t=["_ga","_gid","_fbp","_fbc"];return document.cookie.split(";").forEach(_t=>{const Mt=dt,[Ht,Gt]=_t.trim().split("=");$t.includes(Ht)&&!Mt[Ht]&&(Mt[Ht]=Gt)}),(await Ge.url("/checkouts").post({language:getLanguage(),...st,attribution:{...dt,...st.attribution},vendorId:$e.clientId})).json()}async function Lt(st,dt){return(await Ge.url(`/checkouts/${st}`).patch(dt)).json()}async function Ot(st){return(await Ge.url(`/checkouts/${st}`).get()).json()}async function jt(st){return(await Ge.url(`/paywalls/${st}`).get()).json()}async function Ft(){return(await Ge.url("/vendor").get()).json()}async function Bt(){return(await Ke.url("/vendors").get()).json()}async function Vt(st){return(await Ke.url(`/contracts/${encodeURIComponent(st.contractId)}/amendments`).post({amendmentType:st.amendmentType,discountCode:st.discountCode})).json()}async function Kt(st){return await Ke.url(`/amendments/${encodeURIComponent(st)}/confirm`).post(),!0}async function zt(){const st=await getTokenSilently(!1),dt=new URL(`${getBaseUrl("account",$e.environment)}/subscriptions/${$e.clientId}`);st&&(dt.hash=`#access_token=${st}`),window.location.href=dt.toString()}return{autoOnboardProduct:bt,cancelContract:ct,confirmAmendment:Kt,createAmendment:Vt,createCheckout:Tt,deleteTag:Pt,deleteTally:Rt,deleteUserMetadata:pt,generateLink:kt,getBill:ut,getBills:ft,getCheckout:Ot,getProxyContent:Ye,getContract:tt,getContracts:et,getEntitlement:Xe,getEntitlementAccess:Je,getEntitlements:We,getFulfillments:Qe,getPaywall:jt,getPaymentIssues:nt,getProfile:Ut,getProduct:At,getSubscriptions:at,getTally:yt,getTallies:It,getTags:Et,getTransaction:rt,getTransactions:ot,getUserMetadata:gt,hasAccess:Ze,isSpotifyLinked:it,linkSpotify:St,listUserMetadata:vt,openHostedAccountPage:zt,pushTally:mt,setTag:Nt,setUserMetadata:lt,unlinkSpotify:ht,updateCheckout:Lt,updateProfile:xt,getVendorSettings:Ft,listVendors:Bt}}const name="@sesamy/sesamy-js",version="1.35.4";function i$5($e,De,Fe,Be,He){for(De=De.split?De.split("."):De,Be=0;Be<De.length;Be++)$e=$e?$e[De[Be]]:He;return $e===He?Fe:$e}var e="undefined",o$4="object",g$1=function(){},b$4="any",m$1="*",j="__",F$2=typeof process<"u"?process:{};F$2.env&&F$2.env.NODE_ENV;var $$1=typeof document<"u";F$2.versions!=null&&F$2.versions.node!=null;typeof Deno<"u"&&Deno.core;$$1&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent!==void 0&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1($e,De){return De.charAt(0)[$e]()+De.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2($e){return Y$1($e)?U$1("null"):typeof $e=="object"?yn($e):Object.prototype.toString.call($e).slice(8,-1)}function R$1($e,De){De===void 0&&(De=!0);var Fe=J$2($e);return De?H$1(Fe):Fe}function V$1($e,De){return typeof De===$e}var W$1=V$1.bind(null,"function"),q$1=V$1.bind(null,"string"),I$2=V$1.bind(null,"undefined"),Q$1=V$1.bind(null,"boolean");V$1.bind(null,"symbol");function Y$1($e){return $e===null}function nn($e){return R$1($e)==="number"&&!isNaN($e)}function rn($e){return R$1($e)==="array"}function on($e){if(!un($e))return!1;for(var De=$e;Object.getPrototypeOf(De)!==null;)De=Object.getPrototypeOf(De);return Object.getPrototypeOf($e)===De}function un($e){return $e&&(typeof $e=="object"||$e!==null)}function yn($e){return W$1($e.constructor)?$e.constructor.name:null}function hn($e){return $e instanceof Error||q$1($e.message)&&$e.constructor&&nn($e.constructor.stackTraceLimit)}function On($e,De){if(typeof De!="object"||Y$1(De))return!1;if(De instanceof $e)return!0;var Fe=R$1(new $e(""));if(hn(De))for(;De;){if(R$1(De)===Fe)return!0;De=Object.getPrototypeOf(De)}return!1}On.bind(null,TypeError);On.bind(null,SyntaxError);function $n($e,De){var Fe=$e instanceof Element||$e instanceof HTMLDocument;return Fe&&De?Tn($e,De):Fe}function Tn($e,De){return De===void 0&&(De=""),$e&&$e.nodeName===De.toUpperCase()}function _n($e){var De=[].slice.call(arguments,1);return function(){return $e.apply(void 0,[].slice.call(arguments).concat(De))}}_n($n,"form");_n($n,"button");_n($n,"input");_n($n,"select");function Hn($e){return $e?rn($e)?$e:[$e]:[]}function n$1($e){try{return decodeURIComponent($e.replace(/\+/g," "))}catch{return null}}function o$3(){if($$1){var $e=navigator,De=$e.languages;return $e.userLanguage||(De&&De.length?De[0]:$e.language)}}function a$5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}}function s$1($e){return function(De){for(var Fe,Be=Object.create(null),He=/([^&=]+)=?([^&]*)/g;Fe=He.exec(De);){var Ke=n$1(Fe[1]),Ge=n$1(Fe[2]);Ke.substring(Ke.length-2)==="[]"?(Be[Ke=Ke.substring(0,Ke.length-2)]||(Be[Ke]=[])).push(Ge):Be[Ke]=Ge===""||Ge}for(var We in Be){var Ze=We.split("[");Ze.length>1&&(m(Be,Ze.map(function(Xe){return Xe.replace(/[?[\]\\ ]/g,"")}),Be[We]),delete Be[We])}return Be}(function(De){return $$1&&window.location.search.substring(1)}())}function m($e,De,Fe){for(var Be=De.length-1,He=0;He<Be;++He){var Ke=De[He];if(Ke==="__proto__"||Ke==="constructor")break;Ke in $e||($e[Ke]={}),$e=$e[Ke]}$e[De[Be]]=Fe}function y$1(){for(var $e="",De=0,Fe=4294967295*Math.random()|0;De++<36;){var Be="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[De-1],He=15&Fe;$e+=Be=="-"||Be=="4"?Be:(Be=="x"?He:3&He|8).toString(16),Fe=De%8==0?4294967295*Math.random()|0:Fe>>4}return $e}function b$3($e,De){var Fe,Be,He,Ke=null,Ge=0,We=function(){Ge=new Date,Ke=null,He=$e.apply(Fe,Be)};return function(){var Ze=new Date;Ge||(Ge=Ze);var Xe=De-(Ze-Ge);return Fe=this,Be=arguments,Xe<=0?(clearTimeout(Ke),Ke=null,Ge=Ze,He=$e.apply(Fe,Be)):Ke||(Ke=setTimeout(We,Xe)),He}}var l$2="global",o$2=j+"global"+j,n=typeof self===o$4&&self.self===self&&self||typeof global===o$4&&global.global===global&&global||void 0;function a$4($e){return n[o$2][$e]}function f$1($e,De){return n[o$2][$e]=De}function i$4($e){delete n[o$2][$e]}function u$3($e,De,Fe){var Be;try{if(b$2($e)){var He=window[$e];Be=He[De].bind(He)}}catch{}return Be||Fe}n[o$2]||(n[o$2]={});var c$3={};function b$2($e){if(typeof c$3[$e]!==e)return c$3[$e];try{var De=window[$e];De.setItem(e,e),De.removeItem(e)}catch{return c$3[$e]=!1}return c$3[$e]=!0}function v(){return v=Object.assign||function($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De];for(var Be in Fe)Object.prototype.hasOwnProperty.call(Fe,Be)&&($e[Be]=Fe[Be])}return $e},v.apply(this,arguments)}var y="function",b$1="undefined",I$1="@@redux/"+Math.random().toString(36),w=function(){return typeof Symbol===y&&Symbol.observable||"@@observable"}(),E$1=" != "+y;function P($e,De,Fe){var Be;if(typeof De===y&&typeof Fe===b$1&&(Fe=De,De=void 0),typeof Fe!==b$1){if(typeof Fe!==y)throw new Error("enhancer"+E$1);return Fe(P)($e,De)}if(typeof $e!==y)throw new Error("reducer"+E$1);var He=$e,Ke=De,Ge=[],We=Ge,Ze=!1;function Xe(){We===Ge&&(We=Ge.slice())}function Je(){return Ke}function Ye(et){if(typeof et!==y)throw new Error("Listener"+E$1);var tt=!0;return Xe(),We.push(et),function(){if(tt){tt=!1,Xe();var ct=We.indexOf(et);We.splice(ct,1)}}}function Qe(et){if(!on(et))throw new Error("Act != obj");if(typeof et.type===b$1)throw new Error("ActType "+b$1);if(Ze)throw new Error("Dispatch in reducer");try{Ze=!0,Ke=He(Ke,et)}finally{Ze=!1}for(var tt=Ge=We,ct=0;ct<tt.length;ct++)(0,tt[ct])();return et}return Qe({type:"@@redux/INIT"}),(Be={dispatch:Qe,subscribe:Ye,getState:Je,replaceReducer:function(et){if(typeof et!==y)throw new Error("next reducer"+E$1);He=et,Qe({type:"@@redux/INIT"})}})[w]=function(){var et,tt=Ye;return(et={subscribe:function(ct){if(typeof ct!="object")throw new TypeError("Observer != obj");function at(){ct.next&&ct.next(Je())}return at(),{unsubscribe:tt(at)}}})[w]=function(){return this},et},Be}function S($e,De){var Fe=De&&De.type;return"action "+(Fe&&Fe.toString()||"?")+"reducer "+$e+" returns "+b$1}function N$1(){var $e=[].slice.call(arguments);return $e.length===0?function(De){return De}:$e.length===1?$e[0]:$e.reduce(function(De,Fe){return function(){return De(Fe.apply(void 0,[].slice.call(arguments)))}})}function O$1(){var $e=arguments;return function(De){return function(Fe,Be,He){var Ke,Ge=De(Fe,Be,He),We=Ge.dispatch,Ze={getState:Ge.getState,dispatch:function(Xe){return We(Xe)}};return Ke=[].slice.call($e).map(function(Xe){return Xe(Ze)}),v({},Ge,{dispatch:We=N$1.apply(void 0,Ke)(Ge.dispatch)})}}}var A$1=j+"anon_id",_=j+"user_id",x$1=j+"user_traits",k$1="userId",T="anonymousId",z=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],M=["name","EVENTS","config","loaded"],q=z.reduce(function($e,De){return $e[De]=De,$e},{registerPluginType:function($e){return"registerPlugin:"+$e},pluginReadyType:function($e){return"ready:"+$e}}),U=/^utm_/,V=/^an_prop_/,L$1=/^an_trait_/;function C$1($e){var De=$e.storage.setItem;return function(Fe){return function(Be){return function(He){if(He.type===q.bootstrap){var Ke=He.params,Ge=He.user,We=He.persistedUser,Ze=He.initialUser,Xe=We.userId===Ge.userId;We.anonymousId!==Ge.anonymousId&&De(A$1,Ge.anonymousId),Xe||De(_,Ge.userId),Ze.traits&&De(x$1,v({},Xe&&We.traits?We.traits:{},Ze.traits));var Je=Object.keys(He.params);if(Je.length){var Ye=Ke.an_uid,Qe=Ke.an_event,et=Je.reduce(function(tt,ct){if(ct.match(U)||ct.match(/^(d|g)clid/)){var at=ct.replace(U,"");tt.campaign[at==="campaign"?"name":at]=Ke[ct]}return ct.match(V)&&(tt.props[ct.replace(V,"")]=Ke[ct]),ct.match(L$1)&&(tt.traits[ct.replace(L$1,"")]=Ke[ct]),tt},{campaign:{},props:{},traits:{}});Fe.dispatch(v({type:q.params,raw:Ke},et,Ye?{userId:Ye}:{})),Ye&&setTimeout(function(){return $e.identify(Ye,et.traits)},0),Qe&&setTimeout(function(){return $e.track(Qe,et.props)},0),Object.keys(et.campaign).length&&Fe.dispatch({type:q.campaign,campaign:et.campaign})}}return Be(He)}}}}function R($e){return function(De,Fe){if(De===void 0&&(De={}),Fe===void 0&&(Fe={}),Fe.type===q.setItemEnd){if(Fe.key===A$1)return v({},De,{anonymousId:Fe.value});if(Fe.key===_)return v({},De,{userId:Fe.value})}switch(Fe.type){case q.identify:return Object.assign({},De,{userId:Fe.userId,traits:v({},De.traits,Fe.traits)});case q.reset:return[_,A$1,x$1].forEach(function(Be){$e.removeItem(Be)}),Object.assign({},De,{userId:null,anonymousId:null,traits:{}});default:return De}}}function $($e){return{userId:$e.getItem(_),anonymousId:$e.getItem(A$1),traits:$e.getItem(x$1)}}var D=function($e){return j+"TEMP"+j+$e};function B($e){var De=$e.storage,Fe=De.setItem,Be=De.removeItem,He=De.getItem;return function(Ke){return function(Ge){return function(We){var Ze=We.userId,Xe=We.traits,Je=We.options;if(We.type===q.reset&&([_,x$1,A$1].forEach(function(et){Be(et)}),[k$1,T,"traits"].forEach(function(et){i$4(D(et))})),We.type===q.identify){He(A$1)||Fe(A$1,y$1());var Ye=He(_),Qe=He(x$1)||{};Ye&&Ye!==Ze&&Ke.dispatch({type:q.userIdChanged,old:{userId:Ye,traits:Qe},new:{userId:Ze,traits:Xe},options:Je}),Ze&&Fe(_,Ze),Xe&&Fe(x$1,v({},Qe,Xe))}return Ge(We)}}}}var X={};function J$1($e,De){X[$e]&&W$1(X[$e])&&(X[$e](De),delete X[$e])}function W($e,De,Fe){return new Promise(function(Be,He){return De()?Be($e):Fe<1?He(v({},$e,{queue:!0})):new Promise(function(Ke){return setTimeout(Ke,10)}).then(function(Ke){return W($e,De,Fe-10).then(Be,He)})})}function H($e){return{abort:$e}}function F$1($e,De,Fe){var Be={},He=De(),Ke=$e.getState(),Ge=Ke.plugins,We=Ke.queue,Ze=Ke.user;if(!Ke.context.offline&&We&&We.actions&&We.actions.length){var Xe=We.actions.reduce(function(Ye,Qe,et){return Ge[Qe.plugin].loaded?(Ye.process.push(Qe),Ye.processIndex.push(et)):(Ye.requeue.push(Qe),Ye.requeueIndex.push(et)),Ye},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(Xe.processIndex&&Xe.processIndex.length){Xe.processIndex.forEach(function(Ye){var Qe=We.actions[Ye],et=Qe.plugin,tt=Qe.payload.type,ct=He[et][tt];if(ct&&W$1(ct)){var at,ft=function(rt,lt){return rt===void 0&&(rt={}),lt===void 0&&(lt={}),[k$1,T].reduce(function(pt,gt){return rt.hasOwnProperty(gt)&&lt[gt]&&lt[gt]!==rt[gt]&&(pt[gt]=lt[gt]),pt},rt)}(Qe.payload,Ze),ut=Be[ft.meta.rid];if(!ut&&(at=ct({payload:ft,config:Ge[et].config,instance:Fe,abort:H}))&&on(at)&&at.abort)return void(Be[ft.meta.rid]=!0);if(!ut){var ot=tt+":"+et;$e.dispatch(v({},ft,{type:ot,_:{called:ot,from:"queueDrain"}}))}}});var Je=We.actions.filter(function(Ye,Qe){return!~Xe.processIndex.indexOf(Qe)});We.actions=Je}}}var G$1=function($e){var De=$e.data,Fe=$e.action,Be=$e.instance,He=$e.state,Ke=$e.allPlugins,Ge=$e.allMatches,We=$e.store,Ze=$e.EVENTS;try{var Xe=He.plugins,Je=He.context,Ye=Fe.type,Qe=Ye.match(K),et=De.exact.map(function(at){return at.pluginName});Qe&&(et=Ge.during.map(function(at){return at.pluginName}));var tt=function(at,ft){return function(ut,ot,rt){var lt=ot.config,pt=ot.name,gt=pt+"."+ut.type;rt&&(gt=rt.event);var vt=ut.type.match(K)?function(Et,Pt,Nt,yt,It){return function(Rt,mt){var At=yt?yt.name:Et,Ut=mt&&ae(mt)?mt:Nt;if(yt&&(!(Ut=mt&&ae(mt)?mt:[Et]).includes(Et)||Ut.length!==1))throw new Error("Method "+Pt+" can only abort "+Et+" plugin. "+JSON.stringify(Ut)+" input valid");return v({},It,{abort:{reason:Rt,plugins:Ut,caller:Pt,_:At}})}}(pt,gt,ft,rt,ut):function(Et,Pt){return function(){throw new Error(Et.type+" action not cancellable. Remove abort in "+Pt)}}(ut,gt);return{payload:ce(ut),instance:at,config:lt||{},abort:vt}}}(Be,et),ct=De.exact.reduce(function(at,ft){var ut=ft.pluginName,ot=ft.methodName,rt=!1;return ot.match(/^initialize/)||ot.match(/^reset/)||(rt=!Xe[ut].loaded),Je.offline&&ot.match(/^(page|track|identify)/)&&(rt=!0),at[""+ut]=rt,at},{});return Promise.resolve(De.exact.reduce(function(at,ft,ut){try{var ot=ft.pluginName;return Promise.resolve(at).then(function(rt){function lt(){return Promise.resolve(rt)}var pt=function(){if(De.namespaced&&De.namespaced[ot])return Promise.resolve(De.namespaced[ot].reduce(function(gt,vt,Et){try{return Promise.resolve(gt).then(function(Pt){return vt.method&&W$1(vt.method)?(function(Rt,mt){var At=ue(Rt);if(At&&At.name===mt){var Ut=ue(At.method);throw new Error([mt+" plugin is calling method "+Rt,"Plugins cant call self","Use "+At.method+" "+(Ut?"or "+Ut.method:"")+" in "+mt+" plugin insteadof "+Rt].join(`
34
+ **/var __webpack_require__={d:($e,De)=>{for(var Fe in De)__webpack_require__.o(De,Fe)&&!__webpack_require__.o($e,Fe)&&Object.defineProperty($e,Fe,{enumerable:!0,get:De[Fe]})},o:($e,De)=>Object.prototype.hasOwnProperty.call($e,De)},__webpack_exports__={};__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__,k:()=>detectIncognito});var __awaiter=function($e,De,Fe,Be){return new(Fe||(Fe=Promise))(function(He,Ke){function Ge(Xe){try{Ze(Be.next(Xe))}catch(Je){Ke(Je)}}function We(Xe){try{Ze(Be.throw(Xe))}catch(Je){Ke(Je)}}function Ze(Xe){var Je;Xe.done?He(Xe.value):(Je=Xe.value,Je instanceof Fe?Je:new Fe(function(Ye){Ye(Je)})).then(Ge,We)}Ze((Be=Be.apply($e,[])).next())})},__generator=function($e,De){var Fe,Be,He,Ke,Ge={label:0,sent:function(){if(1&He[0])throw He[1];return He[1]},trys:[],ops:[]};return Ke={next:We(0),throw:We(1),return:We(2)},typeof Symbol=="function"&&(Ke[Symbol.iterator]=function(){return this}),Ke;function We(Ze){return function(Xe){return function(Je){if(Fe)throw new TypeError("Generator is already executing.");for(;Ke&&(Ke=0,Je[0]&&(Ge=0)),Ge;)try{if(Fe=1,Be&&(He=2&Je[0]?Be.return:Je[0]?Be.throw||((He=Be.return)&&He.call(Be),0):Be.next)&&!(He=He.call(Be,Je[1])).done)return He;switch(Be=0,He&&(Je=[2&Je[0],He.value]),Je[0]){case 0:case 1:He=Je;break;case 4:return Ge.label++,{value:Je[1],done:!1};case 5:Ge.label++,Be=Je[1],Je=[0];continue;case 7:Je=Ge.ops.pop(),Ge.trys.pop();continue;default:if(He=Ge.trys,!((He=He.length>0&&He[He.length-1])||Je[0]!==6&&Je[0]!==2)){Ge=0;continue}if(Je[0]===3&&(!He||Je[1]>He[0]&&Je[1]<He[3])){Ge.label=Je[1];break}if(Je[0]===6&&Ge.label<He[1]){Ge.label=He[1],He=Je;break}if(He&&Ge.label<He[2]){Ge.label=He[2],Ge.ops.push(Je);break}He[2]&&Ge.ops.pop(),Ge.trys.pop();continue}Je=De.call($e,Ge)}catch(Ye){Je=[6,Ye],Be=0}finally{Fe=He=0}if(5&Je[0])throw Je[1];return{value:Je[0]?Je[1]:void 0,done:!0}}([Ze,Xe])}}};function detectIncognito(){return __awaiter(this,void 0,Promise,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,new Promise(function(resolve,reject){var browserName="Unknown";function __callback($e){resolve({isPrivate:$e,browserName})}function identifyChromium(){var $e=navigator.userAgent;return $e.match(/Chrome/)?navigator.brave!==void 0?"Brave":$e.match(/Edg/)?"Edge":$e.match(/OPR/)?"Opera":"Chrome":"Chromium"}function assertEvalToString($e){return $e===eval.toString().length}function feid(){var toFixedEngineID=0;try{eval("(-1).toFixed(-1);")}catch($e){toFixedEngineID=$e.message.length}return toFixedEngineID}function isSafari(){return feid()===44}function isChrome(){return feid()===51}function isFirefox(){return feid()===25}function isMSIE(){return navigator.msSaveBlob!==void 0&&assertEvalToString(39)}function newSafariTest(){var $e=String(Math.random());try{window.indexedDB.open($e,1).onupgradeneeded=function(De){var Fe,Be,He=(Fe=De.target)===null||Fe===void 0?void 0:Fe.result;try{He.createObjectStore("test",{autoIncrement:!0}).put(new Blob),__callback(!1)}catch(Ge){var Ke=Ge;return Ge instanceof Error&&(Ke=(Be=Ge.message)!==null&&Be!==void 0?Be:Ge),typeof Ke!="string"?void __callback(!1):void __callback(Ke.includes("BlobURLs are not yet supported"))}finally{He.close(),window.indexedDB.deleteDatabase($e)}}}catch{__callback(!1)}}function oldSafariTest(){var $e=window.openDatabase,De=window.localStorage;try{$e(null,null,null,null)}catch{return void __callback(!0)}try{De.setItem("test","1"),De.removeItem("test")}catch{return void __callback(!0)}__callback(!1)}function safariPrivateTest(){navigator.maxTouchPoints!==void 0?newSafariTest():oldSafariTest()}function getQuotaLimit(){var $e=window;return $e.performance!==void 0&&$e.performance.memory!==void 0&&$e.performance.memory.jsHeapSizeLimit!==void 0?performance.memory.jsHeapSizeLimit:1073741824}function storageQuotaChromePrivateTest(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function($e,De){__callback(Math.round(De/1048576)<2*Math.round(getQuotaLimit()/1048576))},function($e){reject(new Error("detectIncognito somehow failed to query storage quota: "+$e.message))})}function oldChromePrivateTest(){(0,window.webkitRequestFileSystem)(0,1,function(){__callback(!1)},function(){__callback(!0)})}function chromePrivateTest(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?storageQuotaChromePrivateTest():oldChromePrivateTest()}function firefoxPrivateTest(){__callback(navigator.serviceWorker===void 0)}function msiePrivateTest(){__callback(window.indexedDB===void 0)}function main(){isSafari()?(browserName="Safari",safariPrivateTest()):isChrome()?(browserName=identifyChromium(),chromePrivateTest()):isFirefox()?(browserName="Firefox",firefoxPrivateTest()):isMSIE()?(browserName="Internet Explorer",msiePrivateTest()):reject(new Error("detectIncognito cannot determine the browser"))}main()})];case 1:return[2,_a.sent()]}})})}typeof window<"u"&&(window.detectIncognito=detectIncognito);const __WEBPACK_DEFAULT_EXPORT__=detectIncognito;__webpack_exports__.A;var __webpack_exports__detectIncognito=__webpack_exports__.k;async function isIncognito(){try{const{isPrivate:$e}=await __webpack_exports__detectIncognito();return $e}catch{return!1}}function isBrowser(){return typeof window<"u"}const STORAGE_KEY="sesamyFlags";async function saveFlags($e){try{localStorage.setItem(STORAGE_KEY,JSON.stringify($e))}catch{log("Failed to save flags to localStorage")}}async function setFlag($e,De){const Fe=await listFlags();Fe[$e]=De,await saveFlags(Fe)}async function getFlag($e){return(await listFlags())[$e]}async function deleteFlag($e){const De=await listFlags();$e in De&&(delete De[$e],await saveFlags(De))}async function listFlags(){try{const $e=localStorage.getItem(STORAGE_KEY);return $e?JSON.parse($e):{}}catch{return{}}}let auth0Client,organization,initialized=!1,loginInProgress=!1;isBrowser()&&window.addEventListener("pageshow",()=>{loginInProgress=!1});const ACCESS_TOKEN_KEY="sesamyAccessToken",REFRESH_TOKEN_KEY="sesamyRefreshToken";async function waitForInit(){return initialized?!0:new Promise(($e,De)=>{const Fe=setTimeout(()=>{initialized?$e(!0):De(new Error("Initialization failed: Timeout"))},2e3);window.addEventListener(Events.AUTH_INITIALIZED,()=>{clearTimeout(Fe),$e(!0)})})}async function refreshLocalAccessToken($e){if(!$e)return null;const De=localStorage.getItem(REFRESH_TOKEN_KEY);if(!De)return log("No refresh token found in localstorage"),null;const Fe=new URLSearchParams;Fe.set("client_id",$e.iss),Fe.set("refresh_token",De),Fe.set("grant_type","refresh_token");const Be=new URL($e.iss);Be.pathname="/oauth/token",Be.searchParams.set("user_id",$e.sub);try{const He=await fetch(Be.href,{body:Fe.toString(),method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!He.ok)throw localStorage.removeItem(REFRESH_TOKEN_KEY),new Error("Renew token failed");const Ke=await He.json();return localStorage.setItem(REFRESH_TOKEN_KEY,Ke.refresh_token),localStorage.setItem(ACCESS_TOKEN_KEY,Ke.access_token),Ke.access_token}catch{logout()}}async function getLocalStorageAccessToken(){const $e=localStorage.getItem(ACCESS_TOKEN_KEY);if(!$e)return null;const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3){const Fe=await refreshLocalAccessToken(De);if(Fe)return Fe;localStorage.removeItem(ACCESS_TOKEN_KEY)}return $e}function getTopLevelDomain($e){try{const De=new URL($e).hostname,Fe=De.split(".");return Fe.length>1?Fe.slice(-2).join("."):De}catch{return null}}async function init$3($e){if($e.enabled===!1)return;organization=$e.organization;const Fe=await getFlag("newAuth")&&$e.domain?$e.domain:getBaseUrl("token",$e.environment),Be={domain:Fe,clientId:$e.clientId,useCookiesForTransactions:!0};if(getTopLevelDomain(window.location.href)!==getTopLevelDomain(Fe)&&(Be.cacheLocation="localstorage",Be.useRefreshTokens=!0),auth0Client=await oe$1(Be),window.location.search.includes("code=")){log("Code found in URL, handling redirect");try{const Ge=await auth0Client.handleRedirectCallback();log(`Login result: ${JSON.stringify(Ge)}`);const We=await auth0Client.getUser();if(!We)throw log("No user found"),new Error("No user found");log(`User found ${JSON.stringify(We)}`),triggerEvent(Events.AUTHENTICATED,We),log("Rewrite url")}catch(Ge){alert("There was an error logging in"),console.error(Ge)}const He=new URL(location.href),Ke=He.searchParams;Ke.delete("code"),Ke.delete("state"),He.search=Ke.toString(),window.history.replaceState({},document.title,He.toString())}initialized=!0,triggerEvent(Events.AUTH_INITIALIZED,{})}async function isAuthenticated(){return await waitForInit(),await getLocalStorageAccessToken()?!0:auth0Client?auth0Client.isAuthenticated():!1}async function getUser(){return await waitForInit(),await getLocalStorageAccessToken()?(log("Using local user"),{sub:"local",name:"Local User"}):auth0Client?auth0Client.getUser():null}async function loginWithRedirect($e){if(loginInProgress){log("Login already in progress");return}if(loginInProgress=!0,await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),!auth0Client)throw new Error("Auth0 client not initialized");const De=($e==null?void 0:$e.authorizationParams)||{};return await isIncognito()&&navigator.userAgent.includes("Safari")&&navigator.userAgent.includes("iPhone")&&sessionStorage.setItem(SESMAY_CONTENT_RELOAD_KEY,"true"),auth0Client.loginWithRedirect({...$e,authorizationParams:{organization,redirect_uri:window.location.href,ui_locales:getLanguage(),...De}})}async function getTokenSilently($e=!0,De=!1){await waitForInit();const Fe=await getLocalStorageAccessToken();if(Fe)return Fe;try{if(!auth0Client)return log("Auth client not initialized"),null;let Be=await auth0Client.getTokenSilently();const He=getPayloadFromJwt(Be);return De&&(He!=null&&He.exp)&&He.exp+3600<new Date().getTime()/1e3&&(Be=await auth0Client.getTokenSilently({cacheMode:De?"off":"on"})),Be}catch(Be){const He=Be;if(log(`Failed to get token silently: ${He.message}`),He.message==="Invalid refresh token"&&await logout(),$e)throw Be;return null}}async function logout($e={}){if(await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),triggerEvent(Events.LOGOUT,{}),!!auth0Client)return log(`Logout with options: ${JSON.stringify($e)}`),auth0Client.logout({...$e,logoutParams:{returnTo:window.location.href,...$e.logoutParams}})}function getPayloadFromJwt($e){const De=$e.split(".");if(De.length!==3)return null;const Be=De[1].replace(/-/g,"+").replace(/_/g,"/"),He=decodeURIComponent(atob(Be).split("").map(function(Ke){return"%"+("00"+Ke.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(He)}async function setToken($e){const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3)throw new Error("Invalid token");log("Set token"),localStorage.setItem(ACCESS_TOKEN_KEY,$e),triggerEvent(Events.AUTHENTICATED,De)}const defaultSkip=($e,De)=>De.skipDedupe||De.method!=="GET",defaultKey=($e,De)=>De.method+"@"+$e,defaultResolver=$e=>$e.clone(),dedupe=({skip:$e=defaultSkip,key:De=defaultKey,resolver:Fe=defaultResolver}={})=>{const Be=new Map;return He=>(Ke,Ge)=>{if($e(Ke,Ge))return He(Ke,Ge);const We=De(Ke,Ge);if(!Be.has(We))Be.set(We,[]);else return new Promise((Ze,Xe)=>{Be.get(We).push([Ze,Xe])});try{return He(Ke,Ge).then(Ze=>(Be.get(We).forEach(([Xe])=>Xe(Fe(Ze))),Be.delete(We),Ze)).catch(Ze=>{throw Be.get(We).forEach(([,Xe])=>Xe(Ze)),Be.delete(We),Ze})}catch(Ze){return Be.delete(We),Promise.reject(Ze)}}},defaultDelayRamp=($e,De)=>$e*De,defaultUntil=$e=>$e&&$e.ok,retry=({delayTimer:$e=500,delayRamp:De=defaultDelayRamp,maxAttempts:Fe=10,until:Be=defaultUntil,onRetry:He=null,retryOnNetworkError:Ke=!1,resolveWithLatestResponse:Ge=!1,skip:We}={})=>Ze=>(Xe,Je)=>{let Ye=0;if(We&&We(Xe,Je))return Ze(Xe,Je);const Qe=(et,tt)=>Promise.resolve(Be(et,tt)).then(ct=>ct?et&&Ge?et:tt?Promise.reject(tt):et:(Ye++,!Fe||Ye<=Fe?new Promise(at=>{const ft=De($e,Ye);setTimeout(()=>{typeof He=="function"?Promise.resolve(He({response:et,error:tt,url:Xe,options:Je})).then((ut={})=>{var ot,rt;at(Ze((ot=ut&&ut.url)!==null&&ot!==void 0?ot:Xe,(rt=ut&&ut.options)!==null&&rt!==void 0?rt:Je))}):at(Ze(Xe,Je))},ft)}).then(Qe).catch(at=>{if(!Ke)throw at;return Qe(null,at)}):et&&Ge?et:Promise.reject(tt||new Error("Number of attempts exceeded."))));return Ze(Xe,Je).then(Qe).catch(et=>{if(!Ke)throw et;return Qe(null,et)})},JSON_MIME="application/json",CONTENT_TYPE_HEADER="Content-Type",FETCH_ERROR=Symbol(),CATCHER_FALLBACK=Symbol();function extractContentType($e={}){var De;return(De=Object.entries($e).find(([Fe])=>Fe.toLowerCase()===CONTENT_TYPE_HEADER.toLowerCase()))===null||De===void 0?void 0:De[1]}function isLikelyJsonMime($e){return/^application\/.*json.*/.test($e)}const mix=function($e,De,Fe=!1){return Object.entries(De).reduce((Be,[He,Ke])=>{const Ge=$e[He];return Array.isArray(Ge)&&Array.isArray(Ke)?Be[He]=Fe?[...Ge,...Ke]:Ke:typeof Ge=="object"&&typeof Ke=="object"?Be[He]=mix(Ge,Ke,Fe):Be[He]=Ke,Be},{...$e})},config={options:{},errorType:"text",polyfills:{},polyfill($e,De=!0,Fe=!1,...Be){const He=this.polyfills[$e]||(typeof self<"u"?self[$e]:null)||(typeof global<"u"?global[$e]:null);if(De&&!He)throw new Error($e+" is not defined");return Fe&&He?new He(...Be):He}};function setOptions($e,De=!1){config.options=De?$e:mix(config.options,$e)}function setPolyfills($e,De=!1){config.polyfills=De?$e:mix(config.polyfills,$e)}function setErrorType($e){config.errorType=$e}const middlewareHelper=$e=>De=>$e.reduceRight((Fe,Be)=>Be(Fe),De)||De;class WretchError extends Error{}const resolver=$e=>{const De=Object.create(null);$e=$e._addons.reduce((ot,rt)=>rt.beforeRequest&&rt.beforeRequest(ot,$e._options,De)||ot,$e);const{_url:Fe,_options:Be,_config:He,_catchers:Ke,_resolvers:Ge,_middlewares:We,_addons:Ze}=$e,Xe=new Map(Ke),Je=mix(He.options,Be);let Ye=Fe;const Qe=middlewareHelper(We)((ot,rt)=>(Ye=ot,He.polyfill("fetch")(ot,rt)))(Fe,Je),et=new Error,tt=Qe.catch(ot=>{throw{[FETCH_ERROR]:ot}}).then(ot=>{var rt;if(!ot.ok){const lt=new WretchError;if(lt.cause=et,lt.stack=lt.stack+`
35
+ CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque")throw lt;const pt=He.errorType==="json"||((rt=ot.headers.get("Content-Type"))===null||rt===void 0?void 0:rt.split(";")[0])==="application/json";return(He.errorType?pt?ot.text():ot[He.errorType]():Promise.resolve(ot.body)).then(vt=>{throw lt.message=typeof vt=="string"?vt:ot.statusText,vt&&(pt&&typeof vt=="string"?(lt.text=vt,lt.json=JSON.parse(vt)):lt[He.errorType]=vt),lt})}return ot}),ct=ot=>ot.catch(rt=>{const lt=Object.prototype.hasOwnProperty.call(rt,FETCH_ERROR),pt=lt?rt[FETCH_ERROR]:rt,gt=(pt==null?void 0:pt.status)&&Xe.get(pt.status)||Xe.get(pt==null?void 0:pt.name)||lt&&Xe.has(FETCH_ERROR)&&Xe.get(FETCH_ERROR);if(gt)return gt(pt,$e);const vt=Xe.get(CATCHER_FALLBACK);if(vt)return vt(pt,$e);throw pt}),at=ot=>rt=>ct(ot?tt.then(lt=>lt&&lt[ot]()).then(lt=>rt?rt(lt):lt):tt.then(lt=>rt?rt(lt):lt)),ft={_wretchReq:$e,_fetchReq:Qe,_sharedState:De,res:at(null),json:at("json"),blob:at("blob"),formData:at("formData"),arrayBuffer:at("arrayBuffer"),text:at("text"),error(ot,rt){return Xe.set(ot,rt),this},badRequest(ot){return this.error(400,ot)},unauthorized(ot){return this.error(401,ot)},forbidden(ot){return this.error(403,ot)},notFound(ot){return this.error(404,ot)},timeout(ot){return this.error(408,ot)},internalError(ot){return this.error(500,ot)},fetchError(ot){return this.error(FETCH_ERROR,ot)}},ut=Ze.reduce((ot,rt)=>({...ot,...typeof rt.resolver=="function"?rt.resolver(ot):rt.resolver}),ft);return Ge.reduce((ot,rt)=>rt(ot,$e),ut)},core={_url:"",_options:{},_config:config,_catchers:new Map,_resolvers:[],_deferred:[],_middlewares:[],_addons:[],addon($e){return{...this,_addons:[...this._addons,$e],...$e.wretch}},errorType($e){return{...this,_config:{...this._config,errorType:$e}}},polyfills($e,De=!1){return{...this,_config:{...this._config,polyfills:De?$e:mix(this._config.polyfills,$e)}}},url($e,De=!1){if(De)return{...this,_url:$e};const Fe=this._url.split("?");return{...this,_url:Fe.length>1?Fe[0]+$e+"?"+Fe[1]:this._url+$e}},options($e,De=!1){return{...this,_options:De?$e:mix(this._options,$e)}},headers($e){const De=$e?Array.isArray($e)?Object.fromEntries($e):"entries"in $e?Object.fromEntries($e.entries()):$e:{};return{...this,_options:mix(this._options,{headers:De})}},accept($e){return this.headers({Accept:$e})},content($e){return this.headers({[CONTENT_TYPE_HEADER]:$e})},auth($e){return this.headers({Authorization:$e})},catcher($e,De){const Fe=new Map(this._catchers);return Fe.set($e,De),{...this,_catchers:Fe}},catcherFallback($e){return this.catcher(CATCHER_FALLBACK,$e)},resolve($e,De=!1){return{...this,_resolvers:De?[$e]:[...this._resolvers,$e]}},defer($e,De=!1){return{...this,_deferred:De?[$e]:[...this._deferred,$e]}},middlewares($e,De=!1){return{...this,_middlewares:De?$e:[...this._middlewares,...$e]}},fetch($e=this._options.method,De="",Fe=null){let Be=this.url(De).options({method:$e});const He=extractContentType(Be._options.headers),Ke=this._config.polyfill("FormData",!1),Ge=typeof Fe=="object"&&!(Ke&&Fe instanceof Ke)&&(!Be._options.headers||!He||isLikelyJsonMime(He));return Be=Fe?Ge?Be.json(Fe,He):Be.body(Fe):Be,resolver(Be._deferred.reduce((We,Ze)=>Ze(We,We._url,We._options),Be))},get($e=""){return this.fetch("GET",$e)},delete($e=""){return this.fetch("DELETE",$e)},put($e,De=""){return this.fetch("PUT",De,$e)},post($e,De=""){return this.fetch("POST",De,$e)},patch($e,De=""){return this.fetch("PATCH",De,$e)},head($e=""){return this.fetch("HEAD",$e)},opts($e=""){return this.fetch("OPTIONS",$e)},body($e){return{...this,_options:{...this._options,body:$e}}},json($e,De){const Fe=extractContentType(this._options.headers);return this.content(De||isLikelyJsonMime(Fe)&&Fe||JSON_MIME).body(JSON.stringify($e))}};function factory($e="",De={}){return{...core,_url:$e,_options:De}}factory.default=factory;factory.options=setOptions;factory.errorType=setErrorType;factory.polyfills=setPolyfills;factory.WretchError=WretchError;function clearCache(){return sessionStorage.removeItem(CACHE_TIMESTAMP_KEY),log("Cache cleared"),triggerEvent(Events.CLEAR_CACHE,{}),"Cache cleared"}function isValidHttpUrl($e){let De;try{De=new URL($e)}catch{return!1}return De.protocol==="http:"||De.protocol==="https:"}function decodeItemSrc($e,De){if(isValidHttpUrl($e))return{itemSrc:$e};const[Fe,Be,He]=$e.split(":");return{sku:`${Fe}:${Be}`,purchaseOption:De||He}}function removeTrailingSlash($e){return $e.endsWith("/")?$e.slice(0,-1):$e}function compareUrlWithoutHash($e,De){if(!isValidHttpUrl($e)||!isValidHttpUrl(De))return!1;const Fe=new URL($e),Be=new URL(De);return Fe.origin===Be.origin&&removeTrailingSlash(Fe.pathname)===removeTrailingSlash(Be.pathname)}function generateCheckoutLink($e,De,Fe){const Be=new URL(`${getBaseUrl("checkout3",$e.environment)}`);if(De.language&&Be.searchParams.set("lang",De.language),De.sku)Be.searchParams.set("sku",De.sku),De.purchaseOptionId&&Be.searchParams.set("po-id",De.purchaseOptionId);else if(De.itemSrc){const{sku:We,purchaseOption:Ze,itemSrc:Xe}=decodeItemSrc(De.itemSrc,De.purchaseOptionId);Xe&&Be.searchParams.set("url",Xe),We&&Be.searchParams.set("sku",We),Ze&&Be.searchParams.set("po-id",Ze)}De.email&&Be.searchParams.set("email",De.email),De.business&&Be.searchParams.set("business","true"),De.currency&&Be.searchParams.set("currency",De.currency),De.price&&Be.searchParams.set("price",De.price.toString()),De.discountCode&&Be.searchParams.set("discount-code",De.discountCode),De.attributionItemSrc?Be.searchParams.set("itemSrc",De.attributionItemSrc):Fe.itemSrc&&Be.searchParams.set("itemSrc",Fe.itemSrc),De.attributionPublisherContentId?Be.searchParams.set("publisherContentId",De.attributionPublisherContentId):Fe.publisherContentId&&Be.searchParams.set("publisherContentId",Fe.publisherContentId),De.utmSource?Be.searchParams.set("utm_source",De.utmSource):Fe.utmSource&&Be.searchParams.set("utm_source",Fe.utmSource),De.utmMedium?Be.searchParams.set("utm_medium",De.utmMedium):Fe.utmMedium&&Be.searchParams.set("utm_medium",Fe.utmMedium),De.utmCampaign?Be.searchParams.set("utm_campaign",De.utmCampaign):Fe.utmCampaign&&Be.searchParams.set("utm_campaign",Fe.utmCampaign),De.utmTerm?Be.searchParams.set("utm_term",De.utmTerm):Fe.utmTerm&&Be.searchParams.set("utm_term",Fe.utmTerm),De.utmContent?Be.searchParams.set("utm_content",De.utmContent):Fe.utmContent&&Be.searchParams.set("utm_content",Fe.utmContent);const He=["_ga","_gid","_fbp","_fbc"];document.cookie.split(";").map(We=>{const[Ze,Xe]=We.trim().split("=");return{key:Ze,value:Xe}}).filter(We=>He.some(Ze=>Ze===We.key)).forEach(We=>{Be.searchParams.append(We.key,We.value)});const Ge=new URL(De.redirectUrl||window.location.href);return Ge.searchParams.set("force-refetch-entitlements","true"),De.itemSrc&&Ge.searchParams.set("sesamy-purchase",De.itemSrc),Be.searchParams.set("redirect-url",Ge.toString()),De.paymentMethodsFilter&&Be.searchParams.set("paymentmethods-filter",De.paymentMethodsFilter.flatMap(({provider:We,methods:Ze})=>Ze?Ze.map(Xe=>`${We}|${Xe}`):We).join(",")),Be}const SIGNED_URL_KEY="sesamySignedURLs";function getSignedLinks(){const $e=sessionStorage.getItem(SIGNED_URL_KEY);return $e?JSON.parse($e):[]}function addSignedLink($e){const De=getSignedLinks();De.push($e),log(`Adding signed URL: ${$e}`),sessionStorage.setItem(SIGNED_URL_KEY,JSON.stringify(De))}function removeUndefinedValues($e){const De={};return Object.keys($e).forEach(Fe=>{const Be=$e[Fe];Be!=null&&(De[Fe]=Be.toString())}),De}const ATTRIBUTION_KEY="sesamyAttribution";function parseFromLocalStorage($e){const De=localStorage.getItem($e);if(!De)return null;try{return JSON.parse(De).value}catch{return console.error(`Failed to parse ${$e}`),null}}function resetUtmTags($e){return Object.keys($e).find(De=>De.startsWith("utm_"))?{utmSource:void 0,utmMedium:void 0,utmCampaign:void 0,...$e}:$e}function getAttribution(){return parseFromLocalStorage(ATTRIBUTION_KEY)||{}}function setAttribution($e){if($e===null)localStorage.removeItem(ATTRIBUTION_KEY);else{log(`Setting attribution ${JSON.stringify($e)}`);const De=getAttribution()??{},Fe=removeUndefinedValues({...De,...resetUtmTags($e)});localStorage.setItem(ATTRIBUTION_KEY,JSON.stringify({value:Fe}))}}function createApi($e){const De=getBaseUrl("api2",$e.environment),Fe=st=>async(dt,$t)=>{let Ct=sessionStorage.getItem(CACHE_TIMESTAMP_KEY);Ct||(Ct=Date.now().toString(),sessionStorage.setItem(CACHE_TIMESTAMP_KEY,Ct));const _t={...$t,headers:{...$t.headers,"Cache-Timestamp":Ct}};return st(dt,_t)},Be=(st=!0)=>dt=>async($t,Ct)=>{let _t=null;if(_t=await getTokenSilently(st),!_t){if(st)throw new Error("No access token available");return dt($t,Ct)}const Mt={...Ct,headers:{...Ct.headers,..._t?{Authorization:`Bearer ${_t}`}:{}}};return dt($t,Mt)},He=st=>(dt,$t)=>{if($t.headers.Authorization)return st(dt,$t);const Ct=localStorage.getItem("__anon_id"),_t=btoa(`${$e.clientId}|${Ct}:`),Mt={...$t,headers:{...$t.headers,Authorization:`Basic ${_t}`}};return st(dt,Mt)},Ke=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(),dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]),Ge=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(!1),He,dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]);async function We(st={}){const{waitForEntitlementAfter:dt,includeSignedLinks:$t=!0}=st,Ct=dt?`?wait-for-entitlement-after=${dt.toISOString()}`:"",_t=await isAuthenticated()?await Ke.get(`/entitlements${Ct}`).json():[];return $t&&_t.push(...getSignedLinks()),_t}async function Ze(st,dt=[]){const $t=await We();return $t==null?void 0:$t.find(_t=>{const{sku:Mt,purchaseOption:Ht}=decodeItemSrc(st);let Gt="sku"in _t&&Mt===_t.sku;Gt&&Ht&&"purchaseOptionId"in _t&&(Gt=Ht===_t.purchaseOptionId);const tr=compareUrlWithoutHash(st,_t.url),rr=dt.some(nr=>compareUrlWithoutHash(nr,_t.url));return Gt||tr||rr})}async function Xe(st){const dt=await Ke.get("/entitlements").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function Je(st){return Ke.get(`/entitlements/${encodeURIComponent(st)}/access`).json()}async function Ye(st,dt,$t){const Ct=new URL(getBaseUrl("api2",$e.environment));return Ct.pathname="/proxy",Ct.searchParams.set("url",dt),$t&&Ct.searchParams.set("selector",$t),factory(Ct.toString()).headers({Authorization:`Bearer ${st}`}).get().text()}async function Qe(st){return await isAuthenticated()?await Ke.get(`/fulfillments?sku=${encodeURIComponent(st)}`).json():[]}async function et(){return Ke.get("/contracts").json()}async function tt(st){const dt=await Ke.get("/contracts").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ct(st){const dt=await Ke.post({},`/contracts/${encodeURIComponent(st)}/cancel`).res();return clearCache(),dt.ok}async function at(){return console.warn("getSubscriptions is deprecated, use getContracts instead"),Ke.get("/subscriptions").json()}async function ft(){return Ke.get("/bills").json()}async function ut(st){const dt=await Ke.get("/bills").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ot(){return Ke.get("/transactions").json()}async function rt(st){const dt=await Ke.get("/transactions").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function lt(st,dt){const $t=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).put(dt).json();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),$t}async function pt(st){const dt=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function gt(st){return(await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).get().json())[st]}async function vt(){return await Ke.url("/user-metadata").get().json()}async function Et(){return await Ke.url("/tags").get().json()}async function Pt(st){const dt=await Ke.url(`/tags/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function Nt(st){const dt=await Ke.url("/tags").post(encodeURIComponent(st)).res();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),dt.ok}async function yt(st){return(await Ge.url("/tallies").get().json())[st]}async function It(){return await Ge.url("/tallies").get().json()}async function Rt(st){const dt=await Ge.url(`/tallies/${st}`).delete().res();return clearCache(),dt.ok}async function mt(st,dt){return await Ge.url(`/tallies/${encodeURIComponent(st)}/push`).post(dt).json()}async function At(st){return await Ke.url(`/products/${encodeURIComponent(st)}`).get().json()}async function Ut(){return await getTokenSilently(!1)?await Ke.url("/profile").get().json():null}async function xt(st){const dt=await Ke.url("/profile").patch(st).res();return clearCache(),dt.ok}async function nt(){return await Ke.url("/payment-issues").get().json()}async function it(){return(await Ke.url("/profile/spotify-link").get().json()).isSpotifyLinked}async function ht(){return(await Ke.url("/profile/unlink-spotify").post().res()).ok}async function St(st){const dt=await getTokenSilently(!1);if(!dt)throw new Error("No access token available");const $t=new URL(`${getBaseUrl("access-sync",$e.environment)}/spotify/sesamy-callback`);$t.searchParams.set("access_token",dt),$t.searchParams.set("state",st),window.location.href=$t.toString()}async function bt(st){const dt=await Ke.url(`/products/${encodeURIComponent(st)}/auto-onboard`).post().json();return dt.length&&clearCache(),dt}async function wt(st,dt=3600){const{shortlink:$t}=await factory(SHORTLINK_URL).post({url:st,ttl:dt}).json();return $t}async function kt(st){const dt=await getTokenSilently(!1,!0);let $t;const Ct=st.language||getLanguage(),_t=getAttribution();switch(st.target){case"account":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-payment":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/change-payment-method`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-plan":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/edit-plan`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"consume":$t=new URL(`${getBaseUrl("consume",$e.environment)}/${encodeURIComponent(st.language||Ct)}/@${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.sku)}`),st.episodeId?$t.href+=`/${st.episodeId}`:$t.href+="/listen",$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"checkout":$t=generateCheckoutLink($e,{language:Ct,...st},_t);break;default:throw new Error("Invalid target")}return dt&&($t.hash=`#access_token=${dt}`),st.shorten?wt($t.href,st.ttl):$t.href}async function Tt(st){const dt=getAttribution(),$t=["_ga","_gid","_fbp","_fbc"];return document.cookie.split(";").forEach(_t=>{const Mt=dt,[Ht,Gt]=_t.trim().split("=");$t.includes(Ht)&&!Mt[Ht]&&(Mt[Ht]=Gt)}),(await Ge.url("/checkouts").post({language:getLanguage(),...st,attribution:{...dt,...st.attribution},vendorId:$e.clientId})).json()}async function Lt(st,dt){return(await Ge.url(`/checkouts/${st}`).patch(dt)).json()}async function Ot(st){return(await Ge.url(`/checkouts/${st}`).get()).json()}async function jt(st){return(await Ge.url(`/paywalls/${st}`).get()).json()}async function Ft(){return(await Ge.url("/vendor").get()).json()}async function Bt(){return(await Ke.url("/vendors").get()).json()}async function Vt(st){return(await Ke.url(`/contracts/${encodeURIComponent(st.contractId)}/amendments`).post({amendmentType:st.amendmentType,discountCode:st.discountCode})).json()}async function Kt(st){return await Ke.url(`/amendments/${encodeURIComponent(st)}/confirm`).post(),!0}async function zt(){const st=await getTokenSilently(!1),dt=new URL(`${getBaseUrl("account",$e.environment)}/subscriptions/${$e.clientId}`);st&&(dt.hash=`#access_token=${st}`),window.location.href=dt.toString()}return{autoOnboardProduct:bt,cancelContract:ct,confirmAmendment:Kt,createAmendment:Vt,createCheckout:Tt,deleteTag:Pt,deleteTally:Rt,deleteUserMetadata:pt,generateLink:kt,getBill:ut,getBills:ft,getCheckout:Ot,getProxyContent:Ye,getContract:tt,getContracts:et,getEntitlement:Xe,getEntitlementAccess:Je,getEntitlements:We,getFulfillments:Qe,getPaywall:jt,getPaymentIssues:nt,getProfile:Ut,getProduct:At,getSubscriptions:at,getTally:yt,getTallies:It,getTags:Et,getTransaction:rt,getTransactions:ot,getUserMetadata:gt,hasAccess:Ze,isSpotifyLinked:it,linkSpotify:St,listUserMetadata:vt,openHostedAccountPage:zt,pushTally:mt,setTag:Nt,setUserMetadata:lt,unlinkSpotify:ht,updateCheckout:Lt,updateProfile:xt,getVendorSettings:Ft,listVendors:Bt}}const name="@sesamy/sesamy-js",version="1.35.6";function i$5($e,De,Fe,Be,He){for(De=De.split?De.split("."):De,Be=0;Be<De.length;Be++)$e=$e?$e[De[Be]]:He;return $e===He?Fe:$e}var e="undefined",o$4="object",g$1=function(){},b$4="any",m$1="*",j="__",F$2=typeof process<"u"?process:{};F$2.env&&F$2.env.NODE_ENV;var $$1=typeof document<"u";F$2.versions!=null&&F$2.versions.node!=null;typeof Deno<"u"&&Deno.core;$$1&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent!==void 0&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1($e,De){return De.charAt(0)[$e]()+De.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2($e){return Y$1($e)?U$1("null"):typeof $e=="object"?yn($e):Object.prototype.toString.call($e).slice(8,-1)}function R$1($e,De){De===void 0&&(De=!0);var Fe=J$2($e);return De?H$1(Fe):Fe}function V$1($e,De){return typeof De===$e}var W$1=V$1.bind(null,"function"),q$1=V$1.bind(null,"string"),I$2=V$1.bind(null,"undefined"),Q$1=V$1.bind(null,"boolean");V$1.bind(null,"symbol");function Y$1($e){return $e===null}function nn($e){return R$1($e)==="number"&&!isNaN($e)}function rn($e){return R$1($e)==="array"}function on($e){if(!un($e))return!1;for(var De=$e;Object.getPrototypeOf(De)!==null;)De=Object.getPrototypeOf(De);return Object.getPrototypeOf($e)===De}function un($e){return $e&&(typeof $e=="object"||$e!==null)}function yn($e){return W$1($e.constructor)?$e.constructor.name:null}function hn($e){return $e instanceof Error||q$1($e.message)&&$e.constructor&&nn($e.constructor.stackTraceLimit)}function On($e,De){if(typeof De!="object"||Y$1(De))return!1;if(De instanceof $e)return!0;var Fe=R$1(new $e(""));if(hn(De))for(;De;){if(R$1(De)===Fe)return!0;De=Object.getPrototypeOf(De)}return!1}On.bind(null,TypeError);On.bind(null,SyntaxError);function $n($e,De){var Fe=$e instanceof Element||$e instanceof HTMLDocument;return Fe&&De?Tn($e,De):Fe}function Tn($e,De){return De===void 0&&(De=""),$e&&$e.nodeName===De.toUpperCase()}function _n($e){var De=[].slice.call(arguments,1);return function(){return $e.apply(void 0,[].slice.call(arguments).concat(De))}}_n($n,"form");_n($n,"button");_n($n,"input");_n($n,"select");function Hn($e){return $e?rn($e)?$e:[$e]:[]}function n$1($e){try{return decodeURIComponent($e.replace(/\+/g," "))}catch{return null}}function o$3(){if($$1){var $e=navigator,De=$e.languages;return $e.userLanguage||(De&&De.length?De[0]:$e.language)}}function a$5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}}function s$1($e){return function(De){for(var Fe,Be=Object.create(null),He=/([^&=]+)=?([^&]*)/g;Fe=He.exec(De);){var Ke=n$1(Fe[1]),Ge=n$1(Fe[2]);Ke.substring(Ke.length-2)==="[]"?(Be[Ke=Ke.substring(0,Ke.length-2)]||(Be[Ke]=[])).push(Ge):Be[Ke]=Ge===""||Ge}for(var We in Be){var Ze=We.split("[");Ze.length>1&&(m(Be,Ze.map(function(Xe){return Xe.replace(/[?[\]\\ ]/g,"")}),Be[We]),delete Be[We])}return Be}(function(De){return $$1&&window.location.search.substring(1)}())}function m($e,De,Fe){for(var Be=De.length-1,He=0;He<Be;++He){var Ke=De[He];if(Ke==="__proto__"||Ke==="constructor")break;Ke in $e||($e[Ke]={}),$e=$e[Ke]}$e[De[Be]]=Fe}function y$1(){for(var $e="",De=0,Fe=4294967295*Math.random()|0;De++<36;){var Be="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[De-1],He=15&Fe;$e+=Be=="-"||Be=="4"?Be:(Be=="x"?He:3&He|8).toString(16),Fe=De%8==0?4294967295*Math.random()|0:Fe>>4}return $e}function b$3($e,De){var Fe,Be,He,Ke=null,Ge=0,We=function(){Ge=new Date,Ke=null,He=$e.apply(Fe,Be)};return function(){var Ze=new Date;Ge||(Ge=Ze);var Xe=De-(Ze-Ge);return Fe=this,Be=arguments,Xe<=0?(clearTimeout(Ke),Ke=null,Ge=Ze,He=$e.apply(Fe,Be)):Ke||(Ke=setTimeout(We,Xe)),He}}var l$2="global",o$2=j+"global"+j,n=typeof self===o$4&&self.self===self&&self||typeof global===o$4&&global.global===global&&global||void 0;function a$4($e){return n[o$2][$e]}function f$1($e,De){return n[o$2][$e]=De}function i$4($e){delete n[o$2][$e]}function u$3($e,De,Fe){var Be;try{if(b$2($e)){var He=window[$e];Be=He[De].bind(He)}}catch{}return Be||Fe}n[o$2]||(n[o$2]={});var c$3={};function b$2($e){if(typeof c$3[$e]!==e)return c$3[$e];try{var De=window[$e];De.setItem(e,e),De.removeItem(e)}catch{return c$3[$e]=!1}return c$3[$e]=!0}function v(){return v=Object.assign||function($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De];for(var Be in Fe)Object.prototype.hasOwnProperty.call(Fe,Be)&&($e[Be]=Fe[Be])}return $e},v.apply(this,arguments)}var y="function",b$1="undefined",I$1="@@redux/"+Math.random().toString(36),w=function(){return typeof Symbol===y&&Symbol.observable||"@@observable"}(),E$1=" != "+y;function P($e,De,Fe){var Be;if(typeof De===y&&typeof Fe===b$1&&(Fe=De,De=void 0),typeof Fe!==b$1){if(typeof Fe!==y)throw new Error("enhancer"+E$1);return Fe(P)($e,De)}if(typeof $e!==y)throw new Error("reducer"+E$1);var He=$e,Ke=De,Ge=[],We=Ge,Ze=!1;function Xe(){We===Ge&&(We=Ge.slice())}function Je(){return Ke}function Ye(et){if(typeof et!==y)throw new Error("Listener"+E$1);var tt=!0;return Xe(),We.push(et),function(){if(tt){tt=!1,Xe();var ct=We.indexOf(et);We.splice(ct,1)}}}function Qe(et){if(!on(et))throw new Error("Act != obj");if(typeof et.type===b$1)throw new Error("ActType "+b$1);if(Ze)throw new Error("Dispatch in reducer");try{Ze=!0,Ke=He(Ke,et)}finally{Ze=!1}for(var tt=Ge=We,ct=0;ct<tt.length;ct++)(0,tt[ct])();return et}return Qe({type:"@@redux/INIT"}),(Be={dispatch:Qe,subscribe:Ye,getState:Je,replaceReducer:function(et){if(typeof et!==y)throw new Error("next reducer"+E$1);He=et,Qe({type:"@@redux/INIT"})}})[w]=function(){var et,tt=Ye;return(et={subscribe:function(ct){if(typeof ct!="object")throw new TypeError("Observer != obj");function at(){ct.next&&ct.next(Je())}return at(),{unsubscribe:tt(at)}}})[w]=function(){return this},et},Be}function S($e,De){var Fe=De&&De.type;return"action "+(Fe&&Fe.toString()||"?")+"reducer "+$e+" returns "+b$1}function N$1(){var $e=[].slice.call(arguments);return $e.length===0?function(De){return De}:$e.length===1?$e[0]:$e.reduce(function(De,Fe){return function(){return De(Fe.apply(void 0,[].slice.call(arguments)))}})}function O$1(){var $e=arguments;return function(De){return function(Fe,Be,He){var Ke,Ge=De(Fe,Be,He),We=Ge.dispatch,Ze={getState:Ge.getState,dispatch:function(Xe){return We(Xe)}};return Ke=[].slice.call($e).map(function(Xe){return Xe(Ze)}),v({},Ge,{dispatch:We=N$1.apply(void 0,Ke)(Ge.dispatch)})}}}var A$1=j+"anon_id",_=j+"user_id",x$1=j+"user_traits",k$1="userId",T="anonymousId",z=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],M=["name","EVENTS","config","loaded"],q=z.reduce(function($e,De){return $e[De]=De,$e},{registerPluginType:function($e){return"registerPlugin:"+$e},pluginReadyType:function($e){return"ready:"+$e}}),U=/^utm_/,V=/^an_prop_/,L$1=/^an_trait_/;function C$1($e){var De=$e.storage.setItem;return function(Fe){return function(Be){return function(He){if(He.type===q.bootstrap){var Ke=He.params,Ge=He.user,We=He.persistedUser,Ze=He.initialUser,Xe=We.userId===Ge.userId;We.anonymousId!==Ge.anonymousId&&De(A$1,Ge.anonymousId),Xe||De(_,Ge.userId),Ze.traits&&De(x$1,v({},Xe&&We.traits?We.traits:{},Ze.traits));var Je=Object.keys(He.params);if(Je.length){var Ye=Ke.an_uid,Qe=Ke.an_event,et=Je.reduce(function(tt,ct){if(ct.match(U)||ct.match(/^(d|g)clid/)){var at=ct.replace(U,"");tt.campaign[at==="campaign"?"name":at]=Ke[ct]}return ct.match(V)&&(tt.props[ct.replace(V,"")]=Ke[ct]),ct.match(L$1)&&(tt.traits[ct.replace(L$1,"")]=Ke[ct]),tt},{campaign:{},props:{},traits:{}});Fe.dispatch(v({type:q.params,raw:Ke},et,Ye?{userId:Ye}:{})),Ye&&setTimeout(function(){return $e.identify(Ye,et.traits)},0),Qe&&setTimeout(function(){return $e.track(Qe,et.props)},0),Object.keys(et.campaign).length&&Fe.dispatch({type:q.campaign,campaign:et.campaign})}}return Be(He)}}}}function R($e){return function(De,Fe){if(De===void 0&&(De={}),Fe===void 0&&(Fe={}),Fe.type===q.setItemEnd){if(Fe.key===A$1)return v({},De,{anonymousId:Fe.value});if(Fe.key===_)return v({},De,{userId:Fe.value})}switch(Fe.type){case q.identify:return Object.assign({},De,{userId:Fe.userId,traits:v({},De.traits,Fe.traits)});case q.reset:return[_,A$1,x$1].forEach(function(Be){$e.removeItem(Be)}),Object.assign({},De,{userId:null,anonymousId:null,traits:{}});default:return De}}}function $($e){return{userId:$e.getItem(_),anonymousId:$e.getItem(A$1),traits:$e.getItem(x$1)}}var D=function($e){return j+"TEMP"+j+$e};function B($e){var De=$e.storage,Fe=De.setItem,Be=De.removeItem,He=De.getItem;return function(Ke){return function(Ge){return function(We){var Ze=We.userId,Xe=We.traits,Je=We.options;if(We.type===q.reset&&([_,x$1,A$1].forEach(function(et){Be(et)}),[k$1,T,"traits"].forEach(function(et){i$4(D(et))})),We.type===q.identify){He(A$1)||Fe(A$1,y$1());var Ye=He(_),Qe=He(x$1)||{};Ye&&Ye!==Ze&&Ke.dispatch({type:q.userIdChanged,old:{userId:Ye,traits:Qe},new:{userId:Ze,traits:Xe},options:Je}),Ze&&Fe(_,Ze),Xe&&Fe(x$1,v({},Qe,Xe))}return Ge(We)}}}}var X={};function J$1($e,De){X[$e]&&W$1(X[$e])&&(X[$e](De),delete X[$e])}function W($e,De,Fe){return new Promise(function(Be,He){return De()?Be($e):Fe<1?He(v({},$e,{queue:!0})):new Promise(function(Ke){return setTimeout(Ke,10)}).then(function(Ke){return W($e,De,Fe-10).then(Be,He)})})}function H($e){return{abort:$e}}function F$1($e,De,Fe){var Be={},He=De(),Ke=$e.getState(),Ge=Ke.plugins,We=Ke.queue,Ze=Ke.user;if(!Ke.context.offline&&We&&We.actions&&We.actions.length){var Xe=We.actions.reduce(function(Ye,Qe,et){return Ge[Qe.plugin].loaded?(Ye.process.push(Qe),Ye.processIndex.push(et)):(Ye.requeue.push(Qe),Ye.requeueIndex.push(et)),Ye},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(Xe.processIndex&&Xe.processIndex.length){Xe.processIndex.forEach(function(Ye){var Qe=We.actions[Ye],et=Qe.plugin,tt=Qe.payload.type,ct=He[et][tt];if(ct&&W$1(ct)){var at,ft=function(rt,lt){return rt===void 0&&(rt={}),lt===void 0&&(lt={}),[k$1,T].reduce(function(pt,gt){return rt.hasOwnProperty(gt)&&lt[gt]&&lt[gt]!==rt[gt]&&(pt[gt]=lt[gt]),pt},rt)}(Qe.payload,Ze),ut=Be[ft.meta.rid];if(!ut&&(at=ct({payload:ft,config:Ge[et].config,instance:Fe,abort:H}))&&on(at)&&at.abort)return void(Be[ft.meta.rid]=!0);if(!ut){var ot=tt+":"+et;$e.dispatch(v({},ft,{type:ot,_:{called:ot,from:"queueDrain"}}))}}});var Je=We.actions.filter(function(Ye,Qe){return!~Xe.processIndex.indexOf(Qe)});We.actions=Je}}}var G$1=function($e){var De=$e.data,Fe=$e.action,Be=$e.instance,He=$e.state,Ke=$e.allPlugins,Ge=$e.allMatches,We=$e.store,Ze=$e.EVENTS;try{var Xe=He.plugins,Je=He.context,Ye=Fe.type,Qe=Ye.match(K),et=De.exact.map(function(at){return at.pluginName});Qe&&(et=Ge.during.map(function(at){return at.pluginName}));var tt=function(at,ft){return function(ut,ot,rt){var lt=ot.config,pt=ot.name,gt=pt+"."+ut.type;rt&&(gt=rt.event);var vt=ut.type.match(K)?function(Et,Pt,Nt,yt,It){return function(Rt,mt){var At=yt?yt.name:Et,Ut=mt&&ae(mt)?mt:Nt;if(yt&&(!(Ut=mt&&ae(mt)?mt:[Et]).includes(Et)||Ut.length!==1))throw new Error("Method "+Pt+" can only abort "+Et+" plugin. "+JSON.stringify(Ut)+" input valid");return v({},It,{abort:{reason:Rt,plugins:Ut,caller:Pt,_:At}})}}(pt,gt,ft,rt,ut):function(Et,Pt){return function(){throw new Error(Et.type+" action not cancellable. Remove abort in "+Pt)}}(ut,gt);return{payload:ce(ut),instance:at,config:lt||{},abort:vt}}}(Be,et),ct=De.exact.reduce(function(at,ft){var ut=ft.pluginName,ot=ft.methodName,rt=!1;return ot.match(/^initialize/)||ot.match(/^reset/)||(rt=!Xe[ut].loaded),Je.offline&&ot.match(/^(page|track|identify)/)&&(rt=!0),at[""+ut]=rt,at},{});return Promise.resolve(De.exact.reduce(function(at,ft,ut){try{var ot=ft.pluginName;return Promise.resolve(at).then(function(rt){function lt(){return Promise.resolve(rt)}var pt=function(){if(De.namespaced&&De.namespaced[ot])return Promise.resolve(De.namespaced[ot].reduce(function(gt,vt,Et){try{return Promise.resolve(gt).then(function(Pt){return vt.method&&W$1(vt.method)?(function(Rt,mt){var At=ue(Rt);if(At&&At.name===mt){var Ut=ue(At.method);throw new Error([mt+" plugin is calling method "+Rt,"Plugins cant call self","Use "+At.method+" "+(Ut?"or "+Ut.method:"")+" in "+mt+" plugin insteadof "+Rt].join(`
36
36
  `))}}(vt.methodName,vt.pluginName),Promise.resolve(vt.method({payload:Pt,instance:Be,abort:(Nt=Pt,yt=ot,It=vt.pluginName,function(Rt,mt){return v({},Nt,{abort:{reason:Rt,plugins:mt||[yt],caller:Ye,from:It||yt}})}),config:ee(vt.pluginName,Xe,Ke),plugins:Xe})).then(function(Rt){var mt=on(Rt)?Rt:{};return Promise.resolve(v({},Pt,mt))})):Pt;var Nt,yt,It})}catch(Pt){return Promise.reject(Pt)}},Promise.resolve(Fe))).then(function(gt){rt[ot]=gt});rt[ot]=Fe}();return pt&&pt.then?pt.then(lt):lt()})}catch(rt){return Promise.reject(rt)}},Promise.resolve({}))).then(function(at){return Promise.resolve(De.exact.reduce(function(ft,ut,ot){try{var rt=De.exact.length===ot+1,lt=ut.pluginName,pt=Ke[lt];return Promise.resolve(ft).then(function(gt){var vt=at[lt]?at[lt]:{};if(Qe&&(vt=gt),re(vt,lt))return Z({data:vt,method:Ye,instance:Be,pluginName:lt,store:We}),Promise.resolve(gt);if(re(gt,lt))return rt&&Z({data:gt,method:Ye,instance:Be,store:We}),Promise.resolve(gt);if(ct.hasOwnProperty(lt)&&ct[lt]===!0)return We.dispatch({type:"queue",plugin:lt,payload:vt,_:{called:"queue",from:"queueMechanism"}}),Promise.resolve(gt);var Et=tt(at[lt],Ke[lt]);return Promise.resolve(pt[Ye]({abort:Et.abort,payload:vt,instance:Be,config:ee(lt,Xe,Ke),plugins:Xe})).then(function(Pt){var Nt=on(Pt)?Pt:{},yt=v({},gt,Nt),It=at[lt];if(re(It,lt))Z({data:It,method:Ye,instance:Be,pluginName:lt,store:We});else{var Rt=Ye+":"+lt;(Rt.match(/:/g)||[]).length<2&&!Ye.match(Q)&&!Ye.match(Y)&&Be.dispatch(v({},Qe?yt:vt,{type:Rt,_:{called:Rt,from:"submethod"}}))}return Promise.resolve(yt)})})}catch(gt){return Promise.reject(gt)}},Promise.resolve(Fe))).then(function(ft){if(!(Ye.match(K)||Ye.match(/^registerPlugin/)||Ye.match(Y)||Ye.match(Q)||Ye.match(/^params/)||Ye.match(/^userIdChanged/))){if(Ze.plugins.includes(Ye),ft._&&ft._.originalAction===Ye)return ft;var ut=v({},ft,{_:{originalAction:ft.type,called:ft.type,from:"engineEnd"}});ie(ft,De.exact.length)&&!Ye.match(/End$/)&&(ut=v({},ut,{type:ft.type+"Aborted"})),We.dispatch(ut)}return ft})})}catch(at){return Promise.reject(at)}},K=/Start$/,Q=/^bootstrap/,Y=/^ready/;function Z($e){var De=$e.pluginName,Fe=$e.method+"Aborted"+(De?":"+De:"");$e.store.dispatch(v({},$e.data,{type:Fe,_:{called:Fe,from:"abort"}}))}function ee($e,De,Fe){var Be=De[$e]||Fe[$e];return Be&&Be.config?Be.config:{}}function ne($e,De){return De.reduce(function(Fe,Be){return Be[$e]?Fe.concat({methodName:$e,pluginName:Be.name,method:Be[$e]}):Fe},[])}function te($e,De){var Fe=$e.replace(K,""),Be=De?":"+De:"";return[""+$e+Be,""+Fe+Be,Fe+"End"+Be]}function re($e,De){var Fe=$e.abort;return!!Fe&&(Fe===!0||oe(Fe,De)||Fe&&oe(Fe.plugins,De))}function ie($e,De){var Fe=$e.abort;if(!Fe)return!1;if(Fe===!0||q$1(Fe))return!0;var Be=Fe.plugins;return ae(Fe)&&Fe.length===De||ae(Be)&&Be.length===De}function ae($e){return Array.isArray($e)}function oe($e,De){return!(!$e||!ae($e))&&$e.includes(De)}function ue($e){var De=$e.match(/(.*):(.*)/);return!!De&&{method:De[1],name:De[2]}}function ce($e){return Object.keys($e).reduce(function(De,Fe){return Fe==="type"||(De[Fe]=on($e[Fe])?Object.assign({},$e[Fe]):$e[Fe]),De},{})}function se($e,De,Fe){var Be={};return function(He){return function(Ke){return function(Ge){try{var We,Ze=function(rt){return We?rt:Ke(Ye)},Xe=Ge.type,Je=Ge.plugins,Ye=Ge;if(Ge.abort)return Promise.resolve(Ke(Ge));if(Xe===q.enablePlugin&&He.dispatch({type:q.initializeStart,plugins:Je,disabled:[],fromEnable:!0,meta:Ge.meta}),Xe===q.disablePlugin&&setTimeout(function(){return J$1(Ge.meta.rid,{payload:Ge})},0),Xe===q.initializeEnd){var Qe=De(),et=Object.keys(Qe),tt=et.filter(function(rt){return Je.includes(rt)}).map(function(rt){return Qe[rt]}),ct=[],at=[],ft=Ge.disabled,ut=tt.map(function(rt){var lt=rt.loaded,pt=rt.name,gt=rt.config;return W(rt,function(){return lt({config:gt})},1e4).then(function(vt){return Be[pt]||(He.dispatch({type:q.pluginReadyType(pt),name:pt,events:Object.keys(rt).filter(function(Et){return!M.includes(Et)})}),Be[pt]=!0),ct=ct.concat(pt),rt}).catch(function(vt){if(vt instanceof Error)throw new Error(vt);return at=at.concat(vt.name),vt})});Promise.all(ut).then(function(rt){var lt={plugins:ct,failed:at,disabled:ft};setTimeout(function(){et.length===ut.length+ft.length&&He.dispatch(v({},{type:q.ready},lt))},0)})}var ot=function(){if(Xe!==q.bootstrap)return/^ready:([^:]*)$/.test(Xe)&&setTimeout(function(){return F$1(He,De,$e)},0),Promise.resolve(function(rt,lt,pt,gt,vt){try{var Et=W$1(lt)?lt():lt,Pt=rt.type,Nt=Pt.replace(K,"");if(rt._&&rt._.called)return Promise.resolve(rt);var yt=pt.getState(),It=(At=Et,(Ut=yt.plugins)===void 0&&(Ut={}),(xt=rt.options)===void 0&&(xt={}),Object.keys(At).filter(function(nt){var it=xt.plugins||{};return Q$1(it[nt])?it[nt]:it.all!==!1&&(!Ut[nt]||Ut[nt].enabled!==!1)}).map(function(nt){return At[nt]}));Pt===q.initializeStart&&rt.fromEnable&&(It=Object.keys(yt.plugins).filter(function(nt){var it=yt.plugins[nt];return rt.plugins.includes(nt)&&!it.initialized}).map(function(nt){return Et[nt]}));var Rt=It.map(function(nt){return nt.name}),mt=function(nt,it,ht){var St=te(nt).map(function(bt){return ne(bt,it)});return it.reduce(function(bt,wt){var kt=wt.name,Tt=te(nt,kt).map(function(Ft){return ne(Ft,it)}),Lt=Tt[0],Ot=Tt[1],jt=Tt[2];return Lt.length&&(bt.beforeNS[kt]=Lt),Ot.length&&(bt.duringNS[kt]=Ot),jt.length&&(bt.afterNS[kt]=jt),bt},{before:St[0],beforeNS:{},during:St[1],duringNS:{},after:St[2],afterNS:{}})}(Pt,It);return Promise.resolve(G$1({action:rt,data:{exact:mt.before,namespaced:mt.beforeNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(nt){function it(){var bt=function(){if(Pt.match(K))return Promise.resolve(G$1({action:v({},ht,{type:Nt+"End"}),data:{exact:mt.after,namespaced:mt.afterNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(wt){wt.meta&&wt.meta.hasCallback&&J$1(wt.meta.rid,{payload:wt})})}();return bt&&bt.then?bt.then(function(){return nt}):nt}if(ie(nt,Rt.length))return nt;var ht,St=function(){if(Pt!==Nt)return Promise.resolve(G$1({action:v({},nt,{type:Nt}),data:{exact:mt.during,namespaced:mt.duringNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(bt){ht=bt});ht=nt}();return St&&St.then?St.then(it):it()})}catch(nt){return Promise.reject(nt)}var At,Ut,xt}(Ge,De,$e,He,Fe)).then(function(rt){return We=1,Ke(rt)})}();return Promise.resolve(ot&&ot.then?ot.then(Ze):Ze(ot))}catch(rt){return Promise.reject(rt)}}}}}function le($e){return function(De){return function(Fe){return function(Be){var He=Be.type,Ke=Be.key,Ge=Be.value,We=Be.options;if(He===q.setItem||He===q.removeItem){if(Be.abort)return Fe(Be);He===q.setItem?$e.setItem(Ke,Ge,We):$e.removeItem(Ke,We)}return Fe(Be)}}}}var fe=function(){var $e=this;this.before=[],this.after=[],this.addMiddleware=function(De,Fe){$e[Fe]=$e[Fe].concat(De)},this.removeMiddleware=function(De,Fe){var Be=$e[Fe].findIndex(function(He){return He===De});Be!==-1&&($e[Fe]=[].concat($e[Fe].slice(0,Be),$e[Fe].slice(Be+1)))},this.dynamicMiddlewares=function(De){return function(Fe){return function(Be){return function(He){var Ke={getState:Fe.getState,dispatch:function(We){return Fe.dispatch(We)}},Ge=$e[De].map(function(We){return We(Ke)});return N$1.apply(void 0,Ge)(Be)(He)}}}}};function de($e){return function(De,Fe){De===void 0&&(De={});var Be={};if(Fe.type==="initialize:aborted")return De;if(/^registerPlugin:([^:]*)$/.test(Fe.type)){var He=pe(Fe.type,"registerPlugin"),Ke=$e()[He];if(!Ke||!He)return De;var Ge=Fe.enabled,We=Ke.config;return Be[He]={enabled:Ge,initialized:!!Ge&&!Ke.initialize,loaded:!!Ge&&!!Ke.loaded({config:We}),config:We},v({},De,Be)}if(/^initialize:([^:]*)$/.test(Fe.type)){var Ze=pe(Fe.type,q.initialize),Xe=$e()[Ze];return Xe&&Ze?(Be[Ze]=v({},De[Ze],{initialized:!0,loaded:!!Xe.loaded({config:Xe.config})}),v({},De,Be)):De}if(/^ready:([^:]*)$/.test(Fe.type))return Be[Fe.name]=v({},De[Fe.name],{loaded:!0}),v({},De,Be);switch(Fe.type){case q.disablePlugin:return v({},De,me(Fe.plugins,!1,De));case q.enablePlugin:return v({},De,me(Fe.plugins,!0,De));default:return De}}}function pe($e,De){return $e.substring(De.length+1,$e.length)}function me($e,De,Fe){return $e.reduce(function(Be,He){return Be[He]=v({},Fe[He],{enabled:De}),Be},Fe)}function ge($e){try{return JSON.parse(JSON.stringify($e))}catch{}return $e}var he={last:{},history:[]};function ve($e,De){$e===void 0&&($e=he);var Fe=De.options,Be=De.meta;if(De.type===q.track){var He=ge(v({event:De.event,properties:De.properties},Object.keys(Fe).length&&{options:Fe},{meta:Be}));return v({},$e,{last:He,history:$e.history.concat(He)})}return $e}var ye={actions:[]};function be($e,De){$e===void 0&&($e=ye);var Fe=De.payload;switch(De.type){case"queue":var Be;return Be=Fe&&Fe.type&&Fe.type===q.identify?[De].concat($e.actions):$e.actions.concat(De),v({},$e,{actions:Be});case"dequeue":return[];default:return $e}}var Ie=/#.*$/;function we($e){var De=/(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g.exec($e);return"/"+(De&&De[3]?De[3].split("?")[0].replace(Ie,""):"")}var Ee,Pe,Se,Ne,Oe=function($e){if($e===void 0&&($e={}),!$$1)return $e;var De=document,Fe=De.title,Be=De.referrer,He=window,Ke=He.location,Ge=He.innerWidth,We=He.innerHeight,Ze=Ke.hash,Xe=Ke.search,Je=function(Qe){var et=function(){if($$1){for(var tt,ct=document.getElementsByTagName("link"),at=0;tt=ct[at];at++)if(tt.getAttribute("rel")==="canonical")return tt.getAttribute("href")}}();return et?et.match(/\?/)?et:et+Qe:window.location.href.replace(Ie,"")}(Xe),Ye={title:Fe,url:Je,path:we(Je),hash:Ze,search:Xe,width:Ge,height:We};return Be&&Be!==""&&(Ye.referrer=Be),v({},Ye,$e)},Ae={last:{},history:[]};function _e($e,De){$e===void 0&&($e=Ae);var Fe=De.options;if(De.type===q.page){var Be=ge(v({properties:De.properties,meta:De.meta},Object.keys(Fe).length&&{options:Fe}));return v({},$e,{last:Be,history:$e.history.concat(Be)})}return $e}Ee=function(){if(!$$1)return!1;var $e=navigator.appVersion;return~$e.indexOf("Win")?"Windows":~$e.indexOf("Mac")?"MacOS":~$e.indexOf("X11")?"UNIX":~$e.indexOf("Linux")?"Linux":"Unknown OS"}(),Pe=$$1?document.referrer:null,Se=o$3(),Ne=a$5();var xe={initialized:!1,sessionId:y$1(),app:null,version:null,debug:!1,offline:!!$$1&&!navigator.onLine,os:{name:Ee},userAgent:$$1?navigator.userAgent:"node",library:{name:"analytics",version:"0.12.13"},timezone:Ne,locale:Se,campaign:{},referrer:Pe};function je($e,De){$e===void 0&&($e=xe);var Fe=$e.initialized,Be=De.campaign;switch(De.type){case q.campaign:return v({},$e,{campaign:Be});case q.offline:return v({},$e,{offline:!0});case q.online:return v({},$e,{offline:!1});default:return Fe?$e:v({},xe,$e,{initialized:!0})}}var ke=["plugins","reducers","storage"];function Te($e,De,Fe){if($$1){var Be=window[(Fe?"add":"remove")+"EventListener"];$e.split(" ").forEach(function(He){Be(He,De)})}}function ze($e){var De=Te.bind(null,"online offline",function(Fe){return Promise.resolve(!navigator.onLine).then($e)});return De(!0),function(Fe){return De(!1)}}function Me(){return f$1("analytics",[]),function($e){return function(De,Fe,Be){var He=$e(De,Fe,Be),Ke=He.dispatch;return Object.assign(He,{dispatch:function(Ge){return n[o$2].analytics.push(Ge.action||Ge),Ke(Ge)}})}}}function qe($e){return function(){return N$1(N$1.apply(null,arguments),Me())}}function Ue($e){return $e?rn($e)?$e:[$e]:[]}function Ve($e,De,Fe){$e===void 0&&($e={});var Be,He,Ke=y$1();return De&&(X[Ke]=(Be=De,He=function(Ge){for(var We,Ze=Ge||Array.prototype.slice.call(arguments),Xe=0;Xe<Ze.length;Xe++)if(W$1(Ze[Xe])){We=Ze[Xe];break}return We}(Fe),function(Ge){He&&He(Ge),Be(Ge)})),v({},$e,{rid:Ke,ts:new Date().getTime()},De?{hasCallback:!0}:{})}function Le($e){$e===void 0&&($e={});var De=$e.reducers||{},Fe=$e.initialUser||{},Be=($e.plugins||[]).reduce(function(nt,it){if(W$1(it))return nt.middlewares=nt.middlewares.concat(it),nt;if(it.NAMESPACE&&(it.name=it.NAMESPACE),!it.name)throw new Error("https://lytics.dev/errors/1");it.config||(it.config={});var ht=it.EVENTS?Object.keys(it.EVENTS).map(function(wt){return it.EVENTS[wt]}):[];nt.pluginEnabled[it.name]=!(it.enabled===!1||it.config.enabled===!1),delete it.enabled,it.methods&&(nt.methods[it.name]=Object.keys(it.methods).reduce(function(wt,kt){var Tt;return wt[kt]=(Tt=it.methods[kt],function(){for(var Lt=Array.prototype.slice.call(arguments),Ot=new Array(Tt.length),jt=0;jt<Lt.length;jt++)Ot[jt]=Lt[jt];return Ot[Ot.length]=lt,Tt.apply({instance:lt},Ot)}),wt},{}),delete it.methods);var St=Object.keys(it).concat(ht),bt=new Set(nt.events.concat(St));if(nt.events=Array.from(bt),nt.pluginsArray=nt.pluginsArray.concat(it),nt.plugins[it.name])throw new Error(it.name+"AlreadyLoaded");return nt.plugins[it.name]=it,nt.plugins[it.name].loaded||(nt.plugins[it.name].loaded=function(){return!0}),nt},{plugins:{},pluginEnabled:{},methods:{},pluginsArray:[],middlewares:[],events:[]}),He=$e.storage?$e.storage:{getItem:a$4,setItem:f$1,removeItem:i$4},Ke=function(nt){return function(it,ht,St){return ht.getState("user")[it]||(St&&on(St)&&St[it]?St[it]:$(nt)[it]||a$4(D(it))||null)}}(He),Ge=Be.plugins,We=Be.events.filter(function(nt){return!M.includes(nt)}).sort(),Ze=new Set(We.concat(z).filter(function(nt){return!M.includes(nt)})),Xe=Array.from(Ze).sort(),Je=function(){return Ge},Ye=new fe,Qe=Ye.addMiddleware,et=Ye.removeMiddleware,tt=Ye.dynamicMiddlewares,ct=function(){throw new Error("Abort disabled inListener")},at=s$1(),ft=$(He),ut=v({},ft,Fe,at.an_uid?{userId:at.an_uid}:{},at.an_aid?{anonymousId:at.an_aid}:{});ut.anonymousId||(ut.anonymousId=y$1());var ot=v({enable:function(nt,it){return new Promise(function(ht){mt.dispatch({type:q.enablePlugin,plugins:Ue(nt),_:{originalAction:q.enablePlugin}},ht,[it])})},disable:function(nt,it){return new Promise(function(ht){mt.dispatch({type:q.disablePlugin,plugins:Ue(nt),_:{originalAction:q.disablePlugin}},ht,[it])})}},Be.methods),rt=!1,lt={identify:function(nt,it,ht,St){try{var bt=q$1(nt)?nt:null,wt=on(nt)?nt:it,kt=ht||{},Tt=lt.user();f$1(D(k$1),bt);var Lt=bt||wt.userId||Ke(k$1,lt,wt);return Promise.resolve(new Promise(function(Ot){mt.dispatch(v({type:q.identifyStart,userId:Lt,traits:wt||{},options:kt,anonymousId:Tt.anonymousId},Tt.id&&Tt.id!==bt&&{previousId:Tt.id}),Ot,[it,ht,St])}))}catch(Ot){return Promise.reject(Ot)}},track:function(nt,it,ht,St){try{var bt=on(nt)?nt.event:nt;if(!bt||!q$1(bt))throw new Error("EventMissing");var wt=on(nt)?nt:it||{},kt=on(ht)?ht:{};return Promise.resolve(new Promise(function(Tt){mt.dispatch({type:q.trackStart,event:bt,properties:wt,options:kt,userId:Ke(k$1,lt,it),anonymousId:Ke(T,lt,it)},Tt,[it,ht,St])}))}catch(Tt){return Promise.reject(Tt)}},page:function(nt,it,ht){try{var St=on(nt)?nt:{},bt=on(it)?it:{};return Promise.resolve(new Promise(function(wt){mt.dispatch({type:q.pageStart,properties:Oe(St),options:bt,userId:Ke(k$1,lt,St),anonymousId:Ke(T,lt,St)},wt,[nt,it,ht])}))}catch(wt){return Promise.reject(wt)}},user:function(nt){if(nt===k$1||nt==="id")return Ke(k$1,lt);if(nt===T||nt==="anonId")return Ke(T,lt);var it=lt.getState("user");return nt?i$5(it,nt):it},reset:function(nt){return new Promise(function(it){mt.dispatch({type:q.resetStart},it,nt)})},ready:function(nt){return rt&&nt({plugins:ot,instance:lt}),lt.on(q.ready,function(it){nt(it),rt=!0})},on:function(nt,it){if(!nt||!W$1(it))return!1;if(nt===q.bootstrap)throw new Error(".on disabled for "+nt);var ht=/Start$|Start:/;if(nt==="*"){var St=function(Tt){return function(Lt){return function(Ot){return Ot.type.match(ht)&&it({payload:Ot,instance:lt,plugins:Ge}),Lt(Ot)}}},bt=function(Tt){return function(Lt){return function(Ot){return Ot.type.match(ht)||it({payload:Ot,instance:lt,plugins:Ge}),Lt(Ot)}}};return Qe(St,Ce),Qe(bt,Re),function(){et(St,Ce),et(bt,Re)}}var wt=nt.match(ht)?Ce:Re,kt=function(Tt){return function(Lt){return function(Ot){return Ot.type===nt&&it({payload:Ot,instance:lt,plugins:Ge,abort:ct}),Lt(Ot)}}};return Qe(kt,wt),function(){return et(kt,wt)}},once:function(nt,it){if(!nt||!W$1(it))return!1;if(nt===q.bootstrap)throw new Error(".once disabled for "+nt);var ht=lt.on(nt,function(St){it({payload:St.payload,instance:lt,plugins:Ge,abort:ct}),ht()});return ht},getState:function(nt){var it=mt.getState();return nt?i$5(it,nt):Object.assign({},it)},dispatch:function(nt){var it=q$1(nt)?{type:nt}:nt;if(z.includes(it.type))throw new Error("reserved action "+it.type);var ht=v({},it,{_:v({originalAction:it.type},nt._||{})});mt.dispatch(ht)},enablePlugin:ot.enable,disablePlugin:ot.disable,plugins:ot,storage:{getItem:He.getItem,setItem:function(nt,it,ht){mt.dispatch({type:q.setItemStart,key:nt,value:it,options:ht})},removeItem:function(nt,it){mt.dispatch({type:q.removeItemStart,key:nt,options:it})}},setAnonymousId:function(nt,it){lt.storage.setItem(A$1,nt,it)},events:{core:z,plugins:We}},pt=Be.middlewares.concat([function(nt){return function(it){return function(ht){return ht.meta||(ht.meta=Ve()),it(ht)}}},tt(Ce),se(lt,Je,{all:Xe,plugins:We}),le(He),C$1(lt),B(lt),tt(Re)]),gt={context:je,user:R(He),page:_e,track:ve,plugins:de(Je),queue:be},vt=N$1,Et=N$1;if($$1&&$e.debug){var Pt=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;Pt&&(vt=Pt({trace:!0,traceLimit:25})),Et=function(){return arguments.length===0?Me():on(typeof arguments[0])?qe():qe().apply(null,arguments)}}var Nt,yt=function(nt){return Object.keys(nt).reduce(function(it,ht){return ke.includes(ht)||(it[ht]=nt[ht]),it},{})}($e),It=Be.pluginsArray.reduce(function(nt,it){var ht=it.name,St=it.config,bt=it.loaded,wt=Be.pluginEnabled[ht];return nt[ht]={enabled:wt,initialized:!!wt&&!it.initialize,loaded:!!bt({config:St}),config:St},nt},{}),Rt={context:yt,user:ut,plugins:It},mt=P(function(nt){for(var it=Object.keys(nt),ht={},St=0;St<it.length;St++){var bt=it[St];typeof nt[bt]===y&&(ht[bt]=nt[bt])}var wt,kt=Object.keys(ht);try{(function(Tt){Object.keys(Tt).forEach(function(Lt){var Ot=Tt[Lt];if(typeof Ot(void 0,{type:"@@redux/INIT"})===b$1||typeof Ot(void 0,{type:I$1})===b$1)throw new Error("reducer "+Lt+" "+b$1)})})(ht)}catch(Tt){wt=Tt}return function(Tt,Lt){if(Tt===void 0&&(Tt={}),wt)throw wt;for(var Ot=!1,jt={},Ft=0;Ft<kt.length;Ft++){var Bt=kt[Ft],Vt=Tt[Bt],Kt=(0,ht[Bt])(Vt,Lt);if(typeof Kt===b$1){var zt=S(Bt,Lt);throw new Error(zt)}jt[Bt]=Kt,Ot=Ot||Kt!==Vt}return Ot?jt:Tt}}(v({},gt,De)),Rt,Et(vt(O$1.apply(void 0,pt))));mt.dispatch=(Nt=mt.dispatch,function(nt,it,ht){var St=v({},nt,{meta:Ve(nt.meta,it,Ue(ht))});return Nt.apply(null,[St])});var At=Object.keys(Ge);mt.dispatch({type:q.bootstrap,plugins:At,config:yt,params:at,user:ut,initialUser:Fe,persistedUser:ft});var Ut=At.filter(function(nt){return Be.pluginEnabled[nt]}),xt=At.filter(function(nt){return!Be.pluginEnabled[nt]});return mt.dispatch({type:q.registerPlugins,plugins:At,enabled:Be.pluginEnabled}),Be.pluginsArray.map(function(nt,it){var ht=nt.bootstrap,St=nt.config,bt=nt.name;ht&&W$1(ht)&&ht({instance:lt,config:St,payload:nt}),mt.dispatch({type:q.registerPluginType(bt),name:bt,enabled:Be.pluginEnabled[bt],plugin:nt}),Be.pluginsArray.length===it+1&&mt.dispatch({type:q.initializeStart,plugins:Ut,disabled:xt})}),ze(function(nt){mt.dispatch({type:nt?q.offline:q.online})}),function(nt,it,ht){setInterval(function(){return F$1(nt,it,ht)},3e3)}(mt,Je,lt),lt}var Ce="before",Re="after",t="cookie",i$3=a$3(),r$2=d$1,c$2=d$1;function u$2($e){return i$3?d$1($e,"",-1):i$4($e)}function a$3(){if(i$3!==void 0)return i$3;var $e="cookiecookie";try{d$1($e,$e),i$3=document.cookie.indexOf($e)!==-1,u$2($e)}catch{i$3=!1}return i$3}function d$1($e,De,Fe,Be,He,Ke){if(typeof window<"u"){var Ge=arguments.length>1;return i$3===!1&&(Ge?f$1($e,De):a$4($e)),Ge?document.cookie=$e+"="+encodeURIComponent(De)+(Fe?"; expires="+new Date(+new Date+1e3*Fe).toUTCString()+(Be?"; path="+Be:"")+(He?"; domain="+He:"")+(Ke?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+$e+"=")[1]||"").split(";")[0])}}var r$1="localStorage",g=b$2.bind(null,"localStorage");u$3("localStorage","getItem",a$4);u$3("localStorage","setItem",f$1);u$3("localStorage","removeItem",i$4);var a$2="sessionStorage",i$2=b$2.bind(null,"sessionStorage");u$3("sessionStorage","getItem",a$4);u$3("sessionStorage","setItem",f$1);u$3("sessionStorage","removeItem",i$4);function I($e){var De=$e;try{if((De=JSON.parse($e))==="true")return!0;if(De==="false")return!1;if(on(De))return De;parseFloat(De)===De&&(De=parseFloat(De))}catch{}if(De!==null&&De!=="")return De}var k=g(),O=i$2(),x=a$3();function C($e,De){if($e){var Fe=A(De),Be=!N(Fe),He=d(Fe)?I(localStorage.getItem($e)):void 0;if(Be&&!I$2(He))return He;var Ke=h(Fe)?I(r$2($e)):void 0;if(Be&&Ke)return Ke;var Ge=E(Fe)?I(sessionStorage.getItem($e)):void 0;if(Be&&Ge)return Ge;var We=a$4($e);return Be?We:{localStorage:He,sessionStorage:Ge,cookie:Ke,global:We}}}function L($e,De,Fe){if($e&&!I$2(De)){var Be={},He=A(Fe),Ke=JSON.stringify(De),Ge=!N(He);return d(He)&&(Be[r$1]=F(r$1,De,I(localStorage.getItem($e))),localStorage.setItem($e,Ke),Ge)?Be[r$1]:h(He)&&(Be[t]=F(t,De,I(r$2($e))),c$2($e,Ke),Ge)?Be[t]:E(He)&&(Be[a$2]=F(a$2,De,I(sessionStorage.getItem($e))),sessionStorage.setItem($e,Ke),Ge)?Be[a$2]:(Be[l$2]=F(l$2,De,a$4($e)),f$1($e,De),Ge?Be[l$2]:Be)}}function b($e,De){if($e){var Fe=A(De),Be=C($e,m$1),He={};return!I$2(Be.localStorage)&&d(Fe)&&(localStorage.removeItem($e),He[r$1]=Be.localStorage),!I$2(Be.cookie)&&h(Fe)&&(u$2($e),He[t]=Be.cookie),!I$2(Be.sessionStorage)&&E(Fe)&&(sessionStorage.removeItem($e),He[a$2]=Be.sessionStorage),!I$2(Be.global)&&G(Fe,l$2)&&(i$4($e),He[l$2]=Be.global),He}}function A($e){return $e?q$1($e)?$e:$e.storage:b$4}function d($e){return k&&G($e,r$1)}function h($e){return x&&G($e,t)}function E($e){return O&&G($e,a$2)}function N($e){return $e===m$1||$e==="all"}function G($e,De){return $e===b$4||$e===De||N($e)}function F($e,De,Fe){return{location:$e,current:De,previous:Fe}}var J={setItem:L,getItem:C,removeItem:b};function _defineProperty($e,De,Fe){return De in $e?Object.defineProperty($e,De,{value:Fe,enumerable:!0,configurable:!0,writable:!0}):$e[De]=Fe,$e}function ownKeys($e,De){var Fe=Object.keys($e);if(Object.getOwnPropertySymbols){var Be=Object.getOwnPropertySymbols($e);De&&(Be=Be.filter(function(He){return Object.getOwnPropertyDescriptor($e,He).enumerable})),Fe.push.apply(Fe,Be)}return Fe}function _objectSpread2($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De]!=null?arguments[De]:{};De%2?ownKeys(Object(Fe),!0).forEach(function(Be){_defineProperty($e,Be,Fe[Be])}):Object.getOwnPropertyDescriptors?Object.defineProperties($e,Object.getOwnPropertyDescriptors(Fe)):ownKeys(Object(Fe)).forEach(function(Be){Object.defineProperty($e,Be,Object.getOwnPropertyDescriptor(Fe,Be))})}return $e}function analyticsLib(){var $e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},De={storage:J};return Le(_objectSpread2(_objectSpread2({},De),$e))}function saturated($e,De){De=De||{};var Fe,Be,He=[],Ke=De.max||1/0;function Ge(){clearInterval(Fe),$e(He.splice(0,Ke)),We()}function We(){Fe=setInterval(Ge,De.interval||1e4)}return We(),{flush:Ge,push:function(Ze){return Be=He.push(Ze),Be>=Ke&&Ge(),Be},size:function(){return He.length},end:function(Ze){Ze&&Ge(),clearInterval(Fe)}}}function onRouteChange($e){if(typeof window>"u")return;const{addEventListener:De,history:Fe,location:Be}=window;let He=Be.pathname;De("popstate",()=>$e(Be.pathname)),["push","replace"].map(Ke=>{const Ge=`${Ke}State`;if(Ge!=="pushState"&&Ge!=="replaceState")return;const We=Fe[Ge];Fe[Ge]=function(...Ze){var Ye;const Xe=((Ye=Ze[2])==null?void 0:Ye.toString())||"",Je=trimPath(Xe);return He!==Je&&(He=Je,setTimeout(()=>$e(Xe),0)),We.apply(Fe,Ze)}})}function remove($e,De){const Fe=$e.indexOf(De);return Fe>-1?$e.slice(0,Fe):$e}function trimPath($e){return["#","?"].forEach(De=>$e=remove($e,De)),$e}function routeChangeListener(){onRouteChange(()=>{analytics.page()})}function i$1($e){if($e===void 0&&($e={}),!$$1)return g$1;var De=l$1(),Fe=c$1(),Be=o$1(),He=s(Be,De),Ke=s(Fe,De),Ge=[],We=[],Ze=[],Xe=Be,Je=He,Ye=Ke,Qe=Object.keys($e);if(!Qe.length)return g$1;var et=Qe.map(function(ct){return Number(ct)}),tt=b$3(function(){var ct=l$1(),at=function(yt,It){return It.map(function(Rt){return Rt===100?yt-5:yt*(Rt/100)})}(ct,et),ft=c$1(),ut=o$1(),ot=s(ut,ct),rt=s(ft,ct);if(Je=ot>Je?ot:Je,Ye=rt<Ye?rt:Ye,!(Ge.length>=et.length)){var lt=Xe===ut,pt="up";lt?pt="initial":Xe<=ut&&(pt="down");var gt=at,vt=et;(pt==="up"||lt)&&(gt=at.slice().reverse(),vt=et.slice().reverse());var Et=vt.reduce(function(yt,It,Rt){var mt=gt[Rt];return Ze.includes(It)&&ut<=mt&&(Ze=Ze.filter(function(At){return At!==It}),yt.singleFunction=It),pt==="down"&&!Ge.includes(It)&&ut>=mt&&It>Ke?(We.push(It),yt.callbacks=yt.callbacks.concat(It),yt):pt==="up"&&!Ge.includes(It)&&ut<=mt&&It<=ot?(yt.foundFunc=[It],yt):(lt&&ut>=mt&&yt.foundFunc.length===0&&(yt.foundFunc=[It]),!We.includes(It)&&ut>=mt&&(We.push(It),yt.singleFunction?Ze.push(It):yt.singleFunction=It),yt)},{foundFunc:[],singleFunction:null,callbacks:[],direction:pt});if(Xe=ut,pt==="down"&&Et.callbacks&&Et.callbacks.forEach(function(yt){W$1($e[yt])&&($e[yt]({trigger:yt,direction:pt,scrollMin:Ye,scrollMax:Je,range:[Ye,Je]}),Ge.push(yt))}),Et.singleFunction){var Pt=Et.singleFunction,Nt=Et.direction;W$1($e[Pt])&&$e[Pt]({trigger:Pt,direction:Nt,scrollMin:Ye,scrollMax:Je,range:[Ye,Je]}),Ge.push(Pt)}}},500);return window.addEventListener("scroll",tt),function(){return window.removeEventListener("scroll",tt)}}function c$1(){return $$1?document.body.scrollTop||document.documentElement.scrollTop:0}function u$1(){return $$1?window.innerHeight||document.documentElement.clientHeight:0}function o$1(){return Math.round(c$1()+u$1())}function l$1(){if(!$$1)return 0;var $e=document.body,De=document.documentElement;return Math.max($e.scrollHeight,$e.offsetHeight,De.clientHeight,De.scrollHeight,De.offsetHeight)}function s($e,De){return Math.round($e/De*100)}var i="EventListener";function u($e){return function(De,Fe,Be,He){var Ke=Be||g$1,Ge=He||!1;if(!$$1)return Ke;var We=l(Fe),Ze=l(De,!0);if(!Ze.length)throw new Error("noElements");if(!We.length)throw new Error("noEvent");var Xe=[];return function Je(Ye){Ye&&(Xe=[]);for(var Qe=Ye?"add"+i:"remove"+i,et=0;et<Ze.length;et++){var tt=Ze[et];Xe[et]=Ye?Ge&&Ge.once?a$1(Ke):Ke:Xe[et]||Ke;for(var ct=0;ct<We.length;ct++)tt[Qe]?tt["on"+We[ct]]=Ye?Xe[et]:null:tt[Qe](We[ct],Xe[et],Ge)}return Je.bind(null,!Ye)}($e)}}function l($e,De){if(q$1($e))return De?l(document.querySelectorAll($e)):(Fe=$e).split(Fe.indexOf(",")>-1?",":" ").map(function(Ge){return Ge.trim()});var Fe;if(NodeList.prototype.isPrototypeOf($e)){for(var Be=[],He=$e.length>>>0;He--;)Be[He]=$e[He];return Be}var Ke=Hn($e);return De?Ke.map(function(Ge){return q$1(Ge)?l(Ge,!0):Ge}).flat():Ke}function a$1($e,De){var Fe;return function(){return $e&&(Fe=$e.apply(this,arguments),$e=null),Fe}}var f=u("Event");function p($e,De){return $$1&&W$1(window[$e])?(Fe=window[$e],Be=De,(He=window)===void 0&&(He=null),W$1(Fe)?function(){Fe.apply(He,arguments),Be.apply(He,arguments)}:Be):window[$e]=De;var Fe,Be,He}p.bind(null,"onerror");p.bind(null,"onload");var isServer=typeof window>"u",HIDDEN="hidden";function onTabChange($e){if(isServer)return!1;var De=getHiddenProp(),Fe="".concat(De.replace(/[H|h]idden/,""),"visibilitychange"),Be=function(){return $e(!!document[De])},He=function(){return document.addEventListener(Fe,Be)};return He(),function(){return document.removeEventListener(Fe,Be),He}}function getHiddenProp(){var $e=["webkit","moz","ms","o"];return isServer||HIDDEN in document?HIDDEN:$e.reduce(function(De,Fe){var Be=Fe+"Hidden";return!De&&Be in document?Be:De},null)}var o=["mousemove","mousedown","touchmove","touchstart","touchend","keydown"];function r($e,De){De===void 0&&(De={});var Fe=function(Ge,We){var Ze=this,Xe=!1;return function(Je){Xe||(Ge.call(Ze,Je),Xe=!0,setTimeout(function(){return Xe=!1},We))}}($e,De.throttle||1e4),Be=[];function He(){var Ge=onTabChange(function(We){We||Fe({type:"tabVisible"})});return Be=[Ge].concat(o.map(function(We){return f(document,We,Fe)})).concat(f(window,"load",Fe)).concat(f(window,"scroll",Fe,{capture:!0,passive:!0})),Ke}function Ke(){Be.map(function(Ge){return Ge()})}return He(),function(){return Ke(),He}}function a($e){var De,Fe,Be=$e.onIdle,He=$e.onWakeUp,Ke=$e.onHeartbeat,Ge=$e.timeout,We=Ge===void 0?1e4:Ge,Ze=$e.throttle,Xe=Ze===void 0?2e3:Ze,Je=!1,Ye=!1,Qe=new Date,et=function(){return clearTimeout(De)};function tt(at){et(),Ke&&!Je&&Ke(c(Qe),at),He&&Je&&(Je=!1,He(c(Fe),at),Qe=new Date),De=setTimeout(function(){Je=!0,Be&&(Fe=new Date,Be(c(Qe),at))},We)}var ct=r(tt,{throttle:Xe});return{disable:function(){Ye=!0,Je=!1,et();var at=ct();return function(){return Ye=!1,Qe=new Date,tt({type:"load"}),at()}},getStatus:function(){return{isIdle:Je,isDisabled:Ye,active:Je?0:c(Qe,Ye),idle:Je?c(Fe,Ye):0}}}}function c($e,De){return De?0:Math.round((new Date-$e)/1e3)}const timeout=5e3;class ElementTracker{constructor(De){Dt(this,"element");Dt(this,"isInViewport",!1);Dt(this,"isAwake",!1);Dt(this,"isFlushing");Dt(this,"observer");Dt(this,"lastEventAt",Date.now());Dt(this,"registeredView",!1);Dt(this,"viewCallback");Dt(this,"activeDurationCallback");Dt(this,"idleDurationCallback");Dt(this,"scrollCallback");this.element=De.element,this.viewCallback=De.viewCallback,this.activeDurationCallback=De.activeDurationCallback,this.idleDurationCallback=De.idleDurationCallback,this.scrollCallback=De.scrollCallback,this.observer=new IntersectionObserver(Fe=>{Fe.forEach(Be=>{this.handleInViewPort(Be.isIntersecting)})},{threshold:0}),this.observer.observe(this.element),a({onIdle:Fe=>this.handleAwake(!1,Fe),onWakeUp:Fe=>this.handleAwake(!0,Fe),timeout}),i$1({25:this.handleScroll.bind(this),50:this.handleScroll.bind(this),75:this.handleScroll.bind(this),90:this.handleScroll.bind(this),100:this.handleScroll.bind(this)})}flush(){this.isFlushing=!0,this.handleAwake(!this.isAwake)}handleInViewPort(De){De?(this.isAwake=!0,this.trackInViewport()):this.handleAwake(!1),this.isInViewport=De}handleAwake(De,Fe=Math.round((Date.now()-this.lastEventAt)/1e3)){this.isAwake=De,this.lastEventAt=De?Date.now()-Fe*timeout:Date.now(),this.isInViewport&&this.trackAwake(De,Fe)}handleScroll(De){this.scrollCallback&&this.scrollCallback(De)}handleVisibilityChange(){this.isAwake=!1;const De=Math.round((Date.now()-this.lastEventAt)/1e3);De>1&&(this.lastEventAt=Date.now(),this.trackAwake(!1,De))}trackAwake(De,Fe){!De&&this.activeDurationCallback&&this.activeDurationCallback(Fe,this.isFlushing,this.lastEventAt),De&&this.idleDurationCallback&&this.idleDurationCallback(Fe,this.isFlushing,this.lastEventAt)}trackInViewport(){this.registeredView||(this.registeredView=!0,this.viewCallback&&this.viewCallback())}}const SESSION_ID_KEY="sesamy_session_id";function getSessionId(){let $e=sessionStorage.getItem(SESSION_ID_KEY);return $e||($e=Math.random().toString(36).slice(2,9),sessionStorage.setItem(SESSION_ID_KEY,$e)),$e}function generateCSSSelector($e){function De(Be){return Be.id?`#${Be.id}`:Be.classList.length>0?Array.from(Be.classList).map(Ke=>`.${Ke}`).join(""):null}function Fe(Be){const He=[];let Ke=Be;for(;Ke&&Ke!==document.body&&Ke!==document.documentElement;){const Ge=De(Ke);if(Ge){He.unshift(Ge);break}if(Ke.parentElement){const We=Array.from(Ke.parentElement.children),Ze=We.indexOf(Ke)+1,Xe=Ke.tagName.toLowerCase();We.filter(Ye=>Ye.tagName.toLowerCase()===Xe).length>1?He.unshift(`${Xe}:nth-child(${Ze})`):He.unshift(Xe)}Ke=Ke.parentElement}return He.join(" > ")}return Fe($e)}let contentSelectors={article:{selector:"sesamy-article"},image:{selector:"img",attribute:"src"},title:{selector:"h1",attribute:"textContent"},excerpt:{selector:"p",attribute:"textContent"},price:{selector:"sesamy-article",attribute:"price"},currency:{selector:"sesamy-article",attribute:"currency"},url:{selector:"sesamy-article",attribute:"item-src"},accessLevel:{selector:"sesamy-article",attribute:"access-level"},id:{selector:"sesamy-article",attribute:"publisher-content-id"},pass:{selector:"sesamy-article",attribute:"pass"}},api;function init$2($e,De){var Fe;contentSelectors={...contentSelectors,...(Fe=$e.content)==null?void 0:Fe.article},api=De}function getElementFromSelector($e,De){const{selector:Fe}=De;return Fe===contentSelectors.article.selector?$e:$e.querySelector(Fe)}function getElementValue($e,De){if($e)return De.attribute?De.attribute==="textContent"?$e.textContent??void 0:$e.getAttribute(De.attribute)??getElementValue($e.parentElement,De):$e.textContent??void 0}function getMetaTag($e){const De=document.head.querySelectorAll(`[property~='${$e}'][content]`);for(let Be=0;Be<De.length;Be+=1)if(De[Be].content)return De[Be].content;const Fe=document.head.querySelectorAll(`[name~='${$e}'][content]`);for(let Be=0;Be<Fe.length;Be+=1)if(Fe[Be].content)return Fe[Be].content}function getPropertyFromHTML({publisherContentId:$e,key:De,defaultValue:Fe=""}){const Be=$e?document.body.querySelector(`sesamy-content-data[id='${$e}']`):null;return(Be==null?void 0:Be.getAttribute(De))||getMetaTag(`sesamy:${De}`)||getMetaTag(`og:${De}`)||getMetaTag(De)||Fe}function listContent(){const $e=document.querySelectorAll(contentSelectors.article.selector);return Array.from($e).map(getContent$1).filter(De=>De!==null)}function getContent$1($e){const De=typeof $e=="string"?document.querySelector($e):$e;if(!De)return null;const Fe={element:De,selector:typeof $e=="string"?$e:generateCSSSelector(De)},Be=(He,Ke,Ge,We)=>{const Ze=getElementFromSelector(De,Ke);if(Ze){const Xe=getElementValue(Ze,Ke)||getPropertyFromHTML({publisherContentId:Ge,key:He});Xe!==void 0&&(Fe[He]=We?We(Xe):Xe)}};return Be("id",contentSelectors.id),Be("title",contentSelectors.title,Fe.id),Be("excerpt",contentSelectors.excerpt,Fe.id),Be("image",contentSelectors.image,Fe.id),Be("price",contentSelectors.price,Fe.id,He=>parseFloat(He)),Be("currency",contentSelectors.currency,Fe.id),Be("url",contentSelectors.url,Fe.id),Be("pass",contentSelectors.pass,Fe.id),Be("accessLevel",contentSelectors.accessLevel,Fe.id,He=>He||"entitlement"),Fe}async function unlockContent($e,De){var We;const Fe=typeof $e=="string"?document.querySelector($e):$e;if(!Fe)throw new Error("Could not find element");const Be=getContent$1(Fe);if(!(Be!=null&&Be.url))throw new Error("Could not find content for element");const He=await api.entitlements.hasAccess(Be.url||"",((We=Be.pass)==null?void 0:We.split(","))||[]);if(!He)throw new Error("User does not have access to the content");const Ke=await api.entitlements.access(He.id);if(!Ke.token)throw new Error("Could not get access token");const Ge=De||generateCSSSelector(Fe.parentElement||Fe);return api.proxy.getContent(Ke.token,Be.url,Ge)}function onDOMContentLoaded($e){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$e):$e()}let flushing=!1,_clientId,_enabled,_endpoint;const visibilityListeners=new Map;function initAnalytics({clientId:$e,enabled:De=!0,environment:Fe}){_clientId=$e,_enabled=De,_endpoint=`${getBaseUrl("logs",Fe)}/events`,_enabled&&(window.addEventListener("beforeunload",()=>{unloadPageListeners.forEach((Be,He)=>{Be.bind(He)()}),flushQueue()}),window.addEventListener("visibilitychange",()=>{document.visibilityState!=="visible"&&visibilityListeners.forEach((Be,He)=>{Be.bind(He)()})}),routeChangeListener(),onDOMContentLoaded(()=>{const Be=new ElementTracker({element:document.body,viewCallback:()=>{analytics.page()},activeDurationCallback:(He,Ke,Ge)=>{analytics.track("activeDuration",{duration:He,durationStart:Ge,flushing:Ke})},idleDurationCallback:(He,Ke,Ge)=>{analytics.track("idleDuration",{duration:He,durationStart:Ge,flushing:Ke})},scrollCallback:He=>{analytics.track("scroll",{scroll:He.scrollMax})}});addUnloadPageListener(document.body,()=>{Be.flush()}),addVisibilityListener(document.body,()=>{Be.handleVisibilityChange()})}),window.addEventListener(Events.AUTHENTICATED,async Be=>{const He=Be;await analytics.identify(He.detail.sub)}),window.addEventListener(Events.LOGOUT,async()=>{await analytics.track("logout",{}),queue.flush(),await analytics.reset()}))}function createMessage($e){return JSON.stringify($e.map(De=>({...De,clientId:_clientId,requestId:Math.random().toString(36).slice(2,9),sessionId:getSessionId(),timestamp:new Date().toISOString(),version,event:De.event,context:{page:{url:window.location.href,title:document.title,referrer:document.referrer,itemSrc:getMetaTag("sesamy:item-src"),publisherContentId:getMetaTag("sesamy:publisher-content-id")},locale:navigator.language,library:name,userAgent:navigator.userAgent,clientId:_clientId}})))}const queue=saturated(async $e=>{if($e.length>0){const De=createMessage($e);flushing?navigator.sendBeacon(_endpoint,De):(await fetch(_endpoint,{method:"POST",body:De,headers:{"Content-Type":"text/plain"}})).ok}},{max:10,interval:3e3});function send($e){var De;if($e.anonymousId)if((De=$e.properties)!=null&&De.flushing){const Fe={...$e};delete Fe.properties.flushing,navigator.sendBeacon(_endpoint,createMessage([Fe]))}else queue.push($e)}const analytics=analyticsLib({app:name,version,plugins:[{name:"custom-analytics-plugin",page:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be,event:He}=$e;send({anonymousId:Fe,userId:Be,properties:De,event:He,type:"page"})},track:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be,event:He}=$e;send({anonymousId:Fe,userId:Be,properties:De,event:He,type:"track"})},identify:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be}=$e;send({anonymousId:Fe,userId:Be,properties:De,type:"identify"})}}]});function track($e,De){analytics.track($e,De)}function flushQueue(){return flushing=!0,queue.flush()}const unloadPageListeners=new Map;function addUnloadPageListener($e,De){unloadPageListeners.set($e,De)}function addVisibilityListener($e,De){visibilityListeners.set($e,De)}const bannerIds=["AdHeader","AdContainer","AD_Top","homead","ad-lead"];function detectAdblock(){return new Promise($e=>{const De=bannerIds.map(Fe=>{const Be=document.createElement("div");return Be.innerHTML="&nbsp;",Be.id=Fe,Be.style.position="absolute",document.body.appendChild(Be),Be});window.setTimeout(()=>{const Fe=!De.every(Be=>{const He=document.querySelector(`#${Be.id}`);return He==null?void 0:He.offsetParent});De.forEach(Be=>Be.remove()),$e(Fe)},100)})}function isInAppBrowser(){const $e=navigator.userAgent.toLowerCase(),De=[{name:"Facebook",regex:/fbav|fban/i},{name:"LinkedIn",regex:/linkedin/i},{name:"Instagram",regex:/instagram/i},{name:"Gmail",regex:/gmail/i},{name:"Twitter",regex:/twitter/i},{name:"WeChat",regex:/micromessenger/i},{name:"Line",regex:/line/i},{name:"Snapchat",regex:/snapchat/i},{name:"Pinterest",regex:/pinterest/i},{name:"Kakao",regex:/kakaotalk/i},{name:"Skype",regex:/skype/i},{name:"WhatsApp",regex:/whatsapp/i}];for(const Fe of De)if(Fe.regex.test($e))return{isInAppBrowser:!0,browserName:Fe.name};return/; wv\)/.test($e)?{isInAppBrowser:!0,browserName:"Unknown In-App Browser"}:{isInAppBrowser:!1,browserName:null}}function registerAPI($e){const{autoOnboardProduct:De,cancelContract:Fe,createCheckout:Be,deleteTag:He,deleteTally:Ke,deleteUserMetadata:Ge,generateLink:We,getBill:Ze,getBills:Xe,getCheckout:Je,getContract:Ye,getContracts:Qe,getEntitlement:et,getEntitlementAccess:tt,getEntitlements:ct,getFulfillments:at,getPaywall:ft,getPaymentIssues:ut,getProfile:ot,getProduct:rt,getProxyContent:lt,getSubscriptions:pt,getTags:gt,getTally:vt,getTallies:Et,getTransaction:Pt,getTransactions:Nt,getUserMetadata:yt,getVendorSettings:It,listVendors:Rt,hasAccess:mt,isSpotifyLinked:At,linkSpotify:Ut,listUserMetadata:xt,openHostedAccountPage:nt,pushTally:it,setTag:ht,setUserMetadata:St,unlinkSpotify:bt,updateCheckout:wt,updateProfile:kt}=createApi($e),Tt={analytics:{track},attribution:{get:getAttribution,set:setAttribution},auth:{getUser:ot,isAuthenticated,loginWithRedirect,logout,setToken},bills:{get:Ze,list:Xe},browser:{detectAdblock,isInAppBrowser,isIncognito},checkouts:{create:Be,get:Je,update:wt},clearCache,content:{list:listContent,get:getContent$1,getLanguage,unlock:unlockContent,getPropertyFromHTML},contracts:{cancel:Fe,get:Ye,list:Qe},entitlements:{access:tt,get:et,hasAccess:mt,list:ct,signedLinks:getSignedLinks},flags:{get:getFlag,set:setFlag,list:listFlags,delete:deleteFlag},fulfillments:{list:at},generateLink:We,getPaymentIssues:ut,getVersion,isReady:()=>exports.isInitialized,log,paywalls:{get:ft},products:{autoOnboard:De,get:rt,linkSpotify:Ut},profile:{get:ot,isSpotifyLinked:At,openHostedAccountPage:nt,unlinkSpotify:bt,update:kt},proxy:{getContent:lt},subscriptions:{list:pt},tags:{delete:He,list:gt,set:ht},tallies:{delete:Ke,get:vt,list:Et,push:it},transactions:{get:Pt,list:Nt},userMetadata:{delete:Ge,get:yt,list:xt,set:St},vendors:{get:It,list:Rt},setToken};return $e.namespace&&(window[$e.namespace]=Tt),Tt}function getVersion(){return version}function gradient($e,De){$e.style.position="relative",$e.style.height="200px",$e.style.overflow="hidden";let Be=0;const He=Array.from($e.children);for(const Ge of He){const We=Ge.offsetHeight;Be+We>200?Ge.remove():Be+=We}const Ke=document.createElement("style");Ke.innerHTML=`
37
37
  ${De.selector}::before {
38
38
  content: '';
@@ -44,4 +44,4 @@ CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque
44
44
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0), white);
45
45
  pointer-events: none;
46
46
  }
47
- `,document.head.appendChild(Ke)}async function fetchContent($e){try{const De=await fetch($e);return De.ok?await De.text():(console.error(`Failed to fetch content from ${$e}: ${De.statusText}`),null)}catch(De){return console.error(`Error fetching content from ${$e}:`,De),null}}async function getContent($e){if($e.contentType==="selector"&&$e.content){const De=document.querySelector($e.content);if(De)return De.innerHTML;console.warn(`Source element for selector '${$e.content}' not found`)}else if($e.contentType==="url"&&$e.content){const De=await fetchContent($e.content);if(De)return De;console.warn(`Failed to fetch content from URL '${$e.content}'`)}else if($e.content)return $e.content;return""}async function insert($e,De){const Fe=De.insertionPoint||"inside",Be=await getContent(De);switch(Fe){case"before":$e.insertAdjacentHTML("beforebegin",Be);break;case"after":$e.insertAdjacentHTML("afterend",Be);break;case"inside":default:$e.innerHTML+=Be;break}}async function replace($e,De){const Fe=await getContent(De);$e.innerHTML=Fe}async function wrap($e,De){const Fe=await getContent(De);$e.innerHTML=Fe.replace("${content}",$e.innerHTML)}async function init$1({enabled:$e=!1,rules:De}){$e&&onDOMContentLoaded(async()=>{const Fe=await isAuthenticated(),Be=window.location.href;for(const He of De){const Ke=document.querySelectorAll(He.selector);if(!(He.path&&!new RegExp(He.path).test(Be)))for(const Ge of Ke){const We=Ge;if(!(He.authenticated!==void 0&&He.authenticated!==Fe))switch(He.transform){case"insert":await insert(We,He);break;case"replace":await replace(We,He);break;case"remove":Ge.remove();break;case"wrap":await wrap(We,He);break;case"gradient":gradient(We,He);break;default:console.warn(`Unknown transform type: ${He.transform}`)}}}})}const ACCESS_TOKEN="access_token";function handleTokenFromQuerystring(){const $e=new URLSearchParams(window.location.hash.substring(1)),De=$e.get(ACCESS_TOKEN);if(De){setToken(De);const Fe=new URL(window.location.href);$e.delete(ACCESS_TOKEN),Fe.hash=$e.toString(),window.history.replaceState(null,"",Fe)}}const REFRESH_KEY="sesamy-refresh",DEPRECATED_REFRESH_KEY="force-refetch-entitlements";function handleForceRefreshFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(DEPRECATED_REFRESH_KEY),Fe=$e.get(REFRESH_KEY);if(De!==null||Fe!==null){const Be=new URL(window.location.href);$e.delete(DEPRECATED_REFRESH_KEY),$e.delete(REFRESH_KEY),Be.search=$e.toString(),clearCache(),window.history.replaceState(null,"",Be)}}function extractJwt($e){const De=$e.split(".")[1],Fe=atob(De);return JSON.parse(Fe)}function handleSignedLinksFromQuerystring(){var Be,He,Ke,Ge;const $e=new URLSearchParams(window.location.search),De=$e.get("sesamy-token")||$e.get("token");if(!De)return;try{const We=extractJwt(De),Ze=new Date(We.exp*1e3),Xe={id:"",title:(Be=We.p)==null?void 0:Be.toString(),sku:(He=We.s)==null?void 0:He.toString(),purchaseOptionsId:(Ke=We.pid)==null?void 0:Ke.toString(),url:(Ge=We.url)==null?void 0:Ge.toString(),token:De,type:"article",expiresAt:Ze.toISOString(),createdAt:new Date(We.iat).toISOString(),updatedAt:new Date(We.iat).toISOString()};addSignedLink(Xe)}catch(We){log(`Failed to extract signed link ${We}`)}const Fe=new URL(window.location.href);Fe.searchParams.delete("ss"),Fe.searchParams.delete("se"),Fe.searchParams.delete("sp"),Fe.searchParams.delete("so"),Fe.searchParams.delete("token"),Fe.searchParams.delete("sesamy-token"),window.history.replaceState(null,"",Fe)}const SESAMY_USER="sesamy-user";async function handleUserFromQuerystring(){var He;const De=(He=new URLSearchParams(window.location.search).get(SESAMY_USER))==null?void 0:He.toLowerCase();if(!De)return;const Fe=await getUser();(Fe==null?void 0:Fe.email)!==De?(log(`Current user does not match sesamy user: ${Fe==null?void 0:Fe.email} !== ${De}`),clearCache(),loginWithRedirect({authorizationParams:{login_hint:De}})):log(`Current user matches sesamy user: ${Fe==null?void 0:Fe.email} === ${De}`);const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_USER),window.history.replaceState(null,"",Be)}const PURCHASE_KEY="sesamy-purchase";function handlePurchaseFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(PURCHASE_KEY);if(De!==null){const Fe=new URL(window.location.href);$e.delete(PURCHASE_KEY),Fe.search=$e.toString(),log(`Purchase ${De}`),triggerEvent(Events.PURCHASE,{itemSrc:De}),clearCache(),window.history.replaceState(null,"",Fe)}}const SESAMY_LOGIN="sesamy-login",SESAMY_LOGIN_LEGACY="sesamy_login";async function handleLoginFromQuerystring(){const $e=new URLSearchParams(window.location.search);if(!($e.get(SESAMY_LOGIN)||$e.get(SESAMY_LOGIN_LEGACY)))return;await isAuthenticated()||loginWithRedirect();const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_LOGIN),window.history.replaceState(null,"",Be)}const SESAMY_DEBUG="sesamy-debug";async function handleDebugFromQuerystring(){var Be;const De=(Be=new URLSearchParams(window.location.search).get(SESAMY_DEBUG))==null?void 0:Be.toLowerCase();if(!De)return;setDebug(De==="true");const Fe=new URL(window.location.href);Fe.searchParams.delete(SESAMY_DEBUG),window.history.replaceState(null,"",Fe)}function getReferrer(){if(!document.referrer.length)return;const $e=new URL(document.referrer);if(!($e.hostname===window.location.hostname||$e.hostname.includes("sesamy")))return document.referrer}async function handleAttribution($e){if(!isBrowser())return;const De=new URLSearchParams(window.location.search),Fe={utmSource:De.get("utm_source")??void 0,utmMedium:De.get("utm_medium")??void 0,utmCampaign:De.get("utm_campaign")??void 0,utmTerm:De.get("utm_term")??void 0,utmContent:De.get("utm_content")??void 0,ref:De.get("ref")??void 0,referrer:getReferrer()},[Be]=$e.content.list();Be!=null&&Be.url&&(Fe.itemSrc=Be.url,Fe.publisherContentId=Be.id),setAttribution(Fe)}function handleLoginReload(){sessionStorage.getItem(SESMAY_CONTENT_RELOAD_KEY)==="true"&&(sessionStorage.removeItem(SESMAY_CONTENT_RELOAD_KEY),window.location.search.includes("code=")||(log("Reloading page to get query params in incognito browser"),window.location.reload()))}async function handleLinks($e){const De=He=>Ke=>{Ke.preventDefault();try{He()}catch(Ge){console.error("Error handling click:",Ge)}},Fe=(He,Ke)=>{try{document.querySelectorAll(He).forEach(We=>{We.addEventListener("click",De(Ke))})}catch(Ge){console.error(`Error attaching event handlers (selector: ${He}):`,Ge)}};Fe('[sesamy-link="login"]',()=>$e.auth.loginWithRedirect()),Fe('[sesamy-link="logout"]',()=>$e.auth.logout());const Be=await $e.generateLink({target:"account"});Be&&Fe('[sesamy-link="account"]',()=>{window.location.href=Be})}async function handleVisibility($e){const De=await $e.auth.isAuthenticated();try{document.querySelectorAll(`[sesamy-visibility="${De?"not-logged-in":"logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="none")}),document.querySelectorAll(`[sesamy-visibility="${De?"logged-in":"not-logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="")})}catch(Fe){console.error("Error handling visibility:",Fe)}}exports.isInitialized=!1;async function initOtherServices($e,De){log(`Init with config: ${JSON.stringify($e)}`);try{handleLoginReload(),initAnalytics({clientId:$e.clientId,environment:$e.environment,...$e.analytics}),await init$3({clientId:$e.clientId,organization:$e.organization,environment:$e.environment,...$e.auth}),init$2($e,De),$e.transform&&await init$1($e.transform),handleDebugFromQuerystring(),handleAttribution(De),handleTokenFromQuerystring(),handleForceRefreshFromQuerystring(),handleSignedLinksFromQuerystring(),await handleLoginFromQuerystring(),await handleUserFromQuerystring(),handlePurchaseFromQuerystring(),await handleVisibility(De),await handleLinks(De),exports.isInitialized=!0,triggerEvent(Events.READY,{})}catch(Fe){log(`Failed to init ${Fe.message}`)}}async function init($e){var Be;log("Initializing Sesamy");const De=((Be=$e.api)==null?void 0:Be.namespace)||"sesamy";if(isBrowser()&&De in window)return log("Sesamy already initialized. This is likely due to a duplicate import"),exports.isInitialized=!0,window[De];const Fe=registerAPI({clientId:$e.clientId,environment:$e.environment,...$e.api});return isBrowser()?($e.awaitAllServices?await initOtherServices($e,Fe):initOtherServices($e,Fe),Fe):(exports.isInitialized=!0,Fe)}if(isBrowser()){const $e=document.getElementById("sesamy-js");if($e!=null&&$e.textContent)try{const De=JSON.parse($e.textContent);init(De)}catch(De){console.error("Failed to parse config",De)}}exports.init=init;
47
+ `,document.head.appendChild(Ke)}async function fetchContent($e){try{const De=await fetch($e);return De.ok?await De.text():(console.error(`Failed to fetch content from ${$e}: ${De.statusText}`),null)}catch(De){return console.error(`Error fetching content from ${$e}:`,De),null}}async function getContent($e){if($e.contentType==="selector"&&$e.content){const De=document.querySelector($e.content);if(De)return De.innerHTML;console.warn(`Source element for selector '${$e.content}' not found`)}else if($e.contentType==="url"&&$e.content){const De=await fetchContent($e.content);if(De)return De;console.warn(`Failed to fetch content from URL '${$e.content}'`)}else if($e.content)return $e.content;return""}async function insert($e,De){const Fe=De.insertionPoint||"inside",Be=await getContent(De);switch(Fe){case"before":$e.insertAdjacentHTML("beforebegin",Be);break;case"after":$e.insertAdjacentHTML("afterend",Be);break;case"inside":default:$e.innerHTML+=Be;break}}async function replace($e,De){const Fe=await getContent(De);$e.innerHTML=Fe}async function wrap($e,De){const Fe=await getContent(De);$e.innerHTML=Fe.replace("${content}",$e.innerHTML)}async function init$1({enabled:$e=!1,rules:De}){$e&&onDOMContentLoaded(async()=>{const Fe=await isAuthenticated(),Be=window.location.href;for(const He of De){const Ke=document.querySelectorAll(He.selector);if(!(He.path&&!new RegExp(He.path).test(Be)))for(const Ge of Ke){const We=Ge;if(!(He.authenticated!==void 0&&He.authenticated!==Fe))switch(He.transform){case"insert":await insert(We,He);break;case"replace":await replace(We,He);break;case"remove":Ge.remove();break;case"wrap":await wrap(We,He);break;case"gradient":gradient(We,He);break;default:console.warn(`Unknown transform type: ${He.transform}`)}}}})}const ACCESS_TOKEN="access_token";function handleTokenFromQuerystring(){const $e=new URLSearchParams(window.location.hash.substring(1)),De=$e.get(ACCESS_TOKEN);if(De){setToken(De);const Fe=new URL(window.location.href);$e.delete(ACCESS_TOKEN),Fe.hash=$e.toString(),window.history.replaceState(null,"",Fe)}}const REFRESH_KEY="sesamy-refresh",DEPRECATED_REFRESH_KEY="force-refetch-entitlements";function handleForceRefreshFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(DEPRECATED_REFRESH_KEY),Fe=$e.get(REFRESH_KEY);if(De!==null||Fe!==null){const Be=new URL(window.location.href);$e.delete(DEPRECATED_REFRESH_KEY),$e.delete(REFRESH_KEY),Be.search=$e.toString(),clearCache(),window.history.replaceState(null,"",Be)}}function extractJwt($e){const De=$e.split(".")[1],Fe=atob(De);return JSON.parse(Fe)}function handleSignedLinksFromQuerystring(){var Be,He,Ke,Ge;const $e=new URLSearchParams(window.location.search),De=$e.get("sesamy-token")||$e.get("token");if(!De)return;try{const We=extractJwt(De),Ze=new Date(We.exp*1e3),Xe={id:"",title:(Be=We.p)==null?void 0:Be.toString(),sku:(He=We.s)==null?void 0:He.toString(),purchaseOptionsId:(Ke=We.pid)==null?void 0:Ke.toString(),url:(Ge=We.url)==null?void 0:Ge.toString(),token:De,type:"article",expiresAt:Ze.toISOString(),createdAt:new Date(We.iat).toISOString(),updatedAt:new Date(We.iat).toISOString()};addSignedLink(Xe)}catch(We){log(`Failed to extract signed link ${We}`)}const Fe=new URL(window.location.href);Fe.searchParams.delete("ss"),Fe.searchParams.delete("se"),Fe.searchParams.delete("sp"),Fe.searchParams.delete("so"),Fe.searchParams.delete("token"),Fe.searchParams.delete("sesamy-token"),window.history.replaceState(null,"",Fe)}const SESAMY_USER="sesamy-user";async function handleUserFromQuerystring(){var He;const De=(He=new URLSearchParams(window.location.search).get(SESAMY_USER))==null?void 0:He.toLowerCase();if(!De)return;const Fe=await getUser();(Fe==null?void 0:Fe.email)!==De?(log(`Current user does not match sesamy user: ${Fe==null?void 0:Fe.email} !== ${De}`),clearCache(),loginWithRedirect({authorizationParams:{login_hint:De}})):log(`Current user matches sesamy user: ${Fe==null?void 0:Fe.email} === ${De}`);const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_USER),window.history.replaceState(null,"",Be)}const PURCHASE_KEY="sesamy-purchase";function handlePurchaseFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(PURCHASE_KEY);if(De!==null){const Fe=new URL(window.location.href);$e.delete(PURCHASE_KEY),Fe.search=$e.toString(),log(`Purchase ${De}`),triggerEvent(Events.PURCHASE,{itemSrc:De}),clearCache(),window.history.replaceState(null,"",Fe)}}const SESAMY_LOGIN="sesamy-login",SESAMY_LOGIN_LEGACY="sesamy_login";async function handleLoginFromQuerystring(){const $e=new URLSearchParams(window.location.search);if(!($e.get(SESAMY_LOGIN)||$e.get(SESAMY_LOGIN_LEGACY)))return;await isAuthenticated()||loginWithRedirect();const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_LOGIN),window.history.replaceState(null,"",Be)}const SESAMY_DEBUG="sesamy-debug";async function handleDebugFromQuerystring(){var Be;const De=(Be=new URLSearchParams(window.location.search).get(SESAMY_DEBUG))==null?void 0:Be.toLowerCase();if(!De)return;setDebug(De==="true");const Fe=new URL(window.location.href);Fe.searchParams.delete(SESAMY_DEBUG),window.history.replaceState(null,"",Fe)}function getReferrer(){if(!document.referrer.length)return;const $e=new URL(document.referrer);if(!($e.hostname===window.location.hostname||$e.hostname.includes("sesamy")))return document.referrer}async function handleAttribution($e){if(!isBrowser())return;const De=new URLSearchParams(window.location.search),Fe={utmSource:De.get("utm_source")??void 0,utmMedium:De.get("utm_medium")??void 0,utmCampaign:De.get("utm_campaign")??void 0,utmTerm:De.get("utm_term")??void 0,utmContent:De.get("utm_content")??void 0,ref:De.get("ref")??void 0,referrer:getReferrer()},[Be]=$e.content.list();Be!=null&&Be.url&&(Fe.itemSrc=Be.url,Fe.publisherContentId=Be.id),setAttribution(Fe)}function handleLoginReload(){sessionStorage.getItem(SESMAY_CONTENT_RELOAD_KEY)==="true"&&(sessionStorage.removeItem(SESMAY_CONTENT_RELOAD_KEY),window.location.search.includes("code=")||(log("Reloading page to get query params in incognito browser"),window.location.reload()))}async function handleLinks($e){const De=He=>Ke=>{Ke.preventDefault();try{He()}catch(Ge){console.error("Error handling click:",Ge)}},Fe=(He,Ke)=>{try{document.querySelectorAll(He).forEach(We=>{We.addEventListener("click",De(Ke))})}catch(Ge){console.error(`Error attaching event handlers (selector: ${He}):`,Ge)}};Fe('[sesamy-link="login"]',()=>$e.auth.loginWithRedirect()),Fe('[sesamy-link="logout"]',()=>$e.auth.logout());const Be=await $e.generateLink({target:"account"});Be&&Fe('[sesamy-link="account"]',()=>{window.location.href=Be})}async function handleVisibility($e){const De=await $e.auth.isAuthenticated();try{document.querySelectorAll(`[sesamy-visibility="${De?"not-logged-in":"logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="none")}),document.querySelectorAll(`[sesamy-visibility="${De?"logged-in":"not-logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="")})}catch(Fe){console.error("Error handling visibility:",Fe)}}async function handleLockedContentRedirectUrl($e){var He;const De=getMetaTag("sesamy:locked-content-redirect-url");if(!De)return;const[Fe]=$e.content.list();if(!Fe)return;await $e.entitlements.hasAccess(Fe.url||"",((He=Fe.pass)==null?void 0:He.split(","))||[])||(location.href=De)}exports.isInitialized=!1;async function initOtherServices($e,De){log(`Init with config: ${JSON.stringify($e)}`);try{handleLoginReload(),initAnalytics({clientId:$e.clientId,environment:$e.environment,...$e.analytics}),await init$3({clientId:$e.clientId,organization:$e.organization,environment:$e.environment,...$e.auth}),init$2($e,De),$e.transform&&await init$1($e.transform),handleDebugFromQuerystring(),handleAttribution(De),handleTokenFromQuerystring(),handleForceRefreshFromQuerystring(),handleSignedLinksFromQuerystring(),await handleLoginFromQuerystring(),await handleUserFromQuerystring(),handlePurchaseFromQuerystring(),await handleVisibility(De),await handleLinks(De),await handleLockedContentRedirectUrl(De),exports.isInitialized=!0,triggerEvent(Events.READY,{})}catch(Fe){log(`Failed to init ${Fe.message}`)}}async function init($e){var Be;log("Initializing Sesamy");const De=((Be=$e.api)==null?void 0:Be.namespace)||"sesamy";if(isBrowser()&&De in window)return log("Sesamy already initialized. This is likely due to a duplicate import"),exports.isInitialized=!0,window[De];const Fe=registerAPI({clientId:$e.clientId,environment:$e.environment,...$e.api});return isBrowser()?($e.awaitAllServices?await initOtherServices($e,Fe):initOtherServices($e,Fe),Fe):(exports.isInitialized=!0,Fe)}if(isBrowser()){const $e=document.getElementById("sesamy-js");if($e!=null&&$e.textContent)try{const De=JSON.parse($e.textContent);init(De)}catch(De){console.error("Failed to parse config",De)}}exports.init=init;
@@ -31,8 +31,8 @@ var sesamyJs=function(exports){"use strict";var ar=Object.defineProperty;var or=
31
31
  *
32
32
  * Please keep this comment intact in order to properly abide by the MIT License.
33
33
  *
34
- **/var __webpack_require__={d:($e,De)=>{for(var Fe in De)__webpack_require__.o(De,Fe)&&!__webpack_require__.o($e,Fe)&&Object.defineProperty($e,Fe,{enumerable:!0,get:De[Fe]})},o:($e,De)=>Object.prototype.hasOwnProperty.call($e,De)},__webpack_exports__={};__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__,k:()=>detectIncognito});var __awaiter=function($e,De,Fe,Be){return new(Fe||(Fe=Promise))(function(He,Ke){function Ge(Xe){try{Ze(Be.next(Xe))}catch(Je){Ke(Je)}}function We(Xe){try{Ze(Be.throw(Xe))}catch(Je){Ke(Je)}}function Ze(Xe){var Je;Xe.done?He(Xe.value):(Je=Xe.value,Je instanceof Fe?Je:new Fe(function(Ye){Ye(Je)})).then(Ge,We)}Ze((Be=Be.apply($e,[])).next())})},__generator=function($e,De){var Fe,Be,He,Ke,Ge={label:0,sent:function(){if(1&He[0])throw He[1];return He[1]},trys:[],ops:[]};return Ke={next:We(0),throw:We(1),return:We(2)},typeof Symbol=="function"&&(Ke[Symbol.iterator]=function(){return this}),Ke;function We(Ze){return function(Xe){return function(Je){if(Fe)throw new TypeError("Generator is already executing.");for(;Ke&&(Ke=0,Je[0]&&(Ge=0)),Ge;)try{if(Fe=1,Be&&(He=2&Je[0]?Be.return:Je[0]?Be.throw||((He=Be.return)&&He.call(Be),0):Be.next)&&!(He=He.call(Be,Je[1])).done)return He;switch(Be=0,He&&(Je=[2&Je[0],He.value]),Je[0]){case 0:case 1:He=Je;break;case 4:return Ge.label++,{value:Je[1],done:!1};case 5:Ge.label++,Be=Je[1],Je=[0];continue;case 7:Je=Ge.ops.pop(),Ge.trys.pop();continue;default:if(He=Ge.trys,!((He=He.length>0&&He[He.length-1])||Je[0]!==6&&Je[0]!==2)){Ge=0;continue}if(Je[0]===3&&(!He||Je[1]>He[0]&&Je[1]<He[3])){Ge.label=Je[1];break}if(Je[0]===6&&Ge.label<He[1]){Ge.label=He[1],He=Je;break}if(He&&Ge.label<He[2]){Ge.label=He[2],Ge.ops.push(Je);break}He[2]&&Ge.ops.pop(),Ge.trys.pop();continue}Je=De.call($e,Ge)}catch(Ye){Je=[6,Ye],Be=0}finally{Fe=He=0}if(5&Je[0])throw Je[1];return{value:Je[0]?Je[1]:void 0,done:!0}}([Ze,Xe])}}};function detectIncognito(){return __awaiter(this,void 0,Promise,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,new Promise(function(resolve,reject){var browserName="Unknown";function __callback($e){resolve({isPrivate:$e,browserName})}function identifyChromium(){var $e=navigator.userAgent;return $e.match(/Chrome/)?navigator.brave!==void 0?"Brave":$e.match(/Edg/)?"Edge":$e.match(/OPR/)?"Opera":"Chrome":"Chromium"}function assertEvalToString($e){return $e===eval.toString().length}function feid(){var toFixedEngineID=0;try{eval("(-1).toFixed(-1);")}catch($e){toFixedEngineID=$e.message.length}return toFixedEngineID}function isSafari(){return feid()===44}function isChrome(){return feid()===51}function isFirefox(){return feid()===25}function isMSIE(){return navigator.msSaveBlob!==void 0&&assertEvalToString(39)}function newSafariTest(){var $e=String(Math.random());try{window.indexedDB.open($e,1).onupgradeneeded=function(De){var Fe,Be,He=(Fe=De.target)===null||Fe===void 0?void 0:Fe.result;try{He.createObjectStore("test",{autoIncrement:!0}).put(new Blob),__callback(!1)}catch(Ge){var Ke=Ge;return Ge instanceof Error&&(Ke=(Be=Ge.message)!==null&&Be!==void 0?Be:Ge),typeof Ke!="string"?void __callback(!1):void __callback(Ke.includes("BlobURLs are not yet supported"))}finally{He.close(),window.indexedDB.deleteDatabase($e)}}}catch{__callback(!1)}}function oldSafariTest(){var $e=window.openDatabase,De=window.localStorage;try{$e(null,null,null,null)}catch{return void __callback(!0)}try{De.setItem("test","1"),De.removeItem("test")}catch{return void __callback(!0)}__callback(!1)}function safariPrivateTest(){navigator.maxTouchPoints!==void 0?newSafariTest():oldSafariTest()}function getQuotaLimit(){var $e=window;return $e.performance!==void 0&&$e.performance.memory!==void 0&&$e.performance.memory.jsHeapSizeLimit!==void 0?performance.memory.jsHeapSizeLimit:1073741824}function storageQuotaChromePrivateTest(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function($e,De){__callback(Math.round(De/1048576)<2*Math.round(getQuotaLimit()/1048576))},function($e){reject(new Error("detectIncognito somehow failed to query storage quota: "+$e.message))})}function oldChromePrivateTest(){(0,window.webkitRequestFileSystem)(0,1,function(){__callback(!1)},function(){__callback(!0)})}function chromePrivateTest(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?storageQuotaChromePrivateTest():oldChromePrivateTest()}function firefoxPrivateTest(){__callback(navigator.serviceWorker===void 0)}function msiePrivateTest(){__callback(window.indexedDB===void 0)}function main(){isSafari()?(browserName="Safari",safariPrivateTest()):isChrome()?(browserName=identifyChromium(),chromePrivateTest()):isFirefox()?(browserName="Firefox",firefoxPrivateTest()):isMSIE()?(browserName="Internet Explorer",msiePrivateTest()):reject(new Error("detectIncognito cannot determine the browser"))}main()})];case 1:return[2,_a.sent()]}})})}typeof window<"u"&&(window.detectIncognito=detectIncognito);const __WEBPACK_DEFAULT_EXPORT__=detectIncognito;__webpack_exports__.A;var __webpack_exports__detectIncognito=__webpack_exports__.k;async function isIncognito(){try{const{isPrivate:$e}=await __webpack_exports__detectIncognito();return $e}catch{return!1}}function isBrowser(){return typeof window<"u"}const STORAGE_KEY="sesamyFlags";async function saveFlags($e){try{localStorage.setItem(STORAGE_KEY,JSON.stringify($e))}catch{log("Failed to save flags to localStorage")}}async function setFlag($e,De){const Fe=await listFlags();Fe[$e]=De,await saveFlags(Fe)}async function getFlag($e){return(await listFlags())[$e]}async function deleteFlag($e){const De=await listFlags();$e in De&&(delete De[$e],await saveFlags(De))}async function listFlags(){try{const $e=localStorage.getItem(STORAGE_KEY);return $e?JSON.parse($e):{}}catch{return{}}}let auth0Client,organization,initialized=!1,loginInProgress=!1;isBrowser()&&window.addEventListener("pageshow",()=>{loginInProgress=!1});const ACCESS_TOKEN_KEY="sesamyAccessToken",REFRESH_TOKEN_KEY="sesamyRefreshToken";async function waitForInit(){return initialized?!0:new Promise(($e,De)=>{const Fe=setTimeout(()=>{initialized?$e(!0):De(new Error("Initialization failed: Timeout"))},2e3);window.addEventListener(Events.AUTH_INITIALIZED,()=>{clearTimeout(Fe),$e(!0)})})}async function refreshLocalAccessToken($e){if(!$e)return null;const De=localStorage.getItem(REFRESH_TOKEN_KEY);if(!De)return log("No refresh token found in localstorage"),null;const Fe=new URLSearchParams;Fe.set("client_id",$e.iss),Fe.set("refresh_token",De),Fe.set("grant_type","refresh_token");const Be=new URL($e.iss);Be.pathname="/oauth/token",Be.searchParams.set("user_id",$e.sub);try{const He=await fetch(Be.href,{body:Fe.toString(),method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!He.ok)throw localStorage.removeItem(REFRESH_TOKEN_KEY),new Error("Renew token failed");const Ke=await He.json();return localStorage.setItem(REFRESH_TOKEN_KEY,Ke.refresh_token),localStorage.setItem(ACCESS_TOKEN_KEY,Ke.access_token),Ke.access_token}catch{logout()}}async function getLocalStorageAccessToken(){const $e=localStorage.getItem(ACCESS_TOKEN_KEY);if(!$e)return null;const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3){const Fe=await refreshLocalAccessToken(De);if(Fe)return Fe;localStorage.removeItem(ACCESS_TOKEN_KEY)}return $e}function getTopLevelDomain($e){try{const De=new URL($e).hostname,Fe=De.split(".");return Fe.length>1?Fe.slice(-2).join("."):De}catch{return null}}async function init$3($e){if($e.enabled===!1)return;organization=$e.organization;const Be={domain:await getFlag("newAuth")&&$e.domain?$e.domain:getBaseUrl("token",$e.environment),clientId:$e.clientId,useCookiesForTransactions:!0};if(getTopLevelDomain(window.location.href)!==getTopLevelDomain(getBaseUrl("auth",$e.environment))&&(Be.cacheLocation="localstorage",Be.useRefreshTokens=!0),auth0Client=await oe$1(Be),window.location.search.includes("code=")){log("Code found in URL, handling redirect");try{const Ge=await auth0Client.handleRedirectCallback();log(`Login result: ${JSON.stringify(Ge)}`);const We=await auth0Client.getUser();if(!We)throw log("No user found"),new Error("No user found");log(`User found ${JSON.stringify(We)}`),triggerEvent(Events.AUTHENTICATED,We),log("Rewrite url")}catch(Ge){alert("There was an error logging in"),console.error(Ge)}const He=new URL(location.href),Ke=He.searchParams;Ke.delete("code"),Ke.delete("state"),He.search=Ke.toString(),window.history.replaceState({},document.title,He.toString())}initialized=!0,triggerEvent(Events.AUTH_INITIALIZED,{})}async function isAuthenticated(){return await waitForInit(),await getLocalStorageAccessToken()?!0:auth0Client?auth0Client.isAuthenticated():!1}async function getUser(){return await waitForInit(),await getLocalStorageAccessToken()?(log("Using local user"),{sub:"local",name:"Local User"}):auth0Client?auth0Client.getUser():null}async function loginWithRedirect($e){if(loginInProgress){log("Login already in progress");return}if(loginInProgress=!0,await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),!auth0Client)throw new Error("Auth0 client not initialized");const De=($e==null?void 0:$e.authorizationParams)||{};return await isIncognito()&&navigator.userAgent.includes("Safari")&&navigator.userAgent.includes("iPhone")&&sessionStorage.setItem(SESMAY_CONTENT_RELOAD_KEY,"true"),auth0Client.loginWithRedirect({...$e,authorizationParams:{organization,redirect_uri:window.location.href,ui_locales:getLanguage(),...De}})}async function getTokenSilently($e=!0,De=!1){await waitForInit();const Fe=await getLocalStorageAccessToken();if(Fe)return Fe;try{if(!auth0Client)return log("Auth client not initialized"),null;let Be=await auth0Client.getTokenSilently();const He=getPayloadFromJwt(Be);return De&&(He!=null&&He.exp)&&He.exp+3600<new Date().getTime()/1e3&&(Be=await auth0Client.getTokenSilently({cacheMode:De?"off":"on"})),Be}catch(Be){const He=Be;if(log(`Failed to get token silently: ${He.message}`),He.message==="Invalid refresh token"&&await logout(),$e)throw Be;return null}}async function logout($e={}){if(await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),triggerEvent(Events.LOGOUT,{}),!!auth0Client)return log(`Logout with options: ${JSON.stringify($e)}`),auth0Client.logout({...$e,logoutParams:{returnTo:window.location.href,...$e.logoutParams}})}function getPayloadFromJwt($e){const De=$e.split(".");if(De.length!==3)return null;const Be=De[1].replace(/-/g,"+").replace(/_/g,"/"),He=decodeURIComponent(atob(Be).split("").map(function(Ke){return"%"+("00"+Ke.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(He)}async function setToken($e){const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3)throw new Error("Invalid token");log("Set token"),localStorage.setItem(ACCESS_TOKEN_KEY,$e),triggerEvent(Events.AUTHENTICATED,De)}const defaultSkip=($e,De)=>De.skipDedupe||De.method!=="GET",defaultKey=($e,De)=>De.method+"@"+$e,defaultResolver=$e=>$e.clone(),dedupe=({skip:$e=defaultSkip,key:De=defaultKey,resolver:Fe=defaultResolver}={})=>{const Be=new Map;return He=>(Ke,Ge)=>{if($e(Ke,Ge))return He(Ke,Ge);const We=De(Ke,Ge);if(!Be.has(We))Be.set(We,[]);else return new Promise((Ze,Xe)=>{Be.get(We).push([Ze,Xe])});try{return He(Ke,Ge).then(Ze=>(Be.get(We).forEach(([Xe])=>Xe(Fe(Ze))),Be.delete(We),Ze)).catch(Ze=>{throw Be.get(We).forEach(([,Xe])=>Xe(Ze)),Be.delete(We),Ze})}catch(Ze){return Be.delete(We),Promise.reject(Ze)}}},defaultDelayRamp=($e,De)=>$e*De,defaultUntil=$e=>$e&&$e.ok,retry=({delayTimer:$e=500,delayRamp:De=defaultDelayRamp,maxAttempts:Fe=10,until:Be=defaultUntil,onRetry:He=null,retryOnNetworkError:Ke=!1,resolveWithLatestResponse:Ge=!1,skip:We}={})=>Ze=>(Xe,Je)=>{let Ye=0;if(We&&We(Xe,Je))return Ze(Xe,Je);const Qe=(et,tt)=>Promise.resolve(Be(et,tt)).then(ct=>ct?et&&Ge?et:tt?Promise.reject(tt):et:(Ye++,!Fe||Ye<=Fe?new Promise(at=>{const ft=De($e,Ye);setTimeout(()=>{typeof He=="function"?Promise.resolve(He({response:et,error:tt,url:Xe,options:Je})).then((ut={})=>{var ot,rt;at(Ze((ot=ut&&ut.url)!==null&&ot!==void 0?ot:Xe,(rt=ut&&ut.options)!==null&&rt!==void 0?rt:Je))}):at(Ze(Xe,Je))},ft)}).then(Qe).catch(at=>{if(!Ke)throw at;return Qe(null,at)}):et&&Ge?et:Promise.reject(tt||new Error("Number of attempts exceeded."))));return Ze(Xe,Je).then(Qe).catch(et=>{if(!Ke)throw et;return Qe(null,et)})},JSON_MIME="application/json",CONTENT_TYPE_HEADER="Content-Type",FETCH_ERROR=Symbol(),CATCHER_FALLBACK=Symbol();function extractContentType($e={}){var De;return(De=Object.entries($e).find(([Fe])=>Fe.toLowerCase()===CONTENT_TYPE_HEADER.toLowerCase()))===null||De===void 0?void 0:De[1]}function isLikelyJsonMime($e){return/^application\/.*json.*/.test($e)}const mix=function($e,De,Fe=!1){return Object.entries(De).reduce((Be,[He,Ke])=>{const Ge=$e[He];return Array.isArray(Ge)&&Array.isArray(Ke)?Be[He]=Fe?[...Ge,...Ke]:Ke:typeof Ge=="object"&&typeof Ke=="object"?Be[He]=mix(Ge,Ke,Fe):Be[He]=Ke,Be},{...$e})},config={options:{},errorType:"text",polyfills:{},polyfill($e,De=!0,Fe=!1,...Be){const He=this.polyfills[$e]||(typeof self<"u"?self[$e]:null)||(typeof global<"u"?global[$e]:null);if(De&&!He)throw new Error($e+" is not defined");return Fe&&He?new He(...Be):He}};function setOptions($e,De=!1){config.options=De?$e:mix(config.options,$e)}function setPolyfills($e,De=!1){config.polyfills=De?$e:mix(config.polyfills,$e)}function setErrorType($e){config.errorType=$e}const middlewareHelper=$e=>De=>$e.reduceRight((Fe,Be)=>Be(Fe),De)||De;class WretchError extends Error{}const resolver=$e=>{const De=Object.create(null);$e=$e._addons.reduce((ot,rt)=>rt.beforeRequest&&rt.beforeRequest(ot,$e._options,De)||ot,$e);const{_url:Fe,_options:Be,_config:He,_catchers:Ke,_resolvers:Ge,_middlewares:We,_addons:Ze}=$e,Xe=new Map(Ke),Je=mix(He.options,Be);let Ye=Fe;const Qe=middlewareHelper(We)((ot,rt)=>(Ye=ot,He.polyfill("fetch")(ot,rt)))(Fe,Je),et=new Error,tt=Qe.catch(ot=>{throw{[FETCH_ERROR]:ot}}).then(ot=>{var rt;if(!ot.ok){const lt=new WretchError;if(lt.cause=et,lt.stack=lt.stack+`
35
- CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque")throw lt;const pt=He.errorType==="json"||((rt=ot.headers.get("Content-Type"))===null||rt===void 0?void 0:rt.split(";")[0])==="application/json";return(He.errorType?pt?ot.text():ot[He.errorType]():Promise.resolve(ot.body)).then(vt=>{throw lt.message=typeof vt=="string"?vt:ot.statusText,vt&&(pt&&typeof vt=="string"?(lt.text=vt,lt.json=JSON.parse(vt)):lt[He.errorType]=vt),lt})}return ot}),ct=ot=>ot.catch(rt=>{const lt=Object.prototype.hasOwnProperty.call(rt,FETCH_ERROR),pt=lt?rt[FETCH_ERROR]:rt,gt=(pt==null?void 0:pt.status)&&Xe.get(pt.status)||Xe.get(pt==null?void 0:pt.name)||lt&&Xe.has(FETCH_ERROR)&&Xe.get(FETCH_ERROR);if(gt)return gt(pt,$e);const vt=Xe.get(CATCHER_FALLBACK);if(vt)return vt(pt,$e);throw pt}),at=ot=>rt=>ct(ot?tt.then(lt=>lt&&lt[ot]()).then(lt=>rt?rt(lt):lt):tt.then(lt=>rt?rt(lt):lt)),ft={_wretchReq:$e,_fetchReq:Qe,_sharedState:De,res:at(null),json:at("json"),blob:at("blob"),formData:at("formData"),arrayBuffer:at("arrayBuffer"),text:at("text"),error(ot,rt){return Xe.set(ot,rt),this},badRequest(ot){return this.error(400,ot)},unauthorized(ot){return this.error(401,ot)},forbidden(ot){return this.error(403,ot)},notFound(ot){return this.error(404,ot)},timeout(ot){return this.error(408,ot)},internalError(ot){return this.error(500,ot)},fetchError(ot){return this.error(FETCH_ERROR,ot)}},ut=Ze.reduce((ot,rt)=>({...ot,...typeof rt.resolver=="function"?rt.resolver(ot):rt.resolver}),ft);return Ge.reduce((ot,rt)=>rt(ot,$e),ut)},core={_url:"",_options:{},_config:config,_catchers:new Map,_resolvers:[],_deferred:[],_middlewares:[],_addons:[],addon($e){return{...this,_addons:[...this._addons,$e],...$e.wretch}},errorType($e){return{...this,_config:{...this._config,errorType:$e}}},polyfills($e,De=!1){return{...this,_config:{...this._config,polyfills:De?$e:mix(this._config.polyfills,$e)}}},url($e,De=!1){if(De)return{...this,_url:$e};const Fe=this._url.split("?");return{...this,_url:Fe.length>1?Fe[0]+$e+"?"+Fe[1]:this._url+$e}},options($e,De=!1){return{...this,_options:De?$e:mix(this._options,$e)}},headers($e){const De=$e?Array.isArray($e)?Object.fromEntries($e):"entries"in $e?Object.fromEntries($e.entries()):$e:{};return{...this,_options:mix(this._options,{headers:De})}},accept($e){return this.headers({Accept:$e})},content($e){return this.headers({[CONTENT_TYPE_HEADER]:$e})},auth($e){return this.headers({Authorization:$e})},catcher($e,De){const Fe=new Map(this._catchers);return Fe.set($e,De),{...this,_catchers:Fe}},catcherFallback($e){return this.catcher(CATCHER_FALLBACK,$e)},resolve($e,De=!1){return{...this,_resolvers:De?[$e]:[...this._resolvers,$e]}},defer($e,De=!1){return{...this,_deferred:De?[$e]:[...this._deferred,$e]}},middlewares($e,De=!1){return{...this,_middlewares:De?$e:[...this._middlewares,...$e]}},fetch($e=this._options.method,De="",Fe=null){let Be=this.url(De).options({method:$e});const He=extractContentType(Be._options.headers),Ke=this._config.polyfill("FormData",!1),Ge=typeof Fe=="object"&&!(Ke&&Fe instanceof Ke)&&(!Be._options.headers||!He||isLikelyJsonMime(He));return Be=Fe?Ge?Be.json(Fe,He):Be.body(Fe):Be,resolver(Be._deferred.reduce((We,Ze)=>Ze(We,We._url,We._options),Be))},get($e=""){return this.fetch("GET",$e)},delete($e=""){return this.fetch("DELETE",$e)},put($e,De=""){return this.fetch("PUT",De,$e)},post($e,De=""){return this.fetch("POST",De,$e)},patch($e,De=""){return this.fetch("PATCH",De,$e)},head($e=""){return this.fetch("HEAD",$e)},opts($e=""){return this.fetch("OPTIONS",$e)},body($e){return{...this,_options:{...this._options,body:$e}}},json($e,De){const Fe=extractContentType(this._options.headers);return this.content(De||isLikelyJsonMime(Fe)&&Fe||JSON_MIME).body(JSON.stringify($e))}};function factory($e="",De={}){return{...core,_url:$e,_options:De}}factory.default=factory,factory.options=setOptions,factory.errorType=setErrorType,factory.polyfills=setPolyfills,factory.WretchError=WretchError;function clearCache(){return sessionStorage.removeItem(CACHE_TIMESTAMP_KEY),log("Cache cleared"),triggerEvent(Events.CLEAR_CACHE,{}),"Cache cleared"}function isValidHttpUrl($e){let De;try{De=new URL($e)}catch{return!1}return De.protocol==="http:"||De.protocol==="https:"}function decodeItemSrc($e,De){if(isValidHttpUrl($e))return{itemSrc:$e};const[Fe,Be,He]=$e.split(":");return{sku:`${Fe}:${Be}`,purchaseOption:De||He}}function removeTrailingSlash($e){return $e.endsWith("/")?$e.slice(0,-1):$e}function compareUrlWithoutHash($e,De){if(!isValidHttpUrl($e)||!isValidHttpUrl(De))return!1;const Fe=new URL($e),Be=new URL(De);return Fe.origin===Be.origin&&removeTrailingSlash(Fe.pathname)===removeTrailingSlash(Be.pathname)}function generateCheckoutLink($e,De,Fe){const Be=new URL(`${getBaseUrl("checkout3",$e.environment)}`);if(De.language&&Be.searchParams.set("lang",De.language),De.sku)Be.searchParams.set("sku",De.sku),De.purchaseOptionId&&Be.searchParams.set("po-id",De.purchaseOptionId);else if(De.itemSrc){const{sku:We,purchaseOption:Ze,itemSrc:Xe}=decodeItemSrc(De.itemSrc,De.purchaseOptionId);Xe&&Be.searchParams.set("url",Xe),We&&Be.searchParams.set("sku",We),Ze&&Be.searchParams.set("po-id",Ze)}De.email&&Be.searchParams.set("email",De.email),De.business&&Be.searchParams.set("business","true"),De.currency&&Be.searchParams.set("currency",De.currency),De.price&&Be.searchParams.set("price",De.price.toString()),De.discountCode&&Be.searchParams.set("discount-code",De.discountCode),De.attributionItemSrc?Be.searchParams.set("itemSrc",De.attributionItemSrc):Fe.itemSrc&&Be.searchParams.set("itemSrc",Fe.itemSrc),De.attributionPublisherContentId?Be.searchParams.set("publisherContentId",De.attributionPublisherContentId):Fe.publisherContentId&&Be.searchParams.set("publisherContentId",Fe.publisherContentId),De.utmSource?Be.searchParams.set("utm_source",De.utmSource):Fe.utmSource&&Be.searchParams.set("utm_source",Fe.utmSource),De.utmMedium?Be.searchParams.set("utm_medium",De.utmMedium):Fe.utmMedium&&Be.searchParams.set("utm_medium",Fe.utmMedium),De.utmCampaign?Be.searchParams.set("utm_campaign",De.utmCampaign):Fe.utmCampaign&&Be.searchParams.set("utm_campaign",Fe.utmCampaign),De.utmTerm?Be.searchParams.set("utm_term",De.utmTerm):Fe.utmTerm&&Be.searchParams.set("utm_term",Fe.utmTerm),De.utmContent?Be.searchParams.set("utm_content",De.utmContent):Fe.utmContent&&Be.searchParams.set("utm_content",Fe.utmContent);const He=["_ga","_gid","_fbp","_fbc"];document.cookie.split(";").map(We=>{const[Ze,Xe]=We.trim().split("=");return{key:Ze,value:Xe}}).filter(We=>He.some(Ze=>Ze===We.key)).forEach(We=>{Be.searchParams.append(We.key,We.value)});const Ge=new URL(De.redirectUrl||window.location.href);return Ge.searchParams.set("force-refetch-entitlements","true"),De.itemSrc&&Ge.searchParams.set("sesamy-purchase",De.itemSrc),Be.searchParams.set("redirect-url",Ge.toString()),De.paymentMethodsFilter&&Be.searchParams.set("paymentmethods-filter",De.paymentMethodsFilter.flatMap(({provider:We,methods:Ze})=>Ze?Ze.map(Xe=>`${We}|${Xe}`):We).join(",")),Be}const SIGNED_URL_KEY="sesamySignedURLs";function getSignedLinks(){const $e=sessionStorage.getItem(SIGNED_URL_KEY);return $e?JSON.parse($e):[]}function addSignedLink($e){const De=getSignedLinks();De.push($e),log(`Adding signed URL: ${$e}`),sessionStorage.setItem(SIGNED_URL_KEY,JSON.stringify(De))}function removeUndefinedValues($e){const De={};return Object.keys($e).forEach(Fe=>{const Be=$e[Fe];Be!=null&&(De[Fe]=Be.toString())}),De}const ATTRIBUTION_KEY="sesamyAttribution";function parseFromSessionStorage($e){const De=sessionStorage.getItem($e);if(!De)return null;try{return JSON.parse(De).value}catch{return console.error(`Failed to parse ${$e}`),null}}function resetUtmTags($e){return Object.keys($e).find(De=>De.startsWith("utm_"))?{utmSource:void 0,utmMedium:void 0,utmCampaign:void 0,...$e}:$e}function getAttribution(){return parseFromSessionStorage(ATTRIBUTION_KEY)||{}}function setAttribution($e){if($e===null)sessionStorage.removeItem(ATTRIBUTION_KEY);else{log(`Setting attribution ${JSON.stringify($e)}`);const De=getAttribution()??{},Fe=removeUndefinedValues({...De,...resetUtmTags($e)});sessionStorage.setItem(ATTRIBUTION_KEY,JSON.stringify({value:Fe}))}}function createApi($e){const De=getBaseUrl("api2",$e.environment),Fe=st=>async(dt,$t)=>{let Ct=sessionStorage.getItem(CACHE_TIMESTAMP_KEY);Ct||(Ct=Date.now().toString(),sessionStorage.setItem(CACHE_TIMESTAMP_KEY,Ct));const _t={...$t,headers:{...$t.headers,"Cache-Timestamp":Ct}};return st(dt,_t)},Be=(st=!0)=>dt=>async($t,Ct)=>{let _t=null;if(_t=await getTokenSilently(st),!_t){if(st)throw new Error("No access token available");return dt($t,Ct)}const Mt={...Ct,headers:{...Ct.headers,..._t?{Authorization:`Bearer ${_t}`}:{}}};return dt($t,Mt)},He=st=>(dt,$t)=>{if($t.headers.Authorization)return st(dt,$t);const Ct=localStorage.getItem("__anon_id"),_t=btoa(`${$e.clientId}|${Ct}:`),Mt={...$t,headers:{...$t.headers,Authorization:`Basic ${_t}`}};return st(dt,Mt)},Ke=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(),dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]),Ge=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(!1),He,dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]);async function We(st={}){const{waitForEntitlementAfter:dt,includeSignedLinks:$t=!0}=st,Ct=dt?`?wait-for-entitlement-after=${dt.toISOString()}`:"",_t=await isAuthenticated()?await Ke.get(`/entitlements${Ct}`).json():[];return $t&&_t.push(...getSignedLinks()),_t}async function Ze(st,dt=[]){const $t=await We();return $t==null?void 0:$t.find(_t=>{const{sku:Mt,purchaseOption:Ht}=decodeItemSrc(st);let Gt="sku"in _t&&Mt===_t.sku;Gt&&Ht&&"purchaseOptionId"in _t&&(Gt=Ht===_t.purchaseOptionId);const tr=compareUrlWithoutHash(st,_t.url),rr=dt.some(nr=>compareUrlWithoutHash(nr,_t.url));return Gt||tr||rr})}async function Xe(st){const dt=await Ke.get("/entitlements").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function Je(st){return Ke.get(`/entitlements/${encodeURIComponent(st)}/access`).json()}async function Ye(st,dt,$t){const Ct=new URL(getBaseUrl("api2",$e.environment));return Ct.pathname="/proxy",Ct.searchParams.set("url",dt),$t&&Ct.searchParams.set("selector",$t),factory(Ct.toString()).headers({Authorization:`Bearer ${st}`}).get().text()}async function Qe(st){return await isAuthenticated()?await Ke.get(`/fulfillments?sku=${encodeURIComponent(st)}`).json():[]}async function et(){return Ke.get("/contracts").json()}async function tt(st){const dt=await Ke.get("/contracts").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ct(st){const dt=await Ke.post({},`/contracts/${encodeURIComponent(st)}/cancel`).res();return clearCache(),dt.ok}async function at(){return console.warn("getSubscriptions is deprecated, use getContracts instead"),Ke.get("/subscriptions").json()}async function ft(){return Ke.get("/bills").json()}async function ut(st){const dt=await Ke.get("/bills").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ot(){return Ke.get("/transactions").json()}async function rt(st){const dt=await Ke.get("/transactions").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function lt(st,dt){const $t=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).put(dt).json();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),$t}async function pt(st){const dt=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function gt(st){return(await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).get().json())[st]}async function vt(){return await Ke.url("/user-metadata").get().json()}async function Et(){return await Ke.url("/tags").get().json()}async function Pt(st){const dt=await Ke.url(`/tags/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function Nt(st){const dt=await Ke.url("/tags").post(encodeURIComponent(st)).res();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),dt.ok}async function yt(st){return(await Ge.url("/tallies").get().json())[st]}async function It(){return await Ge.url("/tallies").get().json()}async function Rt(st){const dt=await Ge.url(`/tallies/${st}`).delete().res();return clearCache(),dt.ok}async function mt(st,dt){return await Ge.url(`/tallies/${encodeURIComponent(st)}/push`).post(dt).json()}async function At(st){return await Ke.url(`/products/${encodeURIComponent(st)}`).get().json()}async function Ut(){return await getTokenSilently(!1)?await Ke.url("/profile").get().json():null}async function xt(st){const dt=await Ke.url("/profile").patch(st).res();return clearCache(),dt.ok}async function nt(){return await Ke.url("/payment-issues").get().json()}async function it(){return(await Ke.url("/profile/spotify-link").get().json()).isSpotifyLinked}async function ht(){return(await Ke.url("/profile/unlink-spotify").post().res()).ok}async function St(st){const dt=await getTokenSilently(!1);if(!dt)throw new Error("No access token available");const $t=new URL(`${getBaseUrl("access-sync",$e.environment)}/spotify/sesamy-callback`);$t.searchParams.set("access_token",dt),$t.searchParams.set("state",st),window.location.href=$t.toString()}async function bt(st){const dt=await Ke.url(`/products/${encodeURIComponent(st)}/auto-onboard`).post().json();return dt.length&&clearCache(),dt}async function wt(st,dt=3600){const{shortlink:$t}=await factory(SHORTLINK_URL).post({url:st,ttl:dt}).json();return $t}async function kt(st){const dt=await getTokenSilently(!1,!0);let $t;const Ct=st.language||getLanguage(),_t=getAttribution();switch(st.target){case"account":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-payment":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/change-payment-method`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-plan":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/edit-plan`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"consume":$t=new URL(`${getBaseUrl("consume",$e.environment)}/${encodeURIComponent(st.language||Ct)}/@${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.sku)}`),st.episodeId?$t.href+=`/${st.episodeId}`:$t.href+="/listen",$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"checkout":$t=generateCheckoutLink($e,{language:Ct,...st},_t);break;default:throw new Error("Invalid target")}return dt&&($t.hash=`#access_token=${dt}`),st.shorten?wt($t.href,st.ttl):$t.href}async function Tt(st){const dt=getAttribution(),$t=["_ga","_gid","_fbp","_fbc"];return document.cookie.split(";").forEach(_t=>{const Mt=dt,[Ht,Gt]=_t.trim().split("=");$t.includes(Ht)&&!Mt[Ht]&&(Mt[Ht]=Gt)}),(await Ge.url("/checkouts").post({language:getLanguage(),...st,attribution:{...dt,...st.attribution},vendorId:$e.clientId})).json()}async function Lt(st,dt){return(await Ge.url(`/checkouts/${st}`).patch(dt)).json()}async function Ot(st){return(await Ge.url(`/checkouts/${st}`).get()).json()}async function jt(st){return(await Ge.url(`/paywalls/${st}`).get()).json()}async function Ft(){return(await Ge.url("/vendor").get()).json()}async function Bt(){return(await Ke.url("/vendors").get()).json()}async function Vt(st){return(await Ke.url(`/contracts/${encodeURIComponent(st.contractId)}/amendments`).post({amendmentType:st.amendmentType,discountCode:st.discountCode})).json()}async function Kt(st){return await Ke.url(`/amendments/${encodeURIComponent(st)}/confirm`).post(),!0}async function zt(){const st=await getTokenSilently(!1),dt=new URL(`${getBaseUrl("account",$e.environment)}/subscriptions/${$e.clientId}`);st&&(dt.hash=`#access_token=${st}`),window.location.href=dt.toString()}return{autoOnboardProduct:bt,cancelContract:ct,confirmAmendment:Kt,createAmendment:Vt,createCheckout:Tt,deleteTag:Pt,deleteTally:Rt,deleteUserMetadata:pt,generateLink:kt,getBill:ut,getBills:ft,getCheckout:Ot,getProxyContent:Ye,getContract:tt,getContracts:et,getEntitlement:Xe,getEntitlementAccess:Je,getEntitlements:We,getFulfillments:Qe,getPaywall:jt,getPaymentIssues:nt,getProfile:Ut,getProduct:At,getSubscriptions:at,getTally:yt,getTallies:It,getTags:Et,getTransaction:rt,getTransactions:ot,getUserMetadata:gt,hasAccess:Ze,isSpotifyLinked:it,linkSpotify:St,listUserMetadata:vt,openHostedAccountPage:zt,pushTally:mt,setTag:Nt,setUserMetadata:lt,unlinkSpotify:ht,updateCheckout:Lt,updateProfile:xt,getVendorSettings:Ft,listVendors:Bt}}const name="@sesamy/sesamy-js",version="1.35.4";function i$5($e,De,Fe,Be,He){for(De=De.split?De.split("."):De,Be=0;Be<De.length;Be++)$e=$e?$e[De[Be]]:He;return $e===He?Fe:$e}var e="undefined",o$4="object",g$1=function(){},b$4="any",m$1="*",j="__",F$2=typeof process<"u"?process:{};F$2.env&&F$2.env.NODE_ENV;var $$1=typeof document<"u";F$2.versions!=null&&F$2.versions.node!=null,typeof Deno<"u"&&Deno.core,$$1&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent!==void 0&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1($e,De){return De.charAt(0)[$e]()+De.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2($e){return Y$1($e)?U$1("null"):typeof $e=="object"?yn($e):Object.prototype.toString.call($e).slice(8,-1)}function R$1($e,De){De===void 0&&(De=!0);var Fe=J$2($e);return De?H$1(Fe):Fe}function V$1($e,De){return typeof De===$e}var W$1=V$1.bind(null,"function"),q$1=V$1.bind(null,"string"),I$2=V$1.bind(null,"undefined"),Q$1=V$1.bind(null,"boolean");V$1.bind(null,"symbol");function Y$1($e){return $e===null}function nn($e){return R$1($e)==="number"&&!isNaN($e)}function rn($e){return R$1($e)==="array"}function on($e){if(!un($e))return!1;for(var De=$e;Object.getPrototypeOf(De)!==null;)De=Object.getPrototypeOf(De);return Object.getPrototypeOf($e)===De}function un($e){return $e&&(typeof $e=="object"||$e!==null)}function yn($e){return W$1($e.constructor)?$e.constructor.name:null}function hn($e){return $e instanceof Error||q$1($e.message)&&$e.constructor&&nn($e.constructor.stackTraceLimit)}function On($e,De){if(typeof De!="object"||Y$1(De))return!1;if(De instanceof $e)return!0;var Fe=R$1(new $e(""));if(hn(De))for(;De;){if(R$1(De)===Fe)return!0;De=Object.getPrototypeOf(De)}return!1}On.bind(null,TypeError),On.bind(null,SyntaxError);function $n($e,De){var Fe=$e instanceof Element||$e instanceof HTMLDocument;return Fe&&De?Tn($e,De):Fe}function Tn($e,De){return De===void 0&&(De=""),$e&&$e.nodeName===De.toUpperCase()}function _n($e){var De=[].slice.call(arguments,1);return function(){return $e.apply(void 0,[].slice.call(arguments).concat(De))}}_n($n,"form"),_n($n,"button"),_n($n,"input"),_n($n,"select");function Hn($e){return $e?rn($e)?$e:[$e]:[]}function n$1($e){try{return decodeURIComponent($e.replace(/\+/g," "))}catch{return null}}function o$3(){if($$1){var $e=navigator,De=$e.languages;return $e.userLanguage||(De&&De.length?De[0]:$e.language)}}function a$5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}}function s$1($e){return function(De){for(var Fe,Be=Object.create(null),He=/([^&=]+)=?([^&]*)/g;Fe=He.exec(De);){var Ke=n$1(Fe[1]),Ge=n$1(Fe[2]);Ke.substring(Ke.length-2)==="[]"?(Be[Ke=Ke.substring(0,Ke.length-2)]||(Be[Ke]=[])).push(Ge):Be[Ke]=Ge===""||Ge}for(var We in Be){var Ze=We.split("[");Ze.length>1&&(m(Be,Ze.map(function(Xe){return Xe.replace(/[?[\]\\ ]/g,"")}),Be[We]),delete Be[We])}return Be}(function(De){return $$1&&window.location.search.substring(1)}())}function m($e,De,Fe){for(var Be=De.length-1,He=0;He<Be;++He){var Ke=De[He];if(Ke==="__proto__"||Ke==="constructor")break;Ke in $e||($e[Ke]={}),$e=$e[Ke]}$e[De[Be]]=Fe}function y$1(){for(var $e="",De=0,Fe=4294967295*Math.random()|0;De++<36;){var Be="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[De-1],He=15&Fe;$e+=Be=="-"||Be=="4"?Be:(Be=="x"?He:3&He|8).toString(16),Fe=De%8==0?4294967295*Math.random()|0:Fe>>4}return $e}function b$3($e,De){var Fe,Be,He,Ke=null,Ge=0,We=function(){Ge=new Date,Ke=null,He=$e.apply(Fe,Be)};return function(){var Ze=new Date;Ge||(Ge=Ze);var Xe=De-(Ze-Ge);return Fe=this,Be=arguments,Xe<=0?(clearTimeout(Ke),Ke=null,Ge=Ze,He=$e.apply(Fe,Be)):Ke||(Ke=setTimeout(We,Xe)),He}}var l$2="global",o$2=j+"global"+j,n=typeof self===o$4&&self.self===self&&self||typeof global===o$4&&global.global===global&&global||void 0;function a$4($e){return n[o$2][$e]}function f$1($e,De){return n[o$2][$e]=De}function i$4($e){delete n[o$2][$e]}function u$3($e,De,Fe){var Be;try{if(b$2($e)){var He=window[$e];Be=He[De].bind(He)}}catch{}return Be||Fe}n[o$2]||(n[o$2]={});var c$3={};function b$2($e){if(typeof c$3[$e]!==e)return c$3[$e];try{var De=window[$e];De.setItem(e,e),De.removeItem(e)}catch{return c$3[$e]=!1}return c$3[$e]=!0}function v(){return v=Object.assign||function($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De];for(var Be in Fe)Object.prototype.hasOwnProperty.call(Fe,Be)&&($e[Be]=Fe[Be])}return $e},v.apply(this,arguments)}var y="function",b$1="undefined",I$1="@@redux/"+Math.random().toString(36),w=function(){return typeof Symbol===y&&Symbol.observable||"@@observable"}(),E$1=" != "+y;function P($e,De,Fe){var Be;if(typeof De===y&&typeof Fe===b$1&&(Fe=De,De=void 0),typeof Fe!==b$1){if(typeof Fe!==y)throw new Error("enhancer"+E$1);return Fe(P)($e,De)}if(typeof $e!==y)throw new Error("reducer"+E$1);var He=$e,Ke=De,Ge=[],We=Ge,Ze=!1;function Xe(){We===Ge&&(We=Ge.slice())}function Je(){return Ke}function Ye(et){if(typeof et!==y)throw new Error("Listener"+E$1);var tt=!0;return Xe(),We.push(et),function(){if(tt){tt=!1,Xe();var ct=We.indexOf(et);We.splice(ct,1)}}}function Qe(et){if(!on(et))throw new Error("Act != obj");if(typeof et.type===b$1)throw new Error("ActType "+b$1);if(Ze)throw new Error("Dispatch in reducer");try{Ze=!0,Ke=He(Ke,et)}finally{Ze=!1}for(var tt=Ge=We,ct=0;ct<tt.length;ct++)(0,tt[ct])();return et}return Qe({type:"@@redux/INIT"}),(Be={dispatch:Qe,subscribe:Ye,getState:Je,replaceReducer:function(et){if(typeof et!==y)throw new Error("next reducer"+E$1);He=et,Qe({type:"@@redux/INIT"})}})[w]=function(){var et,tt=Ye;return(et={subscribe:function(ct){if(typeof ct!="object")throw new TypeError("Observer != obj");function at(){ct.next&&ct.next(Je())}return at(),{unsubscribe:tt(at)}}})[w]=function(){return this},et},Be}function S($e,De){var Fe=De&&De.type;return"action "+(Fe&&Fe.toString()||"?")+"reducer "+$e+" returns "+b$1}function N$1(){var $e=[].slice.call(arguments);return $e.length===0?function(De){return De}:$e.length===1?$e[0]:$e.reduce(function(De,Fe){return function(){return De(Fe.apply(void 0,[].slice.call(arguments)))}})}function O$1(){var $e=arguments;return function(De){return function(Fe,Be,He){var Ke,Ge=De(Fe,Be,He),We=Ge.dispatch,Ze={getState:Ge.getState,dispatch:function(Xe){return We(Xe)}};return Ke=[].slice.call($e).map(function(Xe){return Xe(Ze)}),v({},Ge,{dispatch:We=N$1.apply(void 0,Ke)(Ge.dispatch)})}}}var A$1=j+"anon_id",_=j+"user_id",x$1=j+"user_traits",k$1="userId",T="anonymousId",z=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],M=["name","EVENTS","config","loaded"],q=z.reduce(function($e,De){return $e[De]=De,$e},{registerPluginType:function($e){return"registerPlugin:"+$e},pluginReadyType:function($e){return"ready:"+$e}}),U=/^utm_/,V=/^an_prop_/,L$1=/^an_trait_/;function C$1($e){var De=$e.storage.setItem;return function(Fe){return function(Be){return function(He){if(He.type===q.bootstrap){var Ke=He.params,Ge=He.user,We=He.persistedUser,Ze=He.initialUser,Xe=We.userId===Ge.userId;We.anonymousId!==Ge.anonymousId&&De(A$1,Ge.anonymousId),Xe||De(_,Ge.userId),Ze.traits&&De(x$1,v({},Xe&&We.traits?We.traits:{},Ze.traits));var Je=Object.keys(He.params);if(Je.length){var Ye=Ke.an_uid,Qe=Ke.an_event,et=Je.reduce(function(tt,ct){if(ct.match(U)||ct.match(/^(d|g)clid/)){var at=ct.replace(U,"");tt.campaign[at==="campaign"?"name":at]=Ke[ct]}return ct.match(V)&&(tt.props[ct.replace(V,"")]=Ke[ct]),ct.match(L$1)&&(tt.traits[ct.replace(L$1,"")]=Ke[ct]),tt},{campaign:{},props:{},traits:{}});Fe.dispatch(v({type:q.params,raw:Ke},et,Ye?{userId:Ye}:{})),Ye&&setTimeout(function(){return $e.identify(Ye,et.traits)},0),Qe&&setTimeout(function(){return $e.track(Qe,et.props)},0),Object.keys(et.campaign).length&&Fe.dispatch({type:q.campaign,campaign:et.campaign})}}return Be(He)}}}}function R($e){return function(De,Fe){if(De===void 0&&(De={}),Fe===void 0&&(Fe={}),Fe.type===q.setItemEnd){if(Fe.key===A$1)return v({},De,{anonymousId:Fe.value});if(Fe.key===_)return v({},De,{userId:Fe.value})}switch(Fe.type){case q.identify:return Object.assign({},De,{userId:Fe.userId,traits:v({},De.traits,Fe.traits)});case q.reset:return[_,A$1,x$1].forEach(function(Be){$e.removeItem(Be)}),Object.assign({},De,{userId:null,anonymousId:null,traits:{}});default:return De}}}function $($e){return{userId:$e.getItem(_),anonymousId:$e.getItem(A$1),traits:$e.getItem(x$1)}}var D=function($e){return j+"TEMP"+j+$e};function B($e){var De=$e.storage,Fe=De.setItem,Be=De.removeItem,He=De.getItem;return function(Ke){return function(Ge){return function(We){var Ze=We.userId,Xe=We.traits,Je=We.options;if(We.type===q.reset&&([_,x$1,A$1].forEach(function(et){Be(et)}),[k$1,T,"traits"].forEach(function(et){i$4(D(et))})),We.type===q.identify){He(A$1)||Fe(A$1,y$1());var Ye=He(_),Qe=He(x$1)||{};Ye&&Ye!==Ze&&Ke.dispatch({type:q.userIdChanged,old:{userId:Ye,traits:Qe},new:{userId:Ze,traits:Xe},options:Je}),Ze&&Fe(_,Ze),Xe&&Fe(x$1,v({},Qe,Xe))}return Ge(We)}}}}var X={};function J$1($e,De){X[$e]&&W$1(X[$e])&&(X[$e](De),delete X[$e])}function W($e,De,Fe){return new Promise(function(Be,He){return De()?Be($e):Fe<1?He(v({},$e,{queue:!0})):new Promise(function(Ke){return setTimeout(Ke,10)}).then(function(Ke){return W($e,De,Fe-10).then(Be,He)})})}function H($e){return{abort:$e}}function F$1($e,De,Fe){var Be={},He=De(),Ke=$e.getState(),Ge=Ke.plugins,We=Ke.queue,Ze=Ke.user;if(!Ke.context.offline&&We&&We.actions&&We.actions.length){var Xe=We.actions.reduce(function(Ye,Qe,et){return Ge[Qe.plugin].loaded?(Ye.process.push(Qe),Ye.processIndex.push(et)):(Ye.requeue.push(Qe),Ye.requeueIndex.push(et)),Ye},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(Xe.processIndex&&Xe.processIndex.length){Xe.processIndex.forEach(function(Ye){var Qe=We.actions[Ye],et=Qe.plugin,tt=Qe.payload.type,ct=He[et][tt];if(ct&&W$1(ct)){var at,ft=function(rt,lt){return rt===void 0&&(rt={}),lt===void 0&&(lt={}),[k$1,T].reduce(function(pt,gt){return rt.hasOwnProperty(gt)&&lt[gt]&&lt[gt]!==rt[gt]&&(pt[gt]=lt[gt]),pt},rt)}(Qe.payload,Ze),ut=Be[ft.meta.rid];if(!ut&&(at=ct({payload:ft,config:Ge[et].config,instance:Fe,abort:H}))&&on(at)&&at.abort)return void(Be[ft.meta.rid]=!0);if(!ut){var ot=tt+":"+et;$e.dispatch(v({},ft,{type:ot,_:{called:ot,from:"queueDrain"}}))}}});var Je=We.actions.filter(function(Ye,Qe){return!~Xe.processIndex.indexOf(Qe)});We.actions=Je}}}var G$1=function($e){var De=$e.data,Fe=$e.action,Be=$e.instance,He=$e.state,Ke=$e.allPlugins,Ge=$e.allMatches,We=$e.store,Ze=$e.EVENTS;try{var Xe=He.plugins,Je=He.context,Ye=Fe.type,Qe=Ye.match(K),et=De.exact.map(function(at){return at.pluginName});Qe&&(et=Ge.during.map(function(at){return at.pluginName}));var tt=function(at,ft){return function(ut,ot,rt){var lt=ot.config,pt=ot.name,gt=pt+"."+ut.type;rt&&(gt=rt.event);var vt=ut.type.match(K)?function(Et,Pt,Nt,yt,It){return function(Rt,mt){var At=yt?yt.name:Et,Ut=mt&&ae(mt)?mt:Nt;if(yt&&(!(Ut=mt&&ae(mt)?mt:[Et]).includes(Et)||Ut.length!==1))throw new Error("Method "+Pt+" can only abort "+Et+" plugin. "+JSON.stringify(Ut)+" input valid");return v({},It,{abort:{reason:Rt,plugins:Ut,caller:Pt,_:At}})}}(pt,gt,ft,rt,ut):function(Et,Pt){return function(){throw new Error(Et.type+" action not cancellable. Remove abort in "+Pt)}}(ut,gt);return{payload:ce(ut),instance:at,config:lt||{},abort:vt}}}(Be,et),ct=De.exact.reduce(function(at,ft){var ut=ft.pluginName,ot=ft.methodName,rt=!1;return ot.match(/^initialize/)||ot.match(/^reset/)||(rt=!Xe[ut].loaded),Je.offline&&ot.match(/^(page|track|identify)/)&&(rt=!0),at[""+ut]=rt,at},{});return Promise.resolve(De.exact.reduce(function(at,ft,ut){try{var ot=ft.pluginName;return Promise.resolve(at).then(function(rt){function lt(){return Promise.resolve(rt)}var pt=function(){if(De.namespaced&&De.namespaced[ot])return Promise.resolve(De.namespaced[ot].reduce(function(gt,vt,Et){try{return Promise.resolve(gt).then(function(Pt){return vt.method&&W$1(vt.method)?(function(Rt,mt){var At=ue(Rt);if(At&&At.name===mt){var Ut=ue(At.method);throw new Error([mt+" plugin is calling method "+Rt,"Plugins cant call self","Use "+At.method+" "+(Ut?"or "+Ut.method:"")+" in "+mt+" plugin insteadof "+Rt].join(`
34
+ **/var __webpack_require__={d:($e,De)=>{for(var Fe in De)__webpack_require__.o(De,Fe)&&!__webpack_require__.o($e,Fe)&&Object.defineProperty($e,Fe,{enumerable:!0,get:De[Fe]})},o:($e,De)=>Object.prototype.hasOwnProperty.call($e,De)},__webpack_exports__={};__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__,k:()=>detectIncognito});var __awaiter=function($e,De,Fe,Be){return new(Fe||(Fe=Promise))(function(He,Ke){function Ge(Xe){try{Ze(Be.next(Xe))}catch(Je){Ke(Je)}}function We(Xe){try{Ze(Be.throw(Xe))}catch(Je){Ke(Je)}}function Ze(Xe){var Je;Xe.done?He(Xe.value):(Je=Xe.value,Je instanceof Fe?Je:new Fe(function(Ye){Ye(Je)})).then(Ge,We)}Ze((Be=Be.apply($e,[])).next())})},__generator=function($e,De){var Fe,Be,He,Ke,Ge={label:0,sent:function(){if(1&He[0])throw He[1];return He[1]},trys:[],ops:[]};return Ke={next:We(0),throw:We(1),return:We(2)},typeof Symbol=="function"&&(Ke[Symbol.iterator]=function(){return this}),Ke;function We(Ze){return function(Xe){return function(Je){if(Fe)throw new TypeError("Generator is already executing.");for(;Ke&&(Ke=0,Je[0]&&(Ge=0)),Ge;)try{if(Fe=1,Be&&(He=2&Je[0]?Be.return:Je[0]?Be.throw||((He=Be.return)&&He.call(Be),0):Be.next)&&!(He=He.call(Be,Je[1])).done)return He;switch(Be=0,He&&(Je=[2&Je[0],He.value]),Je[0]){case 0:case 1:He=Je;break;case 4:return Ge.label++,{value:Je[1],done:!1};case 5:Ge.label++,Be=Je[1],Je=[0];continue;case 7:Je=Ge.ops.pop(),Ge.trys.pop();continue;default:if(He=Ge.trys,!((He=He.length>0&&He[He.length-1])||Je[0]!==6&&Je[0]!==2)){Ge=0;continue}if(Je[0]===3&&(!He||Je[1]>He[0]&&Je[1]<He[3])){Ge.label=Je[1];break}if(Je[0]===6&&Ge.label<He[1]){Ge.label=He[1],He=Je;break}if(He&&Ge.label<He[2]){Ge.label=He[2],Ge.ops.push(Je);break}He[2]&&Ge.ops.pop(),Ge.trys.pop();continue}Je=De.call($e,Ge)}catch(Ye){Je=[6,Ye],Be=0}finally{Fe=He=0}if(5&Je[0])throw Je[1];return{value:Je[0]?Je[1]:void 0,done:!0}}([Ze,Xe])}}};function detectIncognito(){return __awaiter(this,void 0,Promise,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,new Promise(function(resolve,reject){var browserName="Unknown";function __callback($e){resolve({isPrivate:$e,browserName})}function identifyChromium(){var $e=navigator.userAgent;return $e.match(/Chrome/)?navigator.brave!==void 0?"Brave":$e.match(/Edg/)?"Edge":$e.match(/OPR/)?"Opera":"Chrome":"Chromium"}function assertEvalToString($e){return $e===eval.toString().length}function feid(){var toFixedEngineID=0;try{eval("(-1).toFixed(-1);")}catch($e){toFixedEngineID=$e.message.length}return toFixedEngineID}function isSafari(){return feid()===44}function isChrome(){return feid()===51}function isFirefox(){return feid()===25}function isMSIE(){return navigator.msSaveBlob!==void 0&&assertEvalToString(39)}function newSafariTest(){var $e=String(Math.random());try{window.indexedDB.open($e,1).onupgradeneeded=function(De){var Fe,Be,He=(Fe=De.target)===null||Fe===void 0?void 0:Fe.result;try{He.createObjectStore("test",{autoIncrement:!0}).put(new Blob),__callback(!1)}catch(Ge){var Ke=Ge;return Ge instanceof Error&&(Ke=(Be=Ge.message)!==null&&Be!==void 0?Be:Ge),typeof Ke!="string"?void __callback(!1):void __callback(Ke.includes("BlobURLs are not yet supported"))}finally{He.close(),window.indexedDB.deleteDatabase($e)}}}catch{__callback(!1)}}function oldSafariTest(){var $e=window.openDatabase,De=window.localStorage;try{$e(null,null,null,null)}catch{return void __callback(!0)}try{De.setItem("test","1"),De.removeItem("test")}catch{return void __callback(!0)}__callback(!1)}function safariPrivateTest(){navigator.maxTouchPoints!==void 0?newSafariTest():oldSafariTest()}function getQuotaLimit(){var $e=window;return $e.performance!==void 0&&$e.performance.memory!==void 0&&$e.performance.memory.jsHeapSizeLimit!==void 0?performance.memory.jsHeapSizeLimit:1073741824}function storageQuotaChromePrivateTest(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function($e,De){__callback(Math.round(De/1048576)<2*Math.round(getQuotaLimit()/1048576))},function($e){reject(new Error("detectIncognito somehow failed to query storage quota: "+$e.message))})}function oldChromePrivateTest(){(0,window.webkitRequestFileSystem)(0,1,function(){__callback(!1)},function(){__callback(!0)})}function chromePrivateTest(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?storageQuotaChromePrivateTest():oldChromePrivateTest()}function firefoxPrivateTest(){__callback(navigator.serviceWorker===void 0)}function msiePrivateTest(){__callback(window.indexedDB===void 0)}function main(){isSafari()?(browserName="Safari",safariPrivateTest()):isChrome()?(browserName=identifyChromium(),chromePrivateTest()):isFirefox()?(browserName="Firefox",firefoxPrivateTest()):isMSIE()?(browserName="Internet Explorer",msiePrivateTest()):reject(new Error("detectIncognito cannot determine the browser"))}main()})];case 1:return[2,_a.sent()]}})})}typeof window<"u"&&(window.detectIncognito=detectIncognito);const __WEBPACK_DEFAULT_EXPORT__=detectIncognito;__webpack_exports__.A;var __webpack_exports__detectIncognito=__webpack_exports__.k;async function isIncognito(){try{const{isPrivate:$e}=await __webpack_exports__detectIncognito();return $e}catch{return!1}}function isBrowser(){return typeof window<"u"}const STORAGE_KEY="sesamyFlags";async function saveFlags($e){try{localStorage.setItem(STORAGE_KEY,JSON.stringify($e))}catch{log("Failed to save flags to localStorage")}}async function setFlag($e,De){const Fe=await listFlags();Fe[$e]=De,await saveFlags(Fe)}async function getFlag($e){return(await listFlags())[$e]}async function deleteFlag($e){const De=await listFlags();$e in De&&(delete De[$e],await saveFlags(De))}async function listFlags(){try{const $e=localStorage.getItem(STORAGE_KEY);return $e?JSON.parse($e):{}}catch{return{}}}let auth0Client,organization,initialized=!1,loginInProgress=!1;isBrowser()&&window.addEventListener("pageshow",()=>{loginInProgress=!1});const ACCESS_TOKEN_KEY="sesamyAccessToken",REFRESH_TOKEN_KEY="sesamyRefreshToken";async function waitForInit(){return initialized?!0:new Promise(($e,De)=>{const Fe=setTimeout(()=>{initialized?$e(!0):De(new Error("Initialization failed: Timeout"))},2e3);window.addEventListener(Events.AUTH_INITIALIZED,()=>{clearTimeout(Fe),$e(!0)})})}async function refreshLocalAccessToken($e){if(!$e)return null;const De=localStorage.getItem(REFRESH_TOKEN_KEY);if(!De)return log("No refresh token found in localstorage"),null;const Fe=new URLSearchParams;Fe.set("client_id",$e.iss),Fe.set("refresh_token",De),Fe.set("grant_type","refresh_token");const Be=new URL($e.iss);Be.pathname="/oauth/token",Be.searchParams.set("user_id",$e.sub);try{const He=await fetch(Be.href,{body:Fe.toString(),method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!He.ok)throw localStorage.removeItem(REFRESH_TOKEN_KEY),new Error("Renew token failed");const Ke=await He.json();return localStorage.setItem(REFRESH_TOKEN_KEY,Ke.refresh_token),localStorage.setItem(ACCESS_TOKEN_KEY,Ke.access_token),Ke.access_token}catch{logout()}}async function getLocalStorageAccessToken(){const $e=localStorage.getItem(ACCESS_TOKEN_KEY);if(!$e)return null;const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3){const Fe=await refreshLocalAccessToken(De);if(Fe)return Fe;localStorage.removeItem(ACCESS_TOKEN_KEY)}return $e}function getTopLevelDomain($e){try{const De=new URL($e).hostname,Fe=De.split(".");return Fe.length>1?Fe.slice(-2).join("."):De}catch{return null}}async function init$3($e){if($e.enabled===!1)return;organization=$e.organization;const Fe=await getFlag("newAuth")&&$e.domain?$e.domain:getBaseUrl("token",$e.environment),Be={domain:Fe,clientId:$e.clientId,useCookiesForTransactions:!0};if(getTopLevelDomain(window.location.href)!==getTopLevelDomain(Fe)&&(Be.cacheLocation="localstorage",Be.useRefreshTokens=!0),auth0Client=await oe$1(Be),window.location.search.includes("code=")){log("Code found in URL, handling redirect");try{const Ge=await auth0Client.handleRedirectCallback();log(`Login result: ${JSON.stringify(Ge)}`);const We=await auth0Client.getUser();if(!We)throw log("No user found"),new Error("No user found");log(`User found ${JSON.stringify(We)}`),triggerEvent(Events.AUTHENTICATED,We),log("Rewrite url")}catch(Ge){alert("There was an error logging in"),console.error(Ge)}const He=new URL(location.href),Ke=He.searchParams;Ke.delete("code"),Ke.delete("state"),He.search=Ke.toString(),window.history.replaceState({},document.title,He.toString())}initialized=!0,triggerEvent(Events.AUTH_INITIALIZED,{})}async function isAuthenticated(){return await waitForInit(),await getLocalStorageAccessToken()?!0:auth0Client?auth0Client.isAuthenticated():!1}async function getUser(){return await waitForInit(),await getLocalStorageAccessToken()?(log("Using local user"),{sub:"local",name:"Local User"}):auth0Client?auth0Client.getUser():null}async function loginWithRedirect($e){if(loginInProgress){log("Login already in progress");return}if(loginInProgress=!0,await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),!auth0Client)throw new Error("Auth0 client not initialized");const De=($e==null?void 0:$e.authorizationParams)||{};return await isIncognito()&&navigator.userAgent.includes("Safari")&&navigator.userAgent.includes("iPhone")&&sessionStorage.setItem(SESMAY_CONTENT_RELOAD_KEY,"true"),auth0Client.loginWithRedirect({...$e,authorizationParams:{organization,redirect_uri:window.location.href,ui_locales:getLanguage(),...De}})}async function getTokenSilently($e=!0,De=!1){await waitForInit();const Fe=await getLocalStorageAccessToken();if(Fe)return Fe;try{if(!auth0Client)return log("Auth client not initialized"),null;let Be=await auth0Client.getTokenSilently();const He=getPayloadFromJwt(Be);return De&&(He!=null&&He.exp)&&He.exp+3600<new Date().getTime()/1e3&&(Be=await auth0Client.getTokenSilently({cacheMode:De?"off":"on"})),Be}catch(Be){const He=Be;if(log(`Failed to get token silently: ${He.message}`),He.message==="Invalid refresh token"&&await logout(),$e)throw Be;return null}}async function logout($e={}){if(await waitForInit(),localStorage.removeItem(ACCESS_TOKEN_KEY),triggerEvent(Events.LOGOUT,{}),!!auth0Client)return log(`Logout with options: ${JSON.stringify($e)}`),auth0Client.logout({...$e,logoutParams:{returnTo:window.location.href,...$e.logoutParams}})}function getPayloadFromJwt($e){const De=$e.split(".");if(De.length!==3)return null;const Be=De[1].replace(/-/g,"+").replace(/_/g,"/"),He=decodeURIComponent(atob(Be).split("").map(function(Ke){return"%"+("00"+Ke.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(He)}async function setToken($e){const De=getPayloadFromJwt($e);if(!De||!De.exp||De.exp<new Date().getTime()/1e3)throw new Error("Invalid token");log("Set token"),localStorage.setItem(ACCESS_TOKEN_KEY,$e),triggerEvent(Events.AUTHENTICATED,De)}const defaultSkip=($e,De)=>De.skipDedupe||De.method!=="GET",defaultKey=($e,De)=>De.method+"@"+$e,defaultResolver=$e=>$e.clone(),dedupe=({skip:$e=defaultSkip,key:De=defaultKey,resolver:Fe=defaultResolver}={})=>{const Be=new Map;return He=>(Ke,Ge)=>{if($e(Ke,Ge))return He(Ke,Ge);const We=De(Ke,Ge);if(!Be.has(We))Be.set(We,[]);else return new Promise((Ze,Xe)=>{Be.get(We).push([Ze,Xe])});try{return He(Ke,Ge).then(Ze=>(Be.get(We).forEach(([Xe])=>Xe(Fe(Ze))),Be.delete(We),Ze)).catch(Ze=>{throw Be.get(We).forEach(([,Xe])=>Xe(Ze)),Be.delete(We),Ze})}catch(Ze){return Be.delete(We),Promise.reject(Ze)}}},defaultDelayRamp=($e,De)=>$e*De,defaultUntil=$e=>$e&&$e.ok,retry=({delayTimer:$e=500,delayRamp:De=defaultDelayRamp,maxAttempts:Fe=10,until:Be=defaultUntil,onRetry:He=null,retryOnNetworkError:Ke=!1,resolveWithLatestResponse:Ge=!1,skip:We}={})=>Ze=>(Xe,Je)=>{let Ye=0;if(We&&We(Xe,Je))return Ze(Xe,Je);const Qe=(et,tt)=>Promise.resolve(Be(et,tt)).then(ct=>ct?et&&Ge?et:tt?Promise.reject(tt):et:(Ye++,!Fe||Ye<=Fe?new Promise(at=>{const ft=De($e,Ye);setTimeout(()=>{typeof He=="function"?Promise.resolve(He({response:et,error:tt,url:Xe,options:Je})).then((ut={})=>{var ot,rt;at(Ze((ot=ut&&ut.url)!==null&&ot!==void 0?ot:Xe,(rt=ut&&ut.options)!==null&&rt!==void 0?rt:Je))}):at(Ze(Xe,Je))},ft)}).then(Qe).catch(at=>{if(!Ke)throw at;return Qe(null,at)}):et&&Ge?et:Promise.reject(tt||new Error("Number of attempts exceeded."))));return Ze(Xe,Je).then(Qe).catch(et=>{if(!Ke)throw et;return Qe(null,et)})},JSON_MIME="application/json",CONTENT_TYPE_HEADER="Content-Type",FETCH_ERROR=Symbol(),CATCHER_FALLBACK=Symbol();function extractContentType($e={}){var De;return(De=Object.entries($e).find(([Fe])=>Fe.toLowerCase()===CONTENT_TYPE_HEADER.toLowerCase()))===null||De===void 0?void 0:De[1]}function isLikelyJsonMime($e){return/^application\/.*json.*/.test($e)}const mix=function($e,De,Fe=!1){return Object.entries(De).reduce((Be,[He,Ke])=>{const Ge=$e[He];return Array.isArray(Ge)&&Array.isArray(Ke)?Be[He]=Fe?[...Ge,...Ke]:Ke:typeof Ge=="object"&&typeof Ke=="object"?Be[He]=mix(Ge,Ke,Fe):Be[He]=Ke,Be},{...$e})},config={options:{},errorType:"text",polyfills:{},polyfill($e,De=!0,Fe=!1,...Be){const He=this.polyfills[$e]||(typeof self<"u"?self[$e]:null)||(typeof global<"u"?global[$e]:null);if(De&&!He)throw new Error($e+" is not defined");return Fe&&He?new He(...Be):He}};function setOptions($e,De=!1){config.options=De?$e:mix(config.options,$e)}function setPolyfills($e,De=!1){config.polyfills=De?$e:mix(config.polyfills,$e)}function setErrorType($e){config.errorType=$e}const middlewareHelper=$e=>De=>$e.reduceRight((Fe,Be)=>Be(Fe),De)||De;class WretchError extends Error{}const resolver=$e=>{const De=Object.create(null);$e=$e._addons.reduce((ot,rt)=>rt.beforeRequest&&rt.beforeRequest(ot,$e._options,De)||ot,$e);const{_url:Fe,_options:Be,_config:He,_catchers:Ke,_resolvers:Ge,_middlewares:We,_addons:Ze}=$e,Xe=new Map(Ke),Je=mix(He.options,Be);let Ye=Fe;const Qe=middlewareHelper(We)((ot,rt)=>(Ye=ot,He.polyfill("fetch")(ot,rt)))(Fe,Je),et=new Error,tt=Qe.catch(ot=>{throw{[FETCH_ERROR]:ot}}).then(ot=>{var rt;if(!ot.ok){const lt=new WretchError;if(lt.cause=et,lt.stack=lt.stack+`
35
+ CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque")throw lt;const pt=He.errorType==="json"||((rt=ot.headers.get("Content-Type"))===null||rt===void 0?void 0:rt.split(";")[0])==="application/json";return(He.errorType?pt?ot.text():ot[He.errorType]():Promise.resolve(ot.body)).then(vt=>{throw lt.message=typeof vt=="string"?vt:ot.statusText,vt&&(pt&&typeof vt=="string"?(lt.text=vt,lt.json=JSON.parse(vt)):lt[He.errorType]=vt),lt})}return ot}),ct=ot=>ot.catch(rt=>{const lt=Object.prototype.hasOwnProperty.call(rt,FETCH_ERROR),pt=lt?rt[FETCH_ERROR]:rt,gt=(pt==null?void 0:pt.status)&&Xe.get(pt.status)||Xe.get(pt==null?void 0:pt.name)||lt&&Xe.has(FETCH_ERROR)&&Xe.get(FETCH_ERROR);if(gt)return gt(pt,$e);const vt=Xe.get(CATCHER_FALLBACK);if(vt)return vt(pt,$e);throw pt}),at=ot=>rt=>ct(ot?tt.then(lt=>lt&&lt[ot]()).then(lt=>rt?rt(lt):lt):tt.then(lt=>rt?rt(lt):lt)),ft={_wretchReq:$e,_fetchReq:Qe,_sharedState:De,res:at(null),json:at("json"),blob:at("blob"),formData:at("formData"),arrayBuffer:at("arrayBuffer"),text:at("text"),error(ot,rt){return Xe.set(ot,rt),this},badRequest(ot){return this.error(400,ot)},unauthorized(ot){return this.error(401,ot)},forbidden(ot){return this.error(403,ot)},notFound(ot){return this.error(404,ot)},timeout(ot){return this.error(408,ot)},internalError(ot){return this.error(500,ot)},fetchError(ot){return this.error(FETCH_ERROR,ot)}},ut=Ze.reduce((ot,rt)=>({...ot,...typeof rt.resolver=="function"?rt.resolver(ot):rt.resolver}),ft);return Ge.reduce((ot,rt)=>rt(ot,$e),ut)},core={_url:"",_options:{},_config:config,_catchers:new Map,_resolvers:[],_deferred:[],_middlewares:[],_addons:[],addon($e){return{...this,_addons:[...this._addons,$e],...$e.wretch}},errorType($e){return{...this,_config:{...this._config,errorType:$e}}},polyfills($e,De=!1){return{...this,_config:{...this._config,polyfills:De?$e:mix(this._config.polyfills,$e)}}},url($e,De=!1){if(De)return{...this,_url:$e};const Fe=this._url.split("?");return{...this,_url:Fe.length>1?Fe[0]+$e+"?"+Fe[1]:this._url+$e}},options($e,De=!1){return{...this,_options:De?$e:mix(this._options,$e)}},headers($e){const De=$e?Array.isArray($e)?Object.fromEntries($e):"entries"in $e?Object.fromEntries($e.entries()):$e:{};return{...this,_options:mix(this._options,{headers:De})}},accept($e){return this.headers({Accept:$e})},content($e){return this.headers({[CONTENT_TYPE_HEADER]:$e})},auth($e){return this.headers({Authorization:$e})},catcher($e,De){const Fe=new Map(this._catchers);return Fe.set($e,De),{...this,_catchers:Fe}},catcherFallback($e){return this.catcher(CATCHER_FALLBACK,$e)},resolve($e,De=!1){return{...this,_resolvers:De?[$e]:[...this._resolvers,$e]}},defer($e,De=!1){return{...this,_deferred:De?[$e]:[...this._deferred,$e]}},middlewares($e,De=!1){return{...this,_middlewares:De?$e:[...this._middlewares,...$e]}},fetch($e=this._options.method,De="",Fe=null){let Be=this.url(De).options({method:$e});const He=extractContentType(Be._options.headers),Ke=this._config.polyfill("FormData",!1),Ge=typeof Fe=="object"&&!(Ke&&Fe instanceof Ke)&&(!Be._options.headers||!He||isLikelyJsonMime(He));return Be=Fe?Ge?Be.json(Fe,He):Be.body(Fe):Be,resolver(Be._deferred.reduce((We,Ze)=>Ze(We,We._url,We._options),Be))},get($e=""){return this.fetch("GET",$e)},delete($e=""){return this.fetch("DELETE",$e)},put($e,De=""){return this.fetch("PUT",De,$e)},post($e,De=""){return this.fetch("POST",De,$e)},patch($e,De=""){return this.fetch("PATCH",De,$e)},head($e=""){return this.fetch("HEAD",$e)},opts($e=""){return this.fetch("OPTIONS",$e)},body($e){return{...this,_options:{...this._options,body:$e}}},json($e,De){const Fe=extractContentType(this._options.headers);return this.content(De||isLikelyJsonMime(Fe)&&Fe||JSON_MIME).body(JSON.stringify($e))}};function factory($e="",De={}){return{...core,_url:$e,_options:De}}factory.default=factory,factory.options=setOptions,factory.errorType=setErrorType,factory.polyfills=setPolyfills,factory.WretchError=WretchError;function clearCache(){return sessionStorage.removeItem(CACHE_TIMESTAMP_KEY),log("Cache cleared"),triggerEvent(Events.CLEAR_CACHE,{}),"Cache cleared"}function isValidHttpUrl($e){let De;try{De=new URL($e)}catch{return!1}return De.protocol==="http:"||De.protocol==="https:"}function decodeItemSrc($e,De){if(isValidHttpUrl($e))return{itemSrc:$e};const[Fe,Be,He]=$e.split(":");return{sku:`${Fe}:${Be}`,purchaseOption:De||He}}function removeTrailingSlash($e){return $e.endsWith("/")?$e.slice(0,-1):$e}function compareUrlWithoutHash($e,De){if(!isValidHttpUrl($e)||!isValidHttpUrl(De))return!1;const Fe=new URL($e),Be=new URL(De);return Fe.origin===Be.origin&&removeTrailingSlash(Fe.pathname)===removeTrailingSlash(Be.pathname)}function generateCheckoutLink($e,De,Fe){const Be=new URL(`${getBaseUrl("checkout3",$e.environment)}`);if(De.language&&Be.searchParams.set("lang",De.language),De.sku)Be.searchParams.set("sku",De.sku),De.purchaseOptionId&&Be.searchParams.set("po-id",De.purchaseOptionId);else if(De.itemSrc){const{sku:We,purchaseOption:Ze,itemSrc:Xe}=decodeItemSrc(De.itemSrc,De.purchaseOptionId);Xe&&Be.searchParams.set("url",Xe),We&&Be.searchParams.set("sku",We),Ze&&Be.searchParams.set("po-id",Ze)}De.email&&Be.searchParams.set("email",De.email),De.business&&Be.searchParams.set("business","true"),De.currency&&Be.searchParams.set("currency",De.currency),De.price&&Be.searchParams.set("price",De.price.toString()),De.discountCode&&Be.searchParams.set("discount-code",De.discountCode),De.attributionItemSrc?Be.searchParams.set("itemSrc",De.attributionItemSrc):Fe.itemSrc&&Be.searchParams.set("itemSrc",Fe.itemSrc),De.attributionPublisherContentId?Be.searchParams.set("publisherContentId",De.attributionPublisherContentId):Fe.publisherContentId&&Be.searchParams.set("publisherContentId",Fe.publisherContentId),De.utmSource?Be.searchParams.set("utm_source",De.utmSource):Fe.utmSource&&Be.searchParams.set("utm_source",Fe.utmSource),De.utmMedium?Be.searchParams.set("utm_medium",De.utmMedium):Fe.utmMedium&&Be.searchParams.set("utm_medium",Fe.utmMedium),De.utmCampaign?Be.searchParams.set("utm_campaign",De.utmCampaign):Fe.utmCampaign&&Be.searchParams.set("utm_campaign",Fe.utmCampaign),De.utmTerm?Be.searchParams.set("utm_term",De.utmTerm):Fe.utmTerm&&Be.searchParams.set("utm_term",Fe.utmTerm),De.utmContent?Be.searchParams.set("utm_content",De.utmContent):Fe.utmContent&&Be.searchParams.set("utm_content",Fe.utmContent);const He=["_ga","_gid","_fbp","_fbc"];document.cookie.split(";").map(We=>{const[Ze,Xe]=We.trim().split("=");return{key:Ze,value:Xe}}).filter(We=>He.some(Ze=>Ze===We.key)).forEach(We=>{Be.searchParams.append(We.key,We.value)});const Ge=new URL(De.redirectUrl||window.location.href);return Ge.searchParams.set("force-refetch-entitlements","true"),De.itemSrc&&Ge.searchParams.set("sesamy-purchase",De.itemSrc),Be.searchParams.set("redirect-url",Ge.toString()),De.paymentMethodsFilter&&Be.searchParams.set("paymentmethods-filter",De.paymentMethodsFilter.flatMap(({provider:We,methods:Ze})=>Ze?Ze.map(Xe=>`${We}|${Xe}`):We).join(",")),Be}const SIGNED_URL_KEY="sesamySignedURLs";function getSignedLinks(){const $e=sessionStorage.getItem(SIGNED_URL_KEY);return $e?JSON.parse($e):[]}function addSignedLink($e){const De=getSignedLinks();De.push($e),log(`Adding signed URL: ${$e}`),sessionStorage.setItem(SIGNED_URL_KEY,JSON.stringify(De))}function removeUndefinedValues($e){const De={};return Object.keys($e).forEach(Fe=>{const Be=$e[Fe];Be!=null&&(De[Fe]=Be.toString())}),De}const ATTRIBUTION_KEY="sesamyAttribution";function parseFromLocalStorage($e){const De=localStorage.getItem($e);if(!De)return null;try{return JSON.parse(De).value}catch{return console.error(`Failed to parse ${$e}`),null}}function resetUtmTags($e){return Object.keys($e).find(De=>De.startsWith("utm_"))?{utmSource:void 0,utmMedium:void 0,utmCampaign:void 0,...$e}:$e}function getAttribution(){return parseFromLocalStorage(ATTRIBUTION_KEY)||{}}function setAttribution($e){if($e===null)localStorage.removeItem(ATTRIBUTION_KEY);else{log(`Setting attribution ${JSON.stringify($e)}`);const De=getAttribution()??{},Fe=removeUndefinedValues({...De,...resetUtmTags($e)});localStorage.setItem(ATTRIBUTION_KEY,JSON.stringify({value:Fe}))}}function createApi($e){const De=getBaseUrl("api2",$e.environment),Fe=st=>async(dt,$t)=>{let Ct=sessionStorage.getItem(CACHE_TIMESTAMP_KEY);Ct||(Ct=Date.now().toString(),sessionStorage.setItem(CACHE_TIMESTAMP_KEY,Ct));const _t={...$t,headers:{...$t.headers,"Cache-Timestamp":Ct}};return st(dt,_t)},Be=(st=!0)=>dt=>async($t,Ct)=>{let _t=null;if(_t=await getTokenSilently(st),!_t){if(st)throw new Error("No access token available");return dt($t,Ct)}const Mt={...Ct,headers:{...Ct.headers,..._t?{Authorization:`Bearer ${_t}`}:{}}};return dt($t,Mt)},He=st=>(dt,$t)=>{if($t.headers.Authorization)return st(dt,$t);const Ct=localStorage.getItem("__anon_id"),_t=btoa(`${$e.clientId}|${Ct}:`),Mt={...$t,headers:{...$t.headers,Authorization:`Basic ${_t}`}};return st(dt,Mt)},Ke=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(),dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]),Ge=factory(De).headers({"Content-Type":"application/json"}).middlewares([Fe,Be(!1),He,dedupe(),retry({delayTimer:1e3,delayRamp:(st,dt)=>st*dt,maxAttempts:3,until:st=>!!(st&&(st.ok||st.status>=400&&st.status<500)),retryOnNetworkError:!1})]);async function We(st={}){const{waitForEntitlementAfter:dt,includeSignedLinks:$t=!0}=st,Ct=dt?`?wait-for-entitlement-after=${dt.toISOString()}`:"",_t=await isAuthenticated()?await Ke.get(`/entitlements${Ct}`).json():[];return $t&&_t.push(...getSignedLinks()),_t}async function Ze(st,dt=[]){const $t=await We();return $t==null?void 0:$t.find(_t=>{const{sku:Mt,purchaseOption:Ht}=decodeItemSrc(st);let Gt="sku"in _t&&Mt===_t.sku;Gt&&Ht&&"purchaseOptionId"in _t&&(Gt=Ht===_t.purchaseOptionId);const tr=compareUrlWithoutHash(st,_t.url),rr=dt.some(nr=>compareUrlWithoutHash(nr,_t.url));return Gt||tr||rr})}async function Xe(st){const dt=await Ke.get("/entitlements").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function Je(st){return Ke.get(`/entitlements/${encodeURIComponent(st)}/access`).json()}async function Ye(st,dt,$t){const Ct=new URL(getBaseUrl("api2",$e.environment));return Ct.pathname="/proxy",Ct.searchParams.set("url",dt),$t&&Ct.searchParams.set("selector",$t),factory(Ct.toString()).headers({Authorization:`Bearer ${st}`}).get().text()}async function Qe(st){return await isAuthenticated()?await Ke.get(`/fulfillments?sku=${encodeURIComponent(st)}`).json():[]}async function et(){return Ke.get("/contracts").json()}async function tt(st){const dt=await Ke.get("/contracts").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ct(st){const dt=await Ke.post({},`/contracts/${encodeURIComponent(st)}/cancel`).res();return clearCache(),dt.ok}async function at(){return console.warn("getSubscriptions is deprecated, use getContracts instead"),Ke.get("/subscriptions").json()}async function ft(){return Ke.get("/bills").json()}async function ut(st){const dt=await Ke.get("/bills").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function ot(){return Ke.get("/transactions").json()}async function rt(st){const dt=await Ke.get("/transactions").json();return dt==null?void 0:dt.find($t=>$t.id===st)}async function lt(st,dt){const $t=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).put(dt).json();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),$t}async function pt(st){const dt=await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function gt(st){return(await Ke.url(`/user-metadata/${encodeURIComponent(st)}`).get().json())[st]}async function vt(){return await Ke.url("/user-metadata").get().json()}async function Et(){return await Ke.url("/tags").get().json()}async function Pt(st){const dt=await Ke.url(`/tags/${encodeURIComponent(st)}`).delete().res();return clearCache(),dt.ok}async function Nt(st){const dt=await Ke.url("/tags").post(encodeURIComponent(st)).res();return triggerEvent(Events.USER_ATTRIBUTE_CHANGED,{}),clearCache(),dt.ok}async function yt(st){return(await Ge.url("/tallies").get().json())[st]}async function It(){return await Ge.url("/tallies").get().json()}async function Rt(st){const dt=await Ge.url(`/tallies/${st}`).delete().res();return clearCache(),dt.ok}async function mt(st,dt){return await Ge.url(`/tallies/${encodeURIComponent(st)}/push`).post(dt).json()}async function At(st){return await Ke.url(`/products/${encodeURIComponent(st)}`).get().json()}async function Ut(){return await getTokenSilently(!1)?await Ke.url("/profile").get().json():null}async function xt(st){const dt=await Ke.url("/profile").patch(st).res();return clearCache(),dt.ok}async function nt(){return await Ke.url("/payment-issues").get().json()}async function it(){return(await Ke.url("/profile/spotify-link").get().json()).isSpotifyLinked}async function ht(){return(await Ke.url("/profile/unlink-spotify").post().res()).ok}async function St(st){const dt=await getTokenSilently(!1);if(!dt)throw new Error("No access token available");const $t=new URL(`${getBaseUrl("access-sync",$e.environment)}/spotify/sesamy-callback`);$t.searchParams.set("access_token",dt),$t.searchParams.set("state",st),window.location.href=$t.toString()}async function bt(st){const dt=await Ke.url(`/products/${encodeURIComponent(st)}/auto-onboard`).post().json();return dt.length&&clearCache(),dt}async function wt(st,dt=3600){const{shortlink:$t}=await factory(SHORTLINK_URL).post({url:st,ttl:dt}).json();return $t}async function kt(st){const dt=await getTokenSilently(!1,!0);let $t;const Ct=st.language||getLanguage(),_t=getAttribution();switch(st.target){case"account":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-payment":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/change-payment-method`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"change-plan":$t=new URL(`${getBaseUrl("account",$e.environment)}/${encodeURIComponent(st.language||Ct)}/subscriptions/${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.contractId)}/edit-plan`),$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"consume":$t=new URL(`${getBaseUrl("consume",$e.environment)}/${encodeURIComponent(st.language||Ct)}/@${encodeURIComponent($e.clientId)}/${encodeURIComponent(st.sku)}`),st.episodeId?$t.href+=`/${st.episodeId}`:$t.href+="/listen",$t.searchParams.set("sesamy-redirect-url",st.redirectUrl||window.location.href);break;case"checkout":$t=generateCheckoutLink($e,{language:Ct,...st},_t);break;default:throw new Error("Invalid target")}return dt&&($t.hash=`#access_token=${dt}`),st.shorten?wt($t.href,st.ttl):$t.href}async function Tt(st){const dt=getAttribution(),$t=["_ga","_gid","_fbp","_fbc"];return document.cookie.split(";").forEach(_t=>{const Mt=dt,[Ht,Gt]=_t.trim().split("=");$t.includes(Ht)&&!Mt[Ht]&&(Mt[Ht]=Gt)}),(await Ge.url("/checkouts").post({language:getLanguage(),...st,attribution:{...dt,...st.attribution},vendorId:$e.clientId})).json()}async function Lt(st,dt){return(await Ge.url(`/checkouts/${st}`).patch(dt)).json()}async function Ot(st){return(await Ge.url(`/checkouts/${st}`).get()).json()}async function jt(st){return(await Ge.url(`/paywalls/${st}`).get()).json()}async function Ft(){return(await Ge.url("/vendor").get()).json()}async function Bt(){return(await Ke.url("/vendors").get()).json()}async function Vt(st){return(await Ke.url(`/contracts/${encodeURIComponent(st.contractId)}/amendments`).post({amendmentType:st.amendmentType,discountCode:st.discountCode})).json()}async function Kt(st){return await Ke.url(`/amendments/${encodeURIComponent(st)}/confirm`).post(),!0}async function zt(){const st=await getTokenSilently(!1),dt=new URL(`${getBaseUrl("account",$e.environment)}/subscriptions/${$e.clientId}`);st&&(dt.hash=`#access_token=${st}`),window.location.href=dt.toString()}return{autoOnboardProduct:bt,cancelContract:ct,confirmAmendment:Kt,createAmendment:Vt,createCheckout:Tt,deleteTag:Pt,deleteTally:Rt,deleteUserMetadata:pt,generateLink:kt,getBill:ut,getBills:ft,getCheckout:Ot,getProxyContent:Ye,getContract:tt,getContracts:et,getEntitlement:Xe,getEntitlementAccess:Je,getEntitlements:We,getFulfillments:Qe,getPaywall:jt,getPaymentIssues:nt,getProfile:Ut,getProduct:At,getSubscriptions:at,getTally:yt,getTallies:It,getTags:Et,getTransaction:rt,getTransactions:ot,getUserMetadata:gt,hasAccess:Ze,isSpotifyLinked:it,linkSpotify:St,listUserMetadata:vt,openHostedAccountPage:zt,pushTally:mt,setTag:Nt,setUserMetadata:lt,unlinkSpotify:ht,updateCheckout:Lt,updateProfile:xt,getVendorSettings:Ft,listVendors:Bt}}const name="@sesamy/sesamy-js",version="1.35.6";function i$5($e,De,Fe,Be,He){for(De=De.split?De.split("."):De,Be=0;Be<De.length;Be++)$e=$e?$e[De[Be]]:He;return $e===He?Fe:$e}var e="undefined",o$4="object",g$1=function(){},b$4="any",m$1="*",j="__",F$2=typeof process<"u"?process:{};F$2.env&&F$2.env.NODE_ENV;var $$1=typeof document<"u";F$2.versions!=null&&F$2.versions.node!=null,typeof Deno<"u"&&Deno.core,$$1&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent!==void 0&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1($e,De){return De.charAt(0)[$e]()+De.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2($e){return Y$1($e)?U$1("null"):typeof $e=="object"?yn($e):Object.prototype.toString.call($e).slice(8,-1)}function R$1($e,De){De===void 0&&(De=!0);var Fe=J$2($e);return De?H$1(Fe):Fe}function V$1($e,De){return typeof De===$e}var W$1=V$1.bind(null,"function"),q$1=V$1.bind(null,"string"),I$2=V$1.bind(null,"undefined"),Q$1=V$1.bind(null,"boolean");V$1.bind(null,"symbol");function Y$1($e){return $e===null}function nn($e){return R$1($e)==="number"&&!isNaN($e)}function rn($e){return R$1($e)==="array"}function on($e){if(!un($e))return!1;for(var De=$e;Object.getPrototypeOf(De)!==null;)De=Object.getPrototypeOf(De);return Object.getPrototypeOf($e)===De}function un($e){return $e&&(typeof $e=="object"||$e!==null)}function yn($e){return W$1($e.constructor)?$e.constructor.name:null}function hn($e){return $e instanceof Error||q$1($e.message)&&$e.constructor&&nn($e.constructor.stackTraceLimit)}function On($e,De){if(typeof De!="object"||Y$1(De))return!1;if(De instanceof $e)return!0;var Fe=R$1(new $e(""));if(hn(De))for(;De;){if(R$1(De)===Fe)return!0;De=Object.getPrototypeOf(De)}return!1}On.bind(null,TypeError),On.bind(null,SyntaxError);function $n($e,De){var Fe=$e instanceof Element||$e instanceof HTMLDocument;return Fe&&De?Tn($e,De):Fe}function Tn($e,De){return De===void 0&&(De=""),$e&&$e.nodeName===De.toUpperCase()}function _n($e){var De=[].slice.call(arguments,1);return function(){return $e.apply(void 0,[].slice.call(arguments).concat(De))}}_n($n,"form"),_n($n,"button"),_n($n,"input"),_n($n,"select");function Hn($e){return $e?rn($e)?$e:[$e]:[]}function n$1($e){try{return decodeURIComponent($e.replace(/\+/g," "))}catch{return null}}function o$3(){if($$1){var $e=navigator,De=$e.languages;return $e.userLanguage||(De&&De.length?De[0]:$e.language)}}function a$5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}}function s$1($e){return function(De){for(var Fe,Be=Object.create(null),He=/([^&=]+)=?([^&]*)/g;Fe=He.exec(De);){var Ke=n$1(Fe[1]),Ge=n$1(Fe[2]);Ke.substring(Ke.length-2)==="[]"?(Be[Ke=Ke.substring(0,Ke.length-2)]||(Be[Ke]=[])).push(Ge):Be[Ke]=Ge===""||Ge}for(var We in Be){var Ze=We.split("[");Ze.length>1&&(m(Be,Ze.map(function(Xe){return Xe.replace(/[?[\]\\ ]/g,"")}),Be[We]),delete Be[We])}return Be}(function(De){return $$1&&window.location.search.substring(1)}())}function m($e,De,Fe){for(var Be=De.length-1,He=0;He<Be;++He){var Ke=De[He];if(Ke==="__proto__"||Ke==="constructor")break;Ke in $e||($e[Ke]={}),$e=$e[Ke]}$e[De[Be]]=Fe}function y$1(){for(var $e="",De=0,Fe=4294967295*Math.random()|0;De++<36;){var Be="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[De-1],He=15&Fe;$e+=Be=="-"||Be=="4"?Be:(Be=="x"?He:3&He|8).toString(16),Fe=De%8==0?4294967295*Math.random()|0:Fe>>4}return $e}function b$3($e,De){var Fe,Be,He,Ke=null,Ge=0,We=function(){Ge=new Date,Ke=null,He=$e.apply(Fe,Be)};return function(){var Ze=new Date;Ge||(Ge=Ze);var Xe=De-(Ze-Ge);return Fe=this,Be=arguments,Xe<=0?(clearTimeout(Ke),Ke=null,Ge=Ze,He=$e.apply(Fe,Be)):Ke||(Ke=setTimeout(We,Xe)),He}}var l$2="global",o$2=j+"global"+j,n=typeof self===o$4&&self.self===self&&self||typeof global===o$4&&global.global===global&&global||void 0;function a$4($e){return n[o$2][$e]}function f$1($e,De){return n[o$2][$e]=De}function i$4($e){delete n[o$2][$e]}function u$3($e,De,Fe){var Be;try{if(b$2($e)){var He=window[$e];Be=He[De].bind(He)}}catch{}return Be||Fe}n[o$2]||(n[o$2]={});var c$3={};function b$2($e){if(typeof c$3[$e]!==e)return c$3[$e];try{var De=window[$e];De.setItem(e,e),De.removeItem(e)}catch{return c$3[$e]=!1}return c$3[$e]=!0}function v(){return v=Object.assign||function($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De];for(var Be in Fe)Object.prototype.hasOwnProperty.call(Fe,Be)&&($e[Be]=Fe[Be])}return $e},v.apply(this,arguments)}var y="function",b$1="undefined",I$1="@@redux/"+Math.random().toString(36),w=function(){return typeof Symbol===y&&Symbol.observable||"@@observable"}(),E$1=" != "+y;function P($e,De,Fe){var Be;if(typeof De===y&&typeof Fe===b$1&&(Fe=De,De=void 0),typeof Fe!==b$1){if(typeof Fe!==y)throw new Error("enhancer"+E$1);return Fe(P)($e,De)}if(typeof $e!==y)throw new Error("reducer"+E$1);var He=$e,Ke=De,Ge=[],We=Ge,Ze=!1;function Xe(){We===Ge&&(We=Ge.slice())}function Je(){return Ke}function Ye(et){if(typeof et!==y)throw new Error("Listener"+E$1);var tt=!0;return Xe(),We.push(et),function(){if(tt){tt=!1,Xe();var ct=We.indexOf(et);We.splice(ct,1)}}}function Qe(et){if(!on(et))throw new Error("Act != obj");if(typeof et.type===b$1)throw new Error("ActType "+b$1);if(Ze)throw new Error("Dispatch in reducer");try{Ze=!0,Ke=He(Ke,et)}finally{Ze=!1}for(var tt=Ge=We,ct=0;ct<tt.length;ct++)(0,tt[ct])();return et}return Qe({type:"@@redux/INIT"}),(Be={dispatch:Qe,subscribe:Ye,getState:Je,replaceReducer:function(et){if(typeof et!==y)throw new Error("next reducer"+E$1);He=et,Qe({type:"@@redux/INIT"})}})[w]=function(){var et,tt=Ye;return(et={subscribe:function(ct){if(typeof ct!="object")throw new TypeError("Observer != obj");function at(){ct.next&&ct.next(Je())}return at(),{unsubscribe:tt(at)}}})[w]=function(){return this},et},Be}function S($e,De){var Fe=De&&De.type;return"action "+(Fe&&Fe.toString()||"?")+"reducer "+$e+" returns "+b$1}function N$1(){var $e=[].slice.call(arguments);return $e.length===0?function(De){return De}:$e.length===1?$e[0]:$e.reduce(function(De,Fe){return function(){return De(Fe.apply(void 0,[].slice.call(arguments)))}})}function O$1(){var $e=arguments;return function(De){return function(Fe,Be,He){var Ke,Ge=De(Fe,Be,He),We=Ge.dispatch,Ze={getState:Ge.getState,dispatch:function(Xe){return We(Xe)}};return Ke=[].slice.call($e).map(function(Xe){return Xe(Ze)}),v({},Ge,{dispatch:We=N$1.apply(void 0,Ke)(Ge.dispatch)})}}}var A$1=j+"anon_id",_=j+"user_id",x$1=j+"user_traits",k$1="userId",T="anonymousId",z=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],M=["name","EVENTS","config","loaded"],q=z.reduce(function($e,De){return $e[De]=De,$e},{registerPluginType:function($e){return"registerPlugin:"+$e},pluginReadyType:function($e){return"ready:"+$e}}),U=/^utm_/,V=/^an_prop_/,L$1=/^an_trait_/;function C$1($e){var De=$e.storage.setItem;return function(Fe){return function(Be){return function(He){if(He.type===q.bootstrap){var Ke=He.params,Ge=He.user,We=He.persistedUser,Ze=He.initialUser,Xe=We.userId===Ge.userId;We.anonymousId!==Ge.anonymousId&&De(A$1,Ge.anonymousId),Xe||De(_,Ge.userId),Ze.traits&&De(x$1,v({},Xe&&We.traits?We.traits:{},Ze.traits));var Je=Object.keys(He.params);if(Je.length){var Ye=Ke.an_uid,Qe=Ke.an_event,et=Je.reduce(function(tt,ct){if(ct.match(U)||ct.match(/^(d|g)clid/)){var at=ct.replace(U,"");tt.campaign[at==="campaign"?"name":at]=Ke[ct]}return ct.match(V)&&(tt.props[ct.replace(V,"")]=Ke[ct]),ct.match(L$1)&&(tt.traits[ct.replace(L$1,"")]=Ke[ct]),tt},{campaign:{},props:{},traits:{}});Fe.dispatch(v({type:q.params,raw:Ke},et,Ye?{userId:Ye}:{})),Ye&&setTimeout(function(){return $e.identify(Ye,et.traits)},0),Qe&&setTimeout(function(){return $e.track(Qe,et.props)},0),Object.keys(et.campaign).length&&Fe.dispatch({type:q.campaign,campaign:et.campaign})}}return Be(He)}}}}function R($e){return function(De,Fe){if(De===void 0&&(De={}),Fe===void 0&&(Fe={}),Fe.type===q.setItemEnd){if(Fe.key===A$1)return v({},De,{anonymousId:Fe.value});if(Fe.key===_)return v({},De,{userId:Fe.value})}switch(Fe.type){case q.identify:return Object.assign({},De,{userId:Fe.userId,traits:v({},De.traits,Fe.traits)});case q.reset:return[_,A$1,x$1].forEach(function(Be){$e.removeItem(Be)}),Object.assign({},De,{userId:null,anonymousId:null,traits:{}});default:return De}}}function $($e){return{userId:$e.getItem(_),anonymousId:$e.getItem(A$1),traits:$e.getItem(x$1)}}var D=function($e){return j+"TEMP"+j+$e};function B($e){var De=$e.storage,Fe=De.setItem,Be=De.removeItem,He=De.getItem;return function(Ke){return function(Ge){return function(We){var Ze=We.userId,Xe=We.traits,Je=We.options;if(We.type===q.reset&&([_,x$1,A$1].forEach(function(et){Be(et)}),[k$1,T,"traits"].forEach(function(et){i$4(D(et))})),We.type===q.identify){He(A$1)||Fe(A$1,y$1());var Ye=He(_),Qe=He(x$1)||{};Ye&&Ye!==Ze&&Ke.dispatch({type:q.userIdChanged,old:{userId:Ye,traits:Qe},new:{userId:Ze,traits:Xe},options:Je}),Ze&&Fe(_,Ze),Xe&&Fe(x$1,v({},Qe,Xe))}return Ge(We)}}}}var X={};function J$1($e,De){X[$e]&&W$1(X[$e])&&(X[$e](De),delete X[$e])}function W($e,De,Fe){return new Promise(function(Be,He){return De()?Be($e):Fe<1?He(v({},$e,{queue:!0})):new Promise(function(Ke){return setTimeout(Ke,10)}).then(function(Ke){return W($e,De,Fe-10).then(Be,He)})})}function H($e){return{abort:$e}}function F$1($e,De,Fe){var Be={},He=De(),Ke=$e.getState(),Ge=Ke.plugins,We=Ke.queue,Ze=Ke.user;if(!Ke.context.offline&&We&&We.actions&&We.actions.length){var Xe=We.actions.reduce(function(Ye,Qe,et){return Ge[Qe.plugin].loaded?(Ye.process.push(Qe),Ye.processIndex.push(et)):(Ye.requeue.push(Qe),Ye.requeueIndex.push(et)),Ye},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(Xe.processIndex&&Xe.processIndex.length){Xe.processIndex.forEach(function(Ye){var Qe=We.actions[Ye],et=Qe.plugin,tt=Qe.payload.type,ct=He[et][tt];if(ct&&W$1(ct)){var at,ft=function(rt,lt){return rt===void 0&&(rt={}),lt===void 0&&(lt={}),[k$1,T].reduce(function(pt,gt){return rt.hasOwnProperty(gt)&&lt[gt]&&lt[gt]!==rt[gt]&&(pt[gt]=lt[gt]),pt},rt)}(Qe.payload,Ze),ut=Be[ft.meta.rid];if(!ut&&(at=ct({payload:ft,config:Ge[et].config,instance:Fe,abort:H}))&&on(at)&&at.abort)return void(Be[ft.meta.rid]=!0);if(!ut){var ot=tt+":"+et;$e.dispatch(v({},ft,{type:ot,_:{called:ot,from:"queueDrain"}}))}}});var Je=We.actions.filter(function(Ye,Qe){return!~Xe.processIndex.indexOf(Qe)});We.actions=Je}}}var G$1=function($e){var De=$e.data,Fe=$e.action,Be=$e.instance,He=$e.state,Ke=$e.allPlugins,Ge=$e.allMatches,We=$e.store,Ze=$e.EVENTS;try{var Xe=He.plugins,Je=He.context,Ye=Fe.type,Qe=Ye.match(K),et=De.exact.map(function(at){return at.pluginName});Qe&&(et=Ge.during.map(function(at){return at.pluginName}));var tt=function(at,ft){return function(ut,ot,rt){var lt=ot.config,pt=ot.name,gt=pt+"."+ut.type;rt&&(gt=rt.event);var vt=ut.type.match(K)?function(Et,Pt,Nt,yt,It){return function(Rt,mt){var At=yt?yt.name:Et,Ut=mt&&ae(mt)?mt:Nt;if(yt&&(!(Ut=mt&&ae(mt)?mt:[Et]).includes(Et)||Ut.length!==1))throw new Error("Method "+Pt+" can only abort "+Et+" plugin. "+JSON.stringify(Ut)+" input valid");return v({},It,{abort:{reason:Rt,plugins:Ut,caller:Pt,_:At}})}}(pt,gt,ft,rt,ut):function(Et,Pt){return function(){throw new Error(Et.type+" action not cancellable. Remove abort in "+Pt)}}(ut,gt);return{payload:ce(ut),instance:at,config:lt||{},abort:vt}}}(Be,et),ct=De.exact.reduce(function(at,ft){var ut=ft.pluginName,ot=ft.methodName,rt=!1;return ot.match(/^initialize/)||ot.match(/^reset/)||(rt=!Xe[ut].loaded),Je.offline&&ot.match(/^(page|track|identify)/)&&(rt=!0),at[""+ut]=rt,at},{});return Promise.resolve(De.exact.reduce(function(at,ft,ut){try{var ot=ft.pluginName;return Promise.resolve(at).then(function(rt){function lt(){return Promise.resolve(rt)}var pt=function(){if(De.namespaced&&De.namespaced[ot])return Promise.resolve(De.namespaced[ot].reduce(function(gt,vt,Et){try{return Promise.resolve(gt).then(function(Pt){return vt.method&&W$1(vt.method)?(function(Rt,mt){var At=ue(Rt);if(At&&At.name===mt){var Ut=ue(At.method);throw new Error([mt+" plugin is calling method "+Rt,"Plugins cant call self","Use "+At.method+" "+(Ut?"or "+Ut.method:"")+" in "+mt+" plugin insteadof "+Rt].join(`
36
36
  `))}}(vt.methodName,vt.pluginName),Promise.resolve(vt.method({payload:Pt,instance:Be,abort:(Nt=Pt,yt=ot,It=vt.pluginName,function(Rt,mt){return v({},Nt,{abort:{reason:Rt,plugins:mt||[yt],caller:Ye,from:It||yt}})}),config:ee(vt.pluginName,Xe,Ke),plugins:Xe})).then(function(Rt){var mt=on(Rt)?Rt:{};return Promise.resolve(v({},Pt,mt))})):Pt;var Nt,yt,It})}catch(Pt){return Promise.reject(Pt)}},Promise.resolve(Fe))).then(function(gt){rt[ot]=gt});rt[ot]=Fe}();return pt&&pt.then?pt.then(lt):lt()})}catch(rt){return Promise.reject(rt)}},Promise.resolve({}))).then(function(at){return Promise.resolve(De.exact.reduce(function(ft,ut,ot){try{var rt=De.exact.length===ot+1,lt=ut.pluginName,pt=Ke[lt];return Promise.resolve(ft).then(function(gt){var vt=at[lt]?at[lt]:{};if(Qe&&(vt=gt),re(vt,lt))return Z({data:vt,method:Ye,instance:Be,pluginName:lt,store:We}),Promise.resolve(gt);if(re(gt,lt))return rt&&Z({data:gt,method:Ye,instance:Be,store:We}),Promise.resolve(gt);if(ct.hasOwnProperty(lt)&&ct[lt]===!0)return We.dispatch({type:"queue",plugin:lt,payload:vt,_:{called:"queue",from:"queueMechanism"}}),Promise.resolve(gt);var Et=tt(at[lt],Ke[lt]);return Promise.resolve(pt[Ye]({abort:Et.abort,payload:vt,instance:Be,config:ee(lt,Xe,Ke),plugins:Xe})).then(function(Pt){var Nt=on(Pt)?Pt:{},yt=v({},gt,Nt),It=at[lt];if(re(It,lt))Z({data:It,method:Ye,instance:Be,pluginName:lt,store:We});else{var Rt=Ye+":"+lt;(Rt.match(/:/g)||[]).length<2&&!Ye.match(Q)&&!Ye.match(Y)&&Be.dispatch(v({},Qe?yt:vt,{type:Rt,_:{called:Rt,from:"submethod"}}))}return Promise.resolve(yt)})})}catch(gt){return Promise.reject(gt)}},Promise.resolve(Fe))).then(function(ft){if(!(Ye.match(K)||Ye.match(/^registerPlugin/)||Ye.match(Y)||Ye.match(Q)||Ye.match(/^params/)||Ye.match(/^userIdChanged/))){if(Ze.plugins.includes(Ye),ft._&&ft._.originalAction===Ye)return ft;var ut=v({},ft,{_:{originalAction:ft.type,called:ft.type,from:"engineEnd"}});ie(ft,De.exact.length)&&!Ye.match(/End$/)&&(ut=v({},ut,{type:ft.type+"Aborted"})),We.dispatch(ut)}return ft})})}catch(at){return Promise.reject(at)}},K=/Start$/,Q=/^bootstrap/,Y=/^ready/;function Z($e){var De=$e.pluginName,Fe=$e.method+"Aborted"+(De?":"+De:"");$e.store.dispatch(v({},$e.data,{type:Fe,_:{called:Fe,from:"abort"}}))}function ee($e,De,Fe){var Be=De[$e]||Fe[$e];return Be&&Be.config?Be.config:{}}function ne($e,De){return De.reduce(function(Fe,Be){return Be[$e]?Fe.concat({methodName:$e,pluginName:Be.name,method:Be[$e]}):Fe},[])}function te($e,De){var Fe=$e.replace(K,""),Be=De?":"+De:"";return[""+$e+Be,""+Fe+Be,Fe+"End"+Be]}function re($e,De){var Fe=$e.abort;return!!Fe&&(Fe===!0||oe(Fe,De)||Fe&&oe(Fe.plugins,De))}function ie($e,De){var Fe=$e.abort;if(!Fe)return!1;if(Fe===!0||q$1(Fe))return!0;var Be=Fe.plugins;return ae(Fe)&&Fe.length===De||ae(Be)&&Be.length===De}function ae($e){return Array.isArray($e)}function oe($e,De){return!(!$e||!ae($e))&&$e.includes(De)}function ue($e){var De=$e.match(/(.*):(.*)/);return!!De&&{method:De[1],name:De[2]}}function ce($e){return Object.keys($e).reduce(function(De,Fe){return Fe==="type"||(De[Fe]=on($e[Fe])?Object.assign({},$e[Fe]):$e[Fe]),De},{})}function se($e,De,Fe){var Be={};return function(He){return function(Ke){return function(Ge){try{var We,Ze=function(rt){return We?rt:Ke(Ye)},Xe=Ge.type,Je=Ge.plugins,Ye=Ge;if(Ge.abort)return Promise.resolve(Ke(Ge));if(Xe===q.enablePlugin&&He.dispatch({type:q.initializeStart,plugins:Je,disabled:[],fromEnable:!0,meta:Ge.meta}),Xe===q.disablePlugin&&setTimeout(function(){return J$1(Ge.meta.rid,{payload:Ge})},0),Xe===q.initializeEnd){var Qe=De(),et=Object.keys(Qe),tt=et.filter(function(rt){return Je.includes(rt)}).map(function(rt){return Qe[rt]}),ct=[],at=[],ft=Ge.disabled,ut=tt.map(function(rt){var lt=rt.loaded,pt=rt.name,gt=rt.config;return W(rt,function(){return lt({config:gt})},1e4).then(function(vt){return Be[pt]||(He.dispatch({type:q.pluginReadyType(pt),name:pt,events:Object.keys(rt).filter(function(Et){return!M.includes(Et)})}),Be[pt]=!0),ct=ct.concat(pt),rt}).catch(function(vt){if(vt instanceof Error)throw new Error(vt);return at=at.concat(vt.name),vt})});Promise.all(ut).then(function(rt){var lt={plugins:ct,failed:at,disabled:ft};setTimeout(function(){et.length===ut.length+ft.length&&He.dispatch(v({},{type:q.ready},lt))},0)})}var ot=function(){if(Xe!==q.bootstrap)return/^ready:([^:]*)$/.test(Xe)&&setTimeout(function(){return F$1(He,De,$e)},0),Promise.resolve(function(rt,lt,pt,gt,vt){try{var Et=W$1(lt)?lt():lt,Pt=rt.type,Nt=Pt.replace(K,"");if(rt._&&rt._.called)return Promise.resolve(rt);var yt=pt.getState(),It=(At=Et,(Ut=yt.plugins)===void 0&&(Ut={}),(xt=rt.options)===void 0&&(xt={}),Object.keys(At).filter(function(nt){var it=xt.plugins||{};return Q$1(it[nt])?it[nt]:it.all!==!1&&(!Ut[nt]||Ut[nt].enabled!==!1)}).map(function(nt){return At[nt]}));Pt===q.initializeStart&&rt.fromEnable&&(It=Object.keys(yt.plugins).filter(function(nt){var it=yt.plugins[nt];return rt.plugins.includes(nt)&&!it.initialized}).map(function(nt){return Et[nt]}));var Rt=It.map(function(nt){return nt.name}),mt=function(nt,it,ht){var St=te(nt).map(function(bt){return ne(bt,it)});return it.reduce(function(bt,wt){var kt=wt.name,Tt=te(nt,kt).map(function(Ft){return ne(Ft,it)}),Lt=Tt[0],Ot=Tt[1],jt=Tt[2];return Lt.length&&(bt.beforeNS[kt]=Lt),Ot.length&&(bt.duringNS[kt]=Ot),jt.length&&(bt.afterNS[kt]=jt),bt},{before:St[0],beforeNS:{},during:St[1],duringNS:{},after:St[2],afterNS:{}})}(Pt,It);return Promise.resolve(G$1({action:rt,data:{exact:mt.before,namespaced:mt.beforeNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(nt){function it(){var bt=function(){if(Pt.match(K))return Promise.resolve(G$1({action:v({},ht,{type:Nt+"End"}),data:{exact:mt.after,namespaced:mt.afterNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(wt){wt.meta&&wt.meta.hasCallback&&J$1(wt.meta.rid,{payload:wt})})}();return bt&&bt.then?bt.then(function(){return nt}):nt}if(ie(nt,Rt.length))return nt;var ht,St=function(){if(Pt!==Nt)return Promise.resolve(G$1({action:v({},nt,{type:Nt}),data:{exact:mt.during,namespaced:mt.duringNS},state:yt,allPlugins:Et,allMatches:mt,instance:pt,store:gt,EVENTS:vt})).then(function(bt){ht=bt});ht=nt}();return St&&St.then?St.then(it):it()})}catch(nt){return Promise.reject(nt)}var At,Ut,xt}(Ge,De,$e,He,Fe)).then(function(rt){return We=1,Ke(rt)})}();return Promise.resolve(ot&&ot.then?ot.then(Ze):Ze(ot))}catch(rt){return Promise.reject(rt)}}}}}function le($e){return function(De){return function(Fe){return function(Be){var He=Be.type,Ke=Be.key,Ge=Be.value,We=Be.options;if(He===q.setItem||He===q.removeItem){if(Be.abort)return Fe(Be);He===q.setItem?$e.setItem(Ke,Ge,We):$e.removeItem(Ke,We)}return Fe(Be)}}}}var fe=function(){var $e=this;this.before=[],this.after=[],this.addMiddleware=function(De,Fe){$e[Fe]=$e[Fe].concat(De)},this.removeMiddleware=function(De,Fe){var Be=$e[Fe].findIndex(function(He){return He===De});Be!==-1&&($e[Fe]=[].concat($e[Fe].slice(0,Be),$e[Fe].slice(Be+1)))},this.dynamicMiddlewares=function(De){return function(Fe){return function(Be){return function(He){var Ke={getState:Fe.getState,dispatch:function(We){return Fe.dispatch(We)}},Ge=$e[De].map(function(We){return We(Ke)});return N$1.apply(void 0,Ge)(Be)(He)}}}}};function de($e){return function(De,Fe){De===void 0&&(De={});var Be={};if(Fe.type==="initialize:aborted")return De;if(/^registerPlugin:([^:]*)$/.test(Fe.type)){var He=pe(Fe.type,"registerPlugin"),Ke=$e()[He];if(!Ke||!He)return De;var Ge=Fe.enabled,We=Ke.config;return Be[He]={enabled:Ge,initialized:!!Ge&&!Ke.initialize,loaded:!!Ge&&!!Ke.loaded({config:We}),config:We},v({},De,Be)}if(/^initialize:([^:]*)$/.test(Fe.type)){var Ze=pe(Fe.type,q.initialize),Xe=$e()[Ze];return Xe&&Ze?(Be[Ze]=v({},De[Ze],{initialized:!0,loaded:!!Xe.loaded({config:Xe.config})}),v({},De,Be)):De}if(/^ready:([^:]*)$/.test(Fe.type))return Be[Fe.name]=v({},De[Fe.name],{loaded:!0}),v({},De,Be);switch(Fe.type){case q.disablePlugin:return v({},De,me(Fe.plugins,!1,De));case q.enablePlugin:return v({},De,me(Fe.plugins,!0,De));default:return De}}}function pe($e,De){return $e.substring(De.length+1,$e.length)}function me($e,De,Fe){return $e.reduce(function(Be,He){return Be[He]=v({},Fe[He],{enabled:De}),Be},Fe)}function ge($e){try{return JSON.parse(JSON.stringify($e))}catch{}return $e}var he={last:{},history:[]};function ve($e,De){$e===void 0&&($e=he);var Fe=De.options,Be=De.meta;if(De.type===q.track){var He=ge(v({event:De.event,properties:De.properties},Object.keys(Fe).length&&{options:Fe},{meta:Be}));return v({},$e,{last:He,history:$e.history.concat(He)})}return $e}var ye={actions:[]};function be($e,De){$e===void 0&&($e=ye);var Fe=De.payload;switch(De.type){case"queue":var Be;return Be=Fe&&Fe.type&&Fe.type===q.identify?[De].concat($e.actions):$e.actions.concat(De),v({},$e,{actions:Be});case"dequeue":return[];default:return $e}}var Ie=/#.*$/;function we($e){var De=/(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g.exec($e);return"/"+(De&&De[3]?De[3].split("?")[0].replace(Ie,""):"")}var Ee,Pe,Se,Ne,Oe=function($e){if($e===void 0&&($e={}),!$$1)return $e;var De=document,Fe=De.title,Be=De.referrer,He=window,Ke=He.location,Ge=He.innerWidth,We=He.innerHeight,Ze=Ke.hash,Xe=Ke.search,Je=function(Qe){var et=function(){if($$1){for(var tt,ct=document.getElementsByTagName("link"),at=0;tt=ct[at];at++)if(tt.getAttribute("rel")==="canonical")return tt.getAttribute("href")}}();return et?et.match(/\?/)?et:et+Qe:window.location.href.replace(Ie,"")}(Xe),Ye={title:Fe,url:Je,path:we(Je),hash:Ze,search:Xe,width:Ge,height:We};return Be&&Be!==""&&(Ye.referrer=Be),v({},Ye,$e)},Ae={last:{},history:[]};function _e($e,De){$e===void 0&&($e=Ae);var Fe=De.options;if(De.type===q.page){var Be=ge(v({properties:De.properties,meta:De.meta},Object.keys(Fe).length&&{options:Fe}));return v({},$e,{last:Be,history:$e.history.concat(Be)})}return $e}Ee=function(){if(!$$1)return!1;var $e=navigator.appVersion;return~$e.indexOf("Win")?"Windows":~$e.indexOf("Mac")?"MacOS":~$e.indexOf("X11")?"UNIX":~$e.indexOf("Linux")?"Linux":"Unknown OS"}(),Pe=$$1?document.referrer:null,Se=o$3(),Ne=a$5();var xe={initialized:!1,sessionId:y$1(),app:null,version:null,debug:!1,offline:!!$$1&&!navigator.onLine,os:{name:Ee},userAgent:$$1?navigator.userAgent:"node",library:{name:"analytics",version:"0.12.13"},timezone:Ne,locale:Se,campaign:{},referrer:Pe};function je($e,De){$e===void 0&&($e=xe);var Fe=$e.initialized,Be=De.campaign;switch(De.type){case q.campaign:return v({},$e,{campaign:Be});case q.offline:return v({},$e,{offline:!0});case q.online:return v({},$e,{offline:!1});default:return Fe?$e:v({},xe,$e,{initialized:!0})}}var ke=["plugins","reducers","storage"];function Te($e,De,Fe){if($$1){var Be=window[(Fe?"add":"remove")+"EventListener"];$e.split(" ").forEach(function(He){Be(He,De)})}}function ze($e){var De=Te.bind(null,"online offline",function(Fe){return Promise.resolve(!navigator.onLine).then($e)});return De(!0),function(Fe){return De(!1)}}function Me(){return f$1("analytics",[]),function($e){return function(De,Fe,Be){var He=$e(De,Fe,Be),Ke=He.dispatch;return Object.assign(He,{dispatch:function(Ge){return n[o$2].analytics.push(Ge.action||Ge),Ke(Ge)}})}}}function qe($e){return function(){return N$1(N$1.apply(null,arguments),Me())}}function Ue($e){return $e?rn($e)?$e:[$e]:[]}function Ve($e,De,Fe){$e===void 0&&($e={});var Be,He,Ke=y$1();return De&&(X[Ke]=(Be=De,He=function(Ge){for(var We,Ze=Ge||Array.prototype.slice.call(arguments),Xe=0;Xe<Ze.length;Xe++)if(W$1(Ze[Xe])){We=Ze[Xe];break}return We}(Fe),function(Ge){He&&He(Ge),Be(Ge)})),v({},$e,{rid:Ke,ts:new Date().getTime()},De?{hasCallback:!0}:{})}function Le($e){$e===void 0&&($e={});var De=$e.reducers||{},Fe=$e.initialUser||{},Be=($e.plugins||[]).reduce(function(nt,it){if(W$1(it))return nt.middlewares=nt.middlewares.concat(it),nt;if(it.NAMESPACE&&(it.name=it.NAMESPACE),!it.name)throw new Error("https://lytics.dev/errors/1");it.config||(it.config={});var ht=it.EVENTS?Object.keys(it.EVENTS).map(function(wt){return it.EVENTS[wt]}):[];nt.pluginEnabled[it.name]=!(it.enabled===!1||it.config.enabled===!1),delete it.enabled,it.methods&&(nt.methods[it.name]=Object.keys(it.methods).reduce(function(wt,kt){var Tt;return wt[kt]=(Tt=it.methods[kt],function(){for(var Lt=Array.prototype.slice.call(arguments),Ot=new Array(Tt.length),jt=0;jt<Lt.length;jt++)Ot[jt]=Lt[jt];return Ot[Ot.length]=lt,Tt.apply({instance:lt},Ot)}),wt},{}),delete it.methods);var St=Object.keys(it).concat(ht),bt=new Set(nt.events.concat(St));if(nt.events=Array.from(bt),nt.pluginsArray=nt.pluginsArray.concat(it),nt.plugins[it.name])throw new Error(it.name+"AlreadyLoaded");return nt.plugins[it.name]=it,nt.plugins[it.name].loaded||(nt.plugins[it.name].loaded=function(){return!0}),nt},{plugins:{},pluginEnabled:{},methods:{},pluginsArray:[],middlewares:[],events:[]}),He=$e.storage?$e.storage:{getItem:a$4,setItem:f$1,removeItem:i$4},Ke=function(nt){return function(it,ht,St){return ht.getState("user")[it]||(St&&on(St)&&St[it]?St[it]:$(nt)[it]||a$4(D(it))||null)}}(He),Ge=Be.plugins,We=Be.events.filter(function(nt){return!M.includes(nt)}).sort(),Ze=new Set(We.concat(z).filter(function(nt){return!M.includes(nt)})),Xe=Array.from(Ze).sort(),Je=function(){return Ge},Ye=new fe,Qe=Ye.addMiddleware,et=Ye.removeMiddleware,tt=Ye.dynamicMiddlewares,ct=function(){throw new Error("Abort disabled inListener")},at=s$1(),ft=$(He),ut=v({},ft,Fe,at.an_uid?{userId:at.an_uid}:{},at.an_aid?{anonymousId:at.an_aid}:{});ut.anonymousId||(ut.anonymousId=y$1());var ot=v({enable:function(nt,it){return new Promise(function(ht){mt.dispatch({type:q.enablePlugin,plugins:Ue(nt),_:{originalAction:q.enablePlugin}},ht,[it])})},disable:function(nt,it){return new Promise(function(ht){mt.dispatch({type:q.disablePlugin,plugins:Ue(nt),_:{originalAction:q.disablePlugin}},ht,[it])})}},Be.methods),rt=!1,lt={identify:function(nt,it,ht,St){try{var bt=q$1(nt)?nt:null,wt=on(nt)?nt:it,kt=ht||{},Tt=lt.user();f$1(D(k$1),bt);var Lt=bt||wt.userId||Ke(k$1,lt,wt);return Promise.resolve(new Promise(function(Ot){mt.dispatch(v({type:q.identifyStart,userId:Lt,traits:wt||{},options:kt,anonymousId:Tt.anonymousId},Tt.id&&Tt.id!==bt&&{previousId:Tt.id}),Ot,[it,ht,St])}))}catch(Ot){return Promise.reject(Ot)}},track:function(nt,it,ht,St){try{var bt=on(nt)?nt.event:nt;if(!bt||!q$1(bt))throw new Error("EventMissing");var wt=on(nt)?nt:it||{},kt=on(ht)?ht:{};return Promise.resolve(new Promise(function(Tt){mt.dispatch({type:q.trackStart,event:bt,properties:wt,options:kt,userId:Ke(k$1,lt,it),anonymousId:Ke(T,lt,it)},Tt,[it,ht,St])}))}catch(Tt){return Promise.reject(Tt)}},page:function(nt,it,ht){try{var St=on(nt)?nt:{},bt=on(it)?it:{};return Promise.resolve(new Promise(function(wt){mt.dispatch({type:q.pageStart,properties:Oe(St),options:bt,userId:Ke(k$1,lt,St),anonymousId:Ke(T,lt,St)},wt,[nt,it,ht])}))}catch(wt){return Promise.reject(wt)}},user:function(nt){if(nt===k$1||nt==="id")return Ke(k$1,lt);if(nt===T||nt==="anonId")return Ke(T,lt);var it=lt.getState("user");return nt?i$5(it,nt):it},reset:function(nt){return new Promise(function(it){mt.dispatch({type:q.resetStart},it,nt)})},ready:function(nt){return rt&&nt({plugins:ot,instance:lt}),lt.on(q.ready,function(it){nt(it),rt=!0})},on:function(nt,it){if(!nt||!W$1(it))return!1;if(nt===q.bootstrap)throw new Error(".on disabled for "+nt);var ht=/Start$|Start:/;if(nt==="*"){var St=function(Tt){return function(Lt){return function(Ot){return Ot.type.match(ht)&&it({payload:Ot,instance:lt,plugins:Ge}),Lt(Ot)}}},bt=function(Tt){return function(Lt){return function(Ot){return Ot.type.match(ht)||it({payload:Ot,instance:lt,plugins:Ge}),Lt(Ot)}}};return Qe(St,Ce),Qe(bt,Re),function(){et(St,Ce),et(bt,Re)}}var wt=nt.match(ht)?Ce:Re,kt=function(Tt){return function(Lt){return function(Ot){return Ot.type===nt&&it({payload:Ot,instance:lt,plugins:Ge,abort:ct}),Lt(Ot)}}};return Qe(kt,wt),function(){return et(kt,wt)}},once:function(nt,it){if(!nt||!W$1(it))return!1;if(nt===q.bootstrap)throw new Error(".once disabled for "+nt);var ht=lt.on(nt,function(St){it({payload:St.payload,instance:lt,plugins:Ge,abort:ct}),ht()});return ht},getState:function(nt){var it=mt.getState();return nt?i$5(it,nt):Object.assign({},it)},dispatch:function(nt){var it=q$1(nt)?{type:nt}:nt;if(z.includes(it.type))throw new Error("reserved action "+it.type);var ht=v({},it,{_:v({originalAction:it.type},nt._||{})});mt.dispatch(ht)},enablePlugin:ot.enable,disablePlugin:ot.disable,plugins:ot,storage:{getItem:He.getItem,setItem:function(nt,it,ht){mt.dispatch({type:q.setItemStart,key:nt,value:it,options:ht})},removeItem:function(nt,it){mt.dispatch({type:q.removeItemStart,key:nt,options:it})}},setAnonymousId:function(nt,it){lt.storage.setItem(A$1,nt,it)},events:{core:z,plugins:We}},pt=Be.middlewares.concat([function(nt){return function(it){return function(ht){return ht.meta||(ht.meta=Ve()),it(ht)}}},tt(Ce),se(lt,Je,{all:Xe,plugins:We}),le(He),C$1(lt),B(lt),tt(Re)]),gt={context:je,user:R(He),page:_e,track:ve,plugins:de(Je),queue:be},vt=N$1,Et=N$1;if($$1&&$e.debug){var Pt=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;Pt&&(vt=Pt({trace:!0,traceLimit:25})),Et=function(){return arguments.length===0?Me():on(typeof arguments[0])?qe():qe().apply(null,arguments)}}var Nt,yt=function(nt){return Object.keys(nt).reduce(function(it,ht){return ke.includes(ht)||(it[ht]=nt[ht]),it},{})}($e),It=Be.pluginsArray.reduce(function(nt,it){var ht=it.name,St=it.config,bt=it.loaded,wt=Be.pluginEnabled[ht];return nt[ht]={enabled:wt,initialized:!!wt&&!it.initialize,loaded:!!bt({config:St}),config:St},nt},{}),Rt={context:yt,user:ut,plugins:It},mt=P(function(nt){for(var it=Object.keys(nt),ht={},St=0;St<it.length;St++){var bt=it[St];typeof nt[bt]===y&&(ht[bt]=nt[bt])}var wt,kt=Object.keys(ht);try{(function(Tt){Object.keys(Tt).forEach(function(Lt){var Ot=Tt[Lt];if(typeof Ot(void 0,{type:"@@redux/INIT"})===b$1||typeof Ot(void 0,{type:I$1})===b$1)throw new Error("reducer "+Lt+" "+b$1)})})(ht)}catch(Tt){wt=Tt}return function(Tt,Lt){if(Tt===void 0&&(Tt={}),wt)throw wt;for(var Ot=!1,jt={},Ft=0;Ft<kt.length;Ft++){var Bt=kt[Ft],Vt=Tt[Bt],Kt=(0,ht[Bt])(Vt,Lt);if(typeof Kt===b$1){var zt=S(Bt,Lt);throw new Error(zt)}jt[Bt]=Kt,Ot=Ot||Kt!==Vt}return Ot?jt:Tt}}(v({},gt,De)),Rt,Et(vt(O$1.apply(void 0,pt))));mt.dispatch=(Nt=mt.dispatch,function(nt,it,ht){var St=v({},nt,{meta:Ve(nt.meta,it,Ue(ht))});return Nt.apply(null,[St])});var At=Object.keys(Ge);mt.dispatch({type:q.bootstrap,plugins:At,config:yt,params:at,user:ut,initialUser:Fe,persistedUser:ft});var Ut=At.filter(function(nt){return Be.pluginEnabled[nt]}),xt=At.filter(function(nt){return!Be.pluginEnabled[nt]});return mt.dispatch({type:q.registerPlugins,plugins:At,enabled:Be.pluginEnabled}),Be.pluginsArray.map(function(nt,it){var ht=nt.bootstrap,St=nt.config,bt=nt.name;ht&&W$1(ht)&&ht({instance:lt,config:St,payload:nt}),mt.dispatch({type:q.registerPluginType(bt),name:bt,enabled:Be.pluginEnabled[bt],plugin:nt}),Be.pluginsArray.length===it+1&&mt.dispatch({type:q.initializeStart,plugins:Ut,disabled:xt})}),ze(function(nt){mt.dispatch({type:nt?q.offline:q.online})}),function(nt,it,ht){setInterval(function(){return F$1(nt,it,ht)},3e3)}(mt,Je,lt),lt}var Ce="before",Re="after",t="cookie",i$3=a$3(),r$2=d$1,c$2=d$1;function u$2($e){return i$3?d$1($e,"",-1):i$4($e)}function a$3(){if(i$3!==void 0)return i$3;var $e="cookiecookie";try{d$1($e,$e),i$3=document.cookie.indexOf($e)!==-1,u$2($e)}catch{i$3=!1}return i$3}function d$1($e,De,Fe,Be,He,Ke){if(typeof window<"u"){var Ge=arguments.length>1;return i$3===!1&&(Ge?f$1($e,De):a$4($e)),Ge?document.cookie=$e+"="+encodeURIComponent(De)+(Fe?"; expires="+new Date(+new Date+1e3*Fe).toUTCString()+(Be?"; path="+Be:"")+(He?"; domain="+He:"")+(Ke?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+$e+"=")[1]||"").split(";")[0])}}var r$1="localStorage",g=b$2.bind(null,"localStorage");u$3("localStorage","getItem",a$4),u$3("localStorage","setItem",f$1),u$3("localStorage","removeItem",i$4);var a$2="sessionStorage",i$2=b$2.bind(null,"sessionStorage");u$3("sessionStorage","getItem",a$4),u$3("sessionStorage","setItem",f$1),u$3("sessionStorage","removeItem",i$4);function I($e){var De=$e;try{if((De=JSON.parse($e))==="true")return!0;if(De==="false")return!1;if(on(De))return De;parseFloat(De)===De&&(De=parseFloat(De))}catch{}if(De!==null&&De!=="")return De}var k=g(),O=i$2(),x=a$3();function C($e,De){if($e){var Fe=A(De),Be=!N(Fe),He=d(Fe)?I(localStorage.getItem($e)):void 0;if(Be&&!I$2(He))return He;var Ke=h(Fe)?I(r$2($e)):void 0;if(Be&&Ke)return Ke;var Ge=E(Fe)?I(sessionStorage.getItem($e)):void 0;if(Be&&Ge)return Ge;var We=a$4($e);return Be?We:{localStorage:He,sessionStorage:Ge,cookie:Ke,global:We}}}function L($e,De,Fe){if($e&&!I$2(De)){var Be={},He=A(Fe),Ke=JSON.stringify(De),Ge=!N(He);return d(He)&&(Be[r$1]=F(r$1,De,I(localStorage.getItem($e))),localStorage.setItem($e,Ke),Ge)?Be[r$1]:h(He)&&(Be[t]=F(t,De,I(r$2($e))),c$2($e,Ke),Ge)?Be[t]:E(He)&&(Be[a$2]=F(a$2,De,I(sessionStorage.getItem($e))),sessionStorage.setItem($e,Ke),Ge)?Be[a$2]:(Be[l$2]=F(l$2,De,a$4($e)),f$1($e,De),Ge?Be[l$2]:Be)}}function b($e,De){if($e){var Fe=A(De),Be=C($e,m$1),He={};return!I$2(Be.localStorage)&&d(Fe)&&(localStorage.removeItem($e),He[r$1]=Be.localStorage),!I$2(Be.cookie)&&h(Fe)&&(u$2($e),He[t]=Be.cookie),!I$2(Be.sessionStorage)&&E(Fe)&&(sessionStorage.removeItem($e),He[a$2]=Be.sessionStorage),!I$2(Be.global)&&G(Fe,l$2)&&(i$4($e),He[l$2]=Be.global),He}}function A($e){return $e?q$1($e)?$e:$e.storage:b$4}function d($e){return k&&G($e,r$1)}function h($e){return x&&G($e,t)}function E($e){return O&&G($e,a$2)}function N($e){return $e===m$1||$e==="all"}function G($e,De){return $e===b$4||$e===De||N($e)}function F($e,De,Fe){return{location:$e,current:De,previous:Fe}}var J={setItem:L,getItem:C,removeItem:b};function _defineProperty($e,De,Fe){return De in $e?Object.defineProperty($e,De,{value:Fe,enumerable:!0,configurable:!0,writable:!0}):$e[De]=Fe,$e}function ownKeys($e,De){var Fe=Object.keys($e);if(Object.getOwnPropertySymbols){var Be=Object.getOwnPropertySymbols($e);De&&(Be=Be.filter(function(He){return Object.getOwnPropertyDescriptor($e,He).enumerable})),Fe.push.apply(Fe,Be)}return Fe}function _objectSpread2($e){for(var De=1;De<arguments.length;De++){var Fe=arguments[De]!=null?arguments[De]:{};De%2?ownKeys(Object(Fe),!0).forEach(function(Be){_defineProperty($e,Be,Fe[Be])}):Object.getOwnPropertyDescriptors?Object.defineProperties($e,Object.getOwnPropertyDescriptors(Fe)):ownKeys(Object(Fe)).forEach(function(Be){Object.defineProperty($e,Be,Object.getOwnPropertyDescriptor(Fe,Be))})}return $e}function analyticsLib(){var $e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},De={storage:J};return Le(_objectSpread2(_objectSpread2({},De),$e))}function saturated($e,De){De=De||{};var Fe,Be,He=[],Ke=De.max||1/0;function Ge(){clearInterval(Fe),$e(He.splice(0,Ke)),We()}function We(){Fe=setInterval(Ge,De.interval||1e4)}return We(),{flush:Ge,push:function(Ze){return Be=He.push(Ze),Be>=Ke&&Ge(),Be},size:function(){return He.length},end:function(Ze){Ze&&Ge(),clearInterval(Fe)}}}function onRouteChange($e){if(typeof window>"u")return;const{addEventListener:De,history:Fe,location:Be}=window;let He=Be.pathname;De("popstate",()=>$e(Be.pathname)),["push","replace"].map(Ke=>{const Ge=`${Ke}State`;if(Ge!=="pushState"&&Ge!=="replaceState")return;const We=Fe[Ge];Fe[Ge]=function(...Ze){var Ye;const Xe=((Ye=Ze[2])==null?void 0:Ye.toString())||"",Je=trimPath(Xe);return He!==Je&&(He=Je,setTimeout(()=>$e(Xe),0)),We.apply(Fe,Ze)}})}function remove($e,De){const Fe=$e.indexOf(De);return Fe>-1?$e.slice(0,Fe):$e}function trimPath($e){return["#","?"].forEach(De=>$e=remove($e,De)),$e}function routeChangeListener(){onRouteChange(()=>{analytics.page()})}function i$1($e){if($e===void 0&&($e={}),!$$1)return g$1;var De=l$1(),Fe=c$1(),Be=o$1(),He=s(Be,De),Ke=s(Fe,De),Ge=[],We=[],Ze=[],Xe=Be,Je=He,Ye=Ke,Qe=Object.keys($e);if(!Qe.length)return g$1;var et=Qe.map(function(ct){return Number(ct)}),tt=b$3(function(){var ct=l$1(),at=function(yt,It){return It.map(function(Rt){return Rt===100?yt-5:yt*(Rt/100)})}(ct,et),ft=c$1(),ut=o$1(),ot=s(ut,ct),rt=s(ft,ct);if(Je=ot>Je?ot:Je,Ye=rt<Ye?rt:Ye,!(Ge.length>=et.length)){var lt=Xe===ut,pt="up";lt?pt="initial":Xe<=ut&&(pt="down");var gt=at,vt=et;(pt==="up"||lt)&&(gt=at.slice().reverse(),vt=et.slice().reverse());var Et=vt.reduce(function(yt,It,Rt){var mt=gt[Rt];return Ze.includes(It)&&ut<=mt&&(Ze=Ze.filter(function(At){return At!==It}),yt.singleFunction=It),pt==="down"&&!Ge.includes(It)&&ut>=mt&&It>Ke?(We.push(It),yt.callbacks=yt.callbacks.concat(It),yt):pt==="up"&&!Ge.includes(It)&&ut<=mt&&It<=ot?(yt.foundFunc=[It],yt):(lt&&ut>=mt&&yt.foundFunc.length===0&&(yt.foundFunc=[It]),!We.includes(It)&&ut>=mt&&(We.push(It),yt.singleFunction?Ze.push(It):yt.singleFunction=It),yt)},{foundFunc:[],singleFunction:null,callbacks:[],direction:pt});if(Xe=ut,pt==="down"&&Et.callbacks&&Et.callbacks.forEach(function(yt){W$1($e[yt])&&($e[yt]({trigger:yt,direction:pt,scrollMin:Ye,scrollMax:Je,range:[Ye,Je]}),Ge.push(yt))}),Et.singleFunction){var Pt=Et.singleFunction,Nt=Et.direction;W$1($e[Pt])&&$e[Pt]({trigger:Pt,direction:Nt,scrollMin:Ye,scrollMax:Je,range:[Ye,Je]}),Ge.push(Pt)}}},500);return window.addEventListener("scroll",tt),function(){return window.removeEventListener("scroll",tt)}}function c$1(){return $$1?document.body.scrollTop||document.documentElement.scrollTop:0}function u$1(){return $$1?window.innerHeight||document.documentElement.clientHeight:0}function o$1(){return Math.round(c$1()+u$1())}function l$1(){if(!$$1)return 0;var $e=document.body,De=document.documentElement;return Math.max($e.scrollHeight,$e.offsetHeight,De.clientHeight,De.scrollHeight,De.offsetHeight)}function s($e,De){return Math.round($e/De*100)}var i="EventListener";function u($e){return function(De,Fe,Be,He){var Ke=Be||g$1,Ge=He||!1;if(!$$1)return Ke;var We=l(Fe),Ze=l(De,!0);if(!Ze.length)throw new Error("noElements");if(!We.length)throw new Error("noEvent");var Xe=[];return function Je(Ye){Ye&&(Xe=[]);for(var Qe=Ye?"add"+i:"remove"+i,et=0;et<Ze.length;et++){var tt=Ze[et];Xe[et]=Ye?Ge&&Ge.once?a$1(Ke):Ke:Xe[et]||Ke;for(var ct=0;ct<We.length;ct++)tt[Qe]?tt["on"+We[ct]]=Ye?Xe[et]:null:tt[Qe](We[ct],Xe[et],Ge)}return Je.bind(null,!Ye)}($e)}}function l($e,De){if(q$1($e))return De?l(document.querySelectorAll($e)):(Fe=$e).split(Fe.indexOf(",")>-1?",":" ").map(function(Ge){return Ge.trim()});var Fe;if(NodeList.prototype.isPrototypeOf($e)){for(var Be=[],He=$e.length>>>0;He--;)Be[He]=$e[He];return Be}var Ke=Hn($e);return De?Ke.map(function(Ge){return q$1(Ge)?l(Ge,!0):Ge}).flat():Ke}function a$1($e,De){var Fe;return function(){return $e&&(Fe=$e.apply(this,arguments),$e=null),Fe}}var f=u("Event");function p($e,De){return $$1&&W$1(window[$e])?(Fe=window[$e],Be=De,(He=window)===void 0&&(He=null),W$1(Fe)?function(){Fe.apply(He,arguments),Be.apply(He,arguments)}:Be):window[$e]=De;var Fe,Be,He}p.bind(null,"onerror"),p.bind(null,"onload");var isServer=typeof window>"u",HIDDEN="hidden";function onTabChange($e){if(isServer)return!1;var De=getHiddenProp(),Fe="".concat(De.replace(/[H|h]idden/,""),"visibilitychange"),Be=function(){return $e(!!document[De])},He=function(){return document.addEventListener(Fe,Be)};return He(),function(){return document.removeEventListener(Fe,Be),He}}function getHiddenProp(){var $e=["webkit","moz","ms","o"];return isServer||HIDDEN in document?HIDDEN:$e.reduce(function(De,Fe){var Be=Fe+"Hidden";return!De&&Be in document?Be:De},null)}var o=["mousemove","mousedown","touchmove","touchstart","touchend","keydown"];function r($e,De){De===void 0&&(De={});var Fe=function(Ge,We){var Ze=this,Xe=!1;return function(Je){Xe||(Ge.call(Ze,Je),Xe=!0,setTimeout(function(){return Xe=!1},We))}}($e,De.throttle||1e4),Be=[];function He(){var Ge=onTabChange(function(We){We||Fe({type:"tabVisible"})});return Be=[Ge].concat(o.map(function(We){return f(document,We,Fe)})).concat(f(window,"load",Fe)).concat(f(window,"scroll",Fe,{capture:!0,passive:!0})),Ke}function Ke(){Be.map(function(Ge){return Ge()})}return He(),function(){return Ke(),He}}function a($e){var De,Fe,Be=$e.onIdle,He=$e.onWakeUp,Ke=$e.onHeartbeat,Ge=$e.timeout,We=Ge===void 0?1e4:Ge,Ze=$e.throttle,Xe=Ze===void 0?2e3:Ze,Je=!1,Ye=!1,Qe=new Date,et=function(){return clearTimeout(De)};function tt(at){et(),Ke&&!Je&&Ke(c(Qe),at),He&&Je&&(Je=!1,He(c(Fe),at),Qe=new Date),De=setTimeout(function(){Je=!0,Be&&(Fe=new Date,Be(c(Qe),at))},We)}var ct=r(tt,{throttle:Xe});return{disable:function(){Ye=!0,Je=!1,et();var at=ct();return function(){return Ye=!1,Qe=new Date,tt({type:"load"}),at()}},getStatus:function(){return{isIdle:Je,isDisabled:Ye,active:Je?0:c(Qe,Ye),idle:Je?c(Fe,Ye):0}}}}function c($e,De){return De?0:Math.round((new Date-$e)/1e3)}const timeout=5e3;class ElementTracker{constructor(De){Dt(this,"element");Dt(this,"isInViewport",!1);Dt(this,"isAwake",!1);Dt(this,"isFlushing");Dt(this,"observer");Dt(this,"lastEventAt",Date.now());Dt(this,"registeredView",!1);Dt(this,"viewCallback");Dt(this,"activeDurationCallback");Dt(this,"idleDurationCallback");Dt(this,"scrollCallback");this.element=De.element,this.viewCallback=De.viewCallback,this.activeDurationCallback=De.activeDurationCallback,this.idleDurationCallback=De.idleDurationCallback,this.scrollCallback=De.scrollCallback,this.observer=new IntersectionObserver(Fe=>{Fe.forEach(Be=>{this.handleInViewPort(Be.isIntersecting)})},{threshold:0}),this.observer.observe(this.element),a({onIdle:Fe=>this.handleAwake(!1,Fe),onWakeUp:Fe=>this.handleAwake(!0,Fe),timeout}),i$1({25:this.handleScroll.bind(this),50:this.handleScroll.bind(this),75:this.handleScroll.bind(this),90:this.handleScroll.bind(this),100:this.handleScroll.bind(this)})}flush(){this.isFlushing=!0,this.handleAwake(!this.isAwake)}handleInViewPort(De){De?(this.isAwake=!0,this.trackInViewport()):this.handleAwake(!1),this.isInViewport=De}handleAwake(De,Fe=Math.round((Date.now()-this.lastEventAt)/1e3)){this.isAwake=De,this.lastEventAt=De?Date.now()-Fe*timeout:Date.now(),this.isInViewport&&this.trackAwake(De,Fe)}handleScroll(De){this.scrollCallback&&this.scrollCallback(De)}handleVisibilityChange(){this.isAwake=!1;const De=Math.round((Date.now()-this.lastEventAt)/1e3);De>1&&(this.lastEventAt=Date.now(),this.trackAwake(!1,De))}trackAwake(De,Fe){!De&&this.activeDurationCallback&&this.activeDurationCallback(Fe,this.isFlushing,this.lastEventAt),De&&this.idleDurationCallback&&this.idleDurationCallback(Fe,this.isFlushing,this.lastEventAt)}trackInViewport(){this.registeredView||(this.registeredView=!0,this.viewCallback&&this.viewCallback())}}const SESSION_ID_KEY="sesamy_session_id";function getSessionId(){let $e=sessionStorage.getItem(SESSION_ID_KEY);return $e||($e=Math.random().toString(36).slice(2,9),sessionStorage.setItem(SESSION_ID_KEY,$e)),$e}function generateCSSSelector($e){function De(Be){return Be.id?`#${Be.id}`:Be.classList.length>0?Array.from(Be.classList).map(Ke=>`.${Ke}`).join(""):null}function Fe(Be){const He=[];let Ke=Be;for(;Ke&&Ke!==document.body&&Ke!==document.documentElement;){const Ge=De(Ke);if(Ge){He.unshift(Ge);break}if(Ke.parentElement){const We=Array.from(Ke.parentElement.children),Ze=We.indexOf(Ke)+1,Xe=Ke.tagName.toLowerCase();We.filter(Ye=>Ye.tagName.toLowerCase()===Xe).length>1?He.unshift(`${Xe}:nth-child(${Ze})`):He.unshift(Xe)}Ke=Ke.parentElement}return He.join(" > ")}return Fe($e)}let contentSelectors={article:{selector:"sesamy-article"},image:{selector:"img",attribute:"src"},title:{selector:"h1",attribute:"textContent"},excerpt:{selector:"p",attribute:"textContent"},price:{selector:"sesamy-article",attribute:"price"},currency:{selector:"sesamy-article",attribute:"currency"},url:{selector:"sesamy-article",attribute:"item-src"},accessLevel:{selector:"sesamy-article",attribute:"access-level"},id:{selector:"sesamy-article",attribute:"publisher-content-id"},pass:{selector:"sesamy-article",attribute:"pass"}},api;function init$2($e,De){var Fe;contentSelectors={...contentSelectors,...(Fe=$e.content)==null?void 0:Fe.article},api=De}function getElementFromSelector($e,De){const{selector:Fe}=De;return Fe===contentSelectors.article.selector?$e:$e.querySelector(Fe)}function getElementValue($e,De){if($e)return De.attribute?De.attribute==="textContent"?$e.textContent??void 0:$e.getAttribute(De.attribute)??getElementValue($e.parentElement,De):$e.textContent??void 0}function getMetaTag($e){const De=document.head.querySelectorAll(`[property~='${$e}'][content]`);for(let Be=0;Be<De.length;Be+=1)if(De[Be].content)return De[Be].content;const Fe=document.head.querySelectorAll(`[name~='${$e}'][content]`);for(let Be=0;Be<Fe.length;Be+=1)if(Fe[Be].content)return Fe[Be].content}function getPropertyFromHTML({publisherContentId:$e,key:De,defaultValue:Fe=""}){const Be=$e?document.body.querySelector(`sesamy-content-data[id='${$e}']`):null;return(Be==null?void 0:Be.getAttribute(De))||getMetaTag(`sesamy:${De}`)||getMetaTag(`og:${De}`)||getMetaTag(De)||Fe}function listContent(){const $e=document.querySelectorAll(contentSelectors.article.selector);return Array.from($e).map(getContent$1).filter(De=>De!==null)}function getContent$1($e){const De=typeof $e=="string"?document.querySelector($e):$e;if(!De)return null;const Fe={element:De,selector:typeof $e=="string"?$e:generateCSSSelector(De)},Be=(He,Ke,Ge,We)=>{const Ze=getElementFromSelector(De,Ke);if(Ze){const Xe=getElementValue(Ze,Ke)||getPropertyFromHTML({publisherContentId:Ge,key:He});Xe!==void 0&&(Fe[He]=We?We(Xe):Xe)}};return Be("id",contentSelectors.id),Be("title",contentSelectors.title,Fe.id),Be("excerpt",contentSelectors.excerpt,Fe.id),Be("image",contentSelectors.image,Fe.id),Be("price",contentSelectors.price,Fe.id,He=>parseFloat(He)),Be("currency",contentSelectors.currency,Fe.id),Be("url",contentSelectors.url,Fe.id),Be("pass",contentSelectors.pass,Fe.id),Be("accessLevel",contentSelectors.accessLevel,Fe.id,He=>He||"entitlement"),Fe}async function unlockContent($e,De){var We;const Fe=typeof $e=="string"?document.querySelector($e):$e;if(!Fe)throw new Error("Could not find element");const Be=getContent$1(Fe);if(!(Be!=null&&Be.url))throw new Error("Could not find content for element");const He=await api.entitlements.hasAccess(Be.url||"",((We=Be.pass)==null?void 0:We.split(","))||[]);if(!He)throw new Error("User does not have access to the content");const Ke=await api.entitlements.access(He.id);if(!Ke.token)throw new Error("Could not get access token");const Ge=De||generateCSSSelector(Fe.parentElement||Fe);return api.proxy.getContent(Ke.token,Be.url,Ge)}function onDOMContentLoaded($e){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$e):$e()}let flushing=!1,_clientId,_enabled,_endpoint;const visibilityListeners=new Map;function initAnalytics({clientId:$e,enabled:De=!0,environment:Fe}){_clientId=$e,_enabled=De,_endpoint=`${getBaseUrl("logs",Fe)}/events`,_enabled&&(window.addEventListener("beforeunload",()=>{unloadPageListeners.forEach((Be,He)=>{Be.bind(He)()}),flushQueue()}),window.addEventListener("visibilitychange",()=>{document.visibilityState!=="visible"&&visibilityListeners.forEach((Be,He)=>{Be.bind(He)()})}),routeChangeListener(),onDOMContentLoaded(()=>{const Be=new ElementTracker({element:document.body,viewCallback:()=>{analytics.page()},activeDurationCallback:(He,Ke,Ge)=>{analytics.track("activeDuration",{duration:He,durationStart:Ge,flushing:Ke})},idleDurationCallback:(He,Ke,Ge)=>{analytics.track("idleDuration",{duration:He,durationStart:Ge,flushing:Ke})},scrollCallback:He=>{analytics.track("scroll",{scroll:He.scrollMax})}});addUnloadPageListener(document.body,()=>{Be.flush()}),addVisibilityListener(document.body,()=>{Be.handleVisibilityChange()})}),window.addEventListener(Events.AUTHENTICATED,async Be=>{const He=Be;await analytics.identify(He.detail.sub)}),window.addEventListener(Events.LOGOUT,async()=>{await analytics.track("logout",{}),queue.flush(),await analytics.reset()}))}function createMessage($e){return JSON.stringify($e.map(De=>({...De,clientId:_clientId,requestId:Math.random().toString(36).slice(2,9),sessionId:getSessionId(),timestamp:new Date().toISOString(),version,event:De.event,context:{page:{url:window.location.href,title:document.title,referrer:document.referrer,itemSrc:getMetaTag("sesamy:item-src"),publisherContentId:getMetaTag("sesamy:publisher-content-id")},locale:navigator.language,library:name,userAgent:navigator.userAgent,clientId:_clientId}})))}const queue=saturated(async $e=>{if($e.length>0){const De=createMessage($e);flushing?navigator.sendBeacon(_endpoint,De):(await fetch(_endpoint,{method:"POST",body:De,headers:{"Content-Type":"text/plain"}})).ok}},{max:10,interval:3e3});function send($e){var De;if($e.anonymousId)if((De=$e.properties)!=null&&De.flushing){const Fe={...$e};delete Fe.properties.flushing,navigator.sendBeacon(_endpoint,createMessage([Fe]))}else queue.push($e)}const analytics=analyticsLib({app:name,version,plugins:[{name:"custom-analytics-plugin",page:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be,event:He}=$e;send({anonymousId:Fe,userId:Be,properties:De,event:He,type:"page"})},track:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be,event:He}=$e;send({anonymousId:Fe,userId:Be,properties:De,event:He,type:"track"})},identify:({payload:$e})=>{const{properties:De,anonymousId:Fe,userId:Be}=$e;send({anonymousId:Fe,userId:Be,properties:De,type:"identify"})}}]});function track($e,De){analytics.track($e,De)}function flushQueue(){return flushing=!0,queue.flush()}const unloadPageListeners=new Map;function addUnloadPageListener($e,De){unloadPageListeners.set($e,De)}function addVisibilityListener($e,De){visibilityListeners.set($e,De)}const bannerIds=["AdHeader","AdContainer","AD_Top","homead","ad-lead"];function detectAdblock(){return new Promise($e=>{const De=bannerIds.map(Fe=>{const Be=document.createElement("div");return Be.innerHTML="&nbsp;",Be.id=Fe,Be.style.position="absolute",document.body.appendChild(Be),Be});window.setTimeout(()=>{const Fe=!De.every(Be=>{const He=document.querySelector(`#${Be.id}`);return He==null?void 0:He.offsetParent});De.forEach(Be=>Be.remove()),$e(Fe)},100)})}function isInAppBrowser(){const $e=navigator.userAgent.toLowerCase(),De=[{name:"Facebook",regex:/fbav|fban/i},{name:"LinkedIn",regex:/linkedin/i},{name:"Instagram",regex:/instagram/i},{name:"Gmail",regex:/gmail/i},{name:"Twitter",regex:/twitter/i},{name:"WeChat",regex:/micromessenger/i},{name:"Line",regex:/line/i},{name:"Snapchat",regex:/snapchat/i},{name:"Pinterest",regex:/pinterest/i},{name:"Kakao",regex:/kakaotalk/i},{name:"Skype",regex:/skype/i},{name:"WhatsApp",regex:/whatsapp/i}];for(const Fe of De)if(Fe.regex.test($e))return{isInAppBrowser:!0,browserName:Fe.name};return/; wv\)/.test($e)?{isInAppBrowser:!0,browserName:"Unknown In-App Browser"}:{isInAppBrowser:!1,browserName:null}}function registerAPI($e){const{autoOnboardProduct:De,cancelContract:Fe,createCheckout:Be,deleteTag:He,deleteTally:Ke,deleteUserMetadata:Ge,generateLink:We,getBill:Ze,getBills:Xe,getCheckout:Je,getContract:Ye,getContracts:Qe,getEntitlement:et,getEntitlementAccess:tt,getEntitlements:ct,getFulfillments:at,getPaywall:ft,getPaymentIssues:ut,getProfile:ot,getProduct:rt,getProxyContent:lt,getSubscriptions:pt,getTags:gt,getTally:vt,getTallies:Et,getTransaction:Pt,getTransactions:Nt,getUserMetadata:yt,getVendorSettings:It,listVendors:Rt,hasAccess:mt,isSpotifyLinked:At,linkSpotify:Ut,listUserMetadata:xt,openHostedAccountPage:nt,pushTally:it,setTag:ht,setUserMetadata:St,unlinkSpotify:bt,updateCheckout:wt,updateProfile:kt}=createApi($e),Tt={analytics:{track},attribution:{get:getAttribution,set:setAttribution},auth:{getUser:ot,isAuthenticated,loginWithRedirect,logout,setToken},bills:{get:Ze,list:Xe},browser:{detectAdblock,isInAppBrowser,isIncognito},checkouts:{create:Be,get:Je,update:wt},clearCache,content:{list:listContent,get:getContent$1,getLanguage,unlock:unlockContent,getPropertyFromHTML},contracts:{cancel:Fe,get:Ye,list:Qe},entitlements:{access:tt,get:et,hasAccess:mt,list:ct,signedLinks:getSignedLinks},flags:{get:getFlag,set:setFlag,list:listFlags,delete:deleteFlag},fulfillments:{list:at},generateLink:We,getPaymentIssues:ut,getVersion,isReady:()=>exports.isInitialized,log,paywalls:{get:ft},products:{autoOnboard:De,get:rt,linkSpotify:Ut},profile:{get:ot,isSpotifyLinked:At,openHostedAccountPage:nt,unlinkSpotify:bt,update:kt},proxy:{getContent:lt},subscriptions:{list:pt},tags:{delete:He,list:gt,set:ht},tallies:{delete:Ke,get:vt,list:Et,push:it},transactions:{get:Pt,list:Nt},userMetadata:{delete:Ge,get:yt,list:xt,set:St},vendors:{get:It,list:Rt},setToken};return $e.namespace&&(window[$e.namespace]=Tt),Tt}function getVersion(){return version}function gradient($e,De){$e.style.position="relative",$e.style.height="200px",$e.style.overflow="hidden";let Be=0;const He=Array.from($e.children);for(const Ge of He){const We=Ge.offsetHeight;Be+We>200?Ge.remove():Be+=We}const Ke=document.createElement("style");Ke.innerHTML=`
37
37
  ${De.selector}::before {
38
38
  content: '';
@@ -44,4 +44,4 @@ CAUSE: `+et.stack,lt.response=ot,lt.status=ot.status,lt.url=Ye,ot.type==="opaque
44
44
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0), white);
45
45
  pointer-events: none;
46
46
  }
47
- `,document.head.appendChild(Ke)}async function fetchContent($e){try{const De=await fetch($e);return De.ok?await De.text():(console.error(`Failed to fetch content from ${$e}: ${De.statusText}`),null)}catch(De){return console.error(`Error fetching content from ${$e}:`,De),null}}async function getContent($e){if($e.contentType==="selector"&&$e.content){const De=document.querySelector($e.content);if(De)return De.innerHTML;console.warn(`Source element for selector '${$e.content}' not found`)}else if($e.contentType==="url"&&$e.content){const De=await fetchContent($e.content);if(De)return De;console.warn(`Failed to fetch content from URL '${$e.content}'`)}else if($e.content)return $e.content;return""}async function insert($e,De){const Fe=De.insertionPoint||"inside",Be=await getContent(De);switch(Fe){case"before":$e.insertAdjacentHTML("beforebegin",Be);break;case"after":$e.insertAdjacentHTML("afterend",Be);break;case"inside":default:$e.innerHTML+=Be;break}}async function replace($e,De){const Fe=await getContent(De);$e.innerHTML=Fe}async function wrap($e,De){const Fe=await getContent(De);$e.innerHTML=Fe.replace("${content}",$e.innerHTML)}async function init$1({enabled:$e=!1,rules:De}){$e&&onDOMContentLoaded(async()=>{const Fe=await isAuthenticated(),Be=window.location.href;for(const He of De){const Ke=document.querySelectorAll(He.selector);if(!(He.path&&!new RegExp(He.path).test(Be)))for(const Ge of Ke){const We=Ge;if(!(He.authenticated!==void 0&&He.authenticated!==Fe))switch(He.transform){case"insert":await insert(We,He);break;case"replace":await replace(We,He);break;case"remove":Ge.remove();break;case"wrap":await wrap(We,He);break;case"gradient":gradient(We,He);break;default:console.warn(`Unknown transform type: ${He.transform}`)}}}})}const ACCESS_TOKEN="access_token";function handleTokenFromQuerystring(){const $e=new URLSearchParams(window.location.hash.substring(1)),De=$e.get(ACCESS_TOKEN);if(De){setToken(De);const Fe=new URL(window.location.href);$e.delete(ACCESS_TOKEN),Fe.hash=$e.toString(),window.history.replaceState(null,"",Fe)}}const REFRESH_KEY="sesamy-refresh",DEPRECATED_REFRESH_KEY="force-refetch-entitlements";function handleForceRefreshFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(DEPRECATED_REFRESH_KEY),Fe=$e.get(REFRESH_KEY);if(De!==null||Fe!==null){const Be=new URL(window.location.href);$e.delete(DEPRECATED_REFRESH_KEY),$e.delete(REFRESH_KEY),Be.search=$e.toString(),clearCache(),window.history.replaceState(null,"",Be)}}function extractJwt($e){const De=$e.split(".")[1],Fe=atob(De);return JSON.parse(Fe)}function handleSignedLinksFromQuerystring(){var Be,He,Ke,Ge;const $e=new URLSearchParams(window.location.search),De=$e.get("sesamy-token")||$e.get("token");if(!De)return;try{const We=extractJwt(De),Ze=new Date(We.exp*1e3),Xe={id:"",title:(Be=We.p)==null?void 0:Be.toString(),sku:(He=We.s)==null?void 0:He.toString(),purchaseOptionsId:(Ke=We.pid)==null?void 0:Ke.toString(),url:(Ge=We.url)==null?void 0:Ge.toString(),token:De,type:"article",expiresAt:Ze.toISOString(),createdAt:new Date(We.iat).toISOString(),updatedAt:new Date(We.iat).toISOString()};addSignedLink(Xe)}catch(We){log(`Failed to extract signed link ${We}`)}const Fe=new URL(window.location.href);Fe.searchParams.delete("ss"),Fe.searchParams.delete("se"),Fe.searchParams.delete("sp"),Fe.searchParams.delete("so"),Fe.searchParams.delete("token"),Fe.searchParams.delete("sesamy-token"),window.history.replaceState(null,"",Fe)}const SESAMY_USER="sesamy-user";async function handleUserFromQuerystring(){var He;const De=(He=new URLSearchParams(window.location.search).get(SESAMY_USER))==null?void 0:He.toLowerCase();if(!De)return;const Fe=await getUser();(Fe==null?void 0:Fe.email)!==De?(log(`Current user does not match sesamy user: ${Fe==null?void 0:Fe.email} !== ${De}`),clearCache(),loginWithRedirect({authorizationParams:{login_hint:De}})):log(`Current user matches sesamy user: ${Fe==null?void 0:Fe.email} === ${De}`);const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_USER),window.history.replaceState(null,"",Be)}const PURCHASE_KEY="sesamy-purchase";function handlePurchaseFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(PURCHASE_KEY);if(De!==null){const Fe=new URL(window.location.href);$e.delete(PURCHASE_KEY),Fe.search=$e.toString(),log(`Purchase ${De}`),triggerEvent(Events.PURCHASE,{itemSrc:De}),clearCache(),window.history.replaceState(null,"",Fe)}}const SESAMY_LOGIN="sesamy-login",SESAMY_LOGIN_LEGACY="sesamy_login";async function handleLoginFromQuerystring(){const $e=new URLSearchParams(window.location.search);if(!($e.get(SESAMY_LOGIN)||$e.get(SESAMY_LOGIN_LEGACY)))return;await isAuthenticated()||loginWithRedirect();const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_LOGIN),window.history.replaceState(null,"",Be)}const SESAMY_DEBUG="sesamy-debug";async function handleDebugFromQuerystring(){var Be;const De=(Be=new URLSearchParams(window.location.search).get(SESAMY_DEBUG))==null?void 0:Be.toLowerCase();if(!De)return;setDebug(De==="true");const Fe=new URL(window.location.href);Fe.searchParams.delete(SESAMY_DEBUG),window.history.replaceState(null,"",Fe)}function getReferrer(){if(!document.referrer.length)return;const $e=new URL(document.referrer);if(!($e.hostname===window.location.hostname||$e.hostname.includes("sesamy")))return document.referrer}async function handleAttribution($e){if(!isBrowser())return;const De=new URLSearchParams(window.location.search),Fe={utmSource:De.get("utm_source")??void 0,utmMedium:De.get("utm_medium")??void 0,utmCampaign:De.get("utm_campaign")??void 0,utmTerm:De.get("utm_term")??void 0,utmContent:De.get("utm_content")??void 0,ref:De.get("ref")??void 0,referrer:getReferrer()},[Be]=$e.content.list();Be!=null&&Be.url&&(Fe.itemSrc=Be.url,Fe.publisherContentId=Be.id),setAttribution(Fe)}function handleLoginReload(){sessionStorage.getItem(SESMAY_CONTENT_RELOAD_KEY)==="true"&&(sessionStorage.removeItem(SESMAY_CONTENT_RELOAD_KEY),window.location.search.includes("code=")||(log("Reloading page to get query params in incognito browser"),window.location.reload()))}async function handleLinks($e){const De=He=>Ke=>{Ke.preventDefault();try{He()}catch(Ge){console.error("Error handling click:",Ge)}},Fe=(He,Ke)=>{try{document.querySelectorAll(He).forEach(We=>{We.addEventListener("click",De(Ke))})}catch(Ge){console.error(`Error attaching event handlers (selector: ${He}):`,Ge)}};Fe('[sesamy-link="login"]',()=>$e.auth.loginWithRedirect()),Fe('[sesamy-link="logout"]',()=>$e.auth.logout());const Be=await $e.generateLink({target:"account"});Be&&Fe('[sesamy-link="account"]',()=>{window.location.href=Be})}async function handleVisibility($e){const De=await $e.auth.isAuthenticated();try{document.querySelectorAll(`[sesamy-visibility="${De?"not-logged-in":"logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="none")}),document.querySelectorAll(`[sesamy-visibility="${De?"logged-in":"not-logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="")})}catch(Fe){console.error("Error handling visibility:",Fe)}}exports.isInitialized=!1;async function initOtherServices($e,De){log(`Init with config: ${JSON.stringify($e)}`);try{handleLoginReload(),initAnalytics({clientId:$e.clientId,environment:$e.environment,...$e.analytics}),await init$3({clientId:$e.clientId,organization:$e.organization,environment:$e.environment,...$e.auth}),init$2($e,De),$e.transform&&await init$1($e.transform),handleDebugFromQuerystring(),handleAttribution(De),handleTokenFromQuerystring(),handleForceRefreshFromQuerystring(),handleSignedLinksFromQuerystring(),await handleLoginFromQuerystring(),await handleUserFromQuerystring(),handlePurchaseFromQuerystring(),await handleVisibility(De),await handleLinks(De),exports.isInitialized=!0,triggerEvent(Events.READY,{})}catch(Fe){log(`Failed to init ${Fe.message}`)}}async function init($e){var Be;log("Initializing Sesamy");const De=((Be=$e.api)==null?void 0:Be.namespace)||"sesamy";if(isBrowser()&&De in window)return log("Sesamy already initialized. This is likely due to a duplicate import"),exports.isInitialized=!0,window[De];const Fe=registerAPI({clientId:$e.clientId,environment:$e.environment,...$e.api});return isBrowser()?($e.awaitAllServices?await initOtherServices($e,Fe):initOtherServices($e,Fe),Fe):(exports.isInitialized=!0,Fe)}if(isBrowser()){const $e=document.getElementById("sesamy-js");if($e!=null&&$e.textContent)try{const De=JSON.parse($e.textContent);init(De)}catch(De){console.error("Failed to parse config",De)}}return exports.init=init,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports}({});
47
+ `,document.head.appendChild(Ke)}async function fetchContent($e){try{const De=await fetch($e);return De.ok?await De.text():(console.error(`Failed to fetch content from ${$e}: ${De.statusText}`),null)}catch(De){return console.error(`Error fetching content from ${$e}:`,De),null}}async function getContent($e){if($e.contentType==="selector"&&$e.content){const De=document.querySelector($e.content);if(De)return De.innerHTML;console.warn(`Source element for selector '${$e.content}' not found`)}else if($e.contentType==="url"&&$e.content){const De=await fetchContent($e.content);if(De)return De;console.warn(`Failed to fetch content from URL '${$e.content}'`)}else if($e.content)return $e.content;return""}async function insert($e,De){const Fe=De.insertionPoint||"inside",Be=await getContent(De);switch(Fe){case"before":$e.insertAdjacentHTML("beforebegin",Be);break;case"after":$e.insertAdjacentHTML("afterend",Be);break;case"inside":default:$e.innerHTML+=Be;break}}async function replace($e,De){const Fe=await getContent(De);$e.innerHTML=Fe}async function wrap($e,De){const Fe=await getContent(De);$e.innerHTML=Fe.replace("${content}",$e.innerHTML)}async function init$1({enabled:$e=!1,rules:De}){$e&&onDOMContentLoaded(async()=>{const Fe=await isAuthenticated(),Be=window.location.href;for(const He of De){const Ke=document.querySelectorAll(He.selector);if(!(He.path&&!new RegExp(He.path).test(Be)))for(const Ge of Ke){const We=Ge;if(!(He.authenticated!==void 0&&He.authenticated!==Fe))switch(He.transform){case"insert":await insert(We,He);break;case"replace":await replace(We,He);break;case"remove":Ge.remove();break;case"wrap":await wrap(We,He);break;case"gradient":gradient(We,He);break;default:console.warn(`Unknown transform type: ${He.transform}`)}}}})}const ACCESS_TOKEN="access_token";function handleTokenFromQuerystring(){const $e=new URLSearchParams(window.location.hash.substring(1)),De=$e.get(ACCESS_TOKEN);if(De){setToken(De);const Fe=new URL(window.location.href);$e.delete(ACCESS_TOKEN),Fe.hash=$e.toString(),window.history.replaceState(null,"",Fe)}}const REFRESH_KEY="sesamy-refresh",DEPRECATED_REFRESH_KEY="force-refetch-entitlements";function handleForceRefreshFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(DEPRECATED_REFRESH_KEY),Fe=$e.get(REFRESH_KEY);if(De!==null||Fe!==null){const Be=new URL(window.location.href);$e.delete(DEPRECATED_REFRESH_KEY),$e.delete(REFRESH_KEY),Be.search=$e.toString(),clearCache(),window.history.replaceState(null,"",Be)}}function extractJwt($e){const De=$e.split(".")[1],Fe=atob(De);return JSON.parse(Fe)}function handleSignedLinksFromQuerystring(){var Be,He,Ke,Ge;const $e=new URLSearchParams(window.location.search),De=$e.get("sesamy-token")||$e.get("token");if(!De)return;try{const We=extractJwt(De),Ze=new Date(We.exp*1e3),Xe={id:"",title:(Be=We.p)==null?void 0:Be.toString(),sku:(He=We.s)==null?void 0:He.toString(),purchaseOptionsId:(Ke=We.pid)==null?void 0:Ke.toString(),url:(Ge=We.url)==null?void 0:Ge.toString(),token:De,type:"article",expiresAt:Ze.toISOString(),createdAt:new Date(We.iat).toISOString(),updatedAt:new Date(We.iat).toISOString()};addSignedLink(Xe)}catch(We){log(`Failed to extract signed link ${We}`)}const Fe=new URL(window.location.href);Fe.searchParams.delete("ss"),Fe.searchParams.delete("se"),Fe.searchParams.delete("sp"),Fe.searchParams.delete("so"),Fe.searchParams.delete("token"),Fe.searchParams.delete("sesamy-token"),window.history.replaceState(null,"",Fe)}const SESAMY_USER="sesamy-user";async function handleUserFromQuerystring(){var He;const De=(He=new URLSearchParams(window.location.search).get(SESAMY_USER))==null?void 0:He.toLowerCase();if(!De)return;const Fe=await getUser();(Fe==null?void 0:Fe.email)!==De?(log(`Current user does not match sesamy user: ${Fe==null?void 0:Fe.email} !== ${De}`),clearCache(),loginWithRedirect({authorizationParams:{login_hint:De}})):log(`Current user matches sesamy user: ${Fe==null?void 0:Fe.email} === ${De}`);const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_USER),window.history.replaceState(null,"",Be)}const PURCHASE_KEY="sesamy-purchase";function handlePurchaseFromQuerystring(){const $e=new URLSearchParams(window.location.search),De=$e.get(PURCHASE_KEY);if(De!==null){const Fe=new URL(window.location.href);$e.delete(PURCHASE_KEY),Fe.search=$e.toString(),log(`Purchase ${De}`),triggerEvent(Events.PURCHASE,{itemSrc:De}),clearCache(),window.history.replaceState(null,"",Fe)}}const SESAMY_LOGIN="sesamy-login",SESAMY_LOGIN_LEGACY="sesamy_login";async function handleLoginFromQuerystring(){const $e=new URLSearchParams(window.location.search);if(!($e.get(SESAMY_LOGIN)||$e.get(SESAMY_LOGIN_LEGACY)))return;await isAuthenticated()||loginWithRedirect();const Be=new URL(window.location.href);Be.searchParams.delete(SESAMY_LOGIN),window.history.replaceState(null,"",Be)}const SESAMY_DEBUG="sesamy-debug";async function handleDebugFromQuerystring(){var Be;const De=(Be=new URLSearchParams(window.location.search).get(SESAMY_DEBUG))==null?void 0:Be.toLowerCase();if(!De)return;setDebug(De==="true");const Fe=new URL(window.location.href);Fe.searchParams.delete(SESAMY_DEBUG),window.history.replaceState(null,"",Fe)}function getReferrer(){if(!document.referrer.length)return;const $e=new URL(document.referrer);if(!($e.hostname===window.location.hostname||$e.hostname.includes("sesamy")))return document.referrer}async function handleAttribution($e){if(!isBrowser())return;const De=new URLSearchParams(window.location.search),Fe={utmSource:De.get("utm_source")??void 0,utmMedium:De.get("utm_medium")??void 0,utmCampaign:De.get("utm_campaign")??void 0,utmTerm:De.get("utm_term")??void 0,utmContent:De.get("utm_content")??void 0,ref:De.get("ref")??void 0,referrer:getReferrer()},[Be]=$e.content.list();Be!=null&&Be.url&&(Fe.itemSrc=Be.url,Fe.publisherContentId=Be.id),setAttribution(Fe)}function handleLoginReload(){sessionStorage.getItem(SESMAY_CONTENT_RELOAD_KEY)==="true"&&(sessionStorage.removeItem(SESMAY_CONTENT_RELOAD_KEY),window.location.search.includes("code=")||(log("Reloading page to get query params in incognito browser"),window.location.reload()))}async function handleLinks($e){const De=He=>Ke=>{Ke.preventDefault();try{He()}catch(Ge){console.error("Error handling click:",Ge)}},Fe=(He,Ke)=>{try{document.querySelectorAll(He).forEach(We=>{We.addEventListener("click",De(Ke))})}catch(Ge){console.error(`Error attaching event handlers (selector: ${He}):`,Ge)}};Fe('[sesamy-link="login"]',()=>$e.auth.loginWithRedirect()),Fe('[sesamy-link="logout"]',()=>$e.auth.logout());const Be=await $e.generateLink({target:"account"});Be&&Fe('[sesamy-link="account"]',()=>{window.location.href=Be})}async function handleVisibility($e){const De=await $e.auth.isAuthenticated();try{document.querySelectorAll(`[sesamy-visibility="${De?"not-logged-in":"logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="none")}),document.querySelectorAll(`[sesamy-visibility="${De?"logged-in":"not-logged-in"}"]`).forEach(He=>{He instanceof HTMLElement&&(He.style.display="")})}catch(Fe){console.error("Error handling visibility:",Fe)}}async function handleLockedContentRedirectUrl($e){var He;const De=getMetaTag("sesamy:locked-content-redirect-url");if(!De)return;const[Fe]=$e.content.list();if(!Fe)return;await $e.entitlements.hasAccess(Fe.url||"",((He=Fe.pass)==null?void 0:He.split(","))||[])||(location.href=De)}exports.isInitialized=!1;async function initOtherServices($e,De){log(`Init with config: ${JSON.stringify($e)}`);try{handleLoginReload(),initAnalytics({clientId:$e.clientId,environment:$e.environment,...$e.analytics}),await init$3({clientId:$e.clientId,organization:$e.organization,environment:$e.environment,...$e.auth}),init$2($e,De),$e.transform&&await init$1($e.transform),handleDebugFromQuerystring(),handleAttribution(De),handleTokenFromQuerystring(),handleForceRefreshFromQuerystring(),handleSignedLinksFromQuerystring(),await handleLoginFromQuerystring(),await handleUserFromQuerystring(),handlePurchaseFromQuerystring(),await handleVisibility(De),await handleLinks(De),await handleLockedContentRedirectUrl(De),exports.isInitialized=!0,triggerEvent(Events.READY,{})}catch(Fe){log(`Failed to init ${Fe.message}`)}}async function init($e){var Be;log("Initializing Sesamy");const De=((Be=$e.api)==null?void 0:Be.namespace)||"sesamy";if(isBrowser()&&De in window)return log("Sesamy already initialized. This is likely due to a duplicate import"),exports.isInitialized=!0,window[De];const Fe=registerAPI({clientId:$e.clientId,environment:$e.environment,...$e.api});return isBrowser()?($e.awaitAllServices?await initOtherServices($e,Fe):initOtherServices($e,Fe),Fe):(exports.isInitialized=!0,Fe)}if(isBrowser()){const $e=document.getElementById("sesamy-js");if($e!=null&&$e.textContent)try{const De=JSON.parse($e.textContent);init(De)}catch(De){console.error("Failed to parse config",De)}}return exports.init=init,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports}({});
@@ -3432,12 +3432,12 @@ async function init$3($e) {
3432
3432
  if ($e.enabled === !1)
3433
3433
  return;
3434
3434
  organization = $e.organization;
3435
- const Be = {
3436
- domain: await getFlag("newAuth") && $e.domain ? $e.domain : getBaseUrl("token", $e.environment),
3435
+ const Fe = await getFlag("newAuth") && $e.domain ? $e.domain : getBaseUrl("token", $e.environment), Be = {
3436
+ domain: Fe,
3437
3437
  clientId: $e.clientId,
3438
3438
  useCookiesForTransactions: !0
3439
3439
  };
3440
- if (getTopLevelDomain(window.location.href) !== getTopLevelDomain(getBaseUrl("auth", $e.environment)) && (Be.cacheLocation = "localstorage", Be.useRefreshTokens = !0), auth0Client = await oe$1(Be), window.location.search.includes("code=")) {
3440
+ if (getTopLevelDomain(window.location.href) !== getTopLevelDomain(Fe) && (Be.cacheLocation = "localstorage", Be.useRefreshTokens = !0), auth0Client = await oe$1(Be), window.location.search.includes("code=")) {
3441
3441
  log("Code found in URL, handling redirect");
3442
3442
  try {
3443
3443
  const Ge = await auth0Client.handleRedirectCallback();
@@ -3877,8 +3877,8 @@ function removeUndefinedValues($e) {
3877
3877
  }), De;
3878
3878
  }
3879
3879
  const ATTRIBUTION_KEY = "sesamyAttribution";
3880
- function parseFromSessionStorage($e) {
3881
- const De = sessionStorage.getItem($e);
3880
+ function parseFromLocalStorage($e) {
3881
+ const De = localStorage.getItem($e);
3882
3882
  if (!De)
3883
3883
  return null;
3884
3884
  try {
@@ -3891,15 +3891,15 @@ function resetUtmTags($e) {
3891
3891
  return Object.keys($e).find((De) => De.startsWith("utm_")) ? { utmSource: void 0, utmMedium: void 0, utmCampaign: void 0, ...$e } : $e;
3892
3892
  }
3893
3893
  function getAttribution() {
3894
- return parseFromSessionStorage(ATTRIBUTION_KEY) || {};
3894
+ return parseFromLocalStorage(ATTRIBUTION_KEY) || {};
3895
3895
  }
3896
3896
  function setAttribution($e) {
3897
3897
  if ($e === null)
3898
- sessionStorage.removeItem(ATTRIBUTION_KEY);
3898
+ localStorage.removeItem(ATTRIBUTION_KEY);
3899
3899
  else {
3900
3900
  log(`Setting attribution ${JSON.stringify($e)}`);
3901
3901
  const De = getAttribution() ?? {}, Fe = removeUndefinedValues({ ...De, ...resetUtmTags($e) });
3902
- sessionStorage.setItem(ATTRIBUTION_KEY, JSON.stringify({ value: Fe }));
3902
+ localStorage.setItem(ATTRIBUTION_KEY, JSON.stringify({ value: Fe }));
3903
3903
  }
3904
3904
  }
3905
3905
  function createApi($e) {
@@ -4211,7 +4211,7 @@ function createApi($e) {
4211
4211
  listVendors: Bt
4212
4212
  };
4213
4213
  }
4214
- const name = "@sesamy/sesamy-js", version = "1.35.4";
4214
+ const name = "@sesamy/sesamy-js", version = "1.35.6";
4215
4215
  function i$5($e, De, Fe, Be, He) {
4216
4216
  for (De = De.split ? De.split(".") : De, Be = 0; Be < De.length; Be++) $e = $e ? $e[De[Be]] : He;
4217
4217
  return $e === He ? Fe : $e;
@@ -6388,6 +6388,16 @@ async function handleVisibility($e) {
6388
6388
  console.error("Error handling visibility:", Fe);
6389
6389
  }
6390
6390
  }
6391
+ async function handleLockedContentRedirectUrl($e) {
6392
+ var He;
6393
+ const De = getMetaTag("sesamy:locked-content-redirect-url");
6394
+ if (!De)
6395
+ return;
6396
+ const [Fe] = $e.content.list();
6397
+ if (!Fe)
6398
+ return;
6399
+ await $e.entitlements.hasAccess(Fe.url || "", ((He = Fe.pass) == null ? void 0 : He.split(",")) || []) || (location.href = De);
6400
+ }
6391
6401
  let isInitialized = !1;
6392
6402
  async function initOtherServices($e, De) {
6393
6403
  log(`Init with config: ${JSON.stringify($e)}`);
@@ -6403,7 +6413,7 @@ async function initOtherServices($e, De) {
6403
6413
  environment: $e.environment,
6404
6414
  // The default client id can be overridden by the config
6405
6415
  ...$e.auth
6406
- }), init$2($e, De), $e.transform && await init$1($e.transform), handleDebugFromQuerystring(), handleAttribution(De), handleTokenFromQuerystring(), handleForceRefreshFromQuerystring(), handleSignedLinksFromQuerystring(), await handleLoginFromQuerystring(), await handleUserFromQuerystring(), handlePurchaseFromQuerystring(), await handleVisibility(De), await handleLinks(De), isInitialized = !0, triggerEvent(Events.READY, {});
6416
+ }), init$2($e, De), $e.transform && await init$1($e.transform), handleDebugFromQuerystring(), handleAttribution(De), handleTokenFromQuerystring(), handleForceRefreshFromQuerystring(), handleSignedLinksFromQuerystring(), await handleLoginFromQuerystring(), await handleUserFromQuerystring(), handlePurchaseFromQuerystring(), await handleVisibility(De), await handleLinks(De), await handleLockedContentRedirectUrl(De), isInitialized = !0, triggerEvent(Events.READY, {});
6407
6417
  } catch (Fe) {
6408
6418
  log(`Failed to init ${Fe.message}`);
6409
6419
  }
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "registry": "https://registry.npmjs.org/",
7
7
  "tag": "latest"
8
8
  },
9
- "version": "1.35.4",
9
+ "version": "1.35.6",
10
10
  "main": "dist/sesamy-js.cjs",
11
11
  "module": "dist/sesamy-js.mjs",
12
12
  "types": "dist/sesamy-js.d.ts",