!function(){"use strict";function t(t){return t&&t.t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var e,i;function n(){if(i)return e;i=1,e=function(e,i,s){"function"==typeof i&&(s=i,i={}),i||(i={});var o,a,r=i.prefix||"__jp",c=i.name||r+t++,l=i.param||"callback",u=null!=i.timeout?i.timeout:6e4,h=encodeURIComponent,d=document.getElementsByTagName("script")[0]||document.head;function g(){o.parentNode&&o.parentNode.removeChild(o),window[c]=n,a&&clearTimeout(a)}return u&&(a=setTimeout(function(){g(),s&&s(new Error("Timeout"))},u)),window[c]=function(t){g(),s&&s(null,t)},e=(e+=(~e.indexOf("?")?"&":"?")+l+"="+h(c)).replace("?&","?"),(o=document.createElement("script")).src=e,d.parentNode.insertBefore(o,d),function(){window[c]&&g()}};var t=0;function n(){}return e}const s=t(n()),o="Email",a="Push",r="ChromePush",c="Email",l="SMS",u="SafariPush",h="SafariLegacyPush",d="FirefoxPush",g="chrome",p="edge",w="safari",f="firefox",b=[{i:"Opera",o:/(?:opera|opr|opios)/i,l:/(?:opera|opr|opios)[ /](\d+(?:\.\d+)?)/i},{i:"Facebook",o:/FBAN\//i,l:/FBAV\/(\d+(?:\.\d+)?)/i},{i:"Samsung Browser",o:/samsungbrowser/i,l:/samsungbrowser[ /](\d+(?:\.\d+)?)/i},{i:"Yandex Browser",o:/yabrowser/i,l:/yabrowser[ /](\d+(?:\.\d+)?)/i},{i:"Vivaldi",o:/vivaldi/i,l:/vivaldi[ /](\d+(?:\.\d+)?)/i},{i:"UC Browser",o:/ucbrowser/i,l:/ucbrowser[ /](\d+(?:\.\d+)?)/i},{i:"Microsoft Edge",o:/edg/i,l:/edg[ /](\d+(?:\.\d+)?)/i},{i:"Firefox",o:/firefox|iceweasel|fxios/i,l:/(?:firefox|iceweasel|fxios)[ /](\d+(?:\.\d+)?)/i},{i:"Chromium",o:/chromium/i,l:/chromium[ /](\d+(?:\.\d+)?)/i},{i:"Chrome",o:/chrome|crios|crmo/i,l:/(?:chrome|crios|crmo)[ /](\d+(?:\.\d+)?)/i},{i:"Safari",o:/safari|applewebkit/i,l:/version[ /](\d+(?:\.\d+)?)/i}];function m(t){for(const e of b)if(e.o.test(t)){const i=t.match(e.l)?.[1]??"";return{name:e.i,version:i}}return{name:"Unknown",version:""}}const y=t=>!/like android/i.test(t)&&/android/i.test(t),S=t=>t.match(/(iphone|ipod|ipad)/i)?.[1]?.toLowerCase()||"";function v(t=navigator.userAgent){const e=S(t);return/tablet/i.test(t)&&!/tablet pc/i.test(t)||"ipad"===e||y(t)&&!/[^-]mobi/i.test(t)||!/nexus\s*[0-6]\s*/i.test(t)&&/nexus\s*\d+/i.test(t)}function O(t=navigator.userAgent){if(v(t))return!1;const e=S(t);return/[^-]mobi/i.test(t)||"iphone"===e||"ipod"===e||y(t)}const k={Chrome:g,Chromium:g,Firefox:f,"Microsoft Edge":p,Safari:w};function I(){return k[m(navigator.userAgent).name]||"other"}const x=()=>{const t=m(navigator.userAgent).version;if(!t)return-1;const[e,i="0"]=t.split(".");return+`${e}.${i}`};function C(){const t=I(),e=x();return t===f&&e>=72||t===w&&e>=12.1}const _="160509",E=()=>"undefined"!=typeof window,$=()=>E()&&void 0!==window.safari,P=()=>"undefined"!=typeof navigator&&"serviceWorker"in navigator,T="Browser",N=()=>E()&&null!=window.safari?.pushNotification,M="undefined"!=typeof PushSubscriptionOptions&&PushSubscriptionOptions.prototype.hasOwnProperty("applicationServerKey"),A=({action:t,legacy:e=!1}={})=>new URL(e?"https://onesignal.com/api/v1/":"https://api.onesignal.com/"),D=()=>I()===f?d:I()===w&&M&&!N()?u:N()?h:r;function U(){return String(x())}function B(){return navigator.platform}const L="set-alias",R="delete-alias",W="set-property",F="refresh-user",j="login-user",K="create-subscription",z="update-subscription",V="delete-subscription",H="transfer-subscription",q="custom-event",G="external_id",J="onesignal_id";class Y extends Error{status;statusText;constructor(t,e){super("Registration of a Service Worker failed."),this.status=t,this.statusText=e}}class Q extends Error{reason;constructor(t){let e;switch(t){case 1:e="Invalid email";break;case 0:e="Invalid sms";break;case 2:e="Invalid email & sms"}super(e),this.reason=t}}const Z=new Error("Missing app ID"),X=new Error("Retry limit reached"),tt=new Error("Permission blocked"),et=new Error("AppID doesn't match existing apps"),it=new Error("Safari web platform must be enabled"),nt=t=>new Error(`Channel '${t}' already exists`),st=t=>new Error(`"${t}" is empty`),ot=t=>new Error(`"${t}" is malformed`),at=t=>new Error(`"${t}" is the wrong type`);function rt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function ct(t,e){if(e&&e.allowNull&&null===t)return!0;if(e&&e.allowEmpty&&null==t)return!0;try{const i=new URL(t);return!e||!e.requireHttps||"https:"===i.protocol}catch(i){return!1}}function lt(t){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t)}function ut(t){return new Promise(e=>setTimeout(e,t))}function ht(){return Promise.resolve()}function dt(t,e){return null!=t?t:e}function gt(){return location.origin}class pt{static u(){try{const t=window.localStorage.getItem("loglevel");return"trace"===t?.toLowerCase()}catch(t){return!1}}static h(t){try{window.localStorage.setItem("loglevel",t)}catch(e){console.error(e)}}static p(t){return(...e)=>{(this.u()||"error"===t)&&console[t](...e)}}static m=pt.p("debug");static S=pt.p("info");static v=pt.p("warn");static O=pt.p("error")}function wt(t,e,i){return mt("POST",t,e,i)}function ft(t,e,i){return mt("DELETE",t,e,i)}function bt(t,e,i){return mt("PATCH",t,e,i)}function mt(t,e,i,n){if(o=i,!((s=e).startsWith("apps/")||s.startsWith("sync/")?lt(s.split("/")[1]):o&&"string"==typeof o.app_id&<(o.app_id)))return Promise.reject(Z);var s,o;const a=new Headers;if(a.append("Origin",window.location.origin),a.append("SDK-Version",`onesignal/web/${_}`),a.append("Content-Type","application/json;charset=UTF-8"),a.append("Accept","application/vnd.onesignal.v1+json"),n)for(const c of Object.keys(n))a.append(c,n[c]);const r={method:t||"NO_METHOD_SPECIFIED",headers:a,cache:"no-cache"};return i&&(r.body=JSON.stringify(i)),yt(`${A({action:e}).toString()}${e}`,r)}async function yt(t,e,i=5){if(0===i)return Promise.reject(X);try{const i=await fetch(t,e),{status:n,headers:s}=i,o=await i.json(),a=s?.get("Retry-After");return{ok:i.ok,result:o,status:n,retryAfterSeconds:a?parseInt(a):void 0}}catch(n){if(n instanceof Error&&"TypeError"===n.name)return await ut(i>3?1e4*(6-i):3e4),pt.O(`OneSignal: Network timed out while calling ${t}. Retrying...`),yt(t,e,i-1);throw new Error(`Failed to execute HTTP call: ${n}`)}}function St(t){return encodeURIComponent(t).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}async function vt(t,e,i){const{appId:n,subscriptionId:s}=t;if(!lt(n))throw et;const o=s?{"OneSignal-Subscription-Id":s}:void 0;let a={};return o&&(a={...a,...o}),t.jwtHeader&&(a={...a,...t.jwtHeader}),bt(`apps/${n}/users/by/${St(e.label)}/${St(e.id)}`,i,a)}function Ot(t,e){return!!t&&-1!==t.indexOf(e)}function kt(t){return JSON.stringify(t,(t,e)=>"function"==typeof e?"[Function]":e,4)}function It(t){let e="";const i=Object.keys(t);for(const n of i){const i=t[n];e+=`${encodeURIComponent(n)}=${encodeURIComponent(i)}`}return e}async function xt(t){pt.S("Outcome payload:",t);try{await wt("outcomes/measure",t)}catch(e){pt.O("sendOutcome",e)}}async function Ct(t){return await new Promise((e,i)=>{var n;n=`${A().toString()}sync/${t}/web`,s(n,void 0,(t,n)=>{t?i(t):n.success?e(n):i(n)})})}const _t={scope:"/"},Et="OneSignalSDKWorker.js",$t="native",Pt="push",Tt="category",Nt="sms",Mt="email",At="smsAndEmail",Dt={pageViews:1,timeDelay:0},Ut="We'd like to show you notifications for the latest news and updates.",Bt="Allow",Lt="Cancel",Rt="Try Again",Wt="Update your push notification subscription preferences.",Ft="Save Preferences",jt="Cancel",Kt={type:Pt,text:{actionMessage:Ut,acceptButton:Bt,cancelButton:Lt},autoPrompt:!1,delay:Dt},zt="custom";function Vt(t){const e=t.config.staticPrompts,i=e.native?{enabled:e.native.enabled,autoPrompt:e.native.enabled&&!1!==e.native.autoPrompt,pageViews:dt(e.native.pageViews,Dt.pageViews),timeDelay:dt(e.native.timeDelay,Dt.timeDelay)}:{enabled:!1,autoPrompt:!1,pageViews:Dt.pageViews,timeDelay:Dt.timeDelay},{prompts:n}=e.slidedown;return{autoPrompt:i.autoPrompt||Ht(n),native:i,slidedown:{prompts:n},fullscreen:{enabled:e.fullscreen.enabled,actionMessage:e.fullscreen.actionMessage,acceptButton:e.fullscreen.acceptButton,cancelButton:e.fullscreen.cancelButton,title:e.fullscreen.title,message:e.fullscreen.message,caption:e.fullscreen.caption,autoAcceptTitle:e.fullscreen.autoAcceptTitle},customlink:qt(t)}}function Ht(t){if(!t)return!1;for(let e=0;e{if(t.type=dt(t.type,Pt),t.type===Tt&&(t.text={...t.text,positiveUpdateButton:dt(t.text?.positiveUpdateButton,Ft),negativeUpdateButton:dt(t.text?.negativeUpdateButton,jt),updateMessage:dt(t.text?.updateMessage,Wt)}),t.text={...t.text,actionMessage:dt(t.text?.actionMessage,Ut),acceptButton:dt(t.text?.acceptButton,Bt),cancelButton:dt(t.text?.cancelButton,Lt),confirmMessage:dt(t.text?.confirmMessage,"Thank You!")},t.autoPrompt=dt(t.autoPrompt,!0),t.delay={pageViews:dt(t.delay?.pageViews,Dt.pageViews),timeDelay:dt(t.delay?.timeDelay,Dt.timeDelay)},t.categories){const{categories:e}=t;t.categories=structuredClone(e).slice(0,10)}return t}):(o.slidedown={prompts:[]},o.slidedown.prompts=[Kt]),o.native){const t=Object.prototype.hasOwnProperty.call(o.native,"autoPrompt");o.native.autoPrompt=t?!!o.native.enabled&&!!o.native.autoPrompt:!!o.native.enabled,o.native.enabled=!!o.native.enabled,o.native.pageViews=dt(o.native.pageViews,Dt.pageViews),o.native.timeDelay=dt(o.native.timeDelay,Dt.timeDelay)}else o.native={enabled:!1,autoPrompt:!1,pageViews:Dt.pageViews,timeDelay:Dt.timeDelay};return!0===i.autoRegister&&(o.native.enabled=!0,o.native.autoPrompt=!0),o.autoPrompt=o.native.autoPrompt||Ht(o.slidedown.prompts),o}async function Yt(t){return async function(t,e){try{if(!t||!t.appId||!lt(t.appId))throw et;const i=await e(t.appId);!function(t){var e;!!(e=t.promptOptions)&&["acceptButtonText","cancelButtonText","actionMessage"].some(t=>Object.prototype.hasOwnProperty.call(e,t))&&(t.promptOptions=function(t){t.slidedown||(t.slidedown={});const{slidedown:e}=t;return e.acceptButtonText=e.acceptButtonText??t.acceptButtonText??t.acceptButton,e.cancelButtonText=e.cancelButtonText??t.cancelButtonText??t.cancelButton,e.actionMessage=e.actionMessage??t.actionMessage,t}(t.promptOptions)),function(t){return!!t&&["enabled","autoPrompt","pageViews","timeDelay","acceptButton","acceptButtonText","cancelButton","cancelButtonText","actionMessage","customizeTextEnabled","categories"].some(e=>Object.prototype.hasOwnProperty.call(t,e))}(t.promptOptions?.slidedown)&&t.promptOptions?.slidedown&&(t.promptOptions.slidedown=function(t){const e=(o=t,(o?.categories?.tags?.length||0)>0),i=e?Tt:Pt,{categories:n,prompts:s=[]}=t;var o;return{prompts:[...s,{type:i,autoPrompt:t.autoPrompt,text:{actionMessage:t.actionMessage,acceptButton:t.acceptButton??t.acceptButtonText,cancelButton:t.cancelButton??t.cancelButtonText,...e&&{positiveUpdateButton:n?.positiveUpdateButton,negativeUpdateButton:n?.negativeUpdateButton,updateMessage:n?.updateMessage}},delay:{pageViews:t.pageViews,timeDelay:t.timeDelay},categories:n?.tags}]}}(t.promptOptions?.slidedown))}(t);const n=function(t,e){const i=function(t){return t.config.integration?.kind??zt}(e),n=function(t,e,i){switch(Gt(t).configuration){case 0:return i.config.siteInfo.proxyOriginEnabled;case 1:return!!e.subdomainName}}(i,t,e),s=function(t,e,i){switch(Gt(t).configuration){case 0:{const{path:t,serviceWorkerPath:n,serviceWorkerParam:s}=function(t,e){const{serviceWorker:i}=e.config,n=t.serviceWorkerOverrideForTypical;return{path:n?dt(t.path,i.path):i.path,serviceWorkerParam:n?dt(t.serviceWorkerParam,{scope:i.registrationScope}):{scope:i.registrationScope},serviceWorkerPath:n?dt(t.serviceWorkerPath,i.workerName):i.workerName}}(e,i);return{appId:i.app_id,autoRegister:!1,autoResubscribe:i.config.autoResubscribe,path:t,serviceWorkerPath:n,serviceWorkerParam:s,subdomainName:i.config.siteInfo.proxyOrigin,promptOptions:Vt(i),welcomeNotification:{disable:!i.config.welcomeNotification.enable,title:i.config.welcomeNotification.title,message:i.config.welcomeNotification.message,url:i.config.welcomeNotification.url},notifyButton:{enable:i.config.staticPrompts.bell.enabled,displayPredicate:i.config.staticPrompts.bell.hideWhenSubscribed?()=>!OneSignal.User.PushSubscription.optedIn:null,size:i.config.staticPrompts.bell.size,position:i.config.staticPrompts.bell.location,showCredit:!1,offset:{bottom:`${i.config.staticPrompts.bell.offset.bottom}px`,left:`${i.config.staticPrompts.bell.offset.left}px`,right:`${i.config.staticPrompts.bell.offset.right}px`},colors:{"circle.background":i.config.staticPrompts.bell.color.main,"circle.foreground":i.config.staticPrompts.bell.color.accent,"badge.background":"black","badge.foreground":"white","badge.bordercolor":"black","pulse.color":i.config.staticPrompts.bell.color.accent,"dialog.button.background.hovering":i.config.staticPrompts.bell.color.main,"dialog.button.background.active":i.config.staticPrompts.bell.color.main,"dialog.button.background":i.config.staticPrompts.bell.color.main,"dialog.button.foreground":"white"},text:{"tip.state.unsubscribed":i.config.staticPrompts.bell.tooltip.unsubscribed,"tip.state.subscribed":i.config.staticPrompts.bell.tooltip.subscribed,"tip.state.blocked":i.config.staticPrompts.bell.tooltip.blocked,"message.prenotify":i.config.staticPrompts.bell.tooltip.unsubscribed,"message.action.subscribing":i.config.staticPrompts.bell.message.subscribing,"message.action.subscribed":i.config.staticPrompts.bell.message.subscribing,"message.action.resubscribed":i.config.staticPrompts.bell.message.subscribing,"message.action.unsubscribed":i.config.staticPrompts.bell.message.unsubscribing,"dialog.main.title":i.config.staticPrompts.bell.dialog.main.title,"dialog.main.button.subscribe":i.config.staticPrompts.bell.dialog.main.subscribeButton,"dialog.main.button.unsubscribe":i.config.staticPrompts.bell.dialog.main.unsubscribeButton,"dialog.blocked.title":i.config.staticPrompts.bell.dialog.blocked.title,"dialog.blocked.message":i.config.staticPrompts.bell.dialog.blocked.message}},persistNotification:i.config.notificationBehavior?i.config.notificationBehavior.display.persist:void 0,webhooks:{cors:i.config.webhooks.corsEnable,"notification.willDisplay":i.config.webhooks.notificationDisplayedHook,"notification.clicked":i.config.webhooks.notificationClickedHook,"notification.dismissed":i.config.webhooks.notificationDismissedHook},notificationClickHandlerMatch:i.config.notificationBehavior?i.config.notificationBehavior.click.match:void 0,notificationClickHandlerAction:i.config.notificationBehavior?i.config.notificationBehavior.click.action:void 0,outcomes:{direct:i.config.outcomes.direct,indirect:{enabled:i.config.outcomes.indirect.enabled,influencedTimePeriodMin:i.config.outcomes.indirect.notification_attribution.minutes_since_displayed,influencedNotificationsLimit:i.config.outcomes.indirect.notification_attribution.limit},unattributed:i.config.outcomes.unattributed}}}case 1:{const t={...e,promptOptions:Jt(e.promptOptions,i.config.staticPrompts,e),serviceWorkerParam:e.serviceWorkerParam?e.serviceWorkerParam:_t,serviceWorkerPath:e.serviceWorkerPath?e.serviceWorkerPath:Et,path:e.path?e.path:"/",outcomes:{direct:i.config.outcomes.direct,indirect:{enabled:i.config.outcomes.indirect.enabled,influencedTimePeriodMin:i.config.outcomes.indirect.notification_attribution.minutes_since_displayed,influencedNotificationsLimit:i.config.outcomes.indirect.notification_attribution.limit},unattributed:i.config.outcomes.unattributed}};return Object.prototype.hasOwnProperty.call(e,"autoResubscribe")?t.autoResubscribe=!!e.autoResubscribe:Object.prototype.hasOwnProperty.call(e,"autoRegister")?t.autoResubscribe=!!e.autoRegister:t.autoResubscribe=!!i.config.autoResubscribe,t}}}(i,t,e);return{appId:e.app_id,hasUnsupportedSubdomain:n,siteName:e.config.siteInfo.name,origin:e.config.origin,restrictedOriginEnabled:e.features.restrict_origin&&e.features.restrict_origin.enable,safariWebId:e.config.safari_web_id,vapidPublicKey:e.config.vapid_public_key,onesignalVapidPublicKey:e.config.onesignal_vapid_public_key,userConfig:s,enableOnSession:dt(e.features.enable_on_session,false),sessionThreshold:dt(e.features.session_threshold,30),enableSessionDuration:dt(e.features.web_on_focus_enabled,true)}}(t,i);return function(t){const e=!self.isSecureContext;if(t.hasUnsupportedSubdomain||e)throw e?new Error("OneSignalSDK: HTTP sites are no longer supported starting with version 16 (User Model), your public site must start with https://."):new Error('OneSignalSDK: The "My site is not fully HTTPS" option is no longer supported starting with version 16 (User Model) of the OneSignal SDK.')}(n),function(t){if(t.restrictedOriginEnabled&&!function(t){try{return location.origin===new URL(t).origin}catch(e){return!1}}(t.origin))throw new Error(`Can only be used on: ${new URL(t.origin).origin}`)}(n),n}catch(i){if(i instanceof Object&&"code"in i){if(1===i.code)throw et;if(2===i.code)throw new Error("App not configured for web push")}throw i}}(t,Ct)}const Qt=(t,e)=>e.some(e=>t instanceof e);let Zt,Xt;const te=new WeakMap,ee=new WeakMap,ie=new WeakMap;let ne={get(t,e,i){if(t instanceof IDBTransaction){if("done"===e)return te.get(t);if("store"===e)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return ae(t[e])},set:(t,e,i)=>(t[e]=i,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function se(t){ne=t(ne)}function oe(t){return"function"==typeof t?(e=t,(Xt||(Xt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(re(this),t),ae(this.request)}:function(...t){return ae(e.apply(re(this),t))}):(t instanceof IDBTransaction&&function(t){if(te.has(t))return;const e=new Promise((e,i)=>{const n=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{e(),n()},o=()=>{i(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});te.set(t,e)}(t),Qt(t,Zt||(Zt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,ne):t);var e}function ae(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,i)=>{const n=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{e(ae(t.result)),n()},o=()=>{i(t.error),n()};t.addEventListener("success",s),t.addEventListener("error",o)});return ie.set(e,t),e}(t);if(ee.has(t))return ee.get(t);const e=oe(t);return e!==t&&(ee.set(t,e),ie.set(e,t)),e}const re=t=>ie.get(t),ce=["get","getKey","getAll","getAllKeys","count"],le=["put","add","delete","clear"],ue=new Map;function he(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(ue.get(e))return ue.get(e);const i=e.replace(/FromIndex$/,""),n=e!==i,s=le.includes(i);if(!(i in(n?IDBIndex:IDBObjectStore).prototype)||!s&&!ce.includes(i))return;const o=async function(t,...e){const o=this.transaction(t,s?"readwrite":"readonly");let a=o.store;return n&&(a=a.index(e.shift())),(await Promise.all([a[i](...e),s&&o.done]))[0]};return ue.set(e,o),o}se(t=>({...t,get:(e,i,n)=>he(e,i)||t.get(e,i,n),has:(e,i)=>!!he(e,i)||t.has(e,i)}));const de=["continue","continuePrimaryKey","advance"],ge={},pe=new WeakMap,we=new WeakMap,fe={get(t,e){if(!de.includes(e))return t[e];let i=ge[e];return i||(i=ge[e]=function(...t){pe.set(this,we.get(this)[e](...t))}),i}};async function*be(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;const i=new Proxy(e,fe);for(we.set(i,e),ie.set(i,re(e));e;)yield i,e=await(pe.get(i)||e.continue()),pe.delete(i)}function me(t,e){return e===Symbol.asyncIterator&&Qt(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===e&&Qt(t,[IDBIndex,IDBObjectStore])}se(t=>({...t,get:(e,i,n)=>me(e,i)?be:t.get(e,i,n),has:(e,i)=>me(e,i)||t.has(e,i)}));let ye=!1;const Se=async(t=7)=>function(t,e,{blocked:i,upgrade:n,blocking:s,terminated:o}={}){const a=indexedDB.open(t,e),r=ae(a);return n&&a.addEventListener("upgradeneeded",t=>{n(ae(a.result),t.oldVersion,t.newVersion,ae(a.transaction),t)}),i&&a.addEventListener("blocked",t=>i(t.oldVersion,t.newVersion,t)),r.then(t=>{o&&t.addEventListener("close",()=>o()),s&&t.addEventListener("versionchange",t=>s(t.oldVersion,t.newVersion,t))}).catch(()=>{}),r}("ONE_SIGNAL_SDK_DB",t,{upgrade(e,i,n,s){const o=n||t;o>=1&&i<1&&(e.createObjectStore("Ids",{keyPath:"type"}),e.createObjectStore("NotificationOpened",{keyPath:"url"}),e.createObjectStore("Options",{keyPath:"key"})),o>=2&&i<2&&(e.createObjectStore("Sessions",{keyPath:"sessionKey"}),e.createObjectStore("NotificationReceived",{keyPath:"notificationId"}),e.createObjectStore("NotificationClicked",{keyPath:"notificationId"})),o>=3&&i<3&&e.createObjectStore("SentUniqueOutcome",{keyPath:"outcomeName"}),o>=4&&i<4&&(e.createObjectStore("identity",{keyPath:"modelId"}),e.createObjectStore("properties",{keyPath:"modelId"}),e.createObjectStore("pushSubscriptions",{keyPath:"modelId"}),e.createObjectStore("smsSubscriptions",{keyPath:"modelId"}),e.createObjectStore("emailSubscriptions",{keyPath:"modelId"})),o>=5&&i<5&&(async function(t,e){const i="NotificationClicked",n="Outcomes.NotificationClicked";t.createObjectStore(n,{keyPath:"notificationId"});let s=await e.objectStore(i).openCursor();for(;s;){const t=s.value;await e.objectStore(n).put({notificationId:t.notificationId||t.notification.id,appId:t.appId,timestamp:t.timestamp}),s=await s.continue()}t.deleteObjectStore(i)}(e,s),async function(t,e){const i="NotificationReceived",n="Outcomes.NotificationReceived";t.createObjectStore(n,{keyPath:"notificationId"});let s=await e.objectStore(i).openCursor();for(;s;)await e.objectStore(n).put(s.value),s=await s.continue();t.deleteObjectStore(i)}(e,s)),o>=6&&i<6&&async function(t,e){const i="subscriptions";let n;t.createObjectStore(i,{keyPath:"modelId"});const s=await e.objectStore("identity").getAll();s.length>0&&(n=s[0].externalId);for(const o of["emailSubscriptions","pushSubscriptions","smsSubscriptions"]){let s=await e.objectStore(o).openCursor();for(;s;)await e.objectStore(i).put({...s.value,modelName:"subscriptions",externalId:n}),s=await s.continue();t.deleteObjectStore(o)}}(e,s),o>=7&&i<7&&e.createObjectStore("operations",{keyPath:"modelId"}),ye=!1,"undefined"!=typeof OneSignal&&(OneSignal.k=!0)},blocked(){pt.m("IndexedDB: Blocked event")},terminated(){ye||(ye=!0,Oe())}});let ve=Se();const Oe=(t=7)=>(ve=Se(t),ve),ke={get:async(t,e)=>(await ve).get(t,e),getAll:async t=>(await ve).getAll(t),put:async(t,e)=>(await ve).put(t,e),delete:async(t,e)=>(await ve).delete(t,e)},Ie=async t=>{const e=await ke.get("Options",t);return e&&"value"in e?e.value:null},xe=async()=>await ke.get("Sessions","oneSignalSession")??null,Ce="os_pageViews",_e="requiresPrivacyConsent";function Ee(){const t=OneSignal.config?.userConfig.requiresUserPrivacyConsent??!1;return"true"===localStorage.getItem(_e)||t}function $e(){return Number(localStorage.getItem(Ce))}const Pe=async()=>{const t={},e=await(async()=>{const t=await ke.get("Ids","appId");return t&&"id"in t?t.id:null})();return t.appId=e,t.vapidPublicKey=await Ie("vapidPublicKey"),t},Te=async()=>{const t=await Ie("defaultUrl"),e=await Ie("defaultTitle"),i=await Ie("isPushEnabled"),n=await Ie("lastOptedIn");return{defaultNotificationUrl:t,defaultNotificationTitle:e,lastKnownPushEnabled:i,lastKnownPushId:await Ie("lastPushId")??void 0,lastKnownPushToken:await Ie("lastPushToken")??void 0,lastKnownOptedIn:n}},Ne=async t=>{t.defaultNotificationUrl&&await ke.put("Options",{key:"defaultUrl",value:t.defaultNotificationUrl}),(t.defaultNotificationTitle||""===t.defaultNotificationTitle)&&await ke.put("Options",{key:"defaultTitle",value:t.defaultNotificationTitle}),null!=t.lastKnownPushEnabled&&await ke.put("Options",{key:"isPushEnabled",value:t.lastKnownPushEnabled}),null!=t.lastKnownPushId&&await ke.put("Options",{key:"lastPushId",value:t.lastKnownPushId}),null!=t.lastKnownPushToken&&await ke.put("Options",{key:"lastPushToken",value:t.lastKnownPushToken}),null!=t.lastKnownOptedIn&&await ke.put("Options",{key:"lastOptedIn",value:t.lastKnownOptedIn})},Me=()=>{const t=Ee(),e=OneSignal.I,i=t&&!e;return i&&pt.v("Consent required but not given"),i};class Ae{deviceId;subscriptionToken;optedOut;createdAt;expirationTime;C(){return{deviceId:this.deviceId,subscriptionToken:this.subscriptionToken,optedOut:this.optedOut,createdAt:this.createdAt,expirationTime:this.expirationTime}}static _(t){const e=new Ae;return e.deviceId=t.deviceId,e.subscriptionToken=t.subscriptionToken,e.optedOut=t.optedOut,e.createdAt=t.createdAt,e.expirationTime=t.expirationTime,e}}const De=async()=>{const t=new Ae;t.deviceId=(await ke.get("Ids","userId"))?.id,t.subscriptionToken=(await ke.get("Ids","registrationId"))?.id;const e=await Ie("optedOut"),i=await Ie("subscription"),n=await Ie("subscriptionCreatedAt"),s=await Ie("subscriptionExpirationTime");return t.optedOut=null!=e?e:null!=i&&!i,t.createdAt=n??null,t.expirationTime=s??null,t},Ue=async t=>{t.deviceId&&await ke.put("Ids",{type:"userId",id:t.deviceId}),void 0!==t.subscriptionToken&&await ke.put("Ids",{type:"registrationId",id:t.subscriptionToken}),null!=t.optedOut&&await ke.put("Options",{key:"optedOut",value:t.optedOut}),null!=t.createdAt&&await ke.put("Options",{key:"subscriptionCreatedAt",value:t.createdAt}),null!=t.expirationTime?await ke.put("Options",{key:"subscriptionExpirationTime",value:t.expirationTime}):await ke.delete("Options","subscriptionExpirationTime")};function Be(t,e,i){let n;if(n="string"==typeof t?document.querySelector(t):t,!n)throw new Error(`${t} must be a CSS selector string or DOM Element object.`);n.insertAdjacentHTML(e,i)}function Le(t){const e=document.querySelectorAll(t);if(e.length>0)for(let i=0;i=i.timestamp)return localStorage.removeItem(t),null;let n=i.value;try{n=JSON.parse(i.value)}catch(s){return n}return n}const He="push",qe="nonPush",Ge="onesignal-notification-prompt",Je="onesignal-non-push-prompt",Ye={[He]:"promptDismissCount",[qe]:"nonPushPromptsDismissCount"},Qe={[He]:Ge,[qe]:Je};async function Ze(t){const e=Ye[t],i=Qe[t];let n=await Ie(e);n||(n=0),n+=1;let s=3;return 2==n?s=7:n>2&&(s=30),pt.m(`(${T} environment) OneSignal: User dismissed the ${t} notification prompt; reprompt after ${s} days.`),await ke.put("Options",{key:e,value:n}),function(t,e,i){if(!ze())return;const n=void 0!==i?60*i*1e3:0,s={value:JSON.stringify("dismissed"),timestamp:void 0!==i?(new Date).getTime()+n:void 0};localStorage.setItem(t,JSON.stringify(s))}(i,0,24*s*60)}function Xe(t){switch(t){case He:return"dismissed"===Ve(Ge);case qe:return"dismissed"===Ve(Je)}return!1}async function ti(){return new Promise(t=>{OneSignal.initialized?t():OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED,t)})}function ei(t,...e){return pt.m(`Called ${t}(${e.map(kt).join(", ")})`)}function ii(t,e,i,n=!1){if(e||pt.O("Cannot call on() with no event: ",e),i||pt.O("Cannot call on() with no task: ",i),"string"==typeof t){const n=document.querySelectorAll(t);if(n.length>0)for(let t=0;t{if(!ci){ci=!0;try{await ui(t)}finally{ci=!1}}},ui=async t=>{const e=await OneSignal.context.P.getPermissionStatus(),i=await Ie("notificationPermission");(e!==i||t)&&(await ke.put("Options",{key:"notificationPermission",value:e}),await ri.trigger(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,e),hi(i,e,t))},hi=(t,e,i)=>{const n="granted"===e;(e!==t||i)&&ri.trigger(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_BOOLEAN,n)};class di{static async showLocalNotification(t,e,i,n,s,o){if(ei("MainHelper:showLocalNotification: ",t,e,i,n,s,o),!(await Pe()).appId)throw Z;if(!OneSignal.Notifications.permission)throw new Error("User is not subscribed");if(!ct(i))throw ot("url");if(!ct(n,{allowEmpty:!0,requireHttps:!0}))throw ot("icon");if(!n){const t=await di.getNotificationIcons();n=si(t)}const a=t=>{const e=[];for(let i=0;i{if(!i)return void pt.O("Service worker registration not available.");const s={body:e,data:r,icon:n,actions:o?a(o):[]};i.showNotification(t,s)})}static async checkAndTriggerNotificationPermissionChanged(){const t=await Ie("notificationPermission"),e=await OneSignal.context.P.getPermissionStatus();t!==e&&(await li(),await ke.put("Options",{key:"notificationPermission",value:e}))}static async getNotificationIcons(){const t=di.getAppId();if(!t)throw Z;const e=`${A().toString()}apps/${t}/icon`,i=await fetch(e),n=await i.json();if(n.errors)throw pt.O(`API call ${e}`,"failed with:",n.errors),new Error("Failed to get notification icons.");return n}static getSlidedownOptions(t){return dt(t.slidedown,{prompts:[]})}static getFullscreenPermissionMessageOptions(t){return t?t.fullscreen?{autoAcceptTitle:t.fullscreen.autoAcceptTitle,actionMessage:t.fullscreen.actionMessage,exampleNotificationTitleDesktop:t.fullscreen.title,exampleNotificationTitleMobile:t.fullscreen.title,exampleNotificationMessageDesktop:t.fullscreen.message,exampleNotificationMessageMobile:t.fullscreen.message,exampleNotificationCaption:t.fullscreen.caption,acceptButton:t.fullscreen.acceptButton,cancelButton:t.fullscreen.cancelButton}:t:null}static getPromptOptionsQueryString(){let t="";if(di.getFullscreenPermissionMessageOptions(OneSignal.config?.userConfig.promptOptions)){const e=di.getPromptOptionsPostHash();for(const i of Object.keys(e))t+="&"+i+"="+e[i]}return t}static getPromptOptionsPostHash(){const t=di.getFullscreenPermissionMessageOptions(OneSignal.config?.userConfig.promptOptions),e={};if(t){const i={exampleNotificationTitleDesktop:"exampleNotificationTitle",exampleNotificationMessageDesktop:"exampleNotificationMessage",exampleNotificationTitleMobile:"exampleNotificationTitle",exampleNotificationMessageMobile:"exampleNotificationMessage"};for(const e of Object.keys(i)){const n=i[e];t[e]&&(t[n]=t[e])}const n=["autoAcceptTitle","siteName","autoAcceptTitle","subscribeText","showGraphic","actionMessage","exampleNotificationTitle","exampleNotificationMessage","exampleNotificationCaption","acceptButton","cancelButton","timeout"];for(let s=0;s{let t;return t="https://onesignal.com",new URL("https://onesignal.com/sdks/web/v16")})();return this.loadIfNew(0,new URL(`${t}/OneSignalSDK.page.styles.css?v=${_}`))}async loadIfNew(t,e){return this.cache[e.toString()]||(this.cache[e.toString()]=gi.load(t,e)),this.cache[e.toString()]}static async load(t,e){try{let i;return await new Promise((n,s)=>{switch(t){case 1:i=document.createElement("script"),i.setAttribute("type","text/javascript"),i.setAttribute("async","async"),i.setAttribute("src",e.toString());break;case 0:i=document.createElement("link"),i.setAttribute("rel","stylesheet"),i.setAttribute("href",e.toString())}i.onerror=s,i.onload=n,document.querySelector("head")?.appendChild(i)}),0}catch(i){return 1}}}class pi{selector;showClass;activeClass;inactiveClass;nestedContentSelector;constructor(t,e,i,n,s){this.selector=t,this.showClass=e,this.activeClass=i,this.inactiveClass=n,this.nestedContentSelector=s}async show(){const t=this.element;return!t||this.shown||(this.showClass&&t.classList.add(this.showClass),await this.waitForAnimations()),this}async hide(){const t=this.element;return t&&this.shown?(this.showClass&&t.classList.remove(this.showClass),await this.waitForAnimations(),this):this}async activate(){const t=this.element;return!t||this.active||(this.inactiveClass&&t.classList.remove(this.inactiveClass),this.activeClass&&t.classList.add(this.activeClass),await this.waitForAnimations()),this}async inactivate(){const t=this.element;return t&&this.active?(this.activeClass&&t.classList.remove(this.activeClass),this.inactiveClass&&t.classList.add(this.inactiveClass),await this.waitForAnimations(),this):this}async waitForAnimations(){const t=this.element;if(!t)return;const e=t.getAnimations();0!==e.length&&await Promise.allSettled(e.map(t=>t.finished))}get content(){const t=this.element;if(!t)return"";if(this.nestedContentSelector){const e=t.querySelector(this.nestedContentSelector);return e?.textContent??""}return t.textContent??""}set content(t){const e=this.element;if(e)if(this.nestedContentSelector){const i=e.querySelector(this.nestedContentSelector);i&&(i.textContent=t)}else e.textContent=t}get element(){return document.querySelector(this.selector)}get shown(){const t=this.element;return t?.classList.contains(this.showClass??"")??!1}get active(){const t=this.element;return this.inactiveClass?!t?.classList.contains(this.inactiveClass):t?.classList.contains(this.activeClass??"")??!1}}class wi extends pi{constructor(){super(".onesignal-bell-launcher-badge","onesignal-bell-launcher-badge-opened","onesignal-bell-launcher-badge-active")}increment(){if(!isNaN(this.content)){let t=+this.content;t+=1,this.content=t.toString()}}show(){const t=super.show();return OneSignal.notifyButton?.setCustomColorsIfSpecified(),t}decrement(){if(!isNaN(this.content)){let t=+this.content;t-=1,this.content=t>0?t.toString():""}}}class fi{static store={};static LIMIT=2;static put(t,e){return void 0===fi.store[t]&&(fi.store[t]=[null,null]),fi.store[t].push(e),fi.store[t].length==fi.LIMIT+1&&fi.store[t].shift(),fi.store[t]}static get(t){return void 0===fi.store[t]&&(fi.store[t]=[null,null]),fi.store[t]}static getFirst(t){return fi.get(t)[0]}static getLast(t){return fi.get(t)[1]}static remove(t){delete fi.store[t]}static isEmpty(t){const e=fi.get(t);return null===e[0]&&null===e[1]}}class bi extends pi{bell;contentType;queued;constructor(t){super(".onesignal-bell-launcher-message","onesignal-bell-launcher-message-opened",void 0,void 0,".onesignal-bell-launcher-message-body"),this.bell=t,this.contentType="",this.queued=[]}static get TIMEOUT(){return 2500}static get TYPES(){return{TIP:"tip",MESSAGE:"message",QUEUED:"queued"}}display(t,e,i=0){return pt.m(`Calling display(${t}, ${e}, ${i}).`),(this.shown?this.hide():ht()).then(()=>{this.content=Ke(e),this.contentType=t}).then(()=>this.show()).then(()=>ut(i)).then(()=>this.hide()).then(()=>{this.content=this.getTipForState(),this.contentType="tip"})}getTipForState(){return this.bell.state===Oi.STATES.UNSUBSCRIBED?this.bell.options.text["tip.state.unsubscribed"]:this.bell.state===Oi.STATES.SUBSCRIBED?this.bell.options.text["tip.state.subscribed"]:this.bell.state===Oi.STATES.BLOCKED?this.bell.options.text["tip.state.blocked"]:""}enqueue(t){return this.queued.push(Ke(t)),new Promise(t=>{this.bell.badge.shown?this.bell.badge.hide().then(()=>this.bell.badge.increment()).then(()=>this.bell.badge.show()).then(t):(this.bell.badge.increment(),this.bell.initialized?this.bell.badge.show().then(t):t())})}dequeue(t){const e=this.queued.pop(t);return new Promise(t=>{this.bell.badge.shown?this.bell.badge.hide().then(()=>this.bell.badge.decrement()).then(t=>t>0?this.bell.badge.show():Promise.resolve(this)).then(t(e)):(this.bell.badge.decrement(),t(e))})}}class mi extends pi{M=!1;events;bell;constructor(t){super(".onesignal-bell-launcher-button",void 0,"onesignal-bell-launcher-button-active"),this.bell=t,this.events={mouse:"bell.launcher.button.mouse"};const e=this.element;e&&(e.addEventListener("touchstart",()=>{this.onHovering(),this.onTap()},{passive:!0}),e.addEventListener("mouseenter",()=>{this.onHovering()}),e.addEventListener("mouseleave",()=>{this.onHovered()}),e.addEventListener("touchmove",()=>{this.onHovered()},{passive:!0}),e.addEventListener("mousedown",()=>{this.onTap()}),e.addEventListener("mouseup",()=>{this.onEndTap()}),e.addEventListener("click",()=>{this.onHovered(),this.onClick()}))}onHovering(){(fi.isEmpty(this.events.mouse)||"out"===fi.getLast(this.events.mouse))&&ri.trigger(Oi.EVENTS.HOVERING),fi.put(this.events.mouse,"over")}onHovered(){fi.put(this.events.mouse,"out"),ri.trigger(Oi.EVENTS.HOVERED)}onTap(){this.pulse(),this.activate(),this.bell.badge.activate()}onEndTap(){this.inactivate(),this.bell.badge.inactivate()}async onClick(){if(!this.M){this.M=!0,ri.trigger(Oi.EVENTS.BELL_CLICK),ri.trigger(Oi.EVENTS.LAUNCHER_CLICK);try{if(this.bell.message.shown&&this.bell.message.contentType==bi.TYPES.MESSAGE)return;const t=fi.getLast("subscription.optedOut");this.bell.unsubscribed&&!t&&(An(),this.bell.A=!0,OneSignal.emitter.once(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,()=>{this.bell.message.display(bi.TYPES.MESSAGE,this.bell.options.text["message.action.subscribed"],bi.TIMEOUT).then(()=>{this.bell.A=!1,this.bell.launcher.inactivate()})})),(this.bell.unsubscribed||this.bell.subscribed||this.bell.blocked)&&(await this.bell.launcher.activateIfInactive(),await this.D()),await this.bell.message.hide()}finally{this.M=!1}}}async D(){this.bell.dialog.shown?(await this.bell.dialog.hide(),await this.bell.launcher.inactivateIfWasInactive()):await this.bell.showDialogProcedure()}pulse(){Le(".pulse-ring"),this.element&&Be(this.element,"beforeend",'
'),this.bell.setCustomColorsIfSpecified()}}const yi=new URL("https://media.onesignal.com/web-sdk");class Si extends pi{bell;subscribeButtonId;unsubscribeButtonId;notificationIcons;constructor(t){super(".onesignal-bell-launcher-dialog","onesignal-bell-launcher-dialog-opened",void 0,void 0,".onesignal-bell-launcher-dialog-body"),this.bell=t,this.subscribeButtonId="#onesignal-bell-container .onesignal-bell-launcher #subscribe-button",this.unsubscribeButtonId="#onesignal-bell-container .onesignal-bell-launcher #unsubscribe-button",this.notificationIcons=null}show(){return this.updateBellLauncherDialogBody().then(()=>super.show())}get subscribeButtonSelectorId(){return"subscribe-button"}get unsubscribeButtonSelectorId(){return"unsubscribe-button"}get subscribeButton(){return this.element?this.element.querySelector("#"+this.subscribeButtonSelectorId):null}get unsubscribeButton(){return this.element?this.element.querySelector("#"+this.unsubscribeButtonSelectorId):null}updateBellLauncherDialogBody(){return OneSignal.context.U.isPushNotificationsEnabled().then(t=>{this.nestedContentSelector&&function(t){if("string"==typeof t){const e=document.querySelector(t);if(null===e)throw new Error(`Cannot find element with selector "${t}"`);for(;e.firstChild;)e.removeChild(e.firstChild)}else{if("object"!=typeof t)throw new Error(`${t} must be a CSS selector string or DOM Element object.`);for(;t.firstChild;)t.removeChild(t.firstChild)}}(this.nestedContentSelector);let e="Nothing to show.",i="";if(this.bell.options.showCredit&&(i='
Powered by OneSignal
'),this.bell.state===Oi.STATES.SUBSCRIBED&&!0===t||this.bell.state===Oi.STATES.UNSUBSCRIBED&&!1===t){let t="";const n=si(this.notificationIcons);t="default-icon"!=n?`
`:'
';let s="";s=this.bell.state!==Oi.STATES.SUBSCRIBED?``:``,e=`

${this.bell.options.text["dialog.main.title"]}

${t}
${s}
${i}`}else if(this.bell.state===Oi.STATES.BLOCKED){let t=null;const n=I();n===g?O()||v()||(t="/bell/chrome-unblock.jpg"):n===f?t="/bell/firefox-unblock.jpg":n===w?t="/bell/safari-unblock.jpg":n===p&&(t="/bell/edge-unblock.png");let s="";t&&(t=yi+t,s=``),(O()||v())&&n===g&&(s="
  1. Access Settings by tapping the three menu dots
  2. Click Site settings under Advanced.
  3. Click Notifications.
  4. Find and click this entry for this website.
  5. Click Notifications and set it to Allow.
"),e=`

${this.bell.options.text["dialog.blocked.title"]}

${this.bell.options.text["dialog.blocked.message"]}

${s}
${i}`}this.nestedContentSelector&&Be(this.nestedContentSelector,"beforeend",e),this.subscribeButton&&this.subscribeButton.addEventListener("click",()=>{OneSignal.B=!1,ri.trigger(Oi.EVENTS.SUBSCRIBE_CLICK)}),this.unsubscribeButton&&this.unsubscribeButton.addEventListener("click",()=>ri.trigger(Oi.EVENTS.UNSUBSCRIBE_CLICK)),this.bell.setCustomColorsIfSpecified()})}}class vi extends pi{bell;wasInactive;constructor(t){super(".onesignal-bell-launcher","onesignal-bell-launcher-active",void 0,"onesignal-bell-launcher-inactive"),this.bell=t,this.wasInactive=!1}async resize(t){if(!this.element)throw new Error("Missing DOM element");if("small"===t&&je(this.element,"onesignal-bell-launcher-sm")||"medium"===t&&je(this.element,"onesignal-bell-launcher-md")||"large"===t&&je(this.element,"onesignal-bell-launcher-lg"))return Promise.resolve(this);if(Fe(this.element,"onesignal-bell-launcher-sm"),Fe(this.element,"onesignal-bell-launcher-md"),Fe(this.element,"onesignal-bell-launcher-lg"),"small"===t)We(this.element,"onesignal-bell-launcher-sm");else if("medium"===t)We(this.element,"onesignal-bell-launcher-md");else{if("large"!==t)throw new Error("Invalid OneSignal bell size "+t);We(this.element,"onesignal-bell-launcher-lg")}if(!this.shown)return this;await this.waitForAnimations()}async activateIfInactive(){return this.active||(this.wasInactive=!0,await this.activate()),this}async inactivateIfWasInactive(){return this.wasInactive&&(this.wasInactive=!1,await this.inactivate()),this}clearIfWasInactive(){this.wasInactive=!1}inactivate(){return this.bell.message.hide().then(()=>this.bell.badge.content.length>0?this.bell.badge.hide().then(()=>Promise.all([super.inactivate(),this.resize("small")])).then(()=>this.bell.badge.show()):Promise.all([super.inactivate(),this.resize("small")]))}activate(){return this.bell.badge.content.length>0?this.bell.badge.hide().then(()=>Promise.all([super.activate(),this.resize(this.bell.options.size)])):Promise.all([super.activate(),this.resize(this.bell.options.size)])}}class Oi{options;state=Oi.STATES.UNINITIALIZED;A=!1;hovering=!1;initialized=!1;L;R;W;F;j;DEFAULT_SIZE="medium";DEFAULT_POSITION="bottom-right";DEFAULT_THEME="default";static get EVENTS(){return{STATE_CHANGED:"notifyButtonStateChange",LAUNCHER_CLICK:"notifyButtonLauncherClick",BELL_CLICK:"notifyButtonButtonClick",SUBSCRIBE_CLICK:"notifyButtonSubscribeClick",UNSUBSCRIBE_CLICK:"notifyButtonUnsubscribeClick",HOVERING:"notifyButtonHovering",HOVERED:"notifyButtonHover"}}static get STATES(){return{UNINITIALIZED:"uninitialized",SUBSCRIBED:"subscribed",UNSUBSCRIBED:"unsubscribed",BLOCKED:"blocked"}}static get TEXT_SUBS(){return{"prompt.native.grant":{default:"Allow",chrome:"Allow",firefox:"Always Receive Notifications",safari:"Allow"}}}constructor(t,e){this.options={enable:t.enable||!1,size:t.size||this.DEFAULT_SIZE,position:t.position||this.DEFAULT_POSITION,theme:t.theme||this.DEFAULT_THEME,showLauncherAfter:t.showLauncherAfter||10,showBadgeAfter:t.showBadgeAfter||300,text:this.setDefaultTextOptions(t.text||{}),prenotify:t.prenotify,showCredit:t.showCredit,colors:t.colors,offset:t.offset},e&&(this.L=e),this.options.enable&&(this.validateOptions(this.options),this.state=Oi.STATES.UNINITIALIZED,this.A=!1,this.installEventHooks(),this.updateState())}showDialogProcedure(){this.dialog.shown||this.dialog.show().then(()=>{ii(document,"click",(t,e)=>{this.dialog.element.contains(t.target)||(e(),this.dialog.shown&&this.dialog.hide().then(()=>{this.launcher.inactivateIfWasInactive()}))},!0)})}validateOptions(t){if(!t.size||!Ot(["small","medium","large"],t.size))throw new Error(`Invalid size ${t.size} for notify button. Choose among 'small', 'medium', or 'large'.`);if(!t.position||!Ot(["bottom-left","bottom-right"],t.position))throw new Error(`Invalid position ${t.position} for notify button. Choose either 'bottom-left', or 'bottom-right'.`);if(!t.theme||!Ot(["default","inverse"],t.theme))throw new Error(`Invalid theme ${t.theme} for notify button. Choose either 'default', or 'inverse'.`);if(!t.showLauncherAfter||t.showLauncherAfter<0)throw new Error(`Invalid delay duration of ${this.options.showLauncherAfter} for showing the notify button. Choose a value above 0.`);if(!t.showBadgeAfter||t.showBadgeAfter<0)throw new Error(`Invalid delay duration of ${this.options.showBadgeAfter} for showing the notify button's badge. Choose a value above 0.`)}setDefaultTextOptions(t){return{"tip.state.unsubscribed":t["tip.state.unsubscribed"]||"Subscribe to notifications","tip.state.subscribed":t["tip.state.subscribed"]||"You're subscribed to notifications","tip.state.blocked":t["tip.state.blocked"]||"You've blocked notifications","message.prenotify":t["message.prenotify"]||"Click to subscribe to notifications","message.action.subscribed":t["message.action.subscribed"]||"Thanks for subscribing!","message.action.resubscribed":t["message.action.resubscribed"]||"You're subscribed to notifications","message.action.subscribing":t["message.action.subscribing"]||"Click {{prompt.native.grant}} to receive notifications","message.action.unsubscribed":t["message.action.unsubscribed"]||"You won't receive notifications again","dialog.main.title":t["dialog.main.title"]||"Manage Site Notifications","dialog.main.button.subscribe":t["dialog.main.button.subscribe"]||"SUBSCRIBE","dialog.main.button.unsubscribe":t["dialog.main.button.unsubscribe"]||"UNSUBSCRIBE","dialog.blocked.title":t["dialog.blocked.title"]||"Unblock Notifications","dialog.blocked.message":t["dialog.blocked.message"]||"Follow these instructions to allow notifications:"}}installEventHooks(){OneSignal.emitter.on(Oi.EVENTS.SUBSCRIBE_CLICK,()=>{this.dialog.subscribeButton.disabled=!0,this.A=!0,OneSignal.User.PushSubscription.optIn().then(()=>(this.dialog.subscribeButton.disabled=!1,this.dialog.hide())).then(()=>this.message.display(bi.TYPES.MESSAGE,this.options.text["message.action.resubscribed"],bi.TIMEOUT)).then(()=>(this.A=!1,this.launcher.clearIfWasInactive(),this.launcher.inactivate())).then(()=>this.updateState()).catch(t=>{throw t})}),OneSignal.emitter.on(Oi.EVENTS.UNSUBSCRIBE_CLICK,()=>{this.dialog.unsubscribeButton.disabled=!0,OneSignal.User.PushSubscription.optOut().then(()=>(this.dialog.unsubscribeButton.disabled=!1,this.dialog.hide())).then(()=>(this.launcher.clearIfWasInactive(),this.launcher.activate())).then(()=>this.message.display(bi.TYPES.MESSAGE,this.options.text["message.action.unsubscribed"],bi.TIMEOUT)).then(()=>this.updateState())}),OneSignal.emitter.on(Oi.EVENTS.HOVERING,()=>{this.hovering=!0,this.launcher.activateIfInactive(),this.message.shown||this.dialog.shown?this.hovering=!1:this.message.contentType!==bi.TYPES.MESSAGE?new Promise(t=>{if(this.message.queued.length>0)return this.message.dequeue().then(e=>{this.message.content=e,this.message.contentType=bi.TYPES.QUEUED,t()});this.message.content=Ke(this.message.getTipForState()),this.message.contentType=bi.TYPES.TIP,t()}).then(()=>this.message.show()).then(()=>{this.hovering=!1}).catch(t=>{pt.O(t)}):this.hovering=!1}),OneSignal.emitter.on(Oi.EVENTS.HOVERED,()=>{this.message.contentType!==bi.TYPES.MESSAGE&&this.dialog.hidden&&(this.hovering&&(this.hovering=!1,this.message.waitUntilShown().then(()=>ut(bi.TIMEOUT)).then(()=>this.message.hide()).then(()=>{this.launcher.wasInactive&&this.dialog.hidden&&(this.launcher.inactivate(),this.launcher.wasInactive=!1)})),this.message.shown&&this.message.hide().then(()=>{this.launcher.wasInactive&&this.dialog.hidden&&(this.launcher.inactivate(),this.launcher.wasInactive=!1)}))}),OneSignal.emitter.on(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,async t=>{if(t.current.optedIn&&(this.badge.shown&&this.options.prenotify&&this.badge.hide(),null===this.dialog.notificationIcons)){const t=await di.getNotificationIcons();this.dialog.notificationIcons=t}const e=await OneSignal.context.P.getPermissionStatus();let i;i=t.current.optedIn?Oi.STATES.SUBSCRIBED:"denied"===e?Oi.STATES.BLOCKED:Oi.STATES.UNSUBSCRIBED,this.setState(i,this.A)}),OneSignal.emitter.on(Oi.EVENTS.STATE_CHANGED,t=>{this.launcher.element&&(t.to===Oi.STATES.SUBSCRIBED?this.launcher.inactivate():this.launcher.activate())}),OneSignal.emitter.on(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,()=>{this.updateState()})}addDefaultClasses(){const t=this.container;if("bottom-left"===this.options.position)t&&We(t,"onesignal-bell-container-bottom-left"),We(this.launcher.selector,"onesignal-bell-launcher-bottom-left");else{if("bottom-right"!==this.options.position)throw new Error(`Invalid OneSignal notify button position ${this.options.position}`);t&&We(t,"onesignal-bell-container-bottom-right"),We(this.launcher.selector,"onesignal-bell-launcher-bottom-right")}if("default"===this.options.theme)We(this.launcher.selector,"onesignal-bell-launcher-theme-default");else{if("inverse"!==this.options.theme)throw new Error(`Invalid OneSignal notify button theme ${this.options.theme}`);We(this.launcher.selector,"onesignal-bell-launcher-theme-inverse")}}async create(){if(!this.options.enable)return;if(0!==await OneSignal.context.K.loadSdkStylesheet())return void pt.m("Not showing notify button because styles failed to load.");this.container&&Le("#onesignal-bell-container"),Be("body","beforeend",'
'),this.container&&Be(this.container,"beforeend",'
'),Be(this.launcher.selector,"beforeend",'
'),Be(this.launcher.selector,"beforeend",'
'),Be(this.launcher.selector,"beforeend",'
'),Be(this.message.selector,"beforeend",'
'),Be(this.launcher.selector,"beforeend",'
'),Be(this.dialog.selector,"beforeend",'
'),Be(this.button.selector,"beforeend",'');const t=await OneSignal.context.U.isPushNotificationsEnabled();Xe(He);const e=t?"small":this.options.size||this.DEFAULT_SIZE;await this.launcher.resize(e),this.addDefaultClasses(),this.applyOffsetIfSpecified(),this.setCustomColorsIfSpecified(),this.addBadgeShadow(),pt.S("Showing the notify button."),await(t?this.launcher.inactivate():ht()).then(()=>t&&null===this.dialog.notificationIcons?di.getNotificationIcons().then(t=>{this.dialog.notificationIcons=t}):ht()).then(()=>ut(this.options.showLauncherAfter||0)).then(()=>this.launcher.show()).then(()=>ut(this.options.showBadgeAfter||0)).then(()=>this.options.prenotify&&!t&&OneSignal.k?this.message.enqueue(this.options.text["message.prenotify"]).then(()=>this.badge.show()):ht()).then(()=>this.initialized=!0)}addBadgeShadow(){const t="drop-shadow(0 2px 4px rgba(34,36,38,0.35));",e="drop-shadow(0 2px 4px rgba(34,36,38,0));",i="drop-shadow(0px 2px 2px rgba(34,36,38,.15));";this.graphic.setAttribute("style",`filter: ${t}; -webkit-filter: ${t};`),this.badge.element.setAttribute("style",`filter: ${e}; -webkit-filter: ${e};`),this.dialog.element.setAttribute("style",`filter: ${i}; -webkit-filter: ${i};`)}applyOffsetIfSpecified(){const t=this.options.offset;if(t){const e=this.launcher.element;if(!e)return void pt.O("Could not find bell dom element");e.style.cssText="",t.bottom&&(e.style.cssText+=`bottom: ${t.bottom};`),"bottom-right"===this.options.position?t.right&&(e.style.cssText+=`right: ${t.right};`):"bottom-left"===this.options.position&&t.left&&(e.style.cssText+=`left: ${t.left};`)}}setCustomColorsIfSpecified(){const t=this.dialog.element.querySelector("button.action"),e=this.button.element.querySelector(".pulse-ring");this.graphic.querySelector(".background").style.cssText="";const i=this.graphic.querySelectorAll(".foreground");for(let n=0;n{this.setState(t?Oi.STATES.SUBSCRIBED:Oi.STATES.UNSUBSCRIBED),"denied"===e&&this.setState(Oi.STATES.BLOCKED)}).catch(t=>{pt.O(t)})}setState(t,e=!1){const i=this.state;this.state=t,i===t||e||ri.trigger(Oi.EVENTS.STATE_CHANGED,{from:i,to:t})}get container(){return document.querySelector("#onesignal-bell-container")}get graphic(){return this.button.element.querySelector("svg")}get launcher(){return this.L||(this.L=new vi(this)),this.L}get button(){return this.R||(this.R=new mi(this)),this.R}get badge(){return this.W||(this.W=new wi),this.W}get message(){return this.F||(this.F=new bi(this)),this.F}get dialog(){return this.j||(this.j=new Si(this)),this.j}get subscribed(){return this.state===Oi.STATES.SUBSCRIBED}get unsubscribed(){return this.state===Oi.STATES.UNSUBSCRIBED}get blocked(){return this.state===Oi.STATES.BLOCKED}}const ki="onesignal-button-indicator-holder",Ii="onesignal-slidedown-container",xi="onesignal-slidedown-dialog",Ci="onesignal-reset",_i="onesignal-saving-state-button",Ei="slide-up",$i="slide-down",Pi="close-slidedown",Ti="default-icon",Ni="clearfix",Mi="onesignal-slidedown-allow-button",Ai="slidedown-body",Di="onesignal-button-indicator-holder",Ui="onesignal-slidedown-cancel-button",Bi="onesignal-slidedown-container",Li="onesignal-slidedown-dialog",Ri="slidedown-footer",Wi="onesignal-loading-container",Fi="align-right",ji="slidedown-button",Ki="tagging-container",zi="tagging-container-col",Vi="channel-capture-container",Hi="onesignal-error-input",qi="onesignal-validation-element-hidden",Gi="sms-input-with-validation-element",Ji="email-input-with-validation-element",Yi="iti-onesignal-sms-input",Qi="onesignal-email-input",Zi="onesignal-sms-validation-element",Xi="onesignal-email-validation-element",tn="onesignal-reset",en="state-subscribed",nn="state-unsubscribed",sn={containerSelector:".onesignal-customlink-container"};class on{config;constructor(t){this.config=t}async initialize(){if(!this.config?.enabled)return;if(!(await this.loadSdkStyles()))return;pt.S("OneSignal: initializing customlink");const t=await OneSignal.context.U.isPushNotificationsEnabled();if(this.config?.unsubscribeEnabled||!t)for(let e=0;e{pt.S("CustomLink: subscribe clicked"),await this.handleClick(e)}),e.setAttribute("type","button"),t.appendChild(e)}}else pt.O("CustomLink: required property 'text' is missing in the config")}async loadSdkStyles(){return 0===await OneSignal.context.K.loadSdkStylesheet()||(pt.m("Not initializing custom link button because styles failed to load."),!1)}hideElement(t){We(t,"hide")}hideCustomLinkContainers(){this.customlinkContainerElements.forEach(t=>{this.hideElement(t)})}async handleClick(t){if(!OneSignal.User.PushSubscription.optedIn)return await OneSignal.User.PushSubscription.optIn(),void(this.config?.unsubscribeEnabled||this.hideCustomLinkContainers());await OneSignal.User.PushSubscription.optOut(),await this.setTextFromPushStatus(t)}async setTextFromPushStatus(t){this.config?.text?.subscribe&&(await OneSignal.context.U.isPushNotificationsEnabled()||(t.textContent=this.config.text.subscribe)),this.config?.text?.unsubscribe&&await OneSignal.context.U.isPushNotificationsEnabled()&&(t.textContent=this.config.text.unsubscribe)}setCustomColors(t){this.config?.color&&this.config.color.text&&("button"===this.config?.style&&this.config?.color.button?(t.style.backgroundColor=this.config?.color.button,t.style.color=this.config?.color.text):"link"===this.config?.style&&(t.style.color=this.config?.color.text))}get customlinkContainerElements(){const t=document.querySelectorAll(sn.containerSelector);return Array.prototype.slice.call(t)}}const an="onesignal-pageview-count";let rn=!1;function cn(){try{const t=sessionStorage.getItem(an),e=t?parseInt(t):0;return isNaN(e)?0:e}catch(t){return 0}}function ln(){if(rn)return;const t=cn()+1,e=$e()+1;var i;!function(t){try{sessionStorage.setItem(an,t.toString())}catch(e){}}(t),i=e,localStorage.setItem(Ce,i.toString()),rn=!0,pt.m(`Incremented page view count: newCountSingleTab: ${t},\n newCountAccrossTabs: ${e}.`)}function un(){return 1===cn()}class hn{}const dn={LOCAL_PREFIX:"local-",V(){return`${this.LOCAL_PREFIX}${crypto.randomUUID()}`},H(t){return t?.startsWith(this.LOCAL_PREFIX)??!1}};function gn(t){return void 0!==t?.type&&void 0!==t?.id}class pn extends hn{q;G;J;Y;constructor(t,e,i){super(),t&&e?(this.J=!e.optedOut,this.Y=i,this.G=e.subscriptionToken,OneSignal.Z.getPushSubscriptionModel().then(t=>{gn(t)&&(this.q=t.id)}).catch(t=>{pt.O(t)}),OneSignal.emitter.on(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,async t=>{this.q=t?.current.id,this.G=t?.current.token}),OneSignal.emitter.on(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,async t=>{this.Y=t})):pt.v(`PushSubscriptionNamespace: skipping initialization. One or more required params are falsy: initialize: ${t}, subscription: ${e}`)}get id(){return dn.H(this.q)?void 0:this.q}get token(){return this.G}get optedIn(){return!!this.J&&"granted"===this.Y}async optIn(){ei("optIn"),await ti(),this.J=!0,"granted"===await OneSignal.context.P.getPermissionStatus()?await this.X(!0):await OneSignal.Notifications.requestPermission()}async optOut(){ei("optOut"),await ti(),this.J=!1,await this.X(!1)}addEventListener(t,e){OneSignal.emitter.on(t,e)}removeEventListener(t,e){OneSignal.emitter.off(t,e)}async X(t){await ti();const e=await Pe(),i=await De();if(!e.appId)throw Z;if("boolean"!=typeof t)throw ot("enabled");i.optedOut=!t,await Ue(i),async function(t){fi.put("subscription.optedOut",t)}(i.optedOut).catch(t=>{pt.O(t)}),Pn().catch(t=>{pt.O(t)})}}const wn="NORMAL",fn="NO_PROPAGATE",bn="HYDRATE";class mn{subscribers=[];get hasSubscribers(){return this.subscribers.length>0}subscribe(t){this.subscribers.push(t)}unsubscribe(t){const e=this.subscribers.indexOf(t);-1!==e&&this.subscribers.splice(e,1)}subscribeAll(t){for(const e of t.subscribers)this.subscribe(e)}fire(t){for(const e of this.subscribers)t(e)}async suspendingFire(t){for(const e of this.subscribers)await t(e)}}class yn{modelId;data=new Map;changeNotifier=new mn;constructor(){this.modelId=Math.random().toString(36).substring(2)}initializeFromJson(t){const{modelId:e,modelName:i,...n}=t;this.data.clear(),this.data=new Map(Object.entries(n)),e&&(this.modelId=e)}initializeFromModel(t,e){const i=new Map;e.data.forEach((t,e)=>{i.set(e,t)}),null!==t&&(this.modelId=t),this.data.clear(),this.data=i}setProperty(t,e,i=wn,n=!1){const s=this.data.get(t);(s!==e||n)&&(void 0!==e?this.data.set(t,e):this.data.has(t)&&this.data.delete(t),this.notifyChanged(t,i,s,e))}hasProperty(t){return this.data.has(t)}getProperty(t,e){return this.data.get(t)??e}notifyChanged(t,e,i,n){const s={model:this,property:t,oldValue:i,newValue:n};this.changeNotifier.fire(t=>t.onChanged(s,e))}toJSON(){return Object.fromEntries(this.data.entries())}subscribe(t){return this.changeNotifier.subscribe(t)}unsubscribe(t){this.changeNotifier.unsubscribe(t)}get hasSubscribers(){return this.changeNotifier.hasSubscribers}mergeData(t){for(const[e,i]of Object.entries(t))this.data.set(e,i)}}class Sn extends yn{constructor(){super(),this.sdk=_,this.device_model=B(),this.device_os=U()}get onesignalId(){return this.getProperty("onesignalId")}set onesignalId(t){this.setProperty("onesignalId",t)}get id(){return this.getProperty("id")}set id(t){this.setProperty("id",t)}get enabled(){return this.getProperty("enabled")}set enabled(t){this.setProperty("enabled",t)}get type(){return this.getProperty("type")}set type(t){this.setProperty("type",t)}get token(){return this.getProperty("token")}set token(t){this.setProperty("token",t)}get notification_types(){return this.getProperty("notification_types")}set notification_types(t){this.setProperty("notification_types",t)}get sdk(){return this.getProperty("sdk")}set sdk(t){this.setProperty("sdk",t)}get device_model(){return this.getProperty("device_model")}set device_model(t){this.setProperty("device_model",t)}get device_os(){return this.getProperty("device_os")}set device_os(t){this.setProperty("device_os",t)}get web_auth(){return this.getProperty("web_auth")}set web_auth(t){this.setProperty("web_auth",t)}get web_p256(){return this.getProperty("web_p256")}set web_p256(t){this.setProperty("web_p256",t)}}class vn extends yn{constructor(t,e,i){super(),this.name=t,e&&(this.appId=e),i&&(this.onesignalId=i)}get name(){return this.getProperty("name")}set name(t){this.setProperty("name",t)}get appId(){return this.getProperty("appId")}set appId(t){this.setProperty("appId",t)}get onesignalId(){return this.getProperty("onesignalId")}set onesignalId(t){this.setProperty("onesignalId",t)}get applyToRecordId(){return this.onesignalId}get createComparisonKey(){return""}get groupComparisonType(){return 1}get canStartExecute(){return!dn.H(this.onesignalId)}translateIds(t){t[this.onesignalId]&&(this.onesignalId=t[this.onesignalId])}toString(){return JSON.stringify(this.toJSON())}}class On extends vn{constructor(t,e,i,n){super(j,t,e),i&&(this.externalId=i),n&&(this.existingOnesignalId=n)}get externalId(){return this.getProperty("externalId")}set externalId(t){this.setProperty("externalId",t)}get existingOnesignalId(){return this.getProperty("existingOnesignalId")}set existingOnesignalId(t){this.setProperty("existingOnesignalId",t)}get createComparisonKey(){return`${this.appId}.User.${this.onesignalId}`}get modifyComparisonKey(){return""}get groupComparisonType(){return 0}get canStartExecute(){return!this.existingOnesignalId||!dn.H(this.existingOnesignalId)}get applyToRecordId(){return this.existingOnesignalId??this.onesignalId}translateIds(t){this.existingOnesignalId&&t[this.existingOnesignalId]&&(this.existingOnesignalId=t[this.existingOnesignalId])}}class kn{static singletonInstance;static createOrGetInstance(){if(!kn.singletonInstance){kn.singletonInstance=new kn;const t=OneSignal.Z.tt(),e=OneSignal.Z.et(),i=t.onesignalId??dn.V();t.onesignalId||t.setProperty(J,i,fn),e.onesignalId||e.setProperty("onesignalId",i,fn)}return kn.singletonInstance}get onesignalId(){const t=OneSignal.Z.tt().onesignalId;return dn.H(t)?void 0:t}validateStringLabel(t,e){if("string"!=typeof t)throw at(e);if(!t)throw st(e)}validateArray(t,e){if(!Array.isArray(t))throw at(e);if(0===t.length)throw st(e);for(const i of t)this.validateLabel(i,"label")}validateObject(t,e){if(!rt(t))throw at(e);if(!t||0===Object.keys(t).length)throw st(e)}validateLabel(t,e){if(this.validateStringLabel(t,e),"external_id"===t||"onesignal_id"===t)throw new Error(`"${t}" is reserved`)}updateIdentityModel(t){const e=OneSignal.Z.tt();Object.keys(t).forEach(i=>{e.setProperty(i,t[i])})}addAlias(t,e){ei("addAlias",{label:t,id:e}),Me()||(this.validateStringLabel(t,"label"),this.validateStringLabel(e,"id"),this.addAliases({[t]:e}))}addAliases(t){if(ei("addAliases",{aliases:t}),!Me()){this.validateObject(t,"aliases");for(const e of Object.keys(t))this.validateStringLabel(t[e],`key: ${e}`),this.validateLabel(e,`key: ${e}`);this.updateIdentityModel(t)}}removeAlias(t){ei("removeAlias",{label:t}),Me()||this.removeAliases([t])}removeAliases(t){if(ei("removeAliases",{aliases:t}),Me())return;this.validateArray(t,"aliases");const e=Object.fromEntries(t.map(t=>[t,void 0]));this.updateIdentityModel(e)}addEmail(t){if(ei("addEmail",{email:t}),!Me()){if(this.validateStringLabel(t,"email"),!function(t){return!!t&&!!t.match(/^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/)}(t))throw ot("email");xn({type:c,token:t})}}addSms(t){ei("addSms",{sms:t}),Me()||(this.validateStringLabel(t,"sms"),xn({type:l,token:t}))}removeEmail(t){ei("removeEmail",{email:t}),Me()||(this.validateStringLabel(t,"email"),OneSignal.Z.getEmailSubscriptionModels().forEach(e=>{e.token===t&&OneSignal.Z.removeSubscriptionModel(e.modelId)}))}removeSms(t){ei("removeSms",{smsNumber:t}),Me()||(this.validateStringLabel(t,"smsNumber"),OneSignal.Z.getSmsSubscriptionModels().forEach(e=>{e.token===t&&OneSignal.Z.removeSubscriptionModel(e.modelId)}))}addTag(t,e){ei("addTag",{key:t,value:e}),Me()||(this.validateStringLabel(t,"key"),this.validateStringLabel(e,"value"),this.addTags({[t]:e}))}addTags(t){if(Me())return;const e=OneSignal.Z.et(),i={...e.tags,...t};e.tags=i}removeTag(t){ei("removeTag",{tagKey:t}),Me()||(this.validateStringLabel(t,"tagKey"),this.removeTags([t]))}removeTags(t){if(ei("removeTags",{tagKeys:t}),Me())return;this.validateArray(t,"tagKeys");const e=OneSignal.Z.et(),i={...e.tags};t.forEach(t=>{i[t]=""}),e.tags=i}getTags(){return ei("getTags"),OneSignal.Z.et().tags}setLanguage(t){ei("setLanguage",{language:t}),Me()||(this.validateStringLabel(t,"language"),OneSignal.Z.et().language=t)}getLanguage(){return ei("getLanguage"),OneSignal.Z.et().language}trackEvent(t,e={}){if(Me())return;const i=OneSignal.Z.tt().onesignalId;!dn.H(i)||In(i)?function(t){if(!rt(t))return!1;try{return JSON.stringify(t),!0}catch(e){return!1}}(e)?(ei("trackEvent",{name:t,properties:e}),OneSignal.Z.customEventController.sendCustomEvent({name:t,properties:e})):pt.O("Properties must be JSON-serializable"):pt.O("User must be logged in first.")}}function In(t){return OneSignal.Z.operationRepo.queue.find(e=>e.operation instanceof On&&e.operation.onesignalId===t)}function xn({type:t,token:e}){if(OneSignal.Z.subscriptionModelStore.list().find(i=>i.token===e&&i.type===t))return;const i=OneSignal.Z.tt(),n=i.onesignalId;if(dn.H(n)){const t=di.getAppId();In(n)||OneSignal.Z.operationRepo.enqueue(new On(t,n,i.externalId))}const s={id:dn.V(),enabled:!0,notification_types:1,onesignalId:n,token:e,type:t},o=new Sn;o.mergeData(s),OneSignal.Z.addSubscriptionModel(o)}class Cn extends hn{it;PushSubscription=new pn(!1);static nt=new oi;constructor(t,e,i){super(),t&&(this.it=kn.createOrGetInstance(),this.PushSubscription=new pn(!0,e,i))}get onesignalId(){return this.it?.onesignalId}get externalId(){const t=OneSignal.Z.tt();return t?.externalId}addAlias(t,e){this.it?.addAlias(t,e)}addAliases(t){this.it?.addAliases(t)}removeAlias(t){this.it?.removeAlias(t)}removeAliases(t){this.it?.removeAliases(t)}addEmail(t){this.it?.addEmail(t)}removeEmail(t){this.it?.removeEmail(t)}addSms(t){this.it?.addSms(t)}removeSms(t){this.it?.removeSms(t)}addTag(t,e){this.it?.addTag(t,e)}addTags(t){this.it?.addTags(t)}removeTag(t){this.it?.removeTag(t)}removeTags(t){this.it?.removeTags(t)}getTags(){return this.it?.getTags()||{}}setLanguage(t){this.it?.setLanguage(t)}getLanguage(){return this.it?.getLanguage()||""}trackEvent(t,e){return this.it?.trackEvent(t,e)}addEventListener(t,e){Cn.nt.on(t,e)}removeEventListener(t,e){Cn.nt.off(t,e)}}class _n{previousOneSignalId;previousExternalId}function En(t,e){return t?t.filter(t=>t.type===e)[0]:void 0}function $n(t){return t===Pt||t===Tt}async function Pn(){ei("checkAndTriggerSubscriptionChanged");const t=OneSignal.context,e=await OneSignal.context.U.isPushNotificationsEnabled(),i=await OneSignal.context.U.isOptedIn(),n=await Te(),{lastKnownPushEnabled:s,lastKnownPushId:o,lastKnownPushToken:a,lastKnownOptedIn:r}=n,c=await di.getCurrentPushToken(),l=await OneSignal.Z.getPushSubscriptionModel(),u=l?.id;if(e===s&&c===a&&u===o)return;await t.U.updateNotificationTypes(),n.lastKnownPushEnabled=e,n.lastKnownPushToken=c,n.lastKnownPushId=u,n.lastKnownOptedIn=i,await Ne(n);const h={previous:{id:o,token:a,optedIn:r??!0},current:{id:u,token:c,optedIn:i}};pt.S("Push Subscription state changed: ",h),function(t){ri.trigger(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,t)}(h)}function Tn(t){!async function(t,e){if(OneSignal.B)return void pt.m("Not showing welcome notification because user has previously subscribed.");const i=OneSignal.config?.userConfig.welcomeNotification;if(void 0!==i&&!0===i.disable)return;if(!0!==t)return;if(!e)return;let n=void 0!==i&&void 0!==i.title&&null!==i.title?i.title:"",s=void 0!==i&&void 0!==i.message&&null!==i.message&&i.message.length>0?i.message:"Thanks for subscribing!";const o=new URL(location.href).origin+"?_osp=do_not_open",a=i&&i.url&&i.url.length>0?i.url:o;n=Ke(n),s=Ke(s),pt.m("Sending welcome notification."),di.showLocalNotification(n,s,a,void 0,{st:!0},void 0),ri.trigger(OneSignal.EVENTS.WELCOME_NOTIFICATION_SENT,{title:n,message:s,url:a})}(t?.current?.optedIn,t?.current?.id),async function(t){if(!0!==t)return;const e=OneSignal.context.ot.userConfig.promptOptions?.slidedown?.prompts;(function(t){if(!t)return!1;const e=En(t,Tt);return!!e&&!!e.categories&&e.categories.length>0})(e)&&await OneSignal.context.rt.sendTags()}(t?.current?.optedIn),async function(){if(!OneSignal.config?.userConfig.notifyButton)return;const t=OneSignal.config.userConfig.notifyButton.displayPredicate;t&&"function"==typeof t&&OneSignal.notifyButton&&(!1!==await t()?(pt.m("Showing notify button because display predicate returned true."),OneSignal.notifyButton.launcher.show()):(pt.m("Hiding notify button because display predicate returned false."),OneSignal.notifyButton.launcher.hide()))}(),OneSignal.config?.userConfig.promptOptions&&new on(OneSignal.config?.userConfig.promptOptions.customlink).initialize()}class Nn{static async registerForPush(){return await Nn.internalRegisterForPush()}static async internalRegisterForPush(){const t=OneSignal.context;let e=null;try{const i=await t.U.subscribe(0);e=await t.U.ct(i),ln(),await li(),await Pn()}catch(i){pt.O(i)}return e}static isPushSubscriptionType(t){switch(t){case r:case u:case h:case d:return!0;default:return!1}}static toSubscriptionChannel(t){switch(t){case c:return o;case l:return"SMS";default:return this.isPushSubscriptionType(t)?a:void 0}}}async function Mn(){if(pt.m("Called sessionInit()"),OneSignal.lt)return void pt.m("Returning from sessionInit because it has already been called.");OneSignal.lt=!0;try{await async function(){const t=[];t.push(async function(){const t=await OneSignal.context.U.isPushNotificationsEnabled(),e=await OneSignal.context.P.getPermissionStatus(),i=await OneSignal.context.U.isOptedOut();fi.put("subscription.optedOut",i),await ke.put("Options",{key:"isPushEnabled",value:t}),await ke.put("Options",{key:"notificationPermission",value:e})}()),t.push(async function(){try{navigator.permissions&&((await navigator.permissions.query({name:"notifications"})).onchange=function(){li()})}catch(t){pt.v(`Could not install native notification permission change hook w/ error: ${t}`)}}()),t.push(async function(){"granted"===await OneSignal.context.P.getNotificationPermission(OneSignal.context.ot.safariWebId)&&(OneSignal.B=!0)}()),t.push(async function(){if(navigator.serviceWorker&&window.isSecureContext)try{await OneSignal.context.N.ut()}catch(t){pt.O(t)}}()),t.push(async function(){if(!OneSignal.notifyButton){OneSignal.config.userConfig.notifyButton=OneSignal.config.userConfig.notifyButton||{},OneSignal.config.userConfig.bell&&(OneSignal.config.userConfig.bell={...OneSignal.config.userConfig.bell,...OneSignal.config.userConfig.notifyButton},OneSignal.config.userConfig.notifyButton={...OneSignal.config.userConfig.notifyButton,...OneSignal.config.userConfig.bell});const t=OneSignal.config.userConfig.notifyButton.displayPredicate;t&&"function"==typeof t?OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED,async()=>{!1!==await Promise.resolve(OneSignal.config.userConfig.notifyButton.displayPredicate?.())?(OneSignal.notifyButton=new Oi(OneSignal.config.userConfig.notifyButton),OneSignal.notifyButton.create()):pt.m("Notify button display predicate returned false so not showing the notify button.")}):(OneSignal.notifyButton=new Oi(OneSignal.config.userConfig.notifyButton),OneSignal.notifyButton.create())}}()),t.push(async function(){const t=OneSignal.config;t.userConfig.promptOptions&&await new on(t.userConfig.promptOptions.customlink).initialize()}());try{await Promise.all(t)}catch(e){throw pt.O(e),new Error("Unknown init error")}}()}catch(n){if(n instanceof Error)return;throw n}const t=await OneSignal.context.U.isOptedOut()??!1,e=await De();e.optedOut=t,await Ue(e),await async function(t){pt.S("handleAutoResubscribe",{autoResubscribe:OneSignal.config?.userConfig.autoResubscribe,isOptedOut:t}),OneSignal.config?.userConfig.autoResubscribe&&!t&&"granted"==await OneSignal.context.P.getNotificationPermission(OneSignal.context.ot.safariWebId)&&await Nn.registerForPush()}(t);const i=await OneSignal.context.U.isPushNotificationsEnabled();await ke.put("Options",{key:"isPushEnabled",value:!!i}),OneSignal.config?.userConfig.promptOptions?.autoPrompt&&!t&&OneSignal.context.promptsManager.spawnAutoPrompts(),OneSignal.lt=!1,await ri.trigger(OneSignal.EVENTS.SDK_INITIALIZED)}async function An(){return!!(await Nn.registerForPush())}async function Dn(){const t=await async function(){const t=OneSignal.context;if(pt.m("Checking subscription expiration..."),!(await t.U.isSubscriptionExpiring()))return pt.m("Subscription is not considered expired."),!1;pt.m("Subscription is considered expiring.");const e=await t.U.subscribe(1);return await t.U.ct(e),!0}();await OneSignal.context.U.ht()?(OneSignal.context.dt.setupSessionEventListeners(),t||await OneSignal.context.gt.sendOnSessionUpdate()):OneSignal.config?.userConfig.promptOptions?.autoPrompt||OneSignal.config?.userConfig.autoResubscribe||await OneSignal.context.gt.sendOnSessionUpdate(),await ri.trigger(OneSignal.EVENTS.SDK_INITIALIZED_PUBLIC)}class Un extends yn{get onesignalId(){return this.getProperty(J)}set onesignalId(t){this.setProperty(J,t)}get externalId(){return this.getProperty(G)}set externalId(t){this.setProperty(G,t)}}class Bn{modelName;changeSubscription=new mn;models=[];hasLoadedFromCache=!1;constructor(t){this.modelName=t}add(t,e=wn){const i=this.models.find(e=>e.modelId===t.modelId);i&&this.removeItem(i,e),this.addItem(t,e)}addAt(t,e,i=wn){const n=this.models.find(t=>t.modelId===e.modelId);n&&this.removeItem(n,i),this.addItem(e,i,t)}list(){return this.models}get(t){return this.models.find(e=>e.modelId===t)}remove(t,e=wn){const i=this.models.find(e=>e.modelId===t);i&&this.removeItem(i,e)}onChanged(t,e){this.persist(),this.changeSubscription.fire(i=>i.onModelUpdated(t,e))}replaceAll(t,e=wn){this.clear(e);for(const i of t)this.add(i,e)}clear(t=wn){for(const e of this.models)e.unsubscribe(this),this.changeSubscription.fire(i=>i.onModelRemoved(e,t)),ke.delete(this.modelName,e.modelId);this.models=[]}addItem(t,e,i){void 0!==i?this.models.splice(i,0,t):this.models.push(t),t.subscribe(this),this.persist(),this.changeSubscription.fire(i=>i.onModelAdded(t,e))}async removeItem(t,e){const i=this.models.findIndex(e=>e.modelId===t.modelId);-1!==i&&this.models.splice(i,1),t.unsubscribe(this),await ke.delete(this.modelName,t.modelId),this.persist(),this.changeSubscription.fire(i=>i.onModelRemoved(t,e))}async load(){if(!this.modelName)return;const t=await ke.getAll(this.modelName),e=this.models.length>0;for(let i=t.length-1;i>=0;i--){const e=this.create(t[i]);e&&(this.models.unshift(e),e.subscribe(this))}this.hasLoadedFromCache=!0,e&&this.persist()}async persist(){if(this.modelName&&this.hasLoadedFromCache)for(const t of this.models)await ke.put(this.modelName,{modelId:t.modelId,modelName:this.modelName,...t.toJSON()})}subscribe(t){this.changeSubscription.subscribe(t)}unsubscribe(t){this.changeSubscription.unsubscribe(t)}get hasSubscribers(){return this.changeSubscription.hasSubscribers}}class Ln extends Bn{wt;constructor(t,e){super(e),this.wt=t,this.load()}create(t){const e=this.wt();return null!=t&&e.initializeFromJson(t),e}}class Rn{store;changeSubscription=new mn;constructor(t){this.store=t,t.subscribe(this)}get model(){const t=this.store.list()[0];if(t)return t;const e=this.store.create();if(!e)throw new Error(`Unable to initialize model from store ${this.store}`);return this.store.add(e),e}replace(t,e){const i=this.model;i.initializeFromModel(i.modelId,t),this.store.persist(),this.changeSubscription.fire(t=>t.onModelReplaced(i,e))}subscribe(t){this.changeSubscription.subscribe(t)}unsubscribe(t){this.changeSubscription.unsubscribe(t)}get hasSubscribers(){return this.changeSubscription.hasSubscribers}onModelAdded(){}onModelUpdated(t,e){this.changeSubscription.fire(i=>i.onModelUpdated(t,e))}onModelRemoved(){}}class Wn extends Rn{constructor(){super(new Ln(()=>new Un,"identity"))}}class Fn extends vn{constructor(t){super(q,t?.appId,t?.onesignalId),t?.externalId&&(this.externalId=t.externalId),t?.timestamp&&(this.timestamp=t.timestamp),t?.event&&(this.event=t.event)}get externalId(){return this.getProperty("externalId")}set externalId(t){this.setProperty("externalId",t)}get timestamp(){return this.getProperty("timestamp")}set timestamp(t){this.setProperty("timestamp",t)}get event(){return this.getProperty("event")}set event(t){this.setProperty("event",t)}get key(){return`${this.appId}.User.${this.onesignalId}.CustomEvent.${this.event.name}`}get createComparisonKey(){return this.key}get modifyComparisonKey(){return this.key}get groupComparisonType(){return 2}get canStartExecute(){return!dn.H(this.onesignalId)}get applyToRecordId(){return this.onesignalId}translateIds(t){t[this.onesignalId]&&(this.onesignalId=t[this.onesignalId])}}class jn{ft;bt;constructor(t,e){this.ft=t,this.bt=e}sendCustomEvent(t){const e=di.getAppId(),i=this.ft.model,n=new Fn({appId:e,onesignalId:i.onesignalId,externalId:i.externalId,timestamp:(new Date).toISOString(),event:t});this.bt.enqueue(n)}}function Kn(t){switch(t){case 400:case 402:return 0;case 401:case 403:return 2;case 404:case 410:return 3;case 409:return 4;default:return 1}}class zn{result;idTranslations;operations;retryAfterSeconds;constructor(t,e,i,n){this.result=t,this.retryAfterSeconds=e,this.operations=i,this.idTranslations=n}}class Vn{get operations(){return[q]}get eventMetadata(){return{sdk:_,device_model:B(),device_os:U(),type:D()}}async execute(t){pt.m(`CustomEventsOperationExecutor(operations: ${JSON.stringify(t)})`);const e=t[0];if(!(e instanceof Fn))throw new Error(`Unrecognized operation! Expected TrackEventOperation, got: ${e.constructor.name}`);const i=await async function(t,e){const{appId:i}=t;return wt(`apps/${i}/custom_events`,{events:[e]},t.jwtHeader)}({appId:e.appId},{name:e.event.name,onesignal_id:e.onesignalId,external_id:e.externalId,timestamp:e.timestamp,payload:{...e.event.properties??{},os_sdk:this.eventMetadata}}),{ok:n,status:s}=i,o=Kn(s);return new zn(n?0:1===o?2:3)}}class Hn{yt=new Map;get St(){return this.yt}vt(t){this.yt.set(t,Date.now())}Ot(t){if(!t)return!0;const e=this.yt.get(t);return!e||Date.now()-e>=500}kt(t){const e=this.yt.get(t);return!!e&&Date.now()-e<=15e3}}class qn extends vn{constructor(t,e,i,n){super(t,e,i),n&&(this.label=n)}get label(){return this.getProperty("label")}set label(t){this.setProperty("label",t)}}class Gn extends qn{constructor(t,e,i){super(R,t,e,i)}get modifyComparisonKey(){return`${this.appId}.User.${this.onesignalId}.Alias.${this.label}`}get groupComparisonType(){return 2}}class Jn extends qn{constructor(t,e,i,n){super(L,t,e,i),n&&(this.value=n)}get value(){return this.getProperty("value")}set value(t){this.setProperty("value",t)}get modifyComparisonKey(){return`${this.appId}.User.${this.onesignalId}.Identity.${this.label}`}}class Yn{ft;It;xt;constructor(t,e,i){this.ft=t,this.It=e,this.xt=i}get operations(){return[L,R]}async execute(t){if(pt.m(`IdentityOperationExecutor(operations: ${JSON.stringify(t)})`),t.filter(t=>!(t instanceof Jn||t instanceof Gn)).length>0)throw new Error(`Unrecognized operation(s)! Attempted operations:\n${JSON.stringify(t)}`);const e=t.some(t=>t instanceof Jn),i=t.some(t=>t instanceof Gn);if(e&&i)throw new Error("Can't process SetAliasOperation and DeleteAliasOperation at the same time.");const n=t[t.length-1],s=n instanceof Jn,o=s?async function(t,e,i){const{appId:n}=t;return bt(`apps/${n}/users/by/${e.label}/${e.id}/identity`,{identity:i},t.jwtHeader)}({appId:n.appId},{label:J,id:n.onesignalId},{[n.label]:n.value}):async function(t,e,i){const{appId:n}=t;return ft(`apps/${n}/users/by/${e.label}/${e.id}/identity/${i}`,t.jwtHeader)}({appId:n.appId},{label:J,id:n.onesignalId},n.label),{ok:a,status:r,retryAfterSeconds:c}=await o;if(a)return this.ft.model.onesignalId===n.onesignalId&&this.ft.model.setProperty(n.label,s?n.value:void 0,bn),new zn(0);switch(Kn(r)){case 1:return new zn(2,c);case 0:return new zn(3);case 4:return s?new zn(5,c):new zn(0);case 2:return new zn(4,c);case 3:if(404===r&&this.xt.kt(n.onesignalId))return new zn(2,c);if(s){const t=await this.It.getRebuildOperationsIfCurrentUser(n.appId,n.onesignalId);return null==t?new zn(3):new zn(2,c,t)}return new zn(0)}}}class Qn extends yn{constructor(){super()}get onesignalId(){return this.getProperty("onesignalId")}set onesignalId(t){this.setProperty("onesignalId",t)}get ip(){return this.getProperty("ip")}set ip(t){this.setProperty("ip",t)}get country(){return this.getProperty("country")}set country(t){this.setProperty("country",t)}get language(){return this.getProperty("language")}set language(t){this.setProperty("language",t)}get timezone_id(){return this.getProperty("timezone_id")}set timezone_id(t){this.setProperty("timezone_id",t)}get tags(){return this.getProperty("tags")??{}}set tags(t){this.setProperty("tags",t)}}class Zn extends Rn{constructor(){super(new Ln(()=>new Qn,"properties"))}}class Xn extends Ln{constructor(){super(()=>new Sn,"subscriptions")}getBySubscriptionId(t){return super.list().find(e=>e.id===t)}replaceAll(t,e){if(e!==bn)return super.replaceAll(t,e);for(const i of t)if(Nn.isPushSubscriptionType(i.type)){const t=this.get(i.modelId);t&&(i.sdk=t.sdk,i.device_os=t.device_os);break}super.replaceAll(t,e)}}class ts extends vn{constructor(t,e,i,n){super(t,e,i),n&&(this.subscriptionId=n)}get subscriptionId(){return this.getProperty("subscriptionId")}set subscriptionId(t){this.setProperty("subscriptionId",t)}get createComparisonKey(){return`${this.appId}.User.${this.onesignalId}`}get modifyComparisonKey(){return`${this.appId}.User.${this.onesignalId}.Subscription.${this.subscriptionId}`}get canStartExecute(){return!dn.H(this.onesignalId)&&!dn.H(this.subscriptionId)}get applyToRecordId(){return this.subscriptionId}translateIds(t){super.translateIds(t),t[this.subscriptionId]&&(this.subscriptionId=t[this.subscriptionId])}}class es extends ts{constructor(t,e,i,n){super(t,e,i),n&&(this.sdk=_,this.device_model=B(),this.device_os=U(),this.enabled=n.enabled,this.notification_types=n.notification_types,this.subscriptionId=n.subscriptionId,this.token=n.token,this.type=n.type,this.web_auth=n.web_auth,this.web_p256=n.web_p256)}get type(){return this.getProperty("type")}set type(t){this.setProperty("type",t)}get token(){return this.getProperty("token")}set token(t){this.setProperty("token",t)}get enabled(){return this.getProperty("enabled")}set enabled(t){this.setProperty("enabled",t)}get notification_types(){return this.getProperty("notification_types")}set notification_types(t){this.setProperty("notification_types",t)}get sdk(){return this.getProperty("sdk")}set sdk(t){this.setProperty("sdk",t)}get device_model(){return this.getProperty("device_model")}set device_model(t){this.setProperty("device_model",t)}get device_os(){return this.getProperty("device_os")}set device_os(t){this.setProperty("device_os",t)}get web_auth(){return this.getProperty("web_auth")}set web_auth(t){this.setProperty("web_auth",t)}get web_p256(){return this.getProperty("web_p256")}set web_p256(t){this.setProperty("web_p256",t)}}class is extends es{constructor(t){super(K,t?.appId,t?.onesignalId,t)}get canStartExecute(){return!dn.H(this.onesignalId)}get applyToRecordId(){return this.onesignalId}translateIds(t){t[this.onesignalId]&&(this.onesignalId=t[this.onesignalId])}}class ns extends ts{constructor(t,e,i){super(V,t,e),i&&(this.subscriptionId=i)}get groupComparisonType(){return 2}}class ss extends vn{constructor(t,e){super(F,t,e)}get createComparisonKey(){return`${this.appId}.User.${this.onesignalId}.Refresh`}get modifyComparisonKey(){return`${this.appId}.User.${this.onesignalId}.Refresh`}get groupComparisonType(){return 0}}class os extends ts{constructor(t,e,i){super(H,t,e),i&&(this.subscriptionId=i)}get groupComparisonType(){return 2}get modifyComparisonKey(){return`${this.appId}.Subscription.${this.subscriptionId}.Transfer`}}class as extends es{constructor(t){super(z,t?.appId,t?.onesignalId,t)}}class rs{Ct;ft;_t;Et;constructor(t,e,i,n){this.Ct=t,this.ft=e,this._t=i,this.Et=n}get operations(){return[j]}async execute(t){pt.m(`LoginUserOperationExecutor(operation: ${JSON.stringify(t)})`);const e=t[0];if(e instanceof On)return this.loginUser(e,t.slice(1));throw new Error(`Unrecognized operation: ${e.name}`)}async loginUser(t,e){if(!t.existingOnesignalId||!t.externalId)return this.createUser(t,e);const i=await this.Ct.execute([new Jn(t.appId,t.existingOnesignalId,G,t.externalId)]);switch(i.result){case 0:{const e=t.existingOnesignalId,i=t.onesignalId;return this.ft.model.onesignalId===i&&this.ft.model.setProperty(J,e,bn),this._t.model.onesignalId===i&&this._t.model.setProperty("onesignalId",e,bn),new zn(1,void 0,void 0,{[t.onesignalId]:e})}case 5:return pt.m(`Handling 409 for externalId: ${t.externalId}`),this.createUser(t,e);case 3:return pt.O(`Recovering from SetAlias failure for externalId: ${t.externalId}`),this.createUser(t,e);default:return new zn(i.result)}}async createUser(t,e){const i={};let n={};const s={timezone_id:Intl.DateTimeFormat().resolvedOptions().timeZone,language:us()};t.externalId&&(i[G]=t.externalId);for(const l of e){if(!(l instanceof is||l instanceof os||l instanceof as||l instanceof ns))throw new Error(`Unrecognized operation: ${l.name}`);n=this.createSubscriptionsFromOperation(l,n)}const o=Object.entries(n),a=await async function(t,e){const{appId:i,subscriptionId:n}=t,s=n?{"OneSignal-Subscription-Id":n}:void 0;let o={};return s&&(o={...o,...s}),t.jwtHeader&&(o={...o,...t.jwtHeader}),e.refresh_device_metadata=!0,wt(`apps/${i}/users`,e,o)}({appId:t.appId},{identity:i,subscriptions:o.map(([,t])=>t),properties:s});if(a.ok){const e=a.result.identity.onesignal_id,n=t.onesignalId,s={[t.onesignalId]:e};this.ft.model.onesignalId===n&&this.ft.model.setProperty(J,e,bn),this._t.model.onesignalId===n&&this._t.model.setProperty("onesignalId",e,bn);const r=a.result.properties;if(r)for(const[t,i]of Object.entries(r))this._t.model.setProperty(t,i,bn);for(let t=0;t{const t=new _n;return t.previousOneSignalId="",t.previousExternalId="",t.previousOneSignalId=await Ie("previousOneSignalId"),t.previousExternalId=await Ie("previousExternalId"),t})(),{previousOneSignalId:e,previousExternalId:i}=t,n=await OneSignal.Z.tt(),s=n?.onesignalId,o=n?.externalId;if(s===e&&o===i)return;t.previousOneSignalId=s,t.previousExternalId=o,await(async t=>{await ke.put("Options",{key:"previousOneSignalId",value:t.previousOneSignalId}),await ke.put("Options",{key:"previousExternalId",value:t.previousExternalId})})(t);const a={current:{onesignalId:s,externalId:o}};pt.S("User state changed: ",a),function(t){ri.trigger(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,t,Cn.nt)}(a)}();const c=Object.keys(i).length>0?[new ss(t.appId,e)]:void 0;return new zn(0,void 0,c,s)}const{status:r,retryAfterSeconds:c}=a;switch(Kn(r)){case 1:return new zn(2,c);case 2:return new zn(4,c);default:return new zn(6)}}createSubscriptionsFromOperation(t,e){switch(!0){case t instanceof is:{const i=t.subscriptionId;return{...e,[i]:{enabled:t.enabled,device_model:t.device_model,device_os:t.device_os,notification_types:t.notification_types,sdk:t.sdk,token:t.token,type:t.type,web_auth:t.web_auth,web_p256:t.web_p256}}}case t instanceof as:{const i=t.subscriptionId;return e[i]?{...e,[i]:{...e[i],enabled:t.enabled,notification_types:t.notification_types,token:t.token}}:e}case t instanceof os:{const i=t.subscriptionId;return{...e,[i]:{...e[i],id:i}}}case t instanceof ns:{const i={...e};return delete i[t.subscriptionId],i}default:return e}}}const cs=["tw","hant"],ls=["cn","hans"],us=()=>{let t=navigator.language;if(t){t=t.toLowerCase();const e=t.split("-");if("zh"==e[0]){for(const t of cs)if(-1!==e.indexOf(t))return"zh-Hant";for(const t of ls)if(-1!==e.indexOf(t))return"zh-Hans";return"zh-Hant"}return e[0].substring(0,2)}return"en"};class hs{ft;_t;Et;It;xt;constructor(t,e,i,n,s){this.ft=t,this._t=e,this.Et=i,this.It=n,this.xt=s}get operations(){return[F]}async execute(t){if(pt.m(`RefreshUserOperationExecutor(operation: ${JSON.stringify(t)})`),t.some(t=>!(t instanceof ss)))throw new Error(`Unrecognized operation(s)! Attempted operations:\n${JSON.stringify(t)}`);const e=t[0];return this.getUser(e)}async getUser(t){const e=await async function(t,e){const{appId:i}=t;return mt("GET",`apps/${i}/users/by/${e.label}/${e.id}`,t.jwtHeader,void 0)}({appId:t.appId},{label:J,id:t.onesignalId}),{ok:i,result:n,retryAfterSeconds:s,status:o}=e;if(i){if(t.onesignalId!==this.ft.model.onesignalId)return new zn(0);const e=new Un;for(const[t,c]of Object.entries(n.identity))e.setProperty(t,c);const i=new Qn;i.onesignalId=t.onesignalId;const{properties:s={},subscriptions:o=[]}=n;Object.entries(s).forEach(([t,e])=>{i.setProperty(t,e)});const a=[];for(const n of o){const e=new Sn;e.id=n.id,e.token=n.token??"",e.notification_types=n.notification_types??1,e.type=n.type,e.enabled=-2!==e.notification_types,e.sdk=n.sdk,e.device_os=n.device_os,e.device_model=n.device_model,e.onesignalId=t.onesignalId,Nn.isPushSubscriptionType(e.type)||a.push(e)}const r=await OneSignal.Z.getPushSubscriptionModel();return r&&(r.onesignalId=t.onesignalId,a.push(r)),this.ft.replace(e,bn),this._t.replace(i,bn),this.Et.replaceAll(a,bn),new zn(0)}switch(Kn(o)){case 1:return new zn(2,s);case 2:return new zn(4,s);case 3:{if(404===o&&this.xt.kt(t.onesignalId))return new zn(2,s);const e=await this.It.getRebuildOperationsIfCurrentUser(t.appId,t.onesignalId);return e?new zn(2,s,e):new zn(3)}default:return new zn(3)}}}class ds{$t;It;xt;constructor(t,e,i){this.$t=t,this.It=e,this.xt=i}get operations(){return[K,z,V,H]}async execute(t){pt.m(`SubscriptionOperationExecutor(operations: ${t})`);const e=t[0];if(e instanceof is)return this.createSubscription(e,t);if(t.some(t=>t instanceof ns)){if(t.length>1)throw new Error(`Only supports one operation! Attempted operations:\n${t}`);return this.deleteSubscription(t[0])}if(e instanceof as)return this.updateSubscription(t);if(e instanceof os){if(t.length>1)throw new Error(`TransferSubscriptionOperation only supports one operation! Attempted operations:\n${t}`);return this.transferSubscription(e)}throw new Error(`Unrecognized operation: ${e}`)}async createSubscription(t,e){if(e.some(t=>t instanceof ns))return new zn(0);const i=e.toReversed().find(t=>t instanceof as),n=i?.enabled??t.enabled,s=i?.token??t.token,o=i?.notification_types??t.notification_types,a={sdk:t.sdk,type:t.type,enabled:n,token:s,notification_types:o},r=await async function(t,e,i){const{appId:n}=t;return wt(`apps/${n}/users/by/${e.label}/${e.id}/subscriptions`,i,t.jwtHeader)}({appId:t.appId},{label:J,id:t.onesignalId},{subscription:a});if(r.ok){const{subscription:e}=r.result,i=this.$t.getBySubscriptionId(t.subscriptionId),n=e?.id;return n&&(i?.setProperty("id",n,bn),i?.setProperty("onesignalId",t.onesignalId,bn)),new zn(0,void 0,n?void 0:[new ss(t.appId,t.onesignalId)],n?{[t.subscriptionId]:n}:void 0)}const{retryAfterSeconds:c,status:l}=r;switch(Kn(l)){case 1:return new zn(2,c);case 2:return new zn(4,c);case 4:case 0:return new zn(3);case 3:{if(404===l&&this.xt.kt(t.onesignalId))return new zn(2,c);const e=await this.It.getRebuildOperationsIfCurrentUser(t.appId,t.onesignalId);return e?new zn(2,c,e):new zn(3)}}}async updateSubscription(t){const e=t[t.length-1],i={type:e.type,enabled:e.enabled,token:e.token,notification_types:e.notification_types,web_auth:e.web_auth,web_p256:e.web_p256},n=await async function(t,e,i){const{appId:n}=t;return bt(`apps/${n}/subscriptions/${e}`,{subscription:i})}({appId:e.appId},e.subscriptionId,i);if(n.ok)return new zn(0);const{retryAfterSeconds:s,status:o}=n;switch(Kn(o)){case 1:return new zn(2,s);case 3:return 404===o&&[e.onesignalId,e.subscriptionId].some(t=>this.xt.kt(t))?new zn(2,s):new zn(3,void 0,[new is({appId:e.appId,enabled:e.enabled,notification_types:e.notification_types,onesignalId:e.onesignalId,subscriptionId:e.subscriptionId,token:e.token,type:e.type})]);default:return new zn(3)}}async transferSubscription(t){const e=await async function(t,e,i){const{appId:n}=t;return bt(`apps/${n}/subscriptions/${e}/owner`,{identity:{...i},retain_previous_owner:!1},t.jwtHeader)}({appId:t.appId},t.subscriptionId,{onesignal_id:t.onesignalId});if(e.ok)return new zn(0);const{retryAfterSeconds:i,status:n}=e;return 1===Kn(n)?new zn(2,i):new zn(3)}async deleteSubscription(t){const e=await async function(t,e){const{appId:i}=t;return ft(`apps/${i}/subscriptions/${e}`)}({appId:t.appId},t.subscriptionId);if(e.ok)return this.$t.remove(t.subscriptionId,bn),new zn(0);const{retryAfterSeconds:i,status:n}=e;switch(Kn(n)){case 3:return[t.onesignalId,t.subscriptionId].some(t=>this.xt.kt(t))?new zn(2,i):new zn(0);case 1:return new zn(2,i);default:return new zn(3)}}}class gs{ip;tags;language;timezone_id;country;constructor(t={}){this.ip=t.ip,this.tags=t.tags,this.language=t.language,this.timezone_id=t.timezone_id,this.country=t.country}get hasAtLeastOnePropertySet(){return Object.values(this).some(t=>void 0!==t)}}class ps extends vn{constructor(t,e,i,n){super(W,t,e),i&&n&&(this.property=i,this.value=n)}get property(){return this.getProperty("property")}set property(t){this.setProperty("property",t)}get value(){return this.getProperty("value")}set value(t){this.setProperty("value",t)}get modifyComparisonKey(){return`${this.appId}.User.${this.onesignalId}`}}class ws{static createPropertiesFromOperation(t,e){if(t instanceof ps){const i=t.property;return Object.keys(e).includes(i)?new gs({...e,[i]:t.value}):new gs({...e})}throw new Error(`Unsupported operation type: ${t.name}`)}}class fs{ft;_t;It;xt;constructor(t,e,i,n){this.ft=t,this._t=e,this.It=i,this.xt=n}get operations(){return[W]}processOperations(t){let e=null,i=null,n=new gs;for(const s of t){if(!(s instanceof ps))throw new Error(`Unrecognized operation: ${s}`);e||(e=s.appId,i=s.onesignalId),n=ws.createPropertiesFromOperation(s,n)}return{appId:e,onesignalId:i,propertiesObject:n,refreshDeviceMetadata:!1}}async execute(t){pt.m(`UpdateUserOperationExecutor(operation: ${t})`);const{appId:e,onesignalId:i,propertiesObject:n,refreshDeviceMetadata:s}=this.processOperations(t);if(!e||!i)return new zn(0);const o=await vt({appId:e},{label:J,id:i},{properties:n,refresh_device_metadata:s}),{ok:a,retryAfterSeconds:r,status:c}=o,l=t=>"tags"===t.property;if(a){if(this.ft.model.onesignalId===i)for(const e of t)if(e instanceof ps){let t=e.value;if(l(e)){t={...e.value};for(const e in t)""===t[e]&&delete t[e]}this._t.model.setProperty(e.property,t,bn)}return new zn(0)}switch(Kn(c)){case 1:return new zn(2,r);case 2:return new zn(4,r);case 3:{if(404===c&&this.xt.kt(i))return new zn(2,r);const t=await this.It.getRebuildOperationsIfCurrentUser(e,i);return t?new zn(2,r,t):new zn(3)}default:return new zn(3)}}}class bs{store;opRepo;constructor(t,e){this.store=t,this.opRepo=e,this.store.subscribe(this)}onModelReplaced(t,e){if(e!==wn)return;const i=this.getReplaceOperation(t);null!=i&&this.opRepo.enqueue(i)}onModelUpdated(t,e){if(e!==wn)return;const i=this.getUpdateOperation(t.model,t.property,t.oldValue,t.newValue);null!=i&&this.opRepo.enqueue(i)}}class ms extends bs{constructor(t,e){super(t,e)}getReplaceOperation(t){return null}getUpdateOperation(t,e,i,n){const s=di.getAppId();return null!=n&&"string"==typeof n?new Jn(s,t.onesignalId,e,n):new Gn(s,t.onesignalId,e)}}class ys{store;opRepo;constructor(t,e){this.store=t,this.opRepo=e,this.store.subscribe(this)}close(){this.store.unsubscribe(this)}onModelAdded(t,e){if(e!==wn)return;const i=this.getAddOperation(t);null!=i&&this.opRepo.enqueue(i)}async onModelUpdated(t,e){if(e!==wn)return;const i=await this.getUpdateOperation(t.model,t.property,t.oldValue,t.newValue);null!=i&&this.opRepo.enqueue(i)}async onModelRemoved(t,e){if(e!==wn)return;const i=await this.getRemoveOperation(t);null!=i&&this.opRepo.enqueue(i)}}class Ss extends bs{constructor(t,e){super(t,e)}getReplaceOperation(t){return null}getUpdateOperation(t,e,i,n){const s=di.getAppId();return new ps(s,t.onesignalId,e,n)}}class vs extends ys{ft;constructor(t,e,i){super(t,e),this.ft=i}getAddOperation(t){const{enabled:e,notification_types:i}=vs.getSubscriptionEnabledAndStatus(t),n=di.getAppId();return new is({appId:n,onesignalId:this.ft.model.onesignalId,subscriptionId:t.id,type:t.type,enabled:e,token:t.token,notification_types:i})}getRemoveOperation(t){const e=di.getAppId();return new ns(e,this.ft.model.onesignalId,t.id)}getUpdateOperation(t){const{enabled:e,notification_types:i}=vs.getSubscriptionEnabledAndStatus(t),n=di.getAppId();return new as({appId:n,onesignalId:this.ft.model.onesignalId,subscriptionId:t.id,type:t.type,enabled:e,token:t.token,notification_types:i,web_auth:t.web_auth,web_p256:t.web_p256})}static getSubscriptionEnabledAndStatus(t){let e,i;return t.enabled&&1===t.notification_types&&t.token?(e=!0,i=1):(e=!1,i=t.enabled?t.notification_types:-2),{enabled:e,notification_types:i}}}class Os extends Bn{constructor(){super("operations")}async loadOperations(){return this.load()}create(t){if(null===t)return pt.O("null jsonObject sent to OperationModelStore.create"),null;if(!this.isValidOperation(t))return null;const e=t.name;let i;switch(e){case L:i=new Jn;break;case R:i=new Gn;break;case K:i=new is;break;case z:i=new as;break;case V:i=new ns;break;case H:i=new os;break;case j:i=new On;break;case F:i=new ss;break;case W:i=new ps;break;case q:i=new Fn;break;default:throw new Error(`Unrecognized operation: ${e}`)}return i.initializeFromJson(t),i}isValidOperation(t){const e=t?.name;if(!e)return pt.O("jsonObject must have 'name' attribute"),!1;const i=new Set([j]);return!(!t.onesignalId&&!i.has(e)&&(pt.O(`${e} jsonObject must have 'onesignalId' attribute`),1))}}class ks{ft;_t;Et;constructor(t,e,i){this.ft=t,this._t=e,this.Et=i}async getRebuildOperationsIfCurrentUser(t,e){const i=new Un;i.initializeFromModel(null,this.ft.model),(new Qn).initializeFromModel(null,this._t.model);for(const o of this.Et.list())(new Sn).initializeFromModel(null,o);if(i.onesignalId!==e)return null;const n=[];n.push(new On(t,e,i.externalId));const s=await OneSignal.Z.getPushSubscriptionModel();return s&&n.push(new is({appId:t,onesignalId:e,subscriptionId:s.id,type:s.type,enabled:s.enabled,token:s.token,notification_types:s.notification_types})),n.push(new ss(t,e)),n}}const Is=t=>{ke.delete("operations",t.modelId)};class xs{operation;bucket;retries;resolver;constructor(t){this.operation=t.operation,this.bucket=t.bucket,this.retries=t.retries??0,this.resolver=t.resolver}toString(){return`bucket:${this.bucket}, retries:${this.retries}, operation:${this.operation}\n`}}class Cs{Pt;queue=[];Tt=void 0;Nt=0;Mt;xt;constructor(t,e,i){this.Mt=e,this.xt=i,this.Pt=new Map;for(const n of t)for(const t of n.operations)this.Pt.set(t,n)}At(){this.queue=[]}get St(){return this.xt.St}get Dt(){return 0===this.Nt?0:this.Nt-1}Ut(t){return this.queue.some(e=>e.operation instanceof t)}async Bt(){await this.Lt(),this.Rt()}Wt(){clearInterval(this.Tt),this.Tt=void 0,pt.m("OperationRepo: Paused")}enqueue(t){pt.m(`OperationRepo.enqueue(operation: ${t})`),this.Ft(new xs({operation:t,bucket:this.Nt}),!0)}async enqueueAndWait(t){pt.m(`OperationRepo.enqueueAndWaitoperation: ${t})`),await new Promise((e,i)=>{this.Ft(new xs({operation:t,bucket:this.Nt,resolver:t=>t?e():i()}),!0)})}Ft(t,e,i){this.queue.some(e=>e.operation.modelId===t.operation.modelId)?pt.m(`OperationRepo: internalEnqueue - operation.modelId: ${t.operation.modelId} already exists in the queue.`):(void 0!==i?this.queue.splice(i,0,t):this.queue.push(t),e&&this.Mt.add(t.operation))}async Rt(){this.Nt++;let t=!1;this.Tt=setInterval(async()=>{if(t)return pt.m("Operations in progress");const e=this.jt(this.Dt);e?(t=!0,await this.Kt(e),t=!1):this.Nt++},500)}async Kt(t){try{const e=t[0],i=this.Pt.get(e.operation.name);if(!i)throw new Error(`Could not find executor for operation ${e.operation.name}`);const n=t.map(t=>t.operation),s=await i.execute(n),o=s.idTranslations;pt.m(`OperationRepo: execute response = ${s.result}`),o&&(t.forEach(t=>t.operation.translateIds(o)),this.queue.forEach(t=>t.operation.translateIds(o)),Object.values(o).forEach(t=>this.xt.vt(t)));let a=0;switch(s.result){case 0:t.forEach(t=>{this.Mt.remove(t.operation.modelId)}),t.forEach(t=>t.resolver?.(!0));break;case 4:case 3:case 5:pt.O(`Operation execution failed without retry: ${n}`),t.forEach(t=>{this.Mt.remove(t.operation.modelId)}),t.forEach(t=>t.resolver?.(!1));break;case 1:this.Mt.remove(e.operation.modelId),e.resolver?.(!0),t.filter(t=>t!==e).reverse().forEach(t=>this.queue.unshift(t));break;case 2:pt.O(`Operation execution failed, retrying: ${n}`),t.toReversed().forEach(t=>{Is(t.operation),t.retries++,t.retries>a&&(a=t.retries),this.queue.unshift(t)});break;case 6:pt.O(`Operation failed, pausing ops:${n}`),this.Wt(),t.forEach(t=>t.resolver?.(!1)),t.toReversed().forEach(t=>{Is(t.operation),this.queue.unshift(t)})}if(s.operations)for(const t of s.operations.toReversed()){const e=new xs({operation:t,bucket:0});this.queue.unshift(e),this.Mt.addAt(0,e.operation)}await this.zt(a,s.retryAfterSeconds),s.idTranslations&&await ut(500)}catch(e){pt.O(`Error attempting to execute operation: ${t}`,e),t.forEach(t=>{this.Mt.remove(t.operation.modelId)}),t.forEach(t=>t.resolver?.(!1))}}async zt(t,e){pt.m(`retryAfterSeconds: ${e}`);const i=1e3*(e||0),n=1e3*t,s=Math.max(n,i);s<1||(pt.O(`Operations being delay for: ${s} ms`),await ut(s))}jt(t){const e=this.queue.findIndex(e=>e.operation.canStartExecute&&this.xt.Ot(e.operation.applyToRecordId)&&e.bucket<=t);if(-1!==e){const t=this.queue[e];return this.queue.splice(e,1),this.Vt(t)}return null}Vt(t){const e=[t];if(2===t.operation.groupComparisonType)return e;const i=0===t.operation.groupComparisonType?t.operation.createComparisonKey:t.operation.modifyComparisonKey,n=[...this.queue];for(const s of n){const n=0===t.operation.groupComparisonType?s.operation.createComparisonKey:s.operation.modifyComparisonKey;if(""===n&&""===i)throw new Error("Both comparison keys cannot be blank!");if(this.xt.Ot(s.operation.applyToRecordId)&&n===i){const t=this.queue.indexOf(s);-1!==t&&(this.queue.splice(t,1),e.push(s))}}return e}async Lt(){await this.Mt.loadOperations();const t=this.Mt.list().toReversed();for(const e of t)this.Ft(new xs({operation:e,bucket:this.Nt}),!1,0)}}class _s{operationModelStore;operationRepo;newRecordsState;subscriptionModelStore;identityModelStore;propertiesModelStore;customEventController;initPromise;rebuildUserService;executors;listeners;constructor(){this.newRecordsState=new Hn,this.operationModelStore=new Os,this.identityModelStore=new Wn,this.propertiesModelStore=new Zn,this.subscriptionModelStore=new Xn,this.rebuildUserService=new ks(this.identityModelStore,this.propertiesModelStore,this.subscriptionModelStore),this.executors=this.initializeExecutors(),this.operationRepo=new Cs(this.executors,this.operationModelStore,this.newRecordsState),this.customEventController=new jn(this.identityModelStore,this.operationRepo),this.listeners=this.initializeListeners(),this.initPromise=this.operationRepo.Bt()}async init(){return ei("CoreModule.init"),this.initPromise}initializeListeners(){return this.operationRepo?[new ms(this.identityModelStore,this.operationRepo),new Ss(this.propertiesModelStore,this.operationRepo),new vs(this.subscriptionModelStore,this.operationRepo,this.identityModelStore)]:[]}initializeExecutors(){const t=new Yn(this.identityModelStore,this.rebuildUserService,this.newRecordsState);return[t,new rs(t,this.identityModelStore,this.propertiesModelStore,this.subscriptionModelStore),new hs(this.identityModelStore,this.propertiesModelStore,this.subscriptionModelStore,this.rebuildUserService,this.newRecordsState),new ds(this.subscriptionModelStore,this.rebuildUserService,this.newRecordsState),new fs(this.identityModelStore,this.propertiesModelStore,this.rebuildUserService,this.newRecordsState),new Vn]}}class Es{w3cEndpoint;w3cP256dh;w3cAuth;safariDeviceToken;static Ht(t){const e=new Es;if(t&&(e.w3cEndpoint=new URL(t.endpoint),t.getKey)){let n=null;try{n=t.getKey("p256dh")}catch(i){}let s=null;try{s=t.getKey("auth")}catch(i){}if(n){const t=btoa(String.fromCharCode(...new Uint8Array(n)));e.w3cP256dh=t}if(s){const t=btoa(String.fromCharCode(...new Uint8Array(s)));e.w3cAuth=t}}return e}qt(t){t&&(this.safariDeviceToken=t)}C(){return{w3cEndpoint:this.w3cEndpoint?this.w3cEndpoint.toString():null,w3cP256dh:this.w3cP256dh,w3cAuth:this.w3cAuth,safariDeviceToken:this.safariDeviceToken}}static _(t){const e=new Es;if(!t)return e;try{e.w3cEndpoint=new URL(t.w3cEndpoint)}catch(i){}return e.w3cP256dh=t.w3cP256dh,e.w3cAuth=t.w3cAuth,e.safariDeviceToken=t.safariDeviceToken,e}}class $s{type;token;enabled;notificationTypes;sdk;deviceModel;deviceOs;webAuth;webp256;constructor(t){this.token=this.Gt(t),this.type=D(),this.enabled=!0,this.notificationTypes=1,this.sdk=_,this.deviceModel=B(),this.deviceOs=U(),this.webAuth=t.w3cAuth,this.webp256=t.w3cP256dh}Gt(t){return t.w3cEndpoint?t.w3cEndpoint.toString():t.safariDeviceToken}C(){return{type:this.type,token:this.token,enabled:this.enabled,notification_types:this.notificationTypes,sdk:this.sdk,device_model:this.deviceModel,device_os:this.deviceOs,web_auth:this.webAuth,web_p256:this.webp256}}}class Ps{core;constructor(t){this.core=t}get operationRepo(){return this.core.operationRepo}get identityModelStore(){return this.core.identityModelStore}get propertiesModelStore(){return this.core.propertiesModelStore}get subscriptionModelStore(){return this.core.subscriptionModelStore}get newRecordsState(){return this.core.newRecordsState}get customEventController(){return this.core.customEventController}generatePushSubscriptionModel(t){ei("CoreModuleDirector.generatePushSubscriptionModel",{rawPushSubscription:t});const e=new Sn;return e.initializeFromJson(new $s(t).C()),e.id=dn.V(),this.core.subscriptionModelStore.add(e,bn),e}addSubscriptionModel(t){this.core.subscriptionModelStore.add(t)}removeSubscriptionModel(t){this.core.subscriptionModelStore.remove(t)}getEmailSubscriptionModels(){return ei("CoreModuleDirector.getEmailSubscriptionModels"),this.core.subscriptionModelStore.list().filter(t=>t.type===c)}async hasEmail(){const t=this.getEmailSubscriptionModels();return Object.keys(t).length>0}getSmsSubscriptionModels(){return ei("CoreModuleDirector.getSmsSubscriptionModels"),this.core.subscriptionModelStore.list().filter(t=>t.type===l)}async hasSms(){const t=this.getSmsSubscriptionModels();return Object.keys(t).length>0}getAllPushSubscriptionModels(){return ei("CoreModuleDirector.getAllPushSubscriptionModels"),this.core.subscriptionModelStore.list().filter(t=>Nn.isPushSubscriptionType(t.type))}async getPushSubscriptionModelByCurrentToken(){ei("CoreModuleDirector.getPushSubscriptionModelByCurrentToken");const t=await di.getCurrentPushToken();if(t)return this.getSubscriptionOfTypeWithToken(a,t)}async getPushSubscriptionModelByLastKnownToken(){ei("CoreModuleDirector.getPushSubscriptionModelByLastKnownToken");const t=await(async()=>await Ie("lastPushToken"))();if(t)return this.getSubscriptionOfTypeWithToken(a,t)}async getPushSubscriptionModel(){return ei("CoreModuleDirector.getPushSubscriptionModel"),await this.getPushSubscriptionModelByCurrentToken()||await this.getPushSubscriptionModelByLastKnownToken()}tt(){return ei("CoreModuleDirector.getIdentityModel"),this.core.identityModelStore.model}et(){return ei("CoreModuleDirector.getPropertiesModel"),this.core.propertiesModelStore.model}async getAllSubscriptionsModels(){ei("CoreModuleDirector.getAllSubscriptionsModels");const t=this.getEmailSubscriptionModels(),e=this.getSmsSubscriptionModels(),i=await this.getPushSubscriptionModel();return[...t,...e,...i?[i]:[]]}getSubscriptionOfTypeWithToken(t,e){let i;switch(ei("CoreModuleDirector.getSubscriptionOfTypeWithToken",{type:t,token:e}),t){case o:i=this.getEmailSubscriptionModels();break;case"SMS":i=this.getSmsSubscriptionModels();break;case a:i=this.getAllPushSubscriptionModels();break;default:return}return i.find(t=>t.token===e)}}class Ts{static async createUserOnServer(){const t=OneSignal.Z.tt(),e=di.getAppId(),i=OneSignal.Z.subscriptionModelStore.list().length>0,n=!!t.externalId;if(!i&&!n)return void pt.O("No subscriptions or external ID found, skipping user creation");const s=await OneSignal.Z.getPushSubscriptionModel();if(s){const i=s.toJSON();OneSignal.Z.operationRepo.enqueue(new On(e,t.onesignalId,t.externalId)),await OneSignal.Z.operationRepo.enqueueAndWait(new is({...i,appId:e,onesignalId:t.onesignalId,subscriptionId:s.id}))}else OneSignal.Z.operationRepo.enqueue(new On(e,t.onesignalId,t.externalId))}static resetUserModels(){const t=new Un,e=new Qn,i=dn.V();t.onesignalId=i,e.onesignalId=i,OneSignal.Z.identityModelStore.replace(t),OneSignal.Z.propertiesModelStore.replace(e)}}class Ns{static switchingUsersPromise=Promise.resolve();static async login(t,e){await(this.switchingUsersPromise=Ns.Jt(t,e))}static async Jt(t,e){e&&ke.put("Ids",{id:e,type:"jwtToken"});let i=OneSignal.Z.tt();const n=dn.H(i.onesignalId)?void 0:i.onesignalId,s=i.externalId;if(s===t)return void pt.m("Login: External ID already set, skipping login");Ts.resetUserModels(),i=OneSignal.Z.tt(),i.setProperty(G,t,bn);const o=i.onesignalId,a=di.getAppId(),r=[OneSignal.Z.getPushSubscriptionModel().then(t=>{t&&OneSignal.Z.operationRepo.enqueue(new os(a,o,t.id))}),OneSignal.Z.operationRepo.enqueueAndWait(new On(a,o,t,s?void 0:n))];await Promise.all(r)}static async logout(){await(this.switchingUsersPromise=Ns.Yt())}static async Yt(){return OneSignal.Z.tt().externalId?(Ts.resetUserModels(),Ts.createUserOnServer()):pt.m("Logout: User is not logged in, skipping logout")}}function Ms(t){const e=t.active||t.installing||t.waiting;return e||pt.v("Could not find an available ServiceWorker instance!"),e}class As{Qt;constructor(){this.Qt={}}Zt(t,e,i){const n={callback:e,onceListenerOnly:i},s=this.Qt[t.toString()];s?s.push(n):this.Qt[t.toString()]=[n]}Xt(t){return this.Qt[t.toString()]||[]}te(t){this.Qt[t.toString()]=null}ee(){this.Qt={}}ie(t,e){const i=this.Qt[t.toString()];if(null!=i)for(let n=i.length-1;n>=0;n--)i[n]===e&&i.splice(n,1)}}class Ds{ne;Qt;constructor(t,e=new As){this.ne=t,this.Qt=e}se(t,e){this.Qt.Zt(t,e,!1)}oe(t,e){this.Qt.Zt(t,e,!0)}ae(t){t?this.Qt.te(t):this.Qt.ee()}}class Us extends Ds{async listen(){P()&&await this.listenForPage()}async listenForPage(){navigator.serviceWorker.addEventListener("message",this.onPageMessageReceivedFromServiceWorker.bind(this)),pt.m(`(${location.origin}) [Worker Messenger] Page is now listening for messages.`)}onPageMessageReceivedFromServiceWorker(t){const e=t.data;if(!e||!e.command)return;const i=this.Qt.Xt(e.command),n=[],s=[];pt.m("[Worker Messenger] Page received message:",t.data);for(const o of i)o.onceListenerOnly&&n.push(o),s.push(o);for(let o=n.length-1;o>=0;o--){const t=n[o];this.Qt.ie(e.command,t)}for(const o of s)o.callback.apply(null,[e.payload])}async unicast(t,e){pt.m(`[Worker Messenger] [Page -> SW] Unicasting '${t.toString()}' to service worker.`),this.directPostMessageToSW(t,e)}async directPostMessageToSW(t,e){pt.m(`[Worker Messenger] [Page -> SW] Direct command '${t.toString()}' to service worker.`);const i=await(this.ne?.N.re());if(!i)return void pt.O("`[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!");const n=Ms(i);n?n.postMessage({command:t,payload:e}):pt.O("`[Worker Messenger] [Page -> SW] Could not get ServiceWorker to postMessage!")}}class Bs{static QUERY_STRING="?";path;constructor(t){if(!t)throw st("path");this.path=t.trim()}getQueryString(){const t=this.path.indexOf("?");return-1===t?null:this.path.length>t?this.path.substring(t+1):null}getWithoutQueryString(){return this.path.split(Bs.QUERY_STRING)[0]}getFileName(){return this.getWithoutQueryString().split("\\").pop()?.split("/").pop()}getFileNameWithQuery(){return this.path.split("\\").pop()?.split("/").pop()}getFullPath(){return this.path}}class Ls{outcomeName;config;appId;isUnique;constructor(t,e,i,n){this.outcomeName=i,this.config=e,this.appId=t,this.isUnique=n}async getAttribution(){return await async function(t){if(t.direct&&t.direct.enabled){const t=await(async()=>(await ke.getAll("Outcomes.NotificationClicked")).map(t=>{return{appId:(e=t).appId,notificationId:e.notificationId,timestamp:e.timestamp};var e}))();if(t.length>0)return{type:1,notificationIds:[t[0].notificationId]}}if(t.indirect&&t.indirect.enabled){const e=60*t.indirect.influencedTimePeriodMin*1e3,i=new Date((new Date).getTime()-e).getTime(),n=await(async()=>(await ke.getAll("Outcomes.NotificationReceived")).map(t=>{return{appId:(e=t).appId,notificationId:e.notificationId,timestamp:e.timestamp};var e}))();if(pt.m(`\tFound total of ${n.length} received notifications`),n.length>0){const e=t.indirect.influencedNotificationsLimit,s=function(t,e,i=!1,n=!0){const s=n?t:t.slice();return s.sort((t,n)=>{const s=e(t),o=e(n);return s>o?i?-1:1:st.timestamp,!0,!1),o=s.filter(t=>t.timestamp>=i).slice(0,e).map(t=>t.notificationId);pt.m(`\tTotal of ${o.length} received notifications are within reporting window.`);const a=s.filter(t=>-1===o.indexOf(t.notificationId)).map(t=>t.notificationId);if(a.forEach(t=>ke.delete("Outcomes.NotificationReceived",t)),pt.m(`\t${a.length} received notifications will be deleted.`),o.length>0)return{type:2,notificationIds:o}}}return t.unattributed&&t.unattributed.enabled?{type:3,notificationIds:[]}:{type:4,notificationIds:[]}}(this.config)}async beforeOutcomeSend(){return ei(this.isUnique?"sendUniqueOutcome":"sendOutcome",this.outcomeName),this.config?this.outcomeName?(await ti(),!!(await OneSignal.context.U.isPushNotificationsEnabled())||(pt.v("Reporting outcomes is supported only for subscribed users."),!1)):(pt.O("Outcome name is required"),!1):(pt.m("Outcomes feature not supported by main application yet."),!1)}async getAttributedNotifsByUniqueOutcomeName(){return(await ke.getAll("SentUniqueOutcome")).filter(t=>t.outcomeName===this.outcomeName).reduce((t,e)=>[...t,...e.notificationIds||[]],[])}async getNotifsToAttributeWithUniqueOutcome(t){const e=await this.getAttributedNotifsByUniqueOutcomeName();return t.filter(t=>-1===e.indexOf(t))}shouldSendUnique(t,e){return 3===t.type||e.length>0}async saveSentUniqueOutcome(t){const e=this.outcomeName,i=await ke.get("SentUniqueOutcome",e),n=await xe(),s=[...i?i.notificationIds:[],...t],o=n?n.startTimestamp:null;await ke.put("SentUniqueOutcome",{outcomeName:e,notificationIds:s,sentDuringSession:o})}async wasSentDuringSession(){const t=await ke.get("SentUniqueOutcome",this.outcomeName);if(!t)return!1;const e=await xe(),i=e&&t.sentDuringSession===e.startTimestamp,n=!e&&!!t.sentDuringSession;return i||n}async send(t){const{type:e,notificationIds:i,weight:n}=t;switch(e){case 1:return this.isUnique&&await this.saveSentUniqueOutcome(i),void(await OneSignal.context.gt.sendOutcomeDirect(this.appId,i,this.outcomeName,n));case 2:return this.isUnique&&await this.saveSentUniqueOutcome(i),void(await OneSignal.context.gt.sendOutcomeInfluenced(this.appId,i,this.outcomeName,n));case 3:if(this.isUnique){if(await this.wasSentDuringSession())return void pt.v("(Unattributed) unique outcome was already sent during this session");await this.saveSentUniqueOutcome([])}return void(await OneSignal.context.gt.sendOutcomeUnattributed(this.appId,this.outcomeName,n));default:return void pt.v("You are on a free plan. Please upgrade to use this functionality.")}}}function Rs(t,e,i){return function(t,e,i){return`${new URL(t,gt()).href}?${It({appId:e})}&${It({sdkVersion:i})}`}(t.workerPath.getFullPath(),e,i)}const Ws="OneSignal Worker",Fs="3rd Party",js="None",Ks="GetWorkerVersion",zs="os.session.deactivate";class Vs{ne;ce;constructor(t,e){this.ne=t,this.ce=e}async T(){return async function(t){try{const e=location.origin+t;return await navigator.serviceWorker.getRegistration(e)}catch(e){return void pt.v("[Service Worker Status] Error Checking service worker registration",t,e)}}(this.ce.registrationOptions.scope)}async re(){if(await this.le()===Ws)return this.T()}async le(){const t=await this.T();if(!t)return js;const e=Vs.ue(t);return this.he(e)}static ue(t){const e=Ms(t);if(!e)return null;const i=new URL(e.scriptURL).pathname,n=new Bs(i).getFileName();if("akam-sw.js"==n){const t=new URLSearchParams(new URL(e.scriptURL).search).get("othersw");if(t)return pt.m("Found a ServiceWorker under Akamai's akam-sw.js?othersw=",t),new Bs(new URL(t).pathname).getFileName()}return n}he(t){return t?t==this.ce.workerPath.getFileName()||"OneSignalSDK.sw.js"==t?Ws:Fs:js}async de(){return new Promise(async t=>{this.ne.ge.oe(Ks,e=>{t(e)}),await this.ne.ge.unicast(Ks)})}async pe(){if(!P())return!1;if(!OneSignal.config)return!1;const t=await this.le();if(pt.m("[shouldInstallWorker] workerState",t),t===js||t===Fs){const t="granted"===await OneSignal.context.P.getNotificationPermission(OneSignal.config.safariWebId);return t&&pt.S("[shouldInstallWorker] Notification Permissions enabled, will install ServiceWorker"),t}return!!(await this.we())||this.fe()}async we(){const t=await this.T();if(!t)return pt.S("[changedServiceWorkerParams] workerRegistration not found at scope",this.ce.registrationOptions.scope),!0;const e=new URL(t.scope).pathname,i=this.ce.registrationOptions.scope;if(e!=i)return pt.S("[changedServiceWorkerParams] ServiceWorker scope changing",{a_old:e,b_new:i}),!0;const n=Ms(t),s=Rs(this.ce,this.ne.ot.appId,_);return!n?.scriptURL||s!==n.scriptURL&&(pt.S("[changedServiceWorkerParams] ServiceWorker href changing:",{a_old:n?.scriptURL,b_new:s}),!0)}async fe(){let t;pt.S("[Service Worker Update] Checking service worker version...");try{t=await function(t){const e=new Promise((t,e)=>{setTimeout(()=>{e(new Error("Async operation timed out"))},2e3)});return Promise.race([t,e])}(this.de())}catch(e){return pt.S("[Service Worker Update] Worker did not reply to version query; assuming older version and updating."),!0}return t!==_?(pt.S(`[Service Worker Update] Updating service worker from ${t} --\x3e ${_}.`),!0):(pt.S(`[Service Worker Update] Service worker version is current at ${t} (no update required).`),!1)}async ut(){pt.m("establishServiceWorkerChannel");const t=this.ne.ge;t.ae(),t.se("notification.willDisplay",async t=>{pt.m(location.origin,"Received notification display event from service worker.");const e={notification:t.notification,preventDefault:function(){throw new Error("Browser does not support preventing display.")}};await ri.trigger(OneSignal.EVENTS.NOTIFICATION_WILL_DISPLAY,e)}),t.se("notification.clicked",async t=>{0===OneSignal.emitter.numberOfListeners(OneSignal.EVENTS.NOTIFICATION_CLICKED)?pt.m("notification.clicked event received, but no event listeners; storing event in IndexedDb for later retrieval."):await function(t){const e={notification:t.notification,result:t.result};return ri.trigger(OneSignal.EVENTS.NOTIFICATION_CLICKED,e)}(t)}),t.se("notification.dismissed",async t=>{await ri.trigger(OneSignal.EVENTS.NOTIFICATION_DISMISSED,t)});const e=$();t.se("os.page_focused_request",async i=>{if(e){const e={timestamp:i.timestamp,focused:document.hasFocus()};await t.directPostMessageToSW("os.page_focused_response",e)}})}async be(){if(!(await this.pe()))return this.re();pt.S("Installing worker..."),await this.le()===Fs&&pt.S("[Service Worker Installation] 3rd party service worker detected.");const t=Rs(this.ce,this.ne.ot.appId,_),e=`${gt()}${this.ce.registrationOptions.scope}`;let i;pt.S(`[Service Worker Installation] Installing service worker ${t} ${e}.`);try{i=await navigator.serviceWorker.register(t,{scope:e,type:void 0})}catch(n){pt.O(`[Service Worker Installation] Installing service worker failed ${n}`),i=await this.me()}return pt.m("[Service Worker Installation] Service worker installed. Waiting for activation"),await function(t){return new Promise(e=>{const i=t.installing||t.waiting;i&&i.addEventListener("statechange",()=>{pt.m("OneSignal Service Worker state changed:",i.state),t.active&&e()}),t.active&&e()})}(i),pt.m("[Service Worker Installation] Service worker active"),await this.ut(),i}async me(){const t="OneSignalSDK.sw.js",e=Rs({workerPath:new Bs(`/${t}`)},this.ne.ot.appId,_),i=`${gt()}${this.ce.registrationOptions.scope}`;pt.S(`[Service Worker Installation] Attempting to install v16 Beta Worker ${e} ${i}.`);try{const n=await navigator.serviceWorker.register(e,{scope:i}),s=`\n [Service Worker Installation] Successfully installed v16 Beta Worker.\n Deprecation warning: support for the v16 beta worker name of ${t}\n will be removed May 5 2024. We have decided to keep the v15 name.\n To avoid breaking changes for your users, please host both worker files:\n OneSignalSDK.sw.js & OneSignalSDKWorker.js.\n `;return pt.O(s),n}catch(n){const t=await fetch(e);if(403===t.status||404===t.status)throw new Y(t.status,t.statusText);throw n}}}class Hs{ne;ce;constructor(t,e){this.ne=t,this.ce=e}async ct(t,e){t&&(t=Es._(t)),await this.ht()?"gt"in this.ne&&await this.ne.gt.sendPushDeviceRecordUpdate():"dt"in this.ne&&this.ne.dt.upsertSession(1);const i=await De();return i.deviceId="99999999-9999-9999-9999-999999999999",i.optedOut=!1,t?N()?i.subscriptionToken=t.safariDeviceToken:i.subscriptionToken=t.w3cEndpoint?t.w3cEndpoint.toString():null:i.subscriptionToken=null,await Ue(i),ri.trigger(OneSignal.EVENTS.REGISTERED),"undefined"!=typeof OneSignal&&(OneSignal.lt=!1),i}async ht(){const{deviceId:t}=await De();return!!t}async ye(t,e){const i=await t.getSubscription();switch(e){case 0:if(!i)break;i.options?pt.m("[Subscription Manager] An existing push subscription exists and it's options is not null."):(pt.m("[Subscription Manager] An existing push subscription exists and options is null. Unsubscribing from push first now."),await Hs.Se(i));break;case 1:i&&await Hs.Se(i)}const[n,s]=await Hs.ve(t,this.Oe());return await Hs.ke(s,n.expirationTime),Es.Ht(n)}Oe(){let t;return t=I()===f?this.ce.onesignalVapidPublicKey:this.ce.vapidPublicKey,t?function(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),i=atob(e),n=new Uint8Array(i.length);for(let s=0;s{await Ns.switchingUsersPromise;let e=await OneSignal.Z.getPushSubscriptionModel();if(!e)return e=OneSignal.Z.generatePushSubscriptionModel(t),Ts.createUserOnServer();if(dn.H(e.id))return Ts.createUserOnServer();const i=new $s(t).C();for(const n in i){const t=n;e.setProperty(t,i[t])}};class Js extends Hs{safariPermissionPromptFailed=!1;async isPushNotificationsEnabled(){const t=await this.getSubscriptionState();return t.subscribed&&!t.optedOut}async updateNotificationTypes(){const t=await this.getNotificationTypes();await this.updatePushSubscriptionNotificationTypes(t)}async updatePushSubscriptionNotificationTypes(t){const e=await OneSignal.Z.getPushSubscriptionModel();e?(e.notification_types=t,e.enabled=1===t):pt.S("No Push Subscription yet to update notification_types.")}async getNotificationTypes(){const{optedOut:t}=await De();return t?-2:"granted"===await OneSignal.context.P.getPermissionStatus()?1:0}async isOptedIn(){const t=await this.getSubscriptionState();return"granted"===await OneSignal.context.P.getPermissionStatus()&&!t.optedOut}async isOptedOut(t){ei("isOptedOut",t);const{optedOut:e}=await De();return function(t,...e){t&&t.apply(null,e)}(t,e),e}async unsubscribe(t){throw qs}async getSubscriptionState(){const{optedOut:t,subscriptionToken:e}=await De(),i=gn(await OneSignal.Z.getPushSubscriptionModel());if(N()){const n=window.safari?.pushNotification?.permission(this.ce.safariWebId);return{subscribed:!!(i&&e&&"granted"===n?.permission&&n?.deviceToken),optedOut:!!t}}const n=await this.ne.N.re(),s=await this.ne.P.getNotificationPermission(this.ne.ot.safariWebId);return n?{subscribed:!(!i||!e||"granted"!==s),optedOut:!!t}:{subscribed:!1,optedOut:!!t}}async subscribe(t){let e;if("denied"===await OneSignal.context.P.getPermissionStatus())throw tt;if(N()){e=await this.subscribeSafari(),await Gs(e),pt.S("Installing SW on Safari");try{await this.ne.N.be(),pt.S("SW on Safari successfully installed")}catch(i){pt.O("SW on Safari failed to install.")}}else e=await this.Ie(t),await Gs(e);return e}async subscribeSafari(){const t=new Es;if(!this.ce.safariWebId)throw it;const{deviceToken:e}=window.safari?.pushNotification?.permission(this.ce.safariWebId)||{};if(e)return t.qt(e.toLowerCase()),t;ri.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);const i=await this.subscribeSafariPromptPermission();if(li(),!i)throw this.safariPermissionPromptFailed=!0,new Error("Safari url/icon/certificate invalid or in private mode");return t.qt(i),t}async subscribeSafariPromptPermission(){const t=t=>new Promise(e=>{window.safari?.pushNotification?.requestPermission(t,this.ce.safariWebId,{app_id:this.ce.appId},t=>{t&&t.deviceToken?e(t.deviceToken.toLowerCase()):e(null)})});return this.safariPermissionPromptFailed?t(`${A({legacy:!0}).toString()}safari`):t(`${A({legacy:!0}).toString()}safari/apps/${this.ce.appId}`)}async Ie(t){if("default"===Notification.permission){await ri.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);const t=await Js.requestPresubscribeNotificationPermission(),e="default"===t;switch(await li(e),t){case"default":throw pt.m("Exiting subscription and not registering worker because the permission was dismissed."),OneSignal.lt=!1,new Error("Permission dismissed");case"denied":throw pt.m("Exiting subscription and not registering worker because the permission was blocked."),OneSignal.lt=!1,tt}}let e;try{e=await this.ne.N.be()}catch(i){throw i instanceof Y&&(403===i.status?await this.ne.U.registerFailedSubscription(-23):404===i.status&&await this.ne.U.registerFailedSubscription(-24)),i}if(!e)throw new Error("OneSignal service worker not found!");return pt.m("[Subscription Manager] Service worker is ready to continue subscribing."),await this.ye(e.pushManager,t)}async registerFailedSubscription(t){un()&&(this.ne.U.ct(new Es,t),ln())}static async requestPresubscribeNotificationPermission(){return await Js.requestNotificationPermission()}static async requestNotificationPermission(){return await window.Notification.requestPermission()}async isSubscriptionExpiring(){if(await this.ne.N.le()!==Ws)return!1;const t=await this.ne.N.re();if(!t)return!1;if(!t.pushManager)return!1;const e=await t.pushManager.getSubscription();if(!e)return!1;if(!e.expirationTime)return!1;let{createdAt:i}=await De();if(!i){const t=31536e6;i=(new Date).getTime()+t}const n=i+(e.expirationTime-i)/2;return!!e.expirationTime&&((new Date).getTime()>=e.expirationTime||(new Date).getTime()>=n)}}class Ys{static get STORED_PERMISSION_KEY(){return"storedNotificationPermission"}async getPermissionStatus(){if(!OneSignal.context)throw new Error("OneSignal.context is undefined. Call init first");return await OneSignal.context.P.getNotificationPermission(OneSignal.config.safariWebId)}async getNotificationPermission(t){return N()?Ys.getLegacySafariNotificationPermission(t):this.getW3cNotificationPermission()}static getLegacySafariNotificationPermission(t){if(t)return window.safari?.pushNotification?.permission(t).permission;throw st("safariWebId")}getW3cNotificationPermission(){return Notification.permission}}class Qs{context;onSessionSent=!1;constructor(t){this.context=t}async notifySWToUpsertSession(t,e,i){const n={onesignalId:t,subscriptionId:e,appId:this.context.ot.appId,sessionThreshold:this.context.ot.sessionThreshold||0,enableSessionDuration:!!this.context.ot.enableSessionDuration,sessionOrigin:i,isSafari:$(),outcomesConfig:this.context.ot.userConfig.outcomes};P()?(pt.m("Notify SW to upsert session"),await this.context.ge.unicast("os.session.upsert",n)):pt.m("Notify upsert: do nothing")}async notifySWToDeactivateSession(t,e,i){const n={appId:this.context.ot.appId,subscriptionId:e,onesignalId:t,sessionThreshold:this.context.ot.sessionThreshold,enableSessionDuration:this.context.ot.enableSessionDuration,sessionOrigin:i,isSafari:$(),outcomesConfig:this.context.ot.userConfig.outcomes};P()?(pt.m("Notify SW to deactivate session"),await this.context.ge.unicast(zs,n)):pt.m("Notify deactivate: do nothing")}async xe(){const t=OneSignal.Z.tt(),e=await OneSignal.Z.getPushSubscriptionModel();if(!t||!t.onesignalId)throw new Error("No identity");if(!e||!gn(e))throw new Error("No subscription");const{onesignalId:i}=t,{id:n}=e;return{onesignalId:i,subscriptionId:n}}async handleVisibilityChange(){if(await Ns.switchingUsersPromise,kn.singletonInstance?.onesignalId)try{const t=document.visibilityState,{onesignalId:e,subscriptionId:i}=await this.xe();if("visible"===t)return this.setupOnFocusAndOnBlurForSession(),pt.m("handleVisibilityChange","visible",`hasFocus: ${document.hasFocus()}`),void(document.hasFocus()&&await this.notifySWToUpsertSession(e,i,3));if("hidden"===t)return pt.m("handleVisibilityChange","hidden"),OneSignal.cache.focusHandler&&OneSignal.cache.isFocusEventSetup&&(window.removeEventListener("focus",OneSignal.cache.focusHandler,!0),OneSignal.cache.isFocusEventSetup=!1),OneSignal.cache.blurHandler&&OneSignal.cache.isBlurEventSetup&&(window.removeEventListener("blur",OneSignal.cache.blurHandler,!0),OneSignal.cache.isBlurEventSetup=!1),void(await this.notifySWToDeactivateSession(e,i,4));pt.v("Unhandled visibility state happened",t)}catch(t){pt.O("Error handling visibility change:",t)}}async handleOnBeforeUnload(){if(await Ns.switchingUsersPromise,kn.singletonInstance?.onesignalId)try{const{onesignalId:t,subscriptionId:e}=await this.xe(),i={appId:this.context.ot.appId,onesignalId:t,subscriptionId:e,sessionThreshold:this.context.ot.sessionThreshold,enableSessionDuration:this.context.ot.enableSessionDuration,sessionOrigin:5,isSafari:$(),outcomesConfig:this.context.ot.userConfig.outcomes};pt.m("Notify SW to deactivate session (beforeunload)"),this.context.ge.directPostMessageToSW(zs,i)}catch(t){pt.O("Error handling onbeforeunload:",t)}}async handleOnFocus(t){if(await Ns.switchingUsersPromise,pt.m("handleOnFocus",t),kn.singletonInstance?.onesignalId)try{if(t.target!==window)return;const{onesignalId:e,subscriptionId:i}=await this.xe();await this.notifySWToUpsertSession(e,i,7)}catch(e){pt.O("Error handling focus:",e)}}async handleOnBlur(t){if(await Ns.switchingUsersPromise,pt.m("handleOnBlur",t),kn.singletonInstance?.onesignalId)try{if(t.target!==window)return;const{onesignalId:e,subscriptionId:i}=await this.xe();await this.notifySWToDeactivateSession(e,i,8)}catch(e){pt.O("Error handling blur:",e)}}async upsertSession(t){if(await Ns.switchingUsersPromise,kn.singletonInstance?.onesignalId){const{onesignalId:e,subscriptionId:i}=await this.xe();await this.notifySWToUpsertSession(e,i,t)}P()?this.setupSessionEventListeners():(this.onSessionSent=1===t,OneSignal.emitter.emit(OneSignal.EVENTS.SESSION_STARTED))}setupSessionEventListeners(){P()?(this.setupOnFocusAndOnBlurForSession(),OneSignal.cache.isVisibilityChangeEventSetup||(document.addEventListener("visibilitychange",this.handleVisibilityChange.bind(this),!0),OneSignal.cache.isVisibilityChangeEventSetup=!0),OneSignal.cache.isBeforeUnloadEventSetup||(window.addEventListener("beforeunload",t=>{this.handleOnBeforeUnload(),delete t.returnValue},!0),OneSignal.cache.isBeforeUnloadEventSetup=!0)):pt.m("Not setting session event listeners. No service worker possible.")}setupOnFocusAndOnBlurForSession(){pt.m("setupOnFocusAndOnBlurForSession"),OneSignal.cache.focusHandler||(OneSignal.cache.focusHandler=this.handleOnFocus.bind(this)),OneSignal.cache.isFocusEventSetup||(window.addEventListener("focus",OneSignal.cache.focusHandler,!0),OneSignal.cache.isFocusEventSetup=!0),OneSignal.cache.blurHandler||(OneSignal.cache.blurHandler=this.handleOnBlur.bind(this)),OneSignal.cache.isBlurEventSetup||(window.addEventListener("blur",OneSignal.cache.blurHandler,!0),OneSignal.cache.isBlurEventSetup=!0)}async sendOnSessionUpdateFromPage(){if(this.onSessionSent||!un())return;const t=OneSignal.Z.tt().onesignalId;if(!t)return void pt.m("Not sending the on session because user is not registered with OneSignal (no onesignal id)");const e=await OneSignal.Z.getPushSubscriptionModel();if(1!==e?.notification_types&&!0!==OneSignal.config?.enableOnSession)return;let i;gn(e)&&(i=e?.id);try{const e={label:J,id:t},s={refresh_device_metadata:!0,deltas:{session_count:1}},o=di.getAppId();!function(t){if(!t)throw new Error("App id cannot be empty")}(o),function(t){if(!t.id)throw new Error("Alias id cannot be empty")}(e);try{await vt({appId:o,subscriptionId:i},e,s),this.onSessionSent=!0}catch(n){pt.m("Error updating user session:",n)}}catch(n){n instanceof Error&&pt.O(`Failed to update user session. Error "${n.message}" ${n.stack}`)}}}class Zs{context;onSessionSent;constructor(t){this.context=t,this.onSessionSent=cn()>1}async sendPushDeviceRecordUpdate(){kn.singletonInstance?.onesignalId?this.onSessionSent||await this.sendOnSessionUpdate():pt.m("Not sending the update because user is not registered with OneSignal (no onesignal_id)")}async sendOnSessionUpdate(){if(this.onSessionSent)return;if(!un())return;if(!(await this.context.U.ht()))return void pt.m("Not sending the on session because user is not registered with OneSignal (no device id)");const t=await OneSignal.Z.getPushSubscriptionModel();if(1===t?.notification_types||!0===OneSignal.config?.enableOnSession)try{this.context.dt.upsertSession(2),this.onSessionSent=!0}catch(e){e instanceof Error&&pt.O(`Failed to update user session. Error "${e.message}" ${e.stack}`)}}async sendOutcomeDirect(t,e,i,n){ei("sendOutcomeDirect");const s=await OneSignal.Z.getPushSubscriptionModel();if(s&&gn(s)){const o={id:i,app_id:t,notification_ids:e,direct:!0,subscription:{id:s.id,type:D()}};return void 0!==n&&(o.weight=n),void(await xt(o))}pt.v("Send outcome aborted because pushSubscriptionModel is not available.")}async sendOutcomeInfluenced(t,e,i,n){ei("sendOutcomeInfluenced");const s=await OneSignal.Z.getPushSubscriptionModel();if(s&&gn(s)){const o={id:i,app_id:t,notification_ids:e,direct:!1,subscription:{id:s.id,type:D()}};return void 0!==n&&(o.weight=n),void(await xt(o))}pt.v("Send outcome aborted because pushSubscriptionModel is not available.")}async sendOutcomeUnattributed(t,e,i){ei("sendOutcomeUnattributed");const n=await OneSignal.Z.getPushSubscriptionModel();if(n&&gn(n)){const s={id:e,app_id:t,subscription:{id:n.id,type:D()}};return void 0!==i&&(s.weight=i),void(await xt(s))}pt.v("Send outcome aborted because pushSubscriptionModel is not available.")}}class Xs{smsInputFieldIsValid=!0;emailInputFieldIsValid=!0;promptOptions;itiOneSignal;constructor(t){this.promptOptions=t}generateHtml(){const t=document.createElement("div");let e,i,n;switch(We(t,Vi),t.id=Vi,this.promptOptions.type){case Nt:e=this.promptOptions.text.smsLabel||"Phone Number",i=this.getInputWithValidationElement(Nt,e),t.appendChild(i);break;case Mt:e=this.promptOptions.text.emailLabel||"Email",n=this.getInputWithValidationElement(Mt,e),t.appendChild(n);break;case At:e=this.promptOptions.text.emailLabel||"Email",n=this.getInputWithValidationElement(Mt,e),t.appendChild(n),e=this.promptOptions.text.smsLabel||"Phone Number",i=this.getInputWithValidationElement(Nt,e),t.appendChild(i)}return t}getValidationElementWithMessage(t){const e=document.createElement("div"),i=document.createElement("img"),n=document.createElement("p");return n.innerText=t,i.setAttribute("src","data:image/svg+xml;charset=UTF-8,%3csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M7.98775 -0.00114406C5.85015 0.0338508 3.81219 0.908665 2.31442 2.43419C1.565 3.18031 0.973715 4.06987 0.575897 5.04969C0.17808 6.02952 -0.0180997 7.07949 -0.000914196 8.13686C-0.00214385 9.17005 0.200528 10.1933 0.595487 11.148C0.990446 12.1028 1.56993 12.9702 2.30072 13.7005C3.03151 14.4309 3.89925 15.0098 4.85421 15.4042C5.80916 15.7986 6.83256 16.0007 7.86575 15.9989H8.00842C10.1467 15.9769 12.1889 15.1075 13.6869 13.5816C15.185 12.0557 16.0165 9.99781 15.9991 7.85952C16.0015 6.8138 15.7949 5.77814 15.3913 4.81345C14.9876 3.84876 14.3952 2.97451 13.6488 2.24213C12.9023 1.50974 12.017 0.933994 11.0448 0.548751C10.0726 0.163508 9.03324 -0.0234551 7.98775 -0.00114406ZM6.99909 11.0269C6.99428 10.8961 7.01558 10.7658 7.06175 10.6434C7.10792 10.521 7.17803 10.4091 7.26797 10.3141C7.35792 10.2191 7.4659 10.143 7.58559 10.0903C7.70529 10.0375 7.8343 10.0092 7.96509 10.0069H7.98309C8.24616 10.0074 8.49882 10.1097 8.6881 10.2924C8.87739 10.4751 8.9886 10.724 8.99842 10.9869C9.00331 11.1176 8.98207 11.248 8.93594 11.3704C8.8898 11.4928 8.8197 11.6048 8.72974 11.6998C8.63978 11.7948 8.53176 11.8709 8.41202 11.9236C8.29229 11.9763 8.16323 12.0046 8.03242 12.0069H8.01442C7.75145 12.006 7.49897 11.9036 7.30976 11.721C7.12054 11.5383 7.00923 11.2896 6.99909 11.0269ZM7.33242 8.33219V4.33219C7.33242 4.15538 7.40266 3.98581 7.52768 3.86079C7.65271 3.73576 7.82227 3.66552 7.99909 3.66552C8.1759 3.66552 8.34547 3.73576 8.47049 3.86079C8.59551 3.98581 8.66575 4.15538 8.66575 4.33219V8.33219C8.66575 8.509 8.59551 8.67857 8.47049 8.80359C8.34547 8.92862 8.1759 8.99886 7.99909 8.99886C7.82227 8.99886 7.65271 8.92862 7.52768 8.80359C7.40266 8.67857 7.33242 8.509 7.33242 8.33219Z' fill='%23E54B4D'/%3e%3c/svg%3e"),e.appendChild(i),e.appendChild(n),e}getInputWithValidationElement(t,e){const i=this.getTypeSpecificVariablesForValidationElemGeneration(t),n=document.createElement("label"),s=document.createElement("input"),o=document.createElement("div"),a=document.createElement("div"),r=this.getValidationElementWithMessage(i.message),c=document.createElement("div");return o.setAttribute("style","clear:both"),a.setAttribute("style","clear:both"),We(r,qi),We(r,"onesignal-validation-element"),r.id=i.validationElementId,n.title=e,n.innerText=e,n.htmlFor=i.inputElementId,s.type=i.domElementType,s.id=i.inputElementId,s.tabIndex=i.tabIndex,We(s,i.inputClass),We(c,"input-with-validation-element"),c.id=i.wrappingDivId,c.appendChild(n),c.appendChild(o),c.appendChild(s),c.appendChild(a),c.appendChild(r),c}getTypeSpecificVariablesForValidationElemGeneration(t){if(t===Mt)return{message:"Please enter a valid email",domElementType:"email",validationElementId:Xi,inputElementId:Qi,inputClass:"onesignal-email-input",wrappingDivId:Ji,tabIndex:1};if(t===Nt)return{message:"Please enter a valid phone number",domElementType:"tel",validationElementId:Zi,inputElementId:Yi,inputClass:"iti-onesignal-sms-input",wrappingDivId:Gi,tabIndex:2};throw new Error("invalid channel type for input validation")}initializePhoneInputLibrary(){const t=Re(`#${Yi}`);t&&window.intlTelInput?this.itiOneSignal=window.intlTelInput(t,{autoPlaceholder:"off",separateDialCode:!0}):pt.O("OneSignal: there was a problem initializing International Telephone Input")}addSmsInputEventListeners(){const t=Re(`#${Yi}`);t.addEventListener("keyup",e=>{this.smsInputFieldIsValid=this.itiOneSignal?.isValidNumber()||""===t?.value,"Enter"===e.key&&document.getElementById(Mi)?.click(),this.updateValidationOnSmsInputChange()}),t.addEventListener("blur",()=>{this.smsInputFieldIsValid=this.itiOneSignal?.isValidNumber()||""===t?.value,this.updateValidationOnSmsInputChange()})}addEmailInputEventListeners(){const t=Re(`#${Qi}`);t.addEventListener("keyup",e=>{const i=t?.value;this.emailInputFieldIsValid=Xs.validateEmailInputWithReturnVal(i),"Enter"===e.key&&document.getElementById(Mi)?.click(),this.updateValidationOnEmailInputChange()})}updateValidationOnSmsInputChange(){const t=Re(`#${Gi}`),e=Re(`#${Zi}`);Fe(t,Hi),We(e,qi)}updateValidationOnEmailInputChange(){const t=Re(`#${Ji}`),e=Re(`#${Xi}`);Fe(t,Hi),We(e,qi)}async loadPhoneLibraryScripts(){if(OneSignal.Ce)return;const t=document.createElement("script"),e=document.createElement("script"),i=document.createElement("link");t.src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput.min.js",e.src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js",i.href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.min.css",i.rel="stylesheet",t.integrity="sha512-OnkjbJ4TwPpgSmjXACCb5J4cJwi880VRe+vWpPDlr8M38/L3slN5uUAeOeWU2jN+4vN0gImCXFGdJmc0wO4Mig==",e.integrity="sha512-bUcJxlqkiGA3cmoYPuZaLRsyc5ChG9APG4ajom2AXKSlBtOmx4kLV3c8uv/6uSz43FMjI4Q2QI21+D223rT76w==",i.integrity="sha512-yye/u0ehQsrVrfSd6biT17t39Rg9kNc+vENcCXZuMz2a+LWFGvXUnYuWUW6pbfYj1jcBb/C39UZw2ciQvwDDvg==",t.crossOrigin="anonymous",e.crossOrigin="anonymous",i.crossOrigin="anonymous",document.head.appendChild(t),document.head.appendChild(e),document.head.appendChild(i);const n=new Promise(e=>{t.onload=()=>{e()}}),s=new Promise(t=>{e.onload=()=>{t()}});await Promise.all([n,s]),OneSignal.Ce=!0}async mount(){const t=Xs.isUsingSmsInputField(this.promptOptions.type),e=Xs.isUsingEmailInputField(this.promptOptions.type);t&&await this.loadPhoneLibraryScripts();const i=this.generateHtml();Re(`#${Ai}`).appendChild(i),t&&(this.initializePhoneInputLibrary(),this.addSmsInputEventListeners()),e&&this.addEmailInputEventListeners()}isEmailInputFieldEmpty(){return""===this.getValueFromEmailInput()}isSmsInputFieldEmpty(){return""===this.getValueFromSmsInput()}getValueFromEmailInput(){const t=Re(`#${Qi}`);return t?.value||""}getValueFromSmsInput(){return this.itiOneSignal?.getNumber(window.intlTelInputUtils?.numberFormat.E164)||""}static showSmsInputError(t){const e=document.querySelector(`#${Zi}`),i=document.querySelector(`#${Gi}`);e&&i?t?(e.classList.remove(qi),i.classList.add(Hi)):(e.classList.add(qi),i.classList.remove(Hi)):pt.O("OneSignal: couldn't find slidedown validation element")}static showEmailInputError(t){const e=document.querySelector(`#${Xi}`),i=document.querySelector(`#${Ji}`);e&&i?t?(e.classList.remove(qi),i.classList.add(Hi)):(e.classList.add(qi),i.classList.remove(Hi)):pt.O("OneSignal: couldn't find slidedown validation element")}static resetInputErrorStates(t){switch(t){case Nt:Xs.showSmsInputError(!1);break;case Mt:Xs.showEmailInputError(!1);break;case At:Xs.showSmsInputError(!1),Xs.showEmailInputError(!1)}}static validateEmailInputWithReturnVal(t){return/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(t||"")||""===t}static isUsingSmsInputField(t){return t===Nt||t===At}static isUsingEmailInputField(t){return t===Mt||t===At}}function to(t){return` `}class eo{options;notificationIcons;channelCaptureContainer;isShowingFailureState;tagCategories;savingButton="Saving...";errorButton=Rt;updateMessage;positiveUpdateButton;negativeUpdateButton;constructor(t){switch(this.options=t,this.options.text.actionMessage=t.text.actionMessage.substring(0,90),this.options.text.acceptButton=t.text.acceptButton.substring(0,16),this.options.text.cancelButton=t.text.cancelButton.substring(0,16),this.notificationIcons=null,this.channelCaptureContainer=null,this.isShowingFailureState=!1,t.type){case Tt:this.negativeUpdateButton=this.options.text.negativeUpdateButton?.substring(0,16),this.positiveUpdateButton=this.options.text.positiveUpdateButton?.substring(0,16),this.updateMessage=this.options.text.updateMessage?.substring(0,90),this.tagCategories=t.categories,this.errorButton=dt(this.options.text.positiveUpdateButton,Rt);break;case Nt:case Mt:case At:this.errorButton=dt(this.options.text.acceptButton,Rt)}}async create(t){if(null===this.notificationIcons){const e=await di.getNotificationIcons();this.notificationIcons=e,this.container.className.includes(Ii)&&Le(`#${Bi}`);const i=t&&this.tagCategories?this.positiveUpdateButton:this.options.text.acceptButton,n=t&&this.tagCategories?this.negativeUpdateButton:this.options.text.cancelButton,s=function(t){const{icon:e,messageText:i,positiveButtonText:n,negativeButtonText:s}=t,o=e===Ti?"data:image/svg+xml,%3Csvg fill='none' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Cg clip-path='url(%23clip0)'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M33.232 28.434a2.5 2.5 0 001.768.733 1.667 1.667 0 010 3.333H5a1.667 1.667 0 110-3.333 2.5 2.5 0 002.5-2.5v-8.104A13.262 13.262 0 0118.333 5.122V1.667a1.666 1.666 0 113.334 0v3.455A13.262 13.262 0 0132.5 18.563v8.104a2.5 2.5 0 00.732 1.767zM16.273 35h7.454a.413.413 0 01.413.37 4.167 4.167 0 11-8.28 0 .417.417 0 01.413-.37z' fill='%23BDC4CB'/%3E%3C/g%3E%3Cdefs%3E%3CclipPath id='clip0'%3E%3Cpath fill='%23fff' d='M0 0h40v40H0z'/%3E%3C/clipPath%3E%3C/defs%3E%3C/svg%3E":e,a=e===Ti?Ti:"",r=document.createElement("div"),c=document.createElement("div"),l=document.createElement("div"),u=document.createElement("div"),h=document.createElement("div"),d=document.createElement("div"),g=document.createElement("button"),p=document.createElement("button"),w=document.createElement("div"),f=document.createElement("div"),b=document.createElement("img");return We(c,"slidedown-body"),We(u,"slidedown-body-icon"),We(l,"slidedown-body-message"),We(d,"slidedown-footer"),We(w,Ni),We(f,Ni),We(g,Fi),We(g,"primary"),We(g,ji),We(p,Fi),We(p,"secondary"),We(p,ji),r.id="normal-slidedown",c.id=Ai,h.id=Wi,g.id=Mi,p.id=Ui,d.id=Ri,a&&We(b,a),b.setAttribute("alt","notification icon"),b.setAttribute("src",o||""),l.innerText=i||"",g.innerText=n||"",p.innerText=s||"",u.appendChild(b),c.appendChild(u),c.appendChild(l),c.appendChild(w),c.appendChild(h),d.appendChild(g),d.appendChild(p),d.appendChild(f),r.appendChild(c),r.appendChild(d),r}({messageText:t&&this.tagCategories?this.updateMessage:this.options.text.actionMessage,icon:this.options.icon||this.getPlatformNotificationIcon(),positiveButtonText:i,negativeButtonText:n}),o=document.createElement("div"),a=document.createElement("div");o.id=Bi,We(o,Ii),We(o,Ci),Re("body").appendChild(o),a.id=Li,We(a,xi),a.appendChild(s),this.container.appendChild(a),We(this.container,O()?Ei:$i),this.allowButton.addEventListener("click",this.onSlidedownAllowed.bind(this)),this.cancelButton.addEventListener("click",this.onSlidedownCanceled.bind(this))}}static async triggerSlidedownEvent(t){await ri.trigger(t)}async onSlidedownAllowed(t){await eo.triggerSlidedownEvent(eo.EVENTS.ALLOW_CLICK)}onSlidedownCanceled(t){eo.triggerSlidedownEvent(eo.EVENTS.CANCEL_CLICK),this.close(),eo.triggerSlidedownEvent(eo.EVENTS.CLOSED)}close(){We(this.container,Pi),ii(this.dialog,"animationend",(t,e)=>{t.target!==this.dialog||"slideDownExit"!==t.animationName&&"slideUpExit"!==t.animationName||(Le(`#${Bi}`),e())},!0)}setSaveState(){this.allowButton.disabled=!0,this.allowButton.textContent=null,this.allowButton.insertAdjacentElement("beforeend",this.getTextSpan(this.savingButton)),this.allowButton.insertAdjacentElement("beforeend",this.getIndicatorHolder()),Be(this.buttonIndicatorHolder,"beforeend",to("#FFFFFF")),We(this.allowButton,"disabled"),We(this.allowButton,_i)}removeSaveState(){this.allowButton.textContent=this.positiveUpdateButton??"",Le(`#${ki}`),this.allowButton.disabled=!1,Fe(this.allowButton,"disabled"),Fe(this.allowButton,_i)}setFailureState(){this.allowButton.textContent=null,this.allowButton.insertAdjacentElement("beforeend",this.getTextSpan(this.errorButton)),this.options.type===Tt&&(this.allowButton.insertAdjacentElement("beforeend",this.getIndicatorHolder()),Be(this.buttonIndicatorHolder,"beforeend",function(t="#FFFFFF"){return``}()),We(this.allowButton,"onesignal-error-state-button")),this.isShowingFailureState=!0}setFailureStateForInvalidChannelInput(t){switch(t){case 0:Xs.showSmsInputError(!0);break;case 1:Xs.showEmailInputError(!0);break;case 2:Xs.showSmsInputError(!0),Xs.showEmailInputError(!0)}}removeFailureState(){Le("#onesignal-button-indicator-holder"),Fe(this.allowButton,"onesignal-error-state-button"),$n(this.options.type)||Xs.resetInputErrorStates(this.options.type),this.isShowingFailureState=!1}getPlatformNotificationIcon(){return si(this.notificationIcons)}getIndicatorHolder(){const t=document.createElement("div");return t.id=Di,We(t,ki),t}getTextSpan(t){const e=document.createElement("span");return e.textContent=t,e}get container(){return Re(`#${Bi}`)}get dialog(){return Re(`#${Li}`)}get allowButton(){return Re(`#${Mi}`)}get cancelButton(){return Re(`#${Ui}`)}get buttonIndicatorHolder(){return Re(`#${Di}`)}get slidedownFooter(){return Re(`#${Ri}`)}static get EVENTS(){return{ALLOW_CLICK:"slidedownAllowClick",CANCEL_CLICK:"slidedownCancelClick",SHOWN:"slidedownShown",CLOSED:"slidedownClosed",QUEUED:"slidedownQueued"}}}class io{isNativePromptShowing;context;eventHooksInstalled;constructor(t){this.isNativePromptShowing=!1,this.context=t,this.eventHooksInstalled=!1}shouldForceSlidedownOverNative(){const t=x();return I()===g&&t>=63&&(v()||O())||C()}async spawnAutoPrompts(){const t=OneSignal.config?.userConfig.promptOptions,e=this.shouldForceSlidedownOverNative(),i=this.getDelayedPromptOptions(t,$t),n=this.isPageViewConditionMet(i),s=i.enabled&&n,o=e&&s;if(s&&!o)return void this.internalShowDelayedPrompt($t,i.timeDelay||0);const a=!!En(t?.slidedown?.prompts,Pt);o&&!a&&this.internalShowDelayedPrompt(Pt,i.timeDelay||0);const r=t?.slidedown?.prompts;if(r&&r?.length>0)for(let c=0;c0&&await ut(1e3*e),t){case $t:await this.internalShowNativePrompt();break;case Pt:await this.internalShowSlidedownPrompt(i);break;case Tt:await this.internalShowCategorySlidedown(i);break;case Nt:await this.internalShowSmsSlidedown(i);break;case Mt:await this.internalShowEmailSlidedown(i);break;case At:await this.internalShowSmsAndEmailSlidedown(i);break;default:pt.O("Invalid Delayed Prompt type")}else pt.O("internalShowDelayedPrompt: timeDelay not a number")}async internalShowNativePrompt(){if(ei("internalShowNativePrompt"),this.isNativePromptShowing)return pt.m("Already showing autoprompt. Abort showing a native prompt."),!1;this.isNativePromptShowing=!0;const t=await An();return this.isNativePromptShowing=!1,Ze(He),t}async internalShowSlidedownPrompt(t={force:!1}){ei("internalShowSlidedownPrompt"),t.slidedownPromptOptions||(t.slidedownPromptOptions=Kt),0===await this.context.K.loadSdkStylesheet()?(this.eventHooksInstalled||this.installEventHooksForSlidedown(),await this.context._e.createSlidedown(t)):pt.m("Not showing slidedown permission message because styles failed to load.")}async internalShowCategorySlidedown(t){ei("internalShowCategorySlidedown"),await this.internalShowParticularSlidedown(Tt,t)}async internalShowSmsSlidedown(t){ei("internalShowSmsSlidedown"),await this.internalShowParticularSlidedown(Nt,t)}async internalShowEmailSlidedown(t){ei("internalShowEmailSlidedown"),await this.internalShowParticularSlidedown(Mt,t)}async internalShowSmsAndEmailSlidedown(t){ei("internalShowSmsAndEmailSlidedown"),await this.internalShowParticularSlidedown(At,t)}async internalShowParticularSlidedown(t,e){const i=this.context.ot.userConfig.promptOptions?.slidedown?.prompts,n=e?.slidedownPromptOptions||En(i,t);if(!n){if(t!==Pt)return void pt.O(`OneSignal: slidedown of type '${t}' couldn't be shown. Check your configuration on the OneSignal dashboard or your custom code initialization.`);pt.v("The OneSignal 'push' slidedown will be shown with default text settings. To customize, see the OneSignal documentation.")}await this.internalShowSlidedownPrompt({...e,slidedownPromptOptions:n})}installEventHooksForSlidedown(){this.eventHooksInstalled=!0,OneSignal.emitter.on(eo.EVENTS.SHOWN,()=>{this.context._e.setIsSlidedownShowing(!0)}),OneSignal.emitter.on(eo.EVENTS.CLOSED,()=>{this.context._e.setIsSlidedownShowing(!1),this.context._e.showQueued()}),OneSignal.emitter.on(eo.EVENTS.ALLOW_CLICK,async()=>{await this.context._e.handleAllowClick(),ri.trigger(OneSignal.EVENTS.TEST_FINISHED_ALLOW_CLICK_HANDLING)}),OneSignal.emitter.on(eo.EVENTS.CANCEL_CLICK,()=>{if(!this.context._e.slidedown)return;const t=this.context._e.slidedown?.options.type;switch(t){case Pt:case Tt:pt.m("Setting flag to not show the slidedown to the user again."),Ze(He);break;default:pt.m("Setting flag to not show the slidedown to the user again."),Ze(qe)}})}isPageViewConditionMet(t){return!(!t||void 0===t.pageViews)&&(!(!t.autoPrompt||!t.enabled)&&$e()>=t.pageViews)}getDelayedPromptOptions(t,e){const i={enabled:!1,autoPrompt:!1,timeDelay:Dt.timeDelay,pageViews:Dt.pageViews};if(!t||!t.native||!t.slidedown)return i;switch(e){case $t:{const e=t.native;return{enabled:e?.enabled,autoPrompt:e?.autoPrompt,timeDelay:e?.timeDelay,pageViews:e?.pageViews}}case Pt:case Tt:case Mt:case Nt:case At:{const{userConfig:t}=this.context.ot,i=En(t.promptOptions?.slidedown?.prompts||[],e);return{enabled:!!i,autoPrompt:!!i?.autoPrompt,timeDelay:i?.delay?.timeDelay,pageViews:i?.delay?.pageViews}}default:return i}}}class no{static convertTagsApiToBooleans(t){const e={};return Object.keys(t).forEach(i=>{e[i]="1"===t[i]}),e}static convertTagsBooleansToApi(t){const e={};return Object.keys(t).forEach(i=>{e[i]=!0===t[i]?"1":"0"}),e}static getObjectDifference(t,e){const i={};return Object.keys(t).forEach(n=>{e[n]!==t[n]&&(i[n]=t[n])}),i}static markAllTagsAsSpecified(t,e){t.forEach(t=>{t.checked=e})}static isTagObjectEmpty(t){return 0===Object.keys(t).length}static getCheckedTagCategories(t,e){if(!e)return t;if(no.isTagObjectEmpty(e)){const e=structuredClone(t);return no.markAllTagsAsSpecified(e,!0),e}return structuredClone(t).map(t=>{const i=e[t.tag];return t.checked=no.getCheckedStatusForTagValue(i),t})}static getCheckedStatusForTagValue(t){return void 0===t||t}}class so{message;constructor(t){this.message=t}async show(){const t=document.createElement("div"),e=document.createElement("p");e.innerText=this.message,t.appendChild(e);const i=document.createElement("div"),n=document.createElement("div");i.id=Bi,t.id="onesignal-toast-text",We(t,"onesignal-toast-text"),We(i,Ii),We(i,Ci),Re("body").appendChild(i),n.id=Li,We(n,xi),n.appendChild(t),this.container.appendChild(n),We(this.container,O()?Ei:$i),so.triggerSlidedownEvent(so.EVENTS.SHOWN)}static async triggerSlidedownEvent(t){await ri.trigger(t)}close(){We(this.container,Pi),ii(this.dialog,"animationend",(t,e)=>{t.target!==this.dialog||"slideDownExit"!==t.animationName&&"slideUpExit"!==t.animationName||(Le(`#${Bi}`),e())},!0)}get container(){return Re(`#${Bi}`)}get dialog(){return Re(`#${Li}`)}static get EVENTS(){return{SHOWN:"toastShown",CLOSED:"toastClosed"}}}class oo{mount(t,e){const i=this.generateHtml(t,e);Re(`#${Ai}`).appendChild(i),this.taggingContainer&&this.taggingContainer.addEventListener("change",this.toggleCheckedTag);const n=Re(`#${Mi}`);n.disabled=!1,Fe(n,"disabled"),Le(`#${Wi}`)}load(){const t=Re(`#${Wi}`),e=Re(`#${Mi}`),i=document.createElement("div");We(t,"onesignal-loading-container"),We(i,"onesignal-loading-message"),We(e,"disabled"),Be(t,"beforeend",to("#95A1AC")),i.innerText="Fetching your preferences",t.appendChild(i),e.disabled=!0}generateHtml(t,e){const i=no.getCheckedTagCategories(t,e),n=i.filter(t=>i.indexOf(t)%2==0),s=i.filter(t=>i.indexOf(t)%2),o=document.createElement("div"),a=document.createElement("div"),r=document.createElement("div");return We(o,zi),We(a,zi),We(r,Ki),r.id="tagging-container",n.forEach(t=>{o.appendChild(this.getCategoryLabelElement(t))}),s.forEach(t=>{a.appendChild(this.getCategoryLabelElement(t))}),r.appendChild(o),r.appendChild(a),r}getCategoryLabelElement(t){const{label:e}=t,i=document.createElement("label"),n=document.createElement("span"),s=document.createElement("input"),o=document.createElement("span"),a=document.createElement("div"),r=document.createElement("div");return We(i,"onesignal-category-label"),We(n,"onesignal-category-label-text"),We(s,"onesignal-category-label-input"),We(o,"onesignal-checkmark"),i.title=e,n.innerText=e,s.type="checkbox",s.value=t.tag,s.checked=!!t.checked,i.appendChild(n),i.appendChild(s),i.appendChild(o),a.setAttribute("style","clear:both"),r.appendChild(i),r.appendChild(a),r}get taggingContainer(){return Re(`#${Ai} > div.${Ki}`)}toggleCheckedTag(t){const e=t.target;if(e&&"checkbox"===e.getAttribute("type")){const t=e.checked;e.setAttribute("checked",t.toString())}}static getValuesFromTaggingContainer(){const t=`#${Ai} > div.${Ki}> div > div > label > input[type=checkbox]`,e=document.querySelectorAll(t),i={};return e.forEach(t=>{i[t.value]=t.checked}),i}}class ao{context;slidedownQueue;isSlidedownShowing;slidedown;constructor(t){this.context=t,this.slidedownQueue=[],this.isSlidedownShowing=!1}async checkIfSlidedownShouldBeShown(t){const e="denied"===await OneSignal.context.P.getPermissionStatus();let i;const n=await OneSignal.context.U.getSubscriptionState(),{subscribed:s,optedOut:o}=n,a=t.slidedownPromptOptions?.type;let r=!1;if(a&&(r=$n(a)),r){if(s)return!!t.isInUpdateMode||(pt.S(new Error("User is already subscribed")),!1);if(i=Xe(He),o)throw new Error("User is opted out");if(e)return pt.S(tt),!1}else{if(!t.force){const t=await OneSignal.Z.hasSms(),e=await OneSignal.Z.hasEmail(),i=t&&e;if(t&&a===Nt)return pt.S(nt(Nt)),!1;if(e&&a===Mt)return pt.S(nt(Mt)),!1;if(i&&a===At)return pt.S(nt(At)),!1}i=Xe(qe)}return!(i&&!t.force&&!t.isInUpdateMode&&(pt.S(new Error(`${a||"unknown"} was previously dismissed`)),1))}async handleAllowForCategoryType(){if(!this.slidedown)throw ro;const t=oo.getValuesFromTaggingContainer();this.context.rt.storeTagValuesToUpdate(t),An(),await this.context.rt.sendTags(!0)}async handleAllowForEmailType(){if(!this.slidedown)throw ro;const t=this.slidedown.channelCaptureContainer?.emailInputFieldIsValid,e=this.slidedown.channelCaptureContainer?.isEmailInputFieldEmpty();if(!t||e)throw new Q(1);const i=this.slidedown.channelCaptureContainer?.getValueFromEmailInput();this.updateEmail(i)}async handleAllowForSmsType(){if(!this.slidedown)throw ro;const t=this.slidedown.channelCaptureContainer?.smsInputFieldIsValid,e=this.slidedown.channelCaptureContainer?.isSmsInputFieldEmpty();if(!t||e)throw new Q(0);const i=this.slidedown.channelCaptureContainer?.getValueFromSmsInput();this.updateSMS(i)}async handleAllowForSmsAndEmailType(){if(!this.slidedown)throw ro;const t=this.slidedown.channelCaptureContainer?.smsInputFieldIsValid,e=this.slidedown.channelCaptureContainer?.emailInputFieldIsValid,i=this.slidedown.channelCaptureContainer?.isEmailInputFieldEmpty(),n=this.slidedown.channelCaptureContainer?.isSmsInputFieldEmpty();if(!t&&!e||i&&n)throw new Q(2);const s=this.slidedown.channelCaptureContainer?.getValueFromEmailInput(),o=this.slidedown.channelCaptureContainer?.getValueFromSmsInput();if(!e)throw new Q(1);if(i||this.updateEmail(s),!t)throw new Q(0);n||this.updateSMS(o)}updateEmail(t){t&&OneSignal.User.addEmail(t)}updateSMS(t){t&&OneSignal.User.addSms(t)}async showConfirmationToast(){if(!this.slidedown)throw ro;const t=this.slidedown.options.text.confirmMessage;if(!t)return;await ut(1e3);const e=new so(t);await e.show(),await ut(5e3),e.close(),so.triggerSlidedownEvent(so.EVENTS.CLOSED)}async mountAuxiliaryContainers(t){switch(t.slidedownPromptOptions?.type){case Tt:this.mountTaggingContainer(t);break;case Mt:case Nt:case At:await this.mountChannelCaptureContainer(t)}}async mountTaggingContainer(t){ei("mountTaggingContainer");try{let e={};const i=new oo,n=t.slidedownPromptOptions?.categories;if(!n)throw new Error("Categories not defined");const s=OneSignal.Z.et().tags;t.isInUpdateMode&&s?(this.context.rt.storeRemotePlayerTags(s),e=no.convertTagsApiToBooleans(s)):no.markAllTagsAsSpecified(n,!0),i.mount(n,e)}catch(e){pt.O("OneSignal: Attempted to create tagging container with error",e)}}async mountChannelCaptureContainer(t){ei("mountChannelCaptureContainer");try{if(t.slidedownPromptOptions){const e=new Xs(t.slidedownPromptOptions);e.mount(),this.slidedown&&(this.slidedown.channelCaptureContainer=e)}}catch(e){pt.O("OneSignal: Attempted to create channel capture container with error",e)}}async handleAllowClick(){if(!this.slidedown)throw ro;const t=this.slidedown.options.type;this.slidedown.isShowingFailureState&&this.slidedown.removeFailureState();try{switch(t){case Pt:An();break;case Tt:await this.handleAllowForCategoryType();break;case Mt:await this.handleAllowForEmailType();break;case Nt:await this.handleAllowForSmsType();break;case At:await this.handleAllowForSmsAndEmailType()}}catch(e){return pt.v("OneSignal Slidedown failed to update:",e),this.slidedown.removeSaveState(),this.slidedown.setFailureState(),void(e instanceof Q&&this.slidedown.setFailureStateForInvalidChannelInput(e.reason))}switch(this.slidedown&&(this.slidedown.close(),$n(t)||await this.showConfirmationToast(),await ut(1e3),eo.triggerSlidedownEvent(eo.EVENTS.CLOSED)),t){case Pt:case Tt:pt.m("Setting flag to not show the slidedown to the user again."),Ze(He);break;default:pt.m("Setting flag to not show the slidedown to the user again."),Ze(qe)}}setIsSlidedownShowing(t){this.isSlidedownShowing=t}async showQueued(){if(this.slidedownQueue.length>0){const t=this.dequeue();t&&await this.createSlidedown(t)}}enqueue(t){this.slidedownQueue.push(t),eo.triggerSlidedownEvent(eo.EVENTS.QUEUED)}dequeue(){return this.slidedownQueue.shift()}async createSlidedown(t){if(ei("createSlidedown"),!Me()){try{if(!(await this.checkIfSlidedownShouldBeShown(t)))return}catch(e){return void pt.v("checkIfSlidedownShouldBeShown returned an error",e)}if(function(){const t=OneSignal.notifyButton;t&&t.options?.enable&&OneSignal.notifyButton?.launcher?.shown&&OneSignal.notifyButton?.launcher?.show().then(()=>{OneSignal.notifyButton?.launcher?.hide()}),OneSignal.emitter.once(eo.EVENTS.CLOSED,()=>{OneSignal.notifyButton&&OneSignal.notifyButton.options.enable&&OneSignal.notifyButton.launcher.show()})}(),this.isSlidedownShowing)this.enqueue(t);else try{this.setIsSlidedownShowing(!0);const e=t.slidedownPromptOptions||Kt;this.slidedown=new eo(e),await this.slidedown.create(t.isInUpdateMode),await this.mountAuxiliaryContainers(t),pt.m("Showing OneSignal Slidedown"),eo.triggerSlidedownEvent(eo.EVENTS.SHOWN)}catch(e){pt.O("There was an error showing the OneSignal Slidedown:",e),this.setIsSlidedownShowing(!1),this.slidedown?.close()}}}}const ro=new Error("Slidedown is missing");class co{tagsFromTaggingContainer={};context;remoteTags={};constructor(t){this.context=t}async sendTags(){pt.S("Category Slidedown Local Tags:",this.tagsFromTaggingContainer);const t=no.convertTagsBooleansToApi(this.tagsFromTaggingContainer),e=no.getObjectDifference(t,this.remoteTags);return no.isTagObjectEmpty(e)?(pt.v("OneSignal: no change detected in Category preferences. Skipping tag update."),e):(await OneSignal.User.addTags(e),e)}storeTagValuesToUpdate(t){this.tagsFromTaggingContainer=t}storeRemotePlayerTags(t){this.context.rt.remoteTags=t}}class lo{ot;K;U;N;ge;P;gt;promptsManager;dt;rt;_e;constructor(t){var e;this.ot=t,this.U=new Js(this,{safariWebId:(e=this.ot).safariWebId,appId:e.appId,vapidPublicKey:e.vapidPublicKey,onesignalVapidPublicKey:e.onesignalVapidPublicKey}),this.N=function(t){const e=t.ot,i={workerPath:new Bs(Et),registrationOptions:_t};return e.userConfig&&(e.userConfig.path&&(i.workerPath=new Bs(`${e.userConfig.path}${e.userConfig.serviceWorkerPath}`)),e.userConfig.serviceWorkerParam&&(i.registrationOptions=e.userConfig.serviceWorkerParam)),new Vs(t,i)}(this),this.P=new Ys,this.ge=new Us(this),this.gt=new Zs(this),this.dt=new Qs(this),this.rt=new co(this),this._e=new ao(this),this.promptsManager=new io(this),this.K=new gi}}class uo{setLogLevel(t){pt.h(t)}}class ho extends hn{Y;Ee;constructor(t){super(),this.Ee=t,this.Y="granted"===t,"undefined"!=typeof OneSignal&&OneSignal.emitter.on(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,t=>{this.Ee=t,this.Y="granted"===t})}get permissionNative(){return this.Ee}get permission(){return this.Y}async setDefaultUrl(t){if(ei("setDefaultUrl",t),void 0===t)throw st("url");if("string"!=typeof t)throw at("url");if(!ct(t,{allowNull:!0}))throw ot("url");await ti(),ei("setDefaultNotificationUrl",t);const e=await Te();e.defaultNotificationUrl=t,await Ne(e)}async setDefaultTitle(t){if(ei("setDefaultTitle",t),void 0===t)throw st("title");if("string"!=typeof t)throw at("title");await ti();const e=await Te();e.defaultNotificationTitle=t,await Ne(e)}isPushSupported(){return ei("isPushNotificationsSupported"),!0}async requestPermission(){return!Me()&&(await ti(),await OneSignal.context.promptsManager.internalShowNativePrompt())}addEventListener(t,e){OneSignal.emitter.on(t,e)}removeEventListener(t,e){OneSignal.emitter.off(t,e)}}const go={NOTIFICATION_PERMISSION_CHANGED_AS_STRING:"permissionChangeAsString",NOTIFICATION_PERMISSION_CHANGED_AS_BOOLEAN:"permissionChange",SUBSCRIPTION_CHANGED:"change",WELCOME_NOTIFICATION_SENT:"sendWelcomeNotification",NOTIFICATION_WILL_DISPLAY:"foregroundWillDisplay",NOTIFICATION_DISMISSED:"dismiss",NOTIFICATION_CLICKED:"click",SDK_INITIALIZED:"initializeInternal",SDK_INITIALIZED_PUBLIC:"initialize",REGISTERED:"register",PERMISSION_PROMPT_DISPLAYED:"permissionPromptDisplay",TEST_FINISHED_ALLOW_CLICK_HANDLING:"testFinishedAllowClickHandling",SESSION_STARTED:"os.sessionStarted"};class po{async sendOutcome(t,e){const i=OneSignal.config?.userConfig.outcomes;if(!i)return void pt.O(`Could not send ${t}. No outcomes config found.`);const n=new Ls(OneSignal.config.appId,i,t,!1);if(void 0!==e&&"number"!=typeof e)return void pt.O("Outcome weight can only be a number if present.");if(!(await n.beforeOutcomeSend()))return;const s=await n.getAttribution();await n.send({type:s.type,notificationIds:s.notificationIds,weight:e})}async sendUniqueOutcome(t){const e=OneSignal.config?.userConfig.outcomes;if(!e)return void pt.O(`Could not send ${t}. No outcomes config found.`);const i=new Ls(OneSignal.config.appId,e,t,!0);if(!(await i.beforeOutcomeSend()))return;const n=await i.getAttribution();if(4===n.type)return void pt.v("You are on a free plan. Please upgrade to use this functionality.");const{notificationIds:s}=n,o=await i.getNotifsToAttributeWithUniqueOutcome(s);i.shouldSendUnique(n,o)?await i.send({type:n.type,notificationIds:o}):pt.v(`'${t}' was already reported for all notifications.`)}}class wo extends hn{constructor(){super()}async promptPush(t){Me()||(await ti(),await OneSignal.context.promptsManager.internalShowParticularSlidedown(Pt,t))}async promptPushCategories(t){if(Me())return;await ti();const e=await OneSignal.context.U.isPushNotificationsEnabled();await OneSignal.context.promptsManager.internalShowCategorySlidedown({...t,isInUpdateMode:e})}async promptSms(t){Me()||(await ti(),await OneSignal.context.promptsManager.internalShowSmsSlidedown({...t}))}async promptEmail(t){Me()||(await ti(),await OneSignal.context.promptsManager.internalShowEmailSlidedown({...t}))}async promptSmsAndEmail(t){Me()||(await ti(),await OneSignal.context.promptsManager.internalShowSmsAndEmailSlidedown({...t}))}addEventListener(t,e){OneSignal.emitter.on(t,e)}removeEventListener(t,e){OneSignal.emitter.off(t,e)}}let fo=class t{static EVENTS=go;static I=!1;static async $e(){const e=new _s;await e.init(),t.Z=new Ps(e);const i=await De(),n=await t.context.P.getPermissionStatus();t.User=new Cn(!0,i,n),this.Notifications=new ho(n)}static async Pe(e){const i=await Yt(e);pt.m("OneSignal: Final web app config:",i),t.config=i,t.context=new lo(i),t.config=t.context.ot}static async login(t,e){if(ei("login",{externalId:t,jwtToken:e}),!Me()){if(void 0===t)throw st("externalId");if("string"!=typeof t)throw at("externalId");if(void 0!==e&&"string"!=typeof e)throw at("jwtToken");await Ns.login(t,e)}}static async logout(){ei("logout"),Me()||await Ns.logout()}static async init(e){if(ei("init"),pt.m(`Browser Environment: ${I()} ${x()}`),localStorage.removeItem("isOptedOut"),localStorage.removeItem("isPushNotificationsEnabled"),function(){if(OneSignal.Te)throw new Error("SDK already initialized");OneSignal.Te=!0}(),await t.Pe(e),!t.config)throw new Error("OneSignal config not initialized!");I()!==w||t.config.safariWebId?(await t.$e(),t.I=await(async()=>await Ie("userConsent")??!1)(),!Ee()||t.I?await t.Ne():t.pendingInit=!0):pt.v(it)}static async Ne(){async function e(){t.Me||(t.Me=!0,t.emitter.on(t.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,Pn),t.emitter.on(t.EVENTS.SUBSCRIPTION_CHANGED,Tn),t.emitter.on(t.EVENTS.SDK_INITIALIZED,Dn),window.addEventListener("focus",()=>{di.checkAndTriggerNotificationPermissionChanged()}),await async function(){const t=di.getAppId(),e=OneSignal.config;await ke.put("Ids",{type:"appId",id:t});const i=e.siteName||document.title||"Notification";await ke.put("Options",{key:"pageTitle",value:i}),pt.S(`OneSignal: Set pageTitle to be '${i}'.`)}(),await async function(){const t=[],e=OneSignal.config?.userConfig.persistNotification;t.push(ke.put("Options",{key:"persistNotification",value:null==e||e}));const i=OneSignal.config?.userConfig.webhooks;return["notification.willDisplay","notification.clicked","notification.dismissed"].forEach(e=>{i&&i[e]?t.push(ke.put("Options",{key:`webhooks.${e}`,value:i[e]})):t.push(ke.put("Options",{key:`webhooks.${e}`,value:!1}))}),i&&i.cors?t.push(ke.put("Options",{key:"webhooks.cors",value:!0})):t.push(ke.put("Options",{key:"webhooks.cors",value:!1})),OneSignal.config?.userConfig.notificationClickHandlerMatch?t.push(ke.put("Options",{key:"notificationClickHandlerMatch",value:OneSignal.config.userConfig.notificationClickHandlerMatch})):t.push(ke.put("Options",{key:"notificationClickHandlerMatch",value:"exact"})),OneSignal.config?.userConfig.notificationClickHandlerAction?t.push(ke.put("Options",{key:"notificationClickHandlerAction",value:OneSignal.config.userConfig.notificationClickHandlerAction})):t.push(ke.put("Options",{key:"notificationClickHandlerAction",value:"navigate"})),Promise.all(t)}(),await async function(){pt.m("Called internalInit()"),await OneSignal.context.N.be();const t=OneSignal.context.dt;OneSignal.emitter.on(OneSignal.EVENTS.SESSION_STARTED,t.sendOnSessionUpdateFromPage.bind(t)),ln(),"visible"===document.visibilityState?await Mn():ii(document,"visibilitychange",(t,e)=>{"visible"===document.visibilityState&&(e(),Mn())},!0)}())}t.pendingInit=!1,t.context.ge.listen(),"complete"===document.readyState||"interactive"===document.readyState?await e():(pt.m("OneSignal: Waiting for DOMContentLoaded or readyStateChange event before continuing initialization..."),window.addEventListener("DOMContentLoaded",()=>{e()}),document.onreadystatechange=()=>{"complete"!==document.readyState&&"interactive"!==document.readyState||e()})}static async setConsentGiven(e){if(ei("setConsentGiven",{consent:e}),void 0===e)throw st("consent");if("boolean"!=typeof e)throw at("consent");t.I=e,await ke.put("Options",{key:"userConsent",value:e}),e&&t.pendingInit&&await t.Ne()}static async setConsentRequired(t){if(ei("setConsentRequired",{requiresConsent:t}),void 0===t)throw st("requiresConsent");if("boolean"!=typeof t)throw at("requiresConsent");var e;e=t,localStorage.setItem(_e,e.toString())}static async push(e){return function(t,e){if("function"==typeof e)return e(t);throw new Error("Callback is not a function")}(t,e)}static B;static VERSION=_;static config=null;static lt=!1;static k=!1;static initialized=!1;static Ce=!1;static notifyButton=null;static database=ke;static pendingInit=!0;static emitter=new oi;static cache={};static Te=!1;static Me=!1;static context;static Z;static Notifications=new ho;static Slidedown=new wo;static Session=new po;static User=new Cn(!1);static Debug=new uo};pt.S(`OneSignal Web SDK loaded (version ${_},\n ${T} environment).`),pt.m(`Current Page URL: ${"undefined"==typeof location?"NodeJS":location.href}`),function(){if(window.__oneSignalSdkLoadCount=ni()+1,ni()>1)return pt.v("OneSignal: The web push SDK is included more than once. For optimal performance, please include our SDK only once on your page."),void pt.m(`OneSignal: Exiting from SDK initialization to prevent double-initialization errors. Occurred ${ni()} times.`);window.OneSignal=fo,window.OneSignalDeferred=window.OneSignalDeferred??[];const t=async function(t){for(const i of t)try{await fo.push(i)}catch(e){pt.O(e)}}(window.OneSignalDeferred);Object.defineProperty(window.OneSignalDeferred,"push",{value:async function(e){return await t,fo.push(e)}})}()}(); //# sourceMappingURL=OneSignalSDK.page.es6.js.map