(function(){"use strict";class Ot{_events;constructor(){this._events={}}on(e,t){return this._events[e]=this._events[e]||[],this._events[e].push(t),this}once(e,t){const i=this;function n(){i.off(e,n),t.apply(this,arguments)}return n.listener=t,this.on(e,n),this}off(e,t){const i=this._events[e];if(i!==void 0){for(let n=0;n(s.Identity="identity",s.Properties="properties",s.Subscriptions="subscriptions",s))(E||{}),dt=(s=>(s.PushSubscriptions="pushSubscriptions",s.EmailSubscriptions="emailSubscriptions",s.SmsSubscriptions="smsSubscriptions",s))(dt||{});class S extends Error{constructor(e=""){super(e),Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:this.constructor.name,writable:!0}),Object.defineProperty(this,"stack",{configurable:!0,enumerable:!1,value:new Error(e).stack,writable:!0}),Object.setPrototypeOf(this,S.prototype)}}class Ft extends S{constructor(e="The asynchronous operation has timed out."){super(e),this.message=e,Object.setPrototypeOf(this,Ft.prototype)}}class y{static contains(e,t){return e?e.indexOf(t)!==-1:!1}static trimUndefined(e){for(const t in e)e[t]===void 0&&delete e[t];return e}static capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}static isNullOrUndefined(e){return typeof e>"u"||e===null}static valueOrDefault(e,t){return typeof e>"u"||e===null?t:e}static stringify(e){return JSON.stringify(e,(t,i)=>typeof i=="function"?"[Function]":i,4)}static encodeHashAsUriComponent(e){let t="";const i=Object.keys(e);for(const n of i){const o=e[n];t+=`${encodeURIComponent(n)}=${encodeURIComponent(o)}`}return t}static timeoutPromise(e,t){const i=new Promise((n,o)=>{setTimeout(()=>{o(new Ft)},t)});return Promise.race([e,i])}static getValueOrDefault(e,t){return e??t}static padStart(e,t,i){let n=e;for(;n.length{const d=t(a),l=t(c);return d>l?i?-1:1:d"u"||typeof window.localStorage>"u")return!1;const e=window.localStorage.getItem("loglevel");return!!(e&&e.toLowerCase()==="trace")}catch{return!1}}static setLevel(e){if(!(typeof window>"u"||typeof window.localStorage>"u"))try{window.localStorage.setItem("loglevel",e),$e.proxyMethodsCreated=void 0,$e.createProxyMethods()}catch{return}}static createProxyMethods(){if(typeof $e.proxyMethodsCreated<"u")return;$e.proxyMethodsCreated=!0;const e={log:"debug",trace:"trace",info:"info",warn:"warn",error:"error"};for(const t of Object.keys(e)){const i=typeof console[t]<"u",n=e[t];i&&($e.shouldLog()||n==="error")?$e[n]=console[t].bind(console):$e[n]=function(){}}}};r.createProxyMethods();const an=6;class rn{constructor(e,t=an){this.databaseName=e,this.dbVersion=t,this.emitter=new Ot}emitter;database;openLock;open(e){return new Promise(t=>{let i;try{i=indexedDB.open(e,this.dbVersion)}catch{}if(!i)return null;i.onerror=this.onDatabaseOpenError.bind(this),i.onblocked=this.onDatabaseOpenBlocked.bind(this),i.onupgradeneeded=this.onDatabaseUpgradeNeeded.bind(this),i.onsuccess=()=>{this.database=i.result,this.database.onerror=this.onDatabaseError,this.database.onversionchange=this.onDatabaseVersionChange,t(this.database)}})}async close(){(await this.ensureDatabaseOpen()).close(),this.database?.close()}async ensureDatabaseOpen(){return this.openLock||(this.openLock=this.open(this.databaseName)),await this.openLock}onDatabaseOpenError(e){e.preventDefault();const t=e.target.error;y.contains(t.message,"The operation failed for reasons unrelated to the database itself and not covered by any other error code")||y.contains(t.message,"A mutation operation was attempted on a database that did not allow mutations")?r.warn("OneSignal: IndexedDb web storage is not available on this origin since this profile's IndexedDb schema has been upgraded in a newer version of Firefox. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1236557#c6"):r.warn("OneSignal: Fatal error opening IndexedDb database:",t)}objectStoreNames(){return Array.from(this.database?.objectStoreNames||[])}onDatabaseError(e){r.debug("IndexedDb: Generic database error",e.target.errorCode)}onDatabaseOpenBlocked(){r.debug("IndexedDb: Blocked event")}onDatabaseVersionChange(){r.debug("IndexedDb: versionchange event")}onDatabaseUpgradeNeeded(e){r.debug("IndexedDb: Database is being rebuilt or upgraded (upgradeneeded event).");const t=e.target,i=t.transaction;if(!i)throw Error("Can't migrate DB without a transaction");const n=t.result,o=e.newVersion||Number.MAX_SAFE_INTEGER;o>=1&&e.oldVersion<1&&(n.createObjectStore("Ids",{keyPath:"type"}),n.createObjectStore("NotificationOpened",{keyPath:"url"}),n.createObjectStore("Options",{keyPath:"key"})),o>=2&&e.oldVersion<2&&(n.createObjectStore("Sessions",{keyPath:"sessionKey"}),n.createObjectStore("NotificationReceived",{keyPath:"notificationId"}),n.createObjectStore("NotificationClicked",{keyPath:"notificationId"})),o>=3&&e.oldVersion<3&&n.createObjectStore("SentUniqueOutcome",{keyPath:"outcomeName"}),o>=4&&e.oldVersion<4&&(n.createObjectStore(E.Identity,{keyPath:"modelId"}),n.createObjectStore(E.Properties,{keyPath:"modelId"}),n.createObjectStore(dt.PushSubscriptions,{keyPath:"modelId"}),n.createObjectStore(dt.SmsSubscriptions,{keyPath:"modelId"}),n.createObjectStore(dt.EmailSubscriptions,{keyPath:"modelId"})),o>=5&&e.oldVersion<5&&(this.migrateOutcomesNotificationClickedTableForV5(n,i),this.migrateOutcomesNotificationReceivedTableForV5(n,i)),o>=6&&e.oldVersion<6&&this.migrateModelNameSubscriptionsTableForV6(n,i),o>=7&&e.oldVersion<7,typeof OneSignal<"u"&&(OneSignal._isNewVisitor=!0)}migrateOutcomesNotificationClickedTableForV5(e,t){const i="Outcomes.NotificationClicked";e.createObjectStore(i,{keyPath:"notificationId"});const n="NotificationClicked",o=t.objectStore(n).openCursor();o.onsuccess=()=>{if(!o.result){e.deleteObjectStore(n);return}const a=o.result.value;t.objectStore(i).put({notificationId:a.notificationId||a.notification.id,appId:a.appId,timestamp:a.timestamp}),o.result.continue()},o.onerror=()=>{console.error("Could not migrate NotificationClicked records",o.error)}}migrateOutcomesNotificationReceivedTableForV5(e,t){const i="Outcomes.NotificationReceived";e.createObjectStore(i,{keyPath:"notificationId"});const n="NotificationReceived",o=t.objectStore(n).openCursor();o.onsuccess=()=>{if(!o.result){e.deleteObjectStore(n);return}t.objectStore(i).put(o.result.value),o.result.continue()},o.onerror=()=>{console.error("Could not migrate NotificationReceived records",o.error)}}migrateModelNameSubscriptionsTableForV6(e,t){const i=E.Subscriptions;e.createObjectStore(i,{keyPath:"modelId"});let n;const o=t.objectStore(E.Identity).openCursor();o.onsuccess=()=>{o.result&&(n=o.result.value.externalId)},o.onerror=()=>{console.error("Could not find "+E.Identity+" records",o.error)},Object.values(dt).forEach(a=>{const c=t.objectStore(a).openCursor();c.onsuccess=()=>{if(!c.result){e.deleteObjectStore(a);return}const d=c.result.value;t.objectStore(i).put({...d,modelName:E.Subscriptions,externalId:n}),c.result.continue()},c.onerror=()=>{console.error("Could not migrate "+a+" records",c.error)}})}async dbOperation(e,t,i){const n=await this.ensureDatabaseOpen();return await new Promise((o,a)=>{try{const c=n.transaction(e,t==="get"||t==="getAll"?"readonly":"readwrite").objectStore(e),d=t==="getAll"||t==="clear"?c[t]():c[t](i);d.onsuccess=()=>{o(d.result)},d.onerror=l=>{r.error("Database "+t.toUpperCase()+" Transaction Error:",l),a(l)}}catch(c){r.error("Database "+t.toUpperCase()+" Error:",c),a(c)}})}async get(e,t){return t?this.dbOperation(e,"get",t):this.dbOperation(e,"getAll")}async getAll(e){return this.dbOperation(e,"getAll")}async put(e,t){return this.dbOperation(e,"put",t)}async remove(e,t){return t?this.dbOperation(e,"delete",t):this.dbOperation(e,"clear")}}class cn{defaultNotificationUrl;defaultNotificationTitle;lastKnownPushEnabled;lastKnownPushToken;lastKnownPushId;lastKnownOptedIn=!0;pendingNotificationClickEvents}class ln{previousOneSignalId;previousExternalId}class $t{deviceId;subscriptionToken;optedOut;createdAt;expirationTime;serialize(){return{deviceId:this.deviceId,subscriptionToken:this.subscriptionToken,optedOut:this.optedOut,createdAt:this.createdAt,expirationTime:this.expirationTime}}static deserialize(e){const t=new $t;return t.deviceId=e.deviceId,t.subscriptionToken=e.subscriptionToken,t.optedOut=e.optedOut,t.createdAt=e.createdAt,t.expirationTime=e.expirationTime,t}}var Xe=(s=>(s.Active="active",s.Inactive="inactive",s))(Xe||{}),Oe=(s=>(s[s.UserCreate=1]="UserCreate",s[s.UserNewSession=2]="UserNewSession",s[s.VisibilityVisible=3]="VisibilityVisible",s[s.VisibilityHidden=4]="VisibilityHidden",s[s.BeforeUnload=5]="BeforeUnload",s[s.PageRefresh=6]="PageRefresh",s[s.Focus=7]="Focus",s[s.Blur=8]="Blur",s))(Oe||{});const Ht="oneSignalSession";function Oi(s){const e=new Date().getTime(),t=s&&s.notificationId||null;return{accumulatedDuration:0,appId:s.appId,lastActivatedTimestamp:e,lastDeactivatedTimestamp:null,notificationId:t,sessionKey:Ht,startTimestamp:e,status:"active"}}class Ei{static toDatabase(e){const t=e.notification,i=e.result;return{action:i.actionId,badge:t.badgeIcon,buttons:this.toDatabaseButtons(t.actionButtons),content:t.body,data:t.additionalData,heading:t.title,icon:t.icon,id:t.notificationId,image:t.image,rr:t.confirmDelivery,tag:t.topic,timestamp:e.timestamp,url:i.url}}static toDatabaseButtons(e){return e?.map(t=>({action:t.actionId,title:t.text,icon:t.icon,url:t.launchURL}))}static fromDatabase(e){return{result:{actionId:e.action,url:e.url},notification:{notificationId:e.id,title:e.heading,body:e.content,additionalData:e.data,launchURL:e.url,confirmDelivery:e.rr,icon:e.icon,image:e.image,topic:e.tag,badgeIcon:e.badge,actionButtons:this.toOSNotificationButtons(e.buttons)},timestamp:e.timestamp}}static toOSNotificationButtons(e){return e?.map(t=>({actionId:t.action,text:t.title,icon:t.icon,launchURL:t.url}))}}class Ci{static toDatabase(e,t){return{appId:e,notificationId:t.notification.notificationId,timestamp:t.timestamp}}static fromDatabase(e){return{appId:e.appId,notificationId:e.notificationId,timestamp:e.timestamp}}}class Ti{static toDatabase(e,t,i){return{appId:e,notificationId:t.notificationId,timestamp:i}}static fromDatabase(e){return{appId:e.appId,notificationId:e.notificationId,timestamp:e.timestamp}}}var Pi=(s=>(s[s.SET=0]="SET",s))(Pi||{});const dn="ONE_SIGNAL_SDK_DB",Et="Outcomes.NotificationClicked",Ct="Outcomes.NotificationReceived",ut="NotificationOpened",jt="Sessions";class u{constructor(e){this.databaseName=e,this.emitter=new Ot,this.database=new rn(this.databaseName)}emitter;database;static databaseInstanceName;static databaseInstance;static EVENTS=Pi;static resetInstance(){u.databaseInstance=null}static get singletonInstance(){return u.databaseInstanceName||(u.databaseInstanceName=dn),u.databaseInstance||(u.databaseInstance=new u(u.databaseInstanceName)),u.databaseInstance}static applyDbResultFilter(e,t,i){switch(e){case"Options":return i&&t?i.value:i&&!t?i:null;case"Ids":return i&&t?i.id:i&&!t?i:null;default:return i||null}}async get(e,t){const i=await this.database.get(e,t);return u.applyDbResultFilter(e,t,i)}async getAll(e){return await this.database.getAll(e)}async put(e,t){await new Promise(i=>{this.database.put(e,t).then(()=>i())}),this.emitter.emit(u.EVENTS.SET,t)}remove(e,t){return this.database.remove(e,t)}async getAppConfig(){const e={},t=await this.get("Ids","appId");return e.appId=t,e.vapidPublicKey=await this.get("Options","vapidPublicKey"),e}async setAppConfig(e){e.appId&&await this.put("Ids",{type:"appId",id:e.appId}),e.vapidPublicKey&&await this.put("Options",{key:"vapidPublicKey",value:e.vapidPublicKey})}async getAppState(){const e=new cn;return e.defaultNotificationUrl=await this.get("Options","defaultUrl"),e.defaultNotificationTitle=await this.get("Options","defaultTitle"),e.lastKnownPushEnabled=await this.get("Options","isPushEnabled"),e.pendingNotificationClickEvents=await this.getAllPendingNotificationClickEvents(),e.lastKnownPushId=await this.get("Options","lastPushId"),e.lastKnownPushToken=await this.get("Options","lastPushToken"),e.lastKnownOptedIn=await this.get("Options","lastOptedIn"),e}async setIsPushEnabled(e){await this.put("Options",{key:"isPushEnabled",value:e})}async setAppState(e){if(e.defaultNotificationUrl&&await this.put("Options",{key:"defaultUrl",value:e.defaultNotificationUrl}),(e.defaultNotificationTitle||e.defaultNotificationTitle==="")&&await this.put("Options",{key:"defaultTitle",value:e.defaultNotificationTitle}),e.lastKnownPushEnabled!=null&&await this.setIsPushEnabled(e.lastKnownPushEnabled),e.lastKnownPushId!=null&&await this.put("Options",{key:"lastPushId",value:e.lastKnownPushId}),e.lastKnownPushToken!=null&&await this.put("Options",{key:"lastPushToken",value:e.lastKnownPushToken}),e.lastKnownOptedIn!=null&&await this.put("Options",{key:"lastOptedIn",value:e.lastKnownOptedIn}),e.pendingNotificationClickEvents){const t=Object.keys(e.pendingNotificationClickEvents);for(const i of t){const n=e.pendingNotificationClickEvents[i];n?await this.put(ut,{url:i,data:n.data,timestamp:n.timestamp}):n===null&&await this.remove(ut,i)}}}async getUserState(){const e=new ln;return e.previousOneSignalId="",e.previousExternalId="",e.previousOneSignalId=await this.get("Options","previousOneSignalId"),e.previousExternalId=await this.get("Options","previousExternalId"),e}async setUserState(e){await this.put("Options",{key:"previousOneSignalId",value:e.previousOneSignalId}),await this.put("Options",{key:"previousExternalId",value:e.previousExternalId})}async getSubscription(){const e=new $t;e.deviceId=await this.get("Ids","userId"),e.subscriptionToken=await this.get("Ids","registrationId");const t=await this.get("Options","optedOut"),i=await this.get("Options","subscription"),n=await this.get("Options","subscriptionCreatedAt"),o=await this.get("Options","subscriptionExpirationTime");return t!=null?e.optedOut=t:i==null?e.optedOut=!1:e.optedOut=!i,e.createdAt=n,e.expirationTime=o,e}async setDeviceId(e){await this.put("Ids",{type:"userId",id:e})}async setSubscription(e){e.deviceId&&await this.setDeviceId(e.deviceId),typeof e.subscriptionToken<"u"&&await this.put("Ids",{type:"registrationId",id:e.subscriptionToken}),e.optedOut!=null&&await this.put("Options",{key:"optedOut",value:e.optedOut}),e.createdAt!=null&&await this.put("Options",{key:"subscriptionCreatedAt",value:e.createdAt}),e.expirationTime!=null?await this.put("Options",{key:"subscriptionExpirationTime",value:e.expirationTime}):await this.remove("Options","subscriptionExpirationTime")}async setJWTToken(e){await this.put("Ids",{type:"jwtToken",id:e})}async getJWTToken(){return await this.get("Ids","jwtToken")}async setProvideUserConsent(e){await this.put("Options",{key:"userConsent",value:e})}async getConsentGiven(){return await this.get("Options","userConsent")}async getSession(e){return await this.get(jt,e)}async setSession(e){await this.put(jt,e)}async removeSession(e){await this.remove(jt,e)}async getLastNotificationClickedForOutcomes(e){let t=[];try{t=await this.getAllNotificationClickedForOutcomes()}catch(n){r.error("Database.getLastNotificationClickedForOutcomes",n)}const i=n=>n.appId===e;return t.find(i)||null}async getAllNotificationClickedForOutcomes(){return(await this.getAll(Et)).map(t=>Ci.fromDatabase(t))}async putNotificationClickedForOutcomes(e,t){await this.put(Et,Ci.toDatabase(e,t))}async putNotificationClickedEventPendingUrlOpening(e){await this.put(ut,Ei.toDatabase(e))}async getAllPendingNotificationClickEvents(){const e={},t=await this.getAll(ut);for(const i of t){const n=Ei.fromDatabase(i),o=n.result.url;o&&(e[o]=n)}return e}async removeAllNotificationClickedForOutcomes(){await this.remove(Et)}async getAllNotificationReceivedForOutcomes(){return(await this.getAll(Ct)).map(t=>Ti.fromDatabase(t))}async putNotificationReceivedForOutcomes(e,t){await this.put(Ct,Ti.toDatabase(e,t,new Date().getTime()))}async resetSentUniqueOutcomes(){const t=(await this.getAll("SentUniqueOutcome")).map(i=>(i.sentDuringSession=null,u.put("SentUniqueOutcome",i)));await Promise.all(t)}static async rebuild(){return Promise.all([u.singletonInstance.remove("Ids"),u.singletonInstance.remove(ut),u.singletonInstance.remove("Options"),u.singletonInstance.remove(Ct),u.singletonInstance.remove(Et),u.singletonInstance.remove("SentUniqueOutcome")])}static async on(...e){return u.singletonInstance.emitter.on.apply(u.singletonInstance.emitter,e)}static async setIsPushEnabled(e){return u.singletonInstance.setIsPushEnabled(e)}static async getCurrentSession(){return await u.singletonInstance.getSession(Ht)}static async upsertSession(e){await u.singletonInstance.setSession(e)}static async cleanupCurrentSession(){await u.singletonInstance.removeSession(Ht)}static async setSubscription(e){return await u.singletonInstance.setSubscription(e)}static async getSubscription(){return await u.singletonInstance.getSubscription()}static async setJWTToken(e){return await u.singletonInstance.setJWTToken(e)}static async getJWTToken(){return await u.singletonInstance.getJWTToken()}static async setConsentGiven(e){return await u.singletonInstance.setProvideUserConsent(e)}static async getConsentGiven(){return await u.singletonInstance.getConsentGiven()}static async setAppState(e){return await u.singletonInstance.setAppState(e)}static async getAppState(){return await u.singletonInstance.getAppState()}static async setUserState(e){return await u.singletonInstance.setUserState(e)}static async getUserState(){return await u.singletonInstance.getUserState()}static async setAppConfig(e){return await u.singletonInstance.setAppConfig(e)}static async getAppConfig(){return await u.singletonInstance.getAppConfig()}static async getLastNotificationClickedForOutcomes(e){return await u.singletonInstance.getLastNotificationClickedForOutcomes(e)}static async removeAllNotificationClickedForOutcomes(){return await u.singletonInstance.removeAllNotificationClickedForOutcomes()}static async getAllNotificationReceivedForOutcomes(){return await u.singletonInstance.getAllNotificationReceivedForOutcomes()}static async putNotificationReceivedForOutcomes(e,t){return await u.singletonInstance.putNotificationReceivedForOutcomes(e,t)}static async getAllNotificationClickedForOutcomes(){return await u.singletonInstance.getAllNotificationClickedForOutcomes()}static async putNotificationClickedForOutcomes(e,t){return await u.singletonInstance.putNotificationClickedForOutcomes(e,t)}static async putNotificationClickedEventPendingUrlOpening(e){return await u.singletonInstance.putNotificationClickedEventPendingUrlOpening(e)}static async resetSentUniqueOutcomes(){return await u.singletonInstance.resetSentUniqueOutcomes()}static async setDeviceId(e){await u.singletonInstance.setDeviceId(e)}static async remove(e,t){return await u.singletonInstance.remove(e,t)}static async put(e,t){return await u.singletonInstance.put(e,t)}static async get(e,t){return await u.singletonInstance.get(e,t)}static async getAll(e){return await u.singletonInstance.getAll(e)}}var v=(s=>(s[s.Empty=0]="Empty",s[s.Malformed=1]="Malformed",s[s.EnumOutOfRange=2]="EnumOutOfRange",s[s.WrongType=3]="WrongType",s))(v||{});class I extends S{argument;reason;constructor(e,t,i){let n;switch(t){case 0:n=`Supply a non-empty value to '${e}'. ${i}`;break;case 1:n=`The value for '${e}' was malformed. ${i}`;break;case 2:n=`The value for '${e}' was out of range of the expected input enum. ${i}`;break;case 3:n=`The value for '${e}' was of the wrong type. ${i}`;break}super(n),this.argument=e,this.reason=v[t],Object.setPrototypeOf(this,I.prototype)}}function un(){return typeof PushSubscriptionOptions<"u"&&PushSubscriptionOptions.prototype.hasOwnProperty("applicationServerKey")}var Y=(s=>(s.ServiceWorker="ServiceWorker",s.Host="Host",s))(Y||{});function ki(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Tt={exports:{}};/*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */var gn=Tt.exports,Ni;function pn(){return Ni||(Ni=1,function(s){(function(e,t,i){s.exports?s.exports=i():e[t]=i()})(gn,"bowser",function(){var e=!0;function t(l){function p(It){var Ze=l.match(It);return Ze&&Ze.length>1&&Ze[1]||""}function b(It){var Ze=l.match(It);return Ze&&Ze.length>1&&Ze[2]||""}var w=p(/(ipod|iphone|ipad)/i).toLowerCase(),T=/like android/i.test(l),M=!T&&/android/i.test(l),Ye=/nexus\s*[0-6]\s*/i.test(l),ct=!Ye&&/nexus\s*[0-9]+/i.test(l),lt=/CrOS/.test(l),Yi=/silk/i.test(l),Zi=/sailfish/i.test(l),Xi=/tizen/i.test(l),en=/(web|hpw)os/i.test(l),tn=/windows phone/i.test(l),As=!tn&&/windows/i.test(l),Ms=!w&&!Yi&&/macintosh/i.test(l),Ds=!M&&!Zi&&!Xi&&!en&&/linux/i.test(l),Ii=p(/edge\/(\d+(\.\d+)?)/i),G=p(/version\/(\d+(\.\d+)?)/i),nn=/tablet/i.test(l)&&!/tablet pc/i.test(l),sn=!nn&&/[^-]mobi/i.test(l),Us=/xbox/i.test(l),g;/opera/i.test(l)?g={name:"Opera",opera:e,version:G||p(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i)}:/opr\/|opios/i.test(l)?g={name:"Opera",opera:e,version:p(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i)||G}:/SamsungBrowser/i.test(l)?g={name:"Samsung Internet for Android",samsungBrowser:e,version:G||p(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i)}:/coast/i.test(l)?g={name:"Opera Coast",coast:e,version:G||p(/(?:coast)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(l)?g={name:"Yandex Browser",yandexbrowser:e,version:G||p(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/ucbrowser/i.test(l)?g={name:"UC Browser",ucbrowser:e,version:p(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i)}:/mxios/i.test(l)?g={name:"Maxthon",maxthon:e,version:p(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i)}:/epiphany/i.test(l)?g={name:"Epiphany",epiphany:e,version:p(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i)}:/puffin/i.test(l)?g={name:"Puffin",puffin:e,version:p(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i)}:/sleipnir/i.test(l)?g={name:"Sleipnir",sleipnir:e,version:p(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i)}:/k-meleon/i.test(l)?g={name:"K-Meleon",kMeleon:e,version:p(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i)}:tn?(g={name:"Windows Phone",windowsphone:e},Ii?(g.msedge=e,g.version=Ii):(g.msie=e,g.version=p(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(l)?g={name:"Internet Explorer",msie:e,version:p(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:lt?g={name:"Chrome",chromeos:e,chromeBook:e,chrome:e,version:p(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:/chrome.+? edge/i.test(l)?g={name:"Microsoft Edge",msedge:e,version:Ii}:/vivaldi/i.test(l)?g={name:"Vivaldi",vivaldi:e,version:p(/vivaldi\/(\d+(\.\d+)?)/i)||G}:Zi?g={name:"Sailfish",sailfish:e,version:p(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(l)?g={name:"SeaMonkey",seamonkey:e,version:p(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel|fxios/i.test(l)?(g={name:"Firefox",firefox:e,version:p(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(l)&&(g.firefoxos=e)):Yi?g={name:"Amazon Silk",silk:e,version:p(/silk\/(\d+(\.\d+)?)/i)}:/phantom/i.test(l)?g={name:"PhantomJS",phantom:e,version:p(/phantomjs\/(\d+(\.\d+)?)/i)}:/slimerjs/i.test(l)?g={name:"SlimerJS",slimer:e,version:p(/slimerjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(l)||/rim\stablet/i.test(l)?g={name:"BlackBerry",blackberry:e,version:G||p(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:en?(g={name:"WebOS",webos:e,version:G||p(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(l)&&(g.touchpad=e)):/bada/i.test(l)?g={name:"Bada",bada:e,version:p(/dolfin\/(\d+(\.\d+)?)/i)}:Xi?g={name:"Tizen",tizen:e,version:p(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||G}:/qupzilla/i.test(l)?g={name:"QupZilla",qupzilla:e,version:p(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i)||G}:/chromium/i.test(l)?g={name:"Chromium",chromium:e,version:p(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i)||G}:/chrome|crios|crmo/i.test(l)?g={name:"Chrome",chrome:e,version:p(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:M?g={name:"Android",version:G}:/safari|applewebkit/i.test(l)?(g={name:"Safari",safari:e},G&&(g.version=G)):w?(g={name:w=="iphone"?"iPhone":w=="ipad"?"iPad":"iPod"},G&&(g.version=G)):/googlebot/i.test(l)?g={name:"Googlebot",googlebot:e,version:p(/googlebot\/(\d+(\.\d+))/i)||G}:g={name:p(/^(.*)\/(.*) /),version:b(/^(.*)\/(.*) /)},!g.msedge&&/(apple)?webkit/i.test(l)?(/(apple)?webkit\/537\.36/i.test(l)?(g.name=g.name||"Blink",g.blink=e):(g.name=g.name||"Webkit",g.webkit=e),!g.version&&G&&(g.version=G)):!g.opera&&/gecko\//i.test(l)&&(g.name=g.name||"Gecko",g.gecko=e,g.version=g.version||p(/gecko\/(\d+(\.\d+)?)/i)),!g.windowsphone&&!g.msedge&&(M||g.silk)?g.android=e:!g.windowsphone&&!g.msedge&&w?(g[w]=e,g.ios=e):Ms?g.mac=e:Us?g.xbox=e:As?g.windows=e:Ds&&(g.linux=e);function Rs(It){switch(It){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}var Z="";g.windows?Z=Rs(p(/Windows ((NT|XP)( \d\d?.\d)?)/i)):g.windowsphone?Z=p(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i):g.mac?(Z=p(/Mac OS X (\d+([_\.\s]\d+)*)/i),Z=Z.replace(/[_\s]/g,".")):w?(Z=p(/os (\d+([_\s]\d+)*) like mac os x/i),Z=Z.replace(/[_\s]/g,".")):M?Z=p(/android[ \/-](\d+(\.\d+)*)/i):g.webos?Z=p(/(?:web|hpw)os\/(\d+(\.\d+)*)/i):g.blackberry?Z=p(/rim\stablet\sos\s(\d+(\.\d+)*)/i):g.bada?Z=p(/bada\/(\d+(\.\d+)*)/i):g.tizen&&(Z=p(/tizen[\/\s](\d+(\.\d+)*)/i)),Z&&(g.osversion=Z);var on=!g.windows&&Z.split(".")[0];return nn||ct||w=="ipad"||M&&(on==3||on>=4&&!sn)||g.silk?g.tablet=e:(sn||w=="iphone"||w=="ipod"||M||Ye||g.blackberry||g.webos||g.bada)&&(g.mobile=e),g.msedge||g.msie&&g.version>=10||g.yandexbrowser&&g.version>=15||g.vivaldi&&g.version>=1||g.chrome&&g.version>=20||g.samsungBrowser&&g.version>=4||g.firefox&&g.version>=20||g.safari&&g.version>=6||g.opera&&g.version>=10||g.ios&&g.osversion&&g.osversion.split(".")[0]>=6||g.blackberry&&g.version>=10.1||g.chromium&&g.version>=20?g.a=e:g.msie&&g.version<10||g.chrome&&g.version<20||g.firefox&&g.version<20||g.safari&&g.version<6||g.opera&&g.version<10||g.ios&&g.osversion&&g.osversion.split(".")[0]<6||g.chromium&&g.version<20?g.c=e:g.x=e,g}var i=t(typeof navigator<"u"&&navigator.userAgent||"");i.test=function(l){for(var p=0;p=0;){if(b[0][p]>b[1][p])return 1;if(b[0][p]===b[1][p]){if(p===0)return 0}else return-1}}function c(l,p,b){var w=i;typeof p=="string"&&(b=p,p=void 0),p===void 0&&(p=!1),b&&(w=t(b));var T=""+w.version;for(var M in l)if(l.hasOwnProperty(M)&&w[M]){if(typeof l[M]!="string")throw new Error("Browser version in the minVersion map should be a string: "+M+": "+String(l));return a([T,l[M]])<0}return p}function d(l,p,b){return!c(l,p,b)}return i.isUnsupportedBrowser=c,i.compareVersions=a,i.check=d,i._detect=t,i})}(Tt)),Tt.exports}var gt=pn();const Gt=ki(gt);function N(){return{mobile:gt.mobile,tablet:gt.tablet,name:gt.name.toLowerCase(),version:gt.version}}class R{static isBrowser(){return typeof window<"u"}static useSafariLegacyPush(){return this.isBrowser()&&window.safari?.pushNotification!=null}static useSafariVapidPush(){return N().name=="safari"&&un()&&!this.useSafariLegacyPush()}static version(){return 160307}static get TRADITIONAL_CHINESE_LANGUAGE_TAG(){return["tw","hant"]}static get SIMPLIFIED_CHINESE_LANGUAGE_TAG(){return["cn","hans"]}static getLanguage(){let e=navigator.language;if(e){e=e.toLowerCase();const t=e.split("-");if(t[0]=="zh"){for(const i of R.TRADITIONAL_CHINESE_LANGUAGE_TAG)if(t.indexOf(i)!==-1)return"zh-Hant";for(const i of R.SIMPLIFIED_CHINESE_LANGUAGE_TAG)if(t.indexOf(i)!==-1)return"zh-Hans";return"zh-Hant"}else return t[0].substring(0,2)}else return"en"}static supportsServiceWorkers(){switch(x.getWindowEnv()){case Y.ServiceWorker:return!0;default:return typeof navigator<"u"&&"serviceWorker"in navigator}}}var X=(s=>(s.Development="Development",s.Staging="Staging",s.Production="Production",s))(X||{});const hn=4001,fn=3e3,mn=18080,wn=["outcomes","on_focus"];class x{static getBuildEnv(){return X.Production}static getApiEnv(){return X.Production}static getOrigin(){return R.isBrowser()?window.location.origin:typeof self<"u"&&typeof ServiceWorkerGlobalScope<"u"?self.location.origin:"Unknown"}static getWindowEnv(){if(typeof self<"u"&&typeof ServiceWorkerGlobalScope<"u")return Y.ServiceWorker;if(typeof window>"u")throw Error("OneSignalSDK: Unsupported JS runtime!");return Y.Host}static getBuildEnvPrefix(e=x.getBuildEnv()){switch(e){case X.Development:return"Dev-";case X.Staging:return"Staging-";case X.Production:return"";default:throw new I("buildEnv",v.EnumOutOfRange)}}static getOneSignalApiUrl(e=x.getApiEnv(),t){const i="localhost";switch(e){case X.Development:return x.isTurbineEndpoint(t)?new URL(`http://${i}:${mn}/api/v1`):new URL(`http://${i}:${fn}/api/v1`);case X.Staging:return new URL(`https://${i}/api/v1`);case X.Production:return new URL("https://onesignal.com/api/v1");default:throw new I("buildEnv",v.EnumOutOfRange)}}static getOneSignalStaticResourcesUrl(){return new URL("https://media.onesignal.com/web-sdk")}static getOneSignalResourceUrlPath(e=x.getBuildEnv()){const t="localhost";let i;const n="https",o=hn;switch(e){case X.Development:i=`${n}://${t}:${o}`;break;case X.Staging:i=`https://${t}`;break;case X.Production:i="https://onesignal.com";break;default:throw new I("buildEnv",v.EnumOutOfRange)}return new URL(`${i}/sdks/web/v16`)}static getOneSignalCssFileName(e=x.getBuildEnv()){const t="OneSignalSDK.page.styles.css";switch(e){case X.Development:return`Dev-${t}`;case X.Staging:return`Staging-${t}`;case X.Production:return t;default:throw new I("buildEnv",v.EnumOutOfRange)}}static isTurbineEndpoint(e){return e?wn.some(t=>e.indexOf(t)>-1):!1}}class B{static getBaseUrl(){return location.origin}static isLocalhostAllowedAsSecureOrigin(){return OneSignal.config&&OneSignal.config.userConfig&&OneSignal.config.userConfig.allowLocalhostAsSecureOrigin===!0}static redetectBrowserUserAgent(){return N().name===""&&N().version===""?Gt._detect(navigator.userAgent):Gt}static isValidUuid(e){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(e)}static getRandomUuid(){const e=typeof window>"u"?global.crypto:window.crypto||window.msCrypto;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const n=e.getRandomValues(new Uint8Array(1))[0]%16|0;return(i=="x"?n:n&3|8).toString(16)})}static logMethodCall(e,...t){return r.debug(`Called ${e}(${t.map(y.stringify).join(", ")})`)}static isSafari(){return R.isBrowser()&&typeof window.safari<"u"}}const bn=["notifyButtonHovering","notifyButtonHover","notifyButtonButtonClick","notifyButtonLauncherClick","animatedElementHiding","animatedElementHidden","animatedElementShowing","animatedElementShown","activeAnimatedElementActivating","activeAnimatedElementActive","activeAnimatedElementInactivating","activeAnimatedElementInactive"];class P{static async trigger(e,t,i){if(!y.contains(bn,e)){const n=t,o=y.capitalize(x.getWindowEnv().toString());n||n===!1?r.debug(`(${o}) » ${e}:`,n):r.debug(`(${o}) » ${e}`)}if(R.isBrowser()){if(e===OneSignal.EVENTS.SDK_INITIALIZED){if(OneSignal.initialized)return;OneSignal.initialized=!0}i?await i.emit(e,t):await OneSignal.emitter.emit(e,t)}}}class Ee{static executing=!1;static async triggerNotificationPermissionChanged(e=!1){if(!Ee.executing){Ee.executing=!0;try{await Ee.privateTriggerNotificationPermissionChanged(e)}finally{Ee.executing=!1}}}static async privateTriggerNotificationPermissionChanged(e){const t=await OneSignal.context.permissionManager.getPermissionStatus(),i=await u.get("Options","notificationPermission");(t!==i||e)&&(await u.put("Options",{key:"notificationPermission",value:t}),P.trigger(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,t),this.triggerBooleanPermissionChangeEvent(i,t,e))}static triggerBooleanPermissionChangeEvent(e,t,i){const n=t==="granted";(n!==(e==="granted")||i)&&P.trigger(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_BOOLEAN,n)}}function Re(s){const e=document.querySelectorAll(s);if(e.length>0)for(let t=0;t{OneSignal.initialized?s():OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED,s)})}async function Sn(s=!1){return Ee.triggerNotificationPermissionChanged(s)}function yn(s,...e){if(s)return s.apply(null,e)}function h(s,...e){return B.logMethodCall(s,...e)}function vn(s){return!!s&&!!s.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))*$/)}function ie(s,e,t){let i;if(typeof s=="string"?i=document.querySelector(s):i=s,i){i.insertAdjacentHTML(e,t);return}throw new Error(`${s} must be a CSS selector string or DOM Element object.`)}function In(s){if(typeof s=="string"){const e=document.querySelector(s);if(e===null)throw new Error(`Cannot find element with selector "${s}"`);for(;e.firstChild;)e.removeChild(e.firstChild)}else if(typeof s=="object")for(;s.firstChild;)s.removeChild(s.firstChild);else throw new Error(`${s} must be a CSS selector string or DOM Element object.`)}function m(s,e){if(typeof s=="string"){const t=document.querySelector(s);if(t===null)throw new Error(`Cannot find element with selector "${s}"`);t.classList.add(e)}else if(typeof s=="object")s.classList.add(e);else throw new Error(`${s} must be a CSS selector string or DOM Element object.`)}function le(s,e){if(typeof s=="string"){const t=document.querySelector(s);if(t===null)throw new Error(`Cannot find element with selector "${s}"`);t.classList.remove(e)}else if(typeof s=="object")s.classList.remove(e);else throw new Error(`${s} must be a CSS selector string or DOM Element object.`)}function qt(s,e){if(typeof s=="string"){const t=document.querySelector(s);if(t===null)throw new Error(`Cannot find element with selector "${s}"`);return t.classList.contains(e)}else{if(typeof s=="object")return s.classList.contains(e);throw new Error(`${s} must be a CSS selector string or DOM Element object.`)}}function Pt(s){return new Promise(e=>{setTimeout(e,s)})}function et(){return Promise.resolve()}function Le(s,e){return y.contains(s,e)}function zt(s){return B.isValidUuid(s)}function fe(s,e,t,i=!1){if(e||r.error("Cannot call on() with no event: ",e),t||r.error("Cannot call on() with no task: ",t),typeof s=="string"){const n=document.querySelectorAll(s);if(n.length>0)for(let o=0;othis.subscribers.delete(e)}broadcast(e){this.subscribers.forEach(t=>{t(e)})}}var A=(s=>(s.Add="add",s.Remove="remove",s.Update="update",s.Hydrate="hydrate",s))(A||{});class En{constructor(e,t){this.modelId=e,this.payload=t}type=A.Add}class Cn{constructor(e,t){this.modelId=e,this.payload=t}type=A.Remove}class xi{constructor(e,t){this.modelId=e,this.payload=t}type=A.Update}class Zt{constructor(e,t){this.modelId=e,this.payload=t}type=A.Hydrate}class Ai{constructor(e,t,i,n){this.model=e,this.property=t,this.oldValue=i,this.newValue=n}}class Ce extends Yt{constructor(e,t,i){super(),this.modelName=e,this.modelId=i??Math.random().toString(36).substring(2),this.modelName=e,this.data=t,this.onesignalId=void 0,this.externalId=void 0,this.awaitOneSignalIdAvailable=new Promise(n=>{this.onesignalIdAvailableCallback=n})}data;modelId;onesignalId;awaitOneSignalIdAvailable;onesignalIdAvailableCallback;externalId;applyToRecordId;setOneSignalId(e){h("setOneSignalId",{onesignalId:e}),this.onesignalId=e,e&&this.onesignalIdAvailableCallback?.(e)}setExternalId(e){h("setExternalId",{externalId:e}),this.externalId=e}setApplyToRecordId(e){h("setapplyToRecordId",{applyToRecordId:e}),this.applyToRecordId=e}set(e,t,i=!0){h("set",{property:e,newValue:t});let n;if(this.data&&(n=this.data[e],this.data[e]=t),i){const o=new xi(this.modelId,new Ai(this,e,n,t));this.broadcast(o)}}hydrate(e){h("hydrate",{data:e}),this.data=e,this.broadcast(new Zt(this.modelId,this))}encode(){const e=this.modelId,t=this.modelName,i=this.onesignalId,n=this.externalId;return{modelId:e,modelName:t,onesignalId:i,externalId:n,...this.data}}static decode(e){h("decode",{encodedModel:e});const{modelId:t,modelName:i,onesignalId:n,externalId:o,...a}=e,c=new Ce(i,a,t);return c.setOneSignalId(n),c.setExternalId(o),c}}class Tn{_mutexPromise=Promise.resolve();_mutexLocked=!1;async add(e,t){h("ModelCache.add",{modelName:e,model:t});const n={...t.encode()};await u.put(e,n)}async remove(e,t){h("ModelCache.remove",{modelName:e,modelId:t}),await u.remove(e,t)}async update(e,t,i,n){this._mutexLocked&&await this._mutexPromise,this._mutexLocked=!0,this._mutexPromise=new Promise(async(o,a)=>{h("ModelCache.update",{modelName:e,modelId:t,key:i,value:n});const c=await this.get(e,t);c||a("ModelCache: Attempting to update a model that does not exist"),c&&(c[i]=n,await u.put(e,c),this._mutexLocked=!1,o()),setTimeout(a.bind(this,"Database promise never resolved."),1e4)})}async load(e){h("ModelCache.load",{modelNames:e});const t={};for(let i=0;i{e.push(u.singletonInstance.remove(t))}),await Promise.all(e)}}class Xt extends Yt{constructor(e,t){super(),this.modelCache=e,this.modelStores=t,Object.keys(t).forEach(i=>{t[i].subscribe(this.processModelChange.bind(this))})}processModelChange(e){h("processModelChange",{modelStoreChange:e}),e.type===A.Add&&this.processModelAdded(e),e.type===A.Remove&&this.processModelRemoved(e),e.type===A.Update&&this.processModelUpdated(e),e.type===A.Hydrate&&this.processModelHydrated(e)}processModelAdded(e){h("processModelAdded",{modelStoreChange:e});const{payload:t}=e;this.modelCache.add(t.modelName,t),this.broadcast({model:t,changeType:A.Add,applyToRecordId:t?.applyToRecordId})}processModelRemoved(e){h("processModelRemoved",{modelStoreChange:e});const{modelId:t,payload:i}=e;this.modelCache.remove(i.modelName,t),this.broadcast({model:i,changeType:A.Remove,applyToRecordId:i?.applyToRecordId})}processModelUpdated(e){h("processModelUpdated",{modelStoreChange:e});const{modelId:t,payload:i}=e;if(this.modelCache.update(i.model.modelName,t,i.property,i.newValue),i.oldValue!==i.newValue){const n={model:i.model,changeType:A.Update,property:i.property,oldValue:i.oldValue,newValue:i.newValue,applyToRecordId:i.model?.applyToRecordId};this.broadcast(n)}}processModelHydrated(e){h("processModelHydrated",{modelStoreChange:e});const{modelId:t,payload:i}=e;this.modelCache.remove(i.modelName,t),this.modelCache.add(i.modelName,i)}static supportedModels=Object.values(E)}class ei{constructor(e){this.result=e}success=!0;retriable=!1}class ti{constructor(e){this.result=e}success=!1;retriable=!0}class kt{constructor(e){this.result=e}success=!1;retriable=!1}function ii(s){return s.property!==void 0}function Mi(s){return s!==null&&typeof s=="object"&&s?.constructor===Object}function Pn(s){return s!==null&&typeof s=="object"&&s?.constructor===Ce}function kn(s){return s!==null&&typeof s=="object"&&s?.constructor===Ai}function Di(s){return s?.onesignal_id!==void 0}function Nn(s){return s?.type!==void 0}function ne(s){return s?.type!==void 0&&s?.id!==void 0}class Q{constructor(e,t){this.label=e,this.id=t}static ONESIGNAL_ID="onesignal_id";static EXTERNAL_ID="external_id"}function ni(s){const e=s.model,t=e?.data;if(!e)throw new S(`processSubscriptionModel: bad subscription OSModel: ${JSON.stringify(e)}`);if(!Nn(t))throw new S(`processSubscriptionModel: bad subscription object: ${JSON.stringify(t)}`);if(!e.onesignalId)throw new S(`processSubscriptionModel: missing onesignalId: ${JSON.stringify(e)}`);let i;return ne(t)&&(i=t?.id),{subscription:t,aliasPair:new Q(Q.ONESIGNAL_ID,e.onesignalId),subscriptionId:i,payload:s.payload}}function Ui(s){const e=s.model?.data;if(!Di(e))throw new S(`processIdentityModel: bad identity object: ${JSON.stringify(e)}`);const{onesignal_id:t}=e,i=JSON.parse(JSON.stringify(e));if(delete i.onesignal_id,!t)throw new S(`processIdentityModel: missing onesignalId: ${JSON.stringify(e)}`);return{identity:i,aliasPair:new Q(Q.ONESIGNAL_ID,t)}}var si=(s=>(s[s.MissingAppId=0]="MissingAppId",s[s.RetryLimitReached=1]="RetryLimitReached",s))(si||{});class Nt extends S{reason;constructor(e){let t;switch(e){case 0:t="The API call is missing an app ID.";break;case 1:t="The API call has reached the retry limit.";break}super(t),Object.setPrototypeOf(this,Nt.prototype)}}function He(s){return new Promise(e=>setTimeout(e,s))}const oi={5:1e4,4:2e4,3:3e4,2:3e4,1:3e4};class W{static get(e,t,i){return W.call("GET",e,t,i)}static post(e,t,i){return W.call("POST",e,t,i)}static put(e,t,i){return W.call("PUT",e,t,i)}static delete(e,t,i){return W.call("DELETE",e,t,i)}static patch(e,t,i){return W.call("PATCH",e,t,i)}static call(e,t,i,n){if(!this.requestHasAppId(t,i))return Promise.reject(new Nt(si.MissingAppId));const o=new Headers;if(o.append("Origin",x.getOrigin()),o.append("SDK-Version",`onesignal/web/${R.version()}`),o.append("Content-Type","application/json;charset=UTF-8"),n)for(const d of Object.keys(n))o.append(d,n[d]);const a={method:e||"NO_METHOD_SPECIFIED",headers:o,cache:"no-cache"};i&&(a.body=JSON.stringify(i));const c=`${x.getOneSignalApiUrl(void 0,t).toString()}/${t}`;return W.executeFetch(c,a)}static async executeFetch(e,t,i=5){if(i===0)return Promise.reject(new Nt(si.RetryLimitReached));try{const n=await fetch(e,t),{status:o}=n;return{result:await n.json(),status:o}}catch(n){if(n.name==="TypeError")return await He(oi[i]),r.error(`OneSignal: Network timed out while calling ${e}. Retrying...`),W.executeFetch(e,t,i-1);throw new S(`OneSignalApiBase: failed to execute HTTP call: ${n}`)}}static requestHasAppId(e,t){if(e.startsWith("apps/")){const i=e.split("/");return zt(i[1])}if(e.startsWith("sync/")){const i=e.split("/");return zt(i[1])}return t&&typeof t.app_id=="string"?zt(t.app_id):!1}}function xn(s){const e="=".repeat((4-s.length%4)%4),t=(s+e).replace(/-/g,"+").replace(/_/g,"/"),i=atob(t),n=new Uint8Array(i.length);for(let o=0;o`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}var me=(s=>(s[s.InvalidAppId=0]="InvalidAppId",s[s.AppNotConfiguredForWebPush=1]="AppNotConfiguredForWebPush",s[s.WrongSiteUrl=2]="WrongSiteUrl",s[s.MultipleInitialization=3]="MultipleInitialization",s[s.MissingSafariWebId=4]="MissingSafariWebId",s[s.Unknown=5]="Unknown",s))(me||{});class ge extends S{reason;constructor(e,t){let i;switch(e){case 0:i="OneSignal: This app ID does not match any existing app. Double check your app ID.";break;case 1:i="OneSignal: This app ID does not have any web platforms enabled. Double check your app ID, or see step 1 on our setup guide (https://tinyurl.com/2x5jzk83).";break;case 2:t&&t.siteUrl?i=`OneSignal: This web push config can only be used on ${new URL(t.siteUrl).origin}. Your current origin is ${location.origin}.`:i="OneSignal: This web push config can not be used on the current site.";break;case 3:i="OneSignal: The OneSignal web SDK can only be initialized once. Extra initializations are ignored. Please remove calls initializing the SDK more than once.";break;case 4:i="OneSignal: Safari browser support on Mac OS X requires the Safari web platform to be enabled. Please see the Safari Support steps in our web setup guide.";break;case 5:i="OneSignal: An unknown initialization error occurred.";break}super(i),this.reason=me[e],Object.setPrototypeOf(this,ge.prototype)}}class se{static async createUser(e,t){const{appId:i,subscriptionId:n}=e,o=n?{"OneSignal-Subscription-Id":n}:void 0;let a={};return o&&(a={...a,...o}),e.jwtHeader&&(a={...a,...e.jwtHeader}),t.refresh_device_metadata=!0,W.post(`apps/${i}/users`,t,a)}static async getUser(e,t){const{appId:i}=e;return W.get(`apps/${i}/users/by/${t.label}/${t.id}`,e.jwtHeader)}static async updateUser(e,t,i){const{appId:n,subscriptionId:o}=e;if(!B.isValidUuid(n))throw new ge(me.InvalidAppId);const a=o?{"OneSignal-Subscription-Id":o}:void 0;let c={};a&&(c={...c,...a}),e.jwtHeader&&(c={...c,...e.jwtHeader});const d={label:Ri(t.label),id:Ri(t.id)};return W.patch(`apps/${n}/users/by/${d.label}/${d.id}`,i,c)}static async deleteUser(e,t){const{appId:i}=e;return W.delete(`apps/${i}/users/by/${t.label}/${t.id}`,e.jwtHeader)}static async addAlias(e,t,i){const{appId:n}=e;return W.patch(`apps/${n}/users/by/${t.label}/${t.id}/identity`,{identity:i},e.jwtHeader)}static async getUserIdentity(e,t){const{appId:i}=e;return W.get(`apps/${i}/users/by/${t.label}/${t.id}/identity`,e.jwtHeader)}static async deleteAlias(e,t,i){const{appId:n}=e;return W.delete(`apps/${n}/users/by/${t.label}/${t.id}/identity/${i}`,e.jwtHeader)}static async createSubscription(e,t,i){const{appId:n}=e;return W.post(`apps/${n}/users/by/${t.label}/${t.id}/subscriptions`,i,e.jwtHeader)}static async updateSubscription(e,t,i){const{appId:n}=e;return W.patch(`apps/${n}/subscriptions/${t}`,{subscription:i})}static async deleteSubscription(e,t){const{appId:i}=e;return W.delete(`apps/${i}/subscriptions/${t}`)}static async fetchAliasesForSubscription(e,t){const{appId:i}=e;return W.get(`apps/${i}/subscriptions/${t}/identity`)}static async identifyUserForSubscription(e,t,i){const{appId:n}=e;return W.patch(`apps/${n}/users/by/subscriptions/${t}/identity`,{identity:i},e.jwtHeader)}static async transferSubscription(e,t,i,n){const{appId:o}=e;return W.patch(`apps/${o}/subscriptions/${t}/owner`,{identity:{...i},retain_previous_owner:n},e.jwtHeader)}}var Li=(s=>(s.HttpsPermissionRequest="HTTPS permission request",s.SlidedownPermissionMessage="slidedown permission message",s.SubscriptionBell="subscription bell",s))(Li||{}),Ae=(s=>(s[s.MissingAppId=0]="MissingAppId",s[s.RedundantPermissionMessage=1]="RedundantPermissionMessage",s[s.PushPermissionAlreadyGranted=2]="PushPermissionAlreadyGranted",s[s.UnsupportedEnvironment=3]="UnsupportedEnvironment",s[s.MissingDomElement=4]="MissingDomElement",s[s.ServiceWorkerNotActivated=5]="ServiceWorkerNotActivated",s))(Ae||{});class Me extends S{description;reason;constructor(e,t){let i;switch(e){case 0:i="Missing required app ID.";break;case 1:{let n="";t&&t.permissionPromptType&&(n=`(${Li[t.permissionPromptType]})`),i=`Another permission message ${n} is being displayed.`;break}case 2:i="Push permission has already been granted.";break;case 3:i="The current environment does not support this operation.";break;case 5:i="The service worker must be activated first.";break}super(i),this.description=Ae[e],this.reason=e,Object.setPrototypeOf(this,Me.prototype)}}var xt=(s=>(s[s.Unknown=0]="Unknown",s[s.NoDeviceId=1]="NoDeviceId",s[s.NoEmailSet=2]="NoEmailSet",s[s.NoSMSSet=3]="NoSMSSet",s[s.OptedOut=4]="OptedOut",s))(xt||{});class At extends S{reason;constructor(e){let t;switch(e){case 1:t="This operation can only be performed after the user is subscribed.";break;case 2:t="No email is currently set.";break;case 3:t="No sms is currently set.";break;case 4:t="The user has manually opted out of receiving of notifications. This operation can only be performed after the user is fully resubscribed.";break}super(t),this.reason=xt[e],Object.setPrototypeOf(this,At.prototype)}}class Mt{static isValidUrl(e,t){if(t&&t.allowNull&&e===null)return!0;if(t&&t.allowEmpty&&e==null)return!0;try{const i=new URL(e);return t&&t.requireHttps?i.protocol==="https:":!0}catch{return!1}}static isValidBoolean(e,t){return t&&t.allowNull&&e===null?!0:e===!0||e===!1}static isValidArray(e,t){return t&&t.allowNull&&e===null||t&&t.allowEmpty&&e==null?!0:e instanceof Array}}class L{static async showLocalNotification(e,t,i,n,o,a){if(h("MainHelper:showLocalNotification: ",e,t,i,n,o,a),!(await u.getAppConfig()).appId)throw new Me(Ae.MissingAppId);if(!OneSignal.Notifications.permission)throw new At(xt.NoDeviceId);if(!Mt.isValidUrl(i))throw new I("url",v.Malformed);if(!Mt.isValidUrl(n,{allowEmpty:!0,requireHttps:!0}))throw new I("icon",v.Malformed);if(!n){const p=await L.getNotificationIcons();n=Qt(p)}const d=p=>{const b=[];for(let w=0;w{if(!p){r.error("Service worker registration not available.");return}const b={body:t,data:l,icon:n,actions:a?d(a):[]};p.showNotification(e,b)})}static async checkAndTriggerNotificationPermissionChanged(){const e=await u.get("Options","notificationPermission"),t=await OneSignal.context.permissionManager.getPermissionStatus();e!==t&&(await Ee.triggerNotificationPermissionChanged(),await u.put("Options",{key:"notificationPermission",value:t}))}static async getNotificationIcons(){const e=await L.getAppId();if(!e)throw new Me(Ae.MissingAppId);const t=`${x.getOneSignalApiUrl().toString()}/apps/${e}/icon`,n=await(await fetch(t)).json();if(n.errors)throw r.error(`API call ${t}`,"failed with:",n.errors),new Error("Failed to get notification icons.");return n}static getSlidedownOptions(e){return y.getValueOrDefault(e.slidedown,{prompts:[]})}static getFullscreenPermissionMessageOptions(e){return e?e.fullscreen?{autoAcceptTitle:e.fullscreen.autoAcceptTitle,actionMessage:e.fullscreen.actionMessage,exampleNotificationTitleDesktop:e.fullscreen.title,exampleNotificationTitleMobile:e.fullscreen.title,exampleNotificationMessageDesktop:e.fullscreen.message,exampleNotificationMessageMobile:e.fullscreen.message,exampleNotificationCaption:e.fullscreen.caption,acceptButton:e.fullscreen.acceptButton,cancelButton:e.fullscreen.cancelButton}:e:null}static getPromptOptionsQueryString(){const e=L.getFullscreenPermissionMessageOptions(OneSignal.config.userConfig.promptOptions);let t="";if(e){const i=L.getPromptOptionsPostHash();for(const n of Object.keys(i)){const o=i[n];t+="&"+n+"="+o}}return t}static getPromptOptionsPostHash(){const e=L.getFullscreenPermissionMessageOptions(OneSignal.config.userConfig.promptOptions),t={};if(e){const i={exampleNotificationTitleDesktop:"exampleNotificationTitle",exampleNotificationMessageDesktop:"exampleNotificationMessage",exampleNotificationTitleMobile:"exampleNotificationTitle",exampleNotificationMessageMobile:"exampleNotificationMessage"};for(const o of Object.keys(i)){const a=i[o];e[o]&&(e[a]=e[o])}const n=["autoAcceptTitle","siteName","autoAcceptTitle","subscribeText","showGraphic","actionMessage","exampleNotificationTitle","exampleNotificationMessage","exampleNotificationCaption","acceptButton","cancelButton","timeout"];for(let o=0;o=200&&t<300){if(!Di(n))throw new S(`processIdentityResponse: result ${n} is not an identity object`);return new ei(n)}return t>=400&&t<500?new kt:new ti}}class je{static async addSubscription(e){h("SubscriptionRequests.addSubscription",e);const t=await L.getAppId(),{subscription:i,aliasPair:n,subscriptionId:o}=ni(e),a=await se.createSubscription({appId:t},n,{subscription:i}),c=a.status;return c>=200&&c<300&&OneSignal.coreDirector.getNewRecordsState().add(o),je._processSubscriptionResponse(a)}static async removeSubscription(e){h("SubscriptionRequests.removeSubscription",e);const{subscriptionId:t}=ni(e);if(!t)throw new S("removeSubscription: subscriptionId is not defined");const i=await L.getAppId(),n=await se.deleteSubscription({appId:i},t);return je._processSubscriptionResponse(n)}static async updateSubscription(e){h("SubscriptionRequests.updateSubscription",e);const{payload:t,subscriptionId:i}=ni(e);if(!i)throw new S("updateSubscription: subscriptionId is not defined");if(!t)throw new S("updateSubscription: payload is not defined");const n=await L.getAppId(),o=await se.updateSubscription({appId:n},i,t);return je._processSubscriptionResponse(o)}static _processSubscriptionResponse(e){if(!e)throw new Error("processSubscriptionResponse: response is not defined");const{status:t,result:i}=e,n="subscription"in i?i.subscription:void 0;if(t>=200&&t<300){if(n&&!ne(n))throw new S(`processSubscriptionResponse: bad subscription object: ${n}`);return new ei(n)}return t>=400&&t<500?new kt:new ti}}class ai{static async updateUserProperties(e){h("UserPropertyRequests.updateUserProperties",e);const t=e.model,i=t?.data;if(!i||!t)throw new S(`updateUserProperty: bad identity model: ${t}`);if(!t.onesignalId)return r.info("Caching User Property update until subscription is created."),new kt;const n=new Q(Q.ONESIGNAL_ID,t.onesignalId),o=await L.getAppId(),a=await OneSignal.coreDirector.getPushSubscriptionModel();let c;ne(a?.data)&&(c=a?.data.id);const d=await se.updateUser({appId:o,subscriptionId:c},n,{properties:i});return ai._processUserPropertyResponse(d)}static _processUserPropertyResponse(e){if(!e)throw new Error("processUserPropertyResponse: response is not defined");const{status:t,result:i}=e;return t>=200&&t<300?new ei(i?.properties):t>=400&&t<500?new kt:new ti}}const An={add:je.addSubscription,remove:je.removeSubscription,update:je.updateSubscription},Mn={[E.Identity]:{modelName:E.Identity,add:pt.addIdentity,remove:pt.removeIdentity},[E.Properties]:{modelName:E.Properties,update:ai.updateUserProperties},[E.Subscriptions]:{modelName:E.Subscriptions,...An}};class Be{constructor(e,t,i){this.changeType=e,this.modelName=t,this.operationId=Math.random().toString(36).substring(2),this.payload=i?this.getPayload(i):void 0,this.model=i?i[i.length-1].model:void 0,this.applyToRecordId=i?.[i.length-1]?.applyToRecordId,this.timestamp=Date.now(),this.jwtTokenAvailable=new Promise(async n=>{this.jwtToken=await u.getJWTToken(),n()})}operationId;timestamp;payload;model;applyToRecordId;jwtTokenAvailable;jwtToken;getPayload(e){return ii(e[0])?this.aggregateDeltas(e):e[0].model.data}aggregateDeltas(e){const t={};return e.forEach(i=>{if(ii(i)){const n=t.hasOwnProperty(i.property),o=Mi(i.newValue),a=Mi(i.oldValue);if(!(o===a||i.oldValue===void 0))throw new Error("Cannot merge incompatible values");const d=n&&o,l={...t[i.property],...i.newValue};t[i.property]=d?l:i.newValue}}),t}static getInstanceWithModelReference(e){const{operationId:t,payload:i,modelName:n,changeType:o,timestamp:a,model:c}=e;if(!c)throw new S("Operation.fromJSON: model is undefined");const d=OneSignal.coreDirector?.getModelByTypeAndId(n,c.modelId);if(d){const l=new Be(o,n);return l.model=d,l.operationId=t,l.timestamp=a,l.payload=i,l.jwtToken=e.jwtToken,l.jwtTokenAvailable=Promise.resolve(),l}else throw new Error(`Could not find model with id ${c.modelId} of type ${n}. Maybe user logged out?`)}}class tt{static enqueue(e){h("OperationCache.enqueue",{operation:e});const t=localStorage.getItem("operationCache"),i=t?JSON.parse(t):{};i[e.operationId]=e,localStorage.setItem("operationCache",JSON.stringify(i))}static getOperationsWithModelName(e){const t=localStorage.getItem("operationCache"),i=t?Object.values(JSON.parse(t)):[],n=[];for(let a=0;aa.timestamp-c.timestamp).filter(a=>a.modelName===e)}static delete(e){h("OperationCache.delete",{id:e});const t=localStorage.getItem("operationCache"),i=t?JSON.parse(t):{};delete i[e],localStorage.setItem("operationCache",JSON.stringify(i))}static flushOperations(){h("OperationCache.flushOperations"),localStorage.removeItem("operationCache")}}const Dn="isOptedOut",Un="isPushNotificationsEnabled",Bi="os_pageViews",Vi="requiresPrivacyConsent";class Ge{static removeLegacySubscriptionOptions(){localStorage.removeItem(Dn),localStorage.removeItem(Un)}static setConsentRequired(e){localStorage.setItem(Vi,e.toString())}static getConsentRequired(){return localStorage.getItem(Vi)==="true"}static setLocalPageViewCount(e){localStorage.setItem(Bi,e.toString())}static getLocalPageViewCount(){return Number(localStorage.getItem(Bi))}}const Rn=5e3;class it{_deltaQueue=[];_operationQueue=[];_newRecordsState;_executeAdd;_executeUpdate;_executeRemove;onlineStatus=!0;static OPERATIONS_BATCH_PROCESSING_TIME=5;static RETRY_COUNT=5;constructor(e,t){setInterval(()=>{r.debug("OneSignal: checking for operations to process from cache");const i=this.getOperationsFromCache();this._operationQueue=[...i,...this._operationQueue],this._operationQueue.length>0&&this._processOperationQueue.call(this)},it.OPERATIONS_BATCH_PROCESSING_TIME*1e3),window.addEventListener("online",this._onNetworkChange.bind(this,!0)),window.addEventListener("offline",this._onNetworkChange.bind(this,!1)),this._executeAdd=e.add,this._executeUpdate=e.update,this._executeRemove=e.remove,this._newRecordsState=t}enqueueDelta(e){h("ExecutorBase.enqueueDelta",{delta:e});const t=JSON.parse(JSON.stringify(e));this._deltaQueue.push(t)}get deltaQueue(){return this._deltaQueue}get operationQueue(){return this._operationQueue}_enqueueOperation(e){h("ExecutorBase.enqueueOperation",{operation:e}),this._operationQueue.push(e)}_flushDeltas(){this._deltaQueue=[]}_flushOperations(){h("ExecutorBase._flushOperations"),this._operationQueue=[]}_getChangeType(e,t){h("ExecutorBase._getChangeType",{oldValue:e,newValue:t});const i=!e&&!!t,n=!!e&&!t,o=e!==t&&!!t&&!!e;let a;if(i)a=A.Add;else if(n)a=A.Remove;else if(o)a=A.Update;else throw new Error("Unsupported change type");return a}async _processOperationQueue(){const e=OneSignal.config.userConfig.requiresUserPrivacyConsent||Ge.getConsentRequired(),t=await u.getConsentGiven();if(!(e&&!t))for(;this._operationQueue.length>0;){const i=this._operationQueue.shift();i&&(tt.enqueue(i),this._canExecute(i)&&this._processOperation(i,it.RETRY_COUNT).catch(n=>{r.error(n)}))}}async _processOperation(e,t){h("ExecutorBase._processOperation",{operation:e,retries:t}),await e.model?.awaitOneSignalIdAvailable,await e.jwtTokenAvailable;let i={success:!1,retriable:!0};e?.changeType===A.Add?i=await this._executeAdd?.call(this,e):e?.changeType===A.Remove?i=await this._executeRemove?.call(this,e):e?.changeType===A.Update&&(i=await this._executeUpdate?.call(this,e)),i.success?(i.result&&(await Be.getInstanceWithModelReference(e))?.model?.hydrate(i.result),tt.delete(e?.operationId)):i.retriable&&t>0?setTimeout(()=>{this._processOperation(e,t-1).catch(n=>{r.error(n)})},Rn):tt.delete(e?.operationId)}_onNetworkChange(e){h("ExecutorBase._onNetworkChange",{online:e}),this.onlineStatus=e,e&&this._processOperationQueue.call(this)}_canExecute(e){return!(!this.onlineStatus||e.applyToRecordId&&!this._newRecordsState.canAccess(e.applyToRecordId))}}class Ln extends it{constructor(e,t){super(e,t)}processDeltaQueue(){if(this._deltaQueue.length===0)return;const e=[],t=[];this._deltaQueue.forEach(i=>{if(!ii(i))return;const n=this._getChangeType(i.oldValue,i.newValue);n===A.Add||n===A.Update?e.push(i):n===A.Remove&&t.push(i)}),e.length>0&&this._enqueueOperation(new Be(A.Add,E.Identity,e)),t.length>0&&this._enqueueOperation(new Be(A.Remove,E.Identity,t)),this._flushDeltas()}getOperationsFromCache(){return tt.getOperationsWithModelName(E.Identity)}}class Bn extends it{constructor(e,t){super(e,t)}processDeltaQueue(){this._deltaQueue.length!==0&&(this._enqueueOperation(new Be(A.Update,E.Properties,this._deltaQueue)),this._flushDeltas())}getOperationsFromCache(){return tt.getOperationsWithModelName(E.Properties)}}class Vn extends it{constructor(e,t){super(e,t)}processDeltaQueue(){this.separateDeltasByModelId().forEach(t=>{const i=this.separateDeltasByChangeType(t);Object.keys(i).forEach(n=>{const o=i[n];o.length>0&&this._enqueueOperation(new Be(n,o[0].model.modelName,o))})}),this._flushDeltas()}getOperationsFromCache(){return tt.getOperationsWithModelName(E.Subscriptions)}separateDeltasByChangeType(e){const t={[A.Add]:[],[A.Remove]:[],[A.Update]:[]};return e.forEach(i=>{t[i.changeType]||(t[i.changeType]=[]),t[i.changeType]?.push(i)}),t}separateDeltasByModelId(){const e={};return this._deltaQueue.forEach(t=>{const{modelId:i}=t.model;e[i]||(e[i]=[]),e[i].push(t)}),Object.values(e)}}class Wn{static build(e,t){switch(e.modelName){case E.Identity:return new Ln(e,t);case E.Properties:return new Bn(e,t);case E.Subscriptions:return new Vn(e,t)}}}class _n{store={};constructor(e){Object.values(E).forEach(t=>{const i=Mn[t];this.store[t]=Wn.build(i,e)})}forceDeltaQueueProcessingOnAllExecutors(){Object.values(this.store).forEach(e=>{e.processDeltaQueue()})}}class ri{constructor(e,t){this.modelRepo=e,this.newRecordsState=t,this.executorStore=new _n(this.newRecordsState),this._unsubscribeFromModelRepo=this.modelRepo.subscribe(i=>{this._processDelta(i)}),setInterval(()=>{this._processDeltaQueue()},ri.DELTAS_BATCH_PROCESSING_TIME*1e3)}executorStore;newRecordsState;_unsubscribeFromModelRepo;_deltaQueue=[];static DELTAS_BATCH_PROCESSING_TIME=1;setModelRepoAndResubscribe(e){this.modelRepo=e,this._unsubscribeFromModelRepo(),this._unsubscribeFromModelRepo=this.modelRepo.subscribe(t=>{this._processDelta(t)})}forceDeltaQueueProcessingOnAllExecutors(){this.executorStore.forceDeltaQueueProcessingOnAllExecutors()}_flushDeltas(){this._deltaQueue=[]}_processDelta(e){h("OperationRepo._processDelta",{delta:e});const t=JSON.parse(JSON.stringify(e));this._deltaQueue.push(t)}_processDeltaQueue(){h("OperationRepo._processDeltaQueue"),this._deltaQueue.forEach(e=>{const{modelName:t}=e.model;this.executorStore.store[t]?.enqueueDelta(e)}),this.forceDeltaQueueProcessingOnAllExecutors(),this._flushDeltas()}}class Fn extends Yt{models={};unsubscribeCallbacks={};constructor(e=[]){super(),e.forEach(t=>{this.models[t.modelId]=t,this.subscribeUpdateListener(t)})}add(e,t){this.subscribeUpdateListener(e),this.models[e.modelId]=e,t?this.broadcast(new En(e.modelId,e)):this.broadcast(new Zt(e.modelId,e))}remove(e){const t=JSON.stringify(this.models[e]);delete this.models[e],this.unsubscribeCallbacks[e](),this.broadcast(new Cn(e,JSON.parse(t)))}subscribeUpdateListener(e){this.unsubscribeCallbacks[e.modelId]=e.subscribe(t=>{const{payload:i}=t;t.type===A.Update&&kn(i)?this.broadcast(new xi(e.modelId,i)):t.type===A.Hydrate&&Pn(i)&&this.broadcast(new Zt(e.modelId,i))})}}class Wi{static build(e){const t={};return Object.values(E).forEach(i=>{const n=e?e[i]:void 0,o=new Fn(n);t[i]=o}),t}}class $n{OP_REPO_POST_CREATE_DELAY;records=new Map;constructor(e=3e3){this.OP_REPO_POST_CREATE_DELAY=e}add(e,t=!1){(t||this.records.get(e))&&this.records.set(e,Date.now())}canAccess(e){const t=this.records.get(e);return t?Date.now()-t>this.OP_REPO_POST_CREATE_DELAY:!0}}class Hn{modelRepo;operationRepo;initPromise;newRecordsState;modelCache;initResolver=()=>null;constructor(){this.initPromise=new Promise(e=>{this.initResolver=e}),this.modelCache=new Tn,this.modelCache.load(Xt.supportedModels).then(e=>{const t=Wi.build(e);this.modelRepo=new Xt(this.modelCache,t),this.newRecordsState=new $n,this.operationRepo=new ri(this.modelRepo,this.newRecordsState),this.initResolver()}).catch(e=>{r.error(e)})}async init(){h("CoreModule.init"),await this.initPromise}async resetModelRepoAndCache(){h("CoreModule.resetModelRepo"),await this.modelCache.reset();const e=Wi.build();this.modelRepo=new Xt(this.modelCache,e),this.operationRepo?.setModelRepoAndResubscribe(this.modelRepo)}forceDeltaQueueProcessingOnAllExecutors(){this.operationRepo?.forceDeltaQueueProcessingOnAllExecutors()}}var q=(s=>(s.ChromePush="ChromePush",s.SafariPush="SafariPush",s.SafariLegacyPush="SafariLegacyPush",s.FirefoxPush="FirefoxPush",s.Email="Email",s.SMS="SMS",s))(q||{}),De=(s=>(s.Email="Email",s.SMS="SMS",s.Push="Push",s))(De||{}),ht=(s=>(s[s.ResubscribeExisting=0]="ResubscribeExisting",s[s.SubscribeNew=1]="SubscribeNew",s))(ht||{}),Dt=(s=>(s[s.Loaded=0]="Loaded",s[s.Failed=1]="Failed",s))(Dt||{});class ci{cache;constructor(){this.cache={}}getCache(){return{...this.cache}}async loadSdkStylesheet(){const e=x.getOneSignalResourceUrlPath(),t=x.getOneSignalCssFileName();return this.loadIfNew(0,new URL(`${e}/${t}?v=160307`))}async loadIfNew(e,t){return this.cache[t.toString()]||(this.cache[t.toString()]=ci.load(e,t)),this.cache[t.toString()]}static async load(e,t){try{let i;return await new Promise((n,o)=>{switch(e){case 1:i=document.createElement("script"),i.setAttribute("type","text/javascript"),i.setAttribute("async","async"),i.setAttribute("src",t.toString());break;case 0:i=document.createElement("link"),i.setAttribute("rel","stylesheet"),i.setAttribute("href",t.toString());break}i.onerror=o,i.onload=n,document.querySelector("head")?.appendChild(i)}),0}catch{return 1}}}const U={body:"slidedown-body",buttonIndicatorHolder:"onesignal-button-indicator-holder",container:"onesignal-slidedown-container",dialog:"onesignal-slidedown-dialog",footer:"slidedown-footer",reset:"onesignal-reset",savingStateButton:"onesignal-saving-state-button",slideUp:"slide-up",slideDown:"slide-down",closeSlidedown:"close-slidedown",icon:"slidedown-body-icon",message:"slidedown-body-message",defaultIcon:"default-icon",loadingContainer:"onesignal-loading-container",clearfix:"clearfix"},jn={toastText:"onesignal-toast-text"},Gn={toastText:"onesignal-toast-text"},k={allowButton:"onesignal-slidedown-allow-button",body:"slidedown-body",buttonIndicatorHolder:"onesignal-button-indicator-holder",cancelButton:"onesignal-slidedown-cancel-button",container:"onesignal-slidedown-container",dialog:"onesignal-slidedown-dialog",footer:"slidedown-footer",normalSlidedown:"normal-slidedown",loadingContainer:"onesignal-loading-container"},nt={alignRight:"align-right",primary:"primary",secondary:"secondary",slidedownButton:"slidedown-button"},Te={categoryLabelInput:"onesignal-category-label-input",categoryLabelText:"onesignal-category-label-text",categoryLabel:"onesignal-category-label",checkmark:"onesignal-checkmark",taggingContainer:"tagging-container",taggingContainerCol:"tagging-container-col",loadingMessage:"onesignal-loading-message"},qn={taggingContainer:"tagging-container"},zn="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",Kn="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",_i={greyLoadingIndicator:"#95A1AC",whiteLoadingIndicator:"#FFFFFF"},Qn={fetchingPreferences:"Fetching your preferences"},H={channelCaptureContainer:"channel-capture-container",inputWithValidationElement:"input-with-validation-element",onesignalErrorInput:"onesignal-error-input",onesignalSmsInput:"iti-onesignal-sms-input",onesignalEmailInput:"onesignal-email-input",onesignalValidationElementHidden:"onesignal-validation-element-hidden",onesignalValidationElement:"onesignal-validation-element"},z={smsInputWithValidationElement:"sms-input-with-validation-element",emailInputWithValidationElement:"email-input-with-validation-element",onesignalSmsInput:"iti-onesignal-sms-input",onesignalEmailInput:"onesignal-email-input",onesignalSmsValidationElement:"onesignal-sms-validation-element",onesignalEmailValidationElement:"onesignal-email-validation-element"},Pe={containerClass:"onesignal-customlink-container",subscribeClass:"onesignal-customlink-subscribe",explanationClass:"onesignal-customlink-explanation",resetClass:"onesignal-reset",hide:"hide",state:{subscribed:"state-subscribed",unsubscribed:"state-unsubscribed"}},Jn={containerSelector:`.${Pe.containerClass}`};class Fi{config;constructor(e){this.config=e}async initialize(){if(!this.config?.enabled||!await this.loadSdkStyles())return;r.info("OneSignal: initializing customlink");const e=await OneSignal.context.subscriptionManager.isPushNotificationsEnabled();if(!this.config?.unsubscribeEnabled&&e){this.hideCustomLinkContainers();return}for(let t=0;t{r.info("CustomLink: subscribe clicked"),await this.handleClick(t)}),t.setAttribute("type","button"),e.appendChild(t)}}async loadSdkStyles(){return await OneSignal.context.dynamicResourceLoader.loadSdkStylesheet()!==Dt.Loaded?(r.debug("Not initializing custom link button because styles failed to load."),!1):!0}hideElement(e){m(e,Pe.hide)}hideCustomLinkContainers(){this.customlinkContainerElements.forEach(e=>{this.hideElement(e)})}async handleClick(e){if(OneSignal.User.PushSubscription.optedIn)await OneSignal.User.PushSubscription.optOut(),await this.setTextFromPushStatus(e);else{await OneSignal.User.PushSubscription.optIn(),this.config?.unsubscribeEnabled||this.hideCustomLinkContainers();return}}async setTextFromPushStatus(e){this.config?.text?.subscribe&&(await OneSignal.context.subscriptionManager.isPushNotificationsEnabled()||(e.textContent=this.config.text.subscribe)),this.config?.text?.unsubscribe&&await OneSignal.context.subscriptionManager.isPushNotificationsEnabled()&&(e.textContent=this.config.text.unsubscribe)}setCustomColors(e){!this.config?.color||!this.config.color.text||(this.config?.style==="button"&&this.config?.color.button?(e.style.backgroundColor=this.config?.color.button,e.style.color=this.config?.color.text):this.config?.style==="link"&&(e.style.color=this.config?.color.text))}get customlinkContainerElements(){const e=document.querySelectorAll(Jn.containerSelector);return Array.prototype.slice.call(e)}}class F{static store={};static LIMIT=2;static put(e,t){return F.store[e]===void 0&&(F.store[e]=[null,null]),F.store[e].push(t),F.store[e].length==F.LIMIT+1&&F.store[e].shift(),F.store[e]}static get(e){return F.store[e]===void 0&&(F.store[e]=[null,null]),F.store[e]}static getFirst(e){return F.get(e)[0]}static getLast(e){return F.get(e)[1]}static remove(e){delete F.store[e]}static isEmpty(e){const t=F.get(e);return t[0]===null&&t[1]===null}}class ft{static decodeHtmlEntities(e){return typeof DOMParser>"u"?e:new DOMParser().parseFromString(e,"text/html").documentElement.textContent||""}}var f=(s=>(s.Native="native",s.Push="push",s.Category="category",s.Sms="sms",s.Email="email",s.SmsAndEmail="smsAndEmail",s))(f||{});class pe{static isCategorySlidedownConfigured(e){if(!e)return!1;const t=pe.getFirstSlidedownPromptOptionsWithType(e,f.Category);return t?!!t.categories&&t.categories.length>0:!1}static isCategorySlidedownConfiguredVersion1(e){return(e?.categories?.tags?.length||0)>0}static getFirstSlidedownPromptOptionsWithType(e,t){return e?e.filter(i=>i.type===t)[0]:void 0}static isSlidedownAutoPromptConfigured(e){if(!e)return!1;for(let t=0;t=200&&c<300){const l=o.identity?.onesignal_id;l&&OneSignal.coreDirector.getNewRecordsState()?.add(l);const p=o.subscriptions?.[0]?.token,b=d.subscriptions?.find(w=>w.token===p);b&&ne(b)&&OneSignal.coreDirector.getNewRecordsState()?.add(b.id)}return d}catch(t){r.error(t)}}}static async createAndHydrateUser(){const e=await K.createUserOnServer();e&&OneSignal.coreDirector.hydrateUser(e)}static async getAllUserData(){h("LoginManager.getAllUserData");const e=OneSignal.coreDirector.getIdentityModel(),t=OneSignal.coreDirector.getPropertiesModel(),i=await OneSignal.coreDirector.getAllSubscriptionsModels(),n={};return n.identity=e?.data,n.properties=t?.data,n.subscriptions=i?.map(o=>o.data),n}static async copyOneSignalIdPromiseFromIdentityModel(){const e=_.createOrGetInstance(),t=OneSignal.coreDirector.getIdentityModel();e.awaitOneSignalIdAvailable=t?.awaitOneSignalIdAvailable,e.awaitOneSignalIdAvailable?.then(i=>{e.hasOneSignalId=!0,e.onesignalId=i})}static async updateModelWithCurrentUserOneSignalId(e){const t=_.createOrGetInstance();await t.awaitOneSignalIdAvailable,e.setOneSignalId(t.onesignalId)}}class _{hasOneSignalId=!1;onesignalId;awaitOneSignalIdAvailable;isCreatingUser=!1;static singletonInstance=void 0;static createOrGetInstance(){return _.singletonInstance||(_.singletonInstance=new _,K.initializeUser(!0).then(()=>{K.copyOneSignalIdPromiseFromIdentityModel().catch(e=>{console.error(e)})}).catch(e=>{console.error(e)})),_.singletonInstance}addAlias(e,t){if(h("addAlias",{label:e,id:t}),typeof e!="string")throw new I("label",v.WrongType);if(typeof t!="string")throw new I("id",v.WrongType);if(!e)throw new I("label",v.Empty);if(!t)throw new I("id",v.Empty);this.addAliases({[e]:t})}addAliases(e){if(h("addAliases",{aliases:e}),!e||Object.keys(e).length===0)throw new I("aliases",v.Empty);Object.keys(e).forEach(async i=>{if(typeof i!="string")throw new I("label",v.WrongType)});const t=OneSignal.coreDirector.getIdentityModel();t?.setApplyToRecordId(t?.onesignalId),Object.keys(e).forEach(async i=>{t?.set(i,e[i])})}removeAlias(e){if(h("removeAlias",{label:e}),typeof e!="string")throw new I("label",v.WrongType);if(!e)throw new I("label",v.Empty);this.removeAliases([e])}removeAliases(e){if(h("removeAliases",{aliases:e}),!e||e.length===0)throw new I("aliases",v.Empty);const t=OneSignal.coreDirector.getIdentityModel();t?.setApplyToRecordId(t?.onesignalId),e.forEach(async i=>{t?.set(i,void 0)})}async addEmail(e){if(h("addEmail",{email:e}),typeof e!="string")throw new I("email",v.WrongType);if(!e)throw new I("email",v.Empty);if(!vn(e))throw new I("email",v.Malformed);const t={type:q.Email,token:e},i=new Ce(E.Subscriptions,t);if(_.singletonInstance?.isCreatingUser||_.singletonInstance?.hasOneSignalId){i.setOneSignalId(_.singletonInstance?.onesignalId);const o=OneSignal.coreDirector.getIdentityModel();o.data.external_id&&i.setExternalId(o.data.external_id),OneSignal.coreDirector.add(E.Subscriptions,i,!0)}else OneSignal.coreDirector.add(E.Subscriptions,i,!1),await K.createAndHydrateUser();K.updateModelWithCurrentUserOneSignalId(i).catch(o=>{throw o});const n=OneSignal.coreDirector.getIdentityModel();n.data.external_id&&i.setExternalId(n.data.external_id)}async addSms(e){if(h("addSms",{sms:e}),typeof e!="string")throw new I("sms",v.WrongType);if(!e)throw new I("sms",v.Empty);const t={type:q.SMS,token:e},i=new Ce(E.Subscriptions,t);if(_.singletonInstance?.isCreatingUser||_.singletonInstance?.hasOneSignalId){i.setOneSignalId(_.singletonInstance?.onesignalId);const o=OneSignal.coreDirector.getIdentityModel();o.data.external_id&&i.setExternalId(o.data.external_id),OneSignal.coreDirector.add(E.Subscriptions,i,!0)}else OneSignal.coreDirector.add(E.Subscriptions,i,!1),await K.createAndHydrateUser();K.updateModelWithCurrentUserOneSignalId(i).catch(o=>{throw o});const n=OneSignal.coreDirector.getIdentityModel();n.data.external_id&&i.setExternalId(n.data.external_id)}removeEmail(e){if(h("removeEmail",{email:e}),typeof e!="string")throw new I("email",v.WrongType);if(!e)throw new I("email",v.Empty);const t=OneSignal.coreDirector.getEmailSubscriptionModels();Object.keys(t).forEach(async n=>{t[n].data?.token===e&&OneSignal.coreDirector.remove(E.Subscriptions,n)})}removeSms(e){if(h("removeSms",{smsNumber:e}),typeof e!="string")throw new I("smsNumber",v.WrongType);if(!e)throw new I("smsNumber",v.Empty);const t=OneSignal.coreDirector.getSmsSubscriptionModels();Object.keys(t).forEach(async n=>{t[n].data?.token===e&&OneSignal.coreDirector.remove(E.Subscriptions,n)})}addTag(e,t){if(h("addTag",{key:e,value:t}),typeof e!="string")throw new I("key",v.WrongType);if(typeof t!="string")throw new I("value",v.WrongType);if(!e)throw new I("key",v.Empty);if(!t)throw new I("value",v.Empty,"Did you mean to call removeTag?");this.addTags({[e]:t})}addTags(e){if(h("addTags",{tags:e}),typeof e!="object")throw new I("tags",v.WrongType);if(!e)throw new I("tags",v.Empty);const t=OneSignal.coreDirector.getPropertiesModel();e={...t?.data?.tags,...e},t?.set("tags",e)}removeTag(e){if(h("removeTag",{tagKey:e}),typeof e!="string")throw new I("tagKey",v.WrongType);if(typeof e>"u")throw new I("tagKey",v.Empty);this.removeTags([e])}removeTags(e){if(h("removeTags",{tagKeys:e}),!e||e.length===0)throw new I("tagKeys",v.Empty);const t=OneSignal.coreDirector.getPropertiesModel(),i=JSON.parse(JSON.stringify(t?.data?.tags));i&&(e.forEach(n=>{i[n]=""}),t?.setApplyToRecordId(t?.onesignalId),t?.set("tags",i))}getTags(){return h("getTags"),OneSignal.coreDirector.getPropertiesModel()?.data?.tags}setLanguage(e){if(h("setLanguage",{language:e}),typeof e!="string")throw new I("language",v.WrongType);if(!e)throw new I("language",v.Empty);OneSignal.coreDirector.getPropertiesModel()?.set("language",e)}getLanguage(){return h("getLanguage"),OneSignal.coreDirector.getPropertiesModel()?.data?.language}}class Ut{}class $i extends Ut{_id;_token;_optedIn;_permission;constructor(e,t,i){if(super(),!e||!t){r.warn(`PushSubscriptionNamespace: skipping initialization. One or more required params are falsy: initialize: ${e}, subscription: ${t}`);return}this._optedIn=!t.optedOut,this._permission=i,this._token=t.subscriptionToken,OneSignal.coreDirector.getPushSubscriptionModel().then(n=>{n&&ne(n.data)&&(this._id=n.data.id)}).catch(n=>{r.error(n)}),OneSignal.emitter.on(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,async n=>{this._id=n?.current.id,this._token=n?.current.token}),OneSignal.emitter.on(OneSignal.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,async n=>{this._permission=n})}get id(){return this._id}get token(){return this._token}get optedIn(){return!!this._optedIn&&this._permission==="granted"}async optIn(){if(h("optIn"),await ce(),this._optedIn=!0,await OneSignal.context.permissionManager.getPermissionStatus()!=="granted"){await OneSignal.Notifications.requestPermission();return}await this._enable(!0)}async optOut(){h("optOut"),await ce(),this._optedIn=!1,await this._enable(!1)}addEventListener(e,t){OneSignal.emitter.on(e,t)}removeEventListener(e,t){OneSignal.emitter.off(e,t)}async _enable(e){await ce();const t=await u.getAppConfig(),i=await u.getSubscription();if(!t.appId)throw new Me(Ae.MissingAppId);if(!Mt.isValidBoolean(e))throw new I("enabled",v.Malformed);i.optedOut=!e,await u.setSubscription(i),J.onInternalSubscriptionSet(i.optedOut).catch(n=>{r.error(n)}),J.checkAndTriggerSubscriptionChanged().catch(n=>{r.error(n)})}}class st extends Ut{_currentUser;PushSubscription=new $i(!1);static emitter=new Ot;constructor(e,t,i){super(),e&&(this._currentUser=_.createOrGetInstance(),this.PushSubscription=new $i(!0,t,i))}get onesignalId(){return this._currentUser?.onesignalId}get externalId(){return OneSignal.coreDirector.getIdentityModel()?.data?.external_id}addAlias(e,t){this._currentUser?.addAlias(e,t)}addAliases(e){this._currentUser?.addAliases(e)}removeAlias(e){this._currentUser?.removeAlias(e)}removeAliases(e){this._currentUser?.removeAliases(e)}addEmail(e){this._currentUser?.addEmail(e)}removeEmail(e){this._currentUser?.removeEmail(e)}addSms(e){this._currentUser?.addSms(e)}removeSms(e){this._currentUser?.removeSms(e)}addTag(e,t){this._currentUser?.addTag(e,t)}addTags(e){this._currentUser?.addTags(e)}removeTag(e){this._currentUser?.removeTag(e)}removeTags(e){this._currentUser?.removeTags(e)}getTags(){return this._currentUser?.getTags()||{}}setLanguage(e){this._currentUser?.setLanguage(e)}getLanguage(){return this._currentUser?.getLanguage()||""}addEventListener(e,t){st.emitter.on(e,t)}removeEventListener(e,t){st.emitter.off(e,t)}}class J{static onNotificationPermissionChange(){J.checkAndTriggerSubscriptionChanged()}static async onInternalSubscriptionSet(e){F.put("subscription.optedOut",e)}static async checkAndTriggerSubscriptionChanged(){B.logMethodCall("checkAndTriggerSubscriptionChanged");const e=OneSignal.context,t=await OneSignal.context.subscriptionManager.isPushNotificationsEnabled(),i=await OneSignal.context.subscriptionManager.isOptedIn(),n=await u.getAppState(),{lastKnownPushEnabled:o,lastKnownPushId:a,lastKnownPushToken:c,lastKnownOptedIn:d}=n,l=await L.getCurrentPushToken(),b=(await OneSignal.coreDirector.getPushSubscriptionModel())?.data?.id;if(!(o===null||t!==o||l!==c||b!==a))return;await e.subscriptionManager.updateNotificationTypes(),n.lastKnownPushEnabled=t,n.lastKnownPushToken=l,n.lastKnownPushId=b,n.lastKnownOptedIn=i,await u.setAppState(n);const T={previous:{id:a,token:c,optedIn:d??!0},current:{id:b,token:l,optedIn:i}};r.info("Push Subscription state changed: ",T),J.triggerSubscriptionChanged(T)}static async _onSubscriptionChanged(e){J.onSubscriptionChanged_showWelcomeNotification(e?.current?.optedIn,e?.current?.id),J.onSubscriptionChanged_sendCategorySlidedownTags(e?.current?.optedIn),J.onSubscriptionChanged_evaluateNotifyButtonDisplayPredicate(),J.onSubscriptionChanged_updateCustomLink()}static async onSubscriptionChanged_sendCategorySlidedownTags(e){if(e!==!0)return;const t=OneSignal.context.appConfig.userConfig.promptOptions?.slidedown?.prompts;pe.isCategorySlidedownConfigured(t)&&await OneSignal.context.tagManager.sendTags()}static async onSubscriptionChanged_showWelcomeNotification(e,t){if(OneSignal.__doNotShowWelcomeNotification){r.debug("Not showing welcome notification because user has previously subscribed.");return}const i=OneSignal.config?.userConfig.welcomeNotification;if(i!==void 0&&i.disable===!0||e!==!0||!t)return;let o=i!==void 0&&i.title!==void 0&&i.title!==null?i.title:"",a=i!==void 0&&i.message!==void 0&&i.message!==null&&i.message.length>0?i.message:"Thanks for subscribing!";const c=new URL(location.href).origin+"?_osp=do_not_open",d=i&&i.url&&i.url.length>0?i.url:c;o=ft.decodeHtmlEntities(o),a=ft.decodeHtmlEntities(a),r.debug("Sending welcome notification."),L.showLocalNotification(o,a,d,void 0,{__isOneSignalWelcomeNotification:!0},void 0),P.trigger(OneSignal.EVENTS.WELCOME_NOTIFICATION_SENT,{title:o,message:a,url:d})}static async onSubscriptionChanged_evaluateNotifyButtonDisplayPredicate(){if(!OneSignal.config.userConfig.notifyButton)return;const e=OneSignal.config.userConfig.notifyButton.displayPredicate;e&&typeof e=="function"&&OneSignal.notifyButton&&(await e()!==!1?(r.debug("Showing notify button because display predicate returned true."),OneSignal.notifyButton.launcher.show()):(r.debug("Hiding notify button because display predicate returned false."),OneSignal.notifyButton.launcher.hide()))}static async onSubscriptionChanged_updateCustomLink(){OneSignal.config.userConfig.promptOptions&&new Fi(OneSignal.config.userConfig.promptOptions.customlink).initialize()}static triggerSubscriptionChanged(e){P.trigger(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,e)}static triggerUserChanged(e){P.trigger(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,e,st.emitter)}static triggerNotificationClick(e){const t={notification:e.notification,result:e.result};return P.trigger(OneSignal.EVENTS.NOTIFICATION_CLICKED,t)}static async fireStoredNotificationClicks(){await ce();const e=OneSignal.config.pageUrl||OneSignal.config.userConfig.pageUrl||document.URL;async function t(o){const a=await u.getAppState();a.pendingNotificationClickEvents[o.result.url]=null,await u.setAppState(a);const c=o.timestamp;c&&(Date.now()-c)/1e3/60>5||J.triggerNotificationClick(o)}const i=await u.getAppState();if(await u.get("Options","notificationClickHandlerMatch")==="origin"){for(const o of Object.keys(i.pendingNotificationClickEvents))if(new URL(o).origin===location.origin){const a=i.pendingNotificationClickEvents[o];await t(a)}}else{let o=i.pendingNotificationClickEvents[e];if(o)await t(o);else if(!o&&e.endsWith("/")){const a=e.substring(0,e.length-1);o=i.pendingNotificationClickEvents[a],o&&await t(o)}}}static async checkAndTriggerUserChanged(){B.logMethodCall("checkAndTriggerUserChanged");const e=await u.getUserState(),{previousOneSignalId:t,previousExternalId:i}=e,n=await OneSignal.coreDirector.getIdentityModel(),o=n?.onesignalId,a=n?.data?.external_id;if(!(o!==t||a!==i))return;e.previousOneSignalId=o,e.previousExternalId=a,await u.setUserState(e);const d={current:{onesignalId:o,externalId:a}};r.info("User state changed: ",d),J.triggerUserChanged(d)}}class ot{static async registerForPush(){return await ot.internalRegisterForPush()}static async internalRegisterForPush(){const e=OneSignal.context;let t=null;switch(x.getWindowEnv()){case Y.Host:try{const i=await e.subscriptionManager.subscribe(ht.ResubscribeExisting);t=await e.subscriptionManager.registerSubscription(i),e.pageViewManager.incrementPageViewCount(),await Ee.triggerNotificationPermissionChanged(),await J.checkAndTriggerSubscriptionChanged()}catch(i){r.error(i)}break;default:throw new Me(Ae.UnsupportedEnvironment)}return t}static isPushSubscriptionType(e){switch(e){case q.ChromePush:case q.SafariPush:case q.SafariLegacyPush:case q.FirefoxPush:return!0;default:return!1}}static toSubscriptionChannel(e){switch(e){case q.Email:return De.Email;case q.SMS:return De.SMS;default:return this.isPushSubscriptionType(e)?De.Push:void 0}}}var qe=(s=>(s.Safari="safari",s.Firefox="firefox",s.Chrome="chrome",s.Opera="opera",s.Edge="edge",s.Other="other",s))(qe||{});class li{static getEnvironmentInfo(){return{browserType:this.getBrowser(),browserVersion:this.getBrowserVersion(),isBrowserAndSupportsServiceWorkers:this.supportsServiceWorkers(),requiresUserInteraction:this.requiresUserInteraction(),osVersion:this.getOsVersion()}}static getBrowser(){return N().name==="chrome"?qe.Chrome:N().name==="msedge"?qe.Edge:N().name==="opera"?qe.Opera:N().name==="firefox"?qe.Firefox:this.isMacOSSafari()?qe.Safari:qe.Other}static isMacOSSafari(){return typeof window.safari<"u"}static getBrowserVersion(){return y.parseVersionString(N().version)}static supportsServiceWorkers(){return window.navigator&&"serviceWorker"in window.navigator}static requiresUserInteraction(){return this.getBrowser()==="firefox"&&this.getBrowserVersion()>=72||this.getBrowser()==="safari"&&this.getBrowserVersion()>=12.1}static getOsVersion(){return Gt.osversion}}var we=(s=>(s[s.NoNativePermission=0]="NoNativePermission",s[s.Subscribed=1]="Subscribed",s[s.UserOptedOut=-2]="UserOptedOut",s[s.NotSubscribed=-10]="NotSubscribed",s[s.TemporaryWebRecord=-20]="TemporaryWebRecord",s[s.PermissionRevoked=-21]="PermissionRevoked",s[s.PushSubscriptionRevoked=-22]="PushSubscriptionRevoked",s[s.ServiceWorkerStatus403=-23]="ServiceWorkerStatus403",s[s.ServiceWorkerStatus404=-24]="ServiceWorkerStatus404",s))(we||{}),mt=(s=>(s[s.ChromeLike=5]="ChromeLike",s[s.SafariLegacy=7]="SafariLegacy",s[s.Firefox=8]="Firefox",s[s.Email=11]="Email",s[s.Edge=12]="Edge",s[s.SMS=14]="SMS",s[s.SafariVapid=17]="SafariVapid",s))(mt||{});class Ve{type;token;enabled;notificationTypes;sdk;deviceModel;deviceOs;webAuth;webp256;constructor(e){const t=li.getEnvironmentInfo();this.token=this._getToken(e),this.type=Ve.getSubscriptionType(),this.notificationTypes=we.Subscribed,this.sdk="160307",this.deviceModel=navigator.platform,this.deviceOs=isNaN(t.browserVersion)?-1:t.browserVersion,this.webAuth=e.w3cAuth,this.webp256=e.w3cP256dh}_getToken(e){return e.w3cEndpoint?e.w3cEndpoint.toString():e.safariDeviceToken}serialize(){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}}static getSubscriptionType(){return B.redetectBrowserUserAgent().firefox?q.FirefoxPush:R.useSafariVapidPush()?q.SafariPush:R.useSafariLegacyPush()?q.SafariLegacyPush:q.ChromePush}static getDeviceType(){switch(this.getSubscriptionType()){case q.FirefoxPush:return mt.Firefox;case q.SafariLegacyPush:return mt.SafariLegacy;case q.SafariPush:return mt.SafariVapid}return mt.ChromeLike}}class Yn{constructor(e){this.core=e}generatePushSubscriptionModel(e){h("CoreModuleDirector.generatePushSubscriptionModel",{rawPushSubscription:e});const t=new Ce(E.Subscriptions,new Ve(e).serialize()),i=_.createOrGetInstance();i.hasOneSignalId&&t.setOneSignalId(i.onesignalId);const o=this.getIdentityModel()?.data.external_id;o&&t.setExternalId(o),O.coreDirector.add(E.Subscriptions,t,!1)}async resetModelRepoAndCache(){await this.core.resetModelRepoAndCache()}hydrateUser(e,t){h("CoreModuleDirector.hydrateUser",{user:e,externalId:t});try{const i=this.getIdentityModel(),n=this.getPropertiesModel(),{onesignal_id:o}=e.identity;if(!o)throw new S("OneSignal ID is missing from user data");i?.setOneSignalId(o),n?.setOneSignalId(o),t&&(i?.setExternalId(t),n?.setExternalId(t),e.identity.external_id=t),i?.hydrate(e.identity),n?.hydrate(e.properties),this._hydrateSubscriptions(e.subscriptions,o,t),J.checkAndTriggerUserChanged()}catch(i){r.error(`Error hydrating user: ${i}`)}}_hydrateSubscriptions(e,t,i){if(h("CoreModuleDirector._hydrateSubscriptions",{subscriptions:e,onesignalId:t,externalId:i}),!e)return;const n=this.getModelStores();e.forEach(async o=>{const a=o.token?this.getSubscriptionOfTypeWithToken(ot.toSubscriptionChannel(o.type),o.token):void 0;if(a)a.setOneSignalId(t),i&&a?.setExternalId(i),a.hydrate(o);else{const c=new Ce(E.Subscriptions,o);c.setOneSignalId(t),i&&c?.setExternalId(i),n[E.Subscriptions].add(c,!1)}})}forceDeltaQueueProcessingOnAllExecutors(){h("CoreModuleDirector.forceDeltaQueueProcessingOnAllExecutors"),this.core.forceDeltaQueueProcessingOnAllExecutors()}add(e,t,i=!0){h("CoreModuleDirector.add",{modelName:e,model:t}),this.getModelStores()[e].add(t,i)}remove(e,t){h("CoreModuleDirector.remove",{modelName:e,modelId:t}),this.getModelStores()[e].remove(t)}getNewRecordsState(){return this.core.newRecordsState}getModelByTypeAndId(e,t){return h("CoreModuleDirector.getModelByTypeAndId",{modelName:e,modelId:t}),this.getModelStores()[e].models[t]}getEmailSubscriptionModels(){h("CoreModuleDirector.getEmailSubscriptionModels");const t=this.getModelStores().subscriptions.models;return Object.fromEntries(Object.entries(t).filter(([,n])=>n.data?.type===q.Email))}async hasEmail(){const e=this.getEmailSubscriptionModels();return Object.keys(e).length>0}getSmsSubscriptionModels(){h("CoreModuleDirector.getSmsSubscriptionModels");const t=this.getModelStores().subscriptions.models;return Object.fromEntries(Object.entries(t).filter(([,n])=>n.data?.type===q.SMS))}async hasSms(){const e=this.getSmsSubscriptionModels();return Object.keys(e).length>0}getAllPushSubscriptionModels(){h("CoreModuleDirector.getAllPushSubscriptionModels");const t=this.getModelStores().subscriptions.models;return Object.fromEntries(Object.entries(t).filter(([,n])=>ot.isPushSubscriptionType(n.data?.type)))}async getPushSubscriptionModelByCurrentToken(){h("CoreModuleDirector.getPushSubscriptionModelByCurrentToken");const e=await L.getCurrentPushToken();if(e)return this.getSubscriptionOfTypeWithToken(De.Push,e)}async getPushSubscriptionModelByLastKnownToken(){h("CoreModuleDirector.getPushSubscriptionModelByLastKnownToken");const{lastKnownPushToken:e}=await u.getAppState();if(e)return this.getSubscriptionOfTypeWithToken(De.Push,e)}async getPushSubscriptionModel(){return h("CoreModuleDirector.getPushSubscriptionModel"),await this.getPushSubscriptionModelByCurrentToken()||await this.getPushSubscriptionModelByLastKnownToken()}getIdentityModel(){h("CoreModuleDirector.getIdentityModel");const e=this.getModelStores(),t=Object.keys(e.identity.models);return e.identity.models[t[0]]}getPropertiesModel(){h("CoreModuleDirector.getPropertiesModel");const e=this.getModelStores(),t=Object.keys(e.properties.models);return e.properties.models[t[0]]}async getAllSubscriptionsModels(){h("CoreModuleDirector.getAllSubscriptionsModels");const e=this.getEmailSubscriptionModels(),t=this.getSmsSubscriptionModels(),i=await this.getPushSubscriptionModel();return Object.values(e).concat(Object.values(t)).concat(i?[i]:[])}getSubscriptionOfTypeWithToken(e,t){h("CoreModuleDirector.getSubscriptionOfTypeWithToken",{type:e,token:t});let i;switch(e){case De.Email:i=this.getEmailSubscriptionModels();break;case De.SMS:i=this.getSmsSubscriptionModels();break;case De.Push:i=this.getAllPushSubscriptionModels();break;default:return}return Object.values(i).find(n=>n.data.token===t)}getModelStores(){return this.core.modelRepo?.modelStores}}var di,Hi;function Zn(){if(Hi)return di;Hi=1,di=t;var s=0;function e(){}function t(i,n,o){typeof n=="function"&&(o=n,n={}),n||(n={});var a=n.prefix||"__jp",c=n.name||a+s++,d=n.param||"callback",l=n.timeout!=null?n.timeout:6e4,p=encodeURIComponent,b=document.getElementsByTagName("script")[0]||document.head,w,T;l&&(T=setTimeout(function(){M(),o&&o(new Error("Timeout"))},l));function M(){w.parentNode&&w.parentNode.removeChild(w),window[c]=e,T&&clearTimeout(T)}function Ye(){window[c]&&M()}return window[c]=function(ct){M(),o&&o(null,ct)},i+=(~i.indexOf("?")?"&":"?")+d+"="+p(c),i=i.replace("?&","?"),w=document.createElement("script"),w.src=i,b.parentNode.insertBefore(w,b),Ye}return di}var Xn=Zn();const es=ki(Xn);var be=(s=>(s[s.Direct=1]="Direct",s[s.Indirect=2]="Indirect",s[s.Unattributed=3]="Unattributed",s[s.NotSupported=4]="NotSupported",s))(be||{});class Rt{static async sendOutcome(e){r.info("Outcome payload:",e);try{await W.post("outcomes/measure",e)}catch(t){r.error("sendOutcome",t)}}}class ui{static async downloadServerAppConfig(e){return y.enforceAppId(e),(await W.get(`sync/${e}/web`,null))?.result}static getUserIdFromSubscriptionIdentifier(e,t,i){return y.enforceAppId(e),W.post("players",{app_id:e,device_type:t,identifier:i,notification_types:we.TemporaryWebRecord}).then(n=>n?.result?.id?n.result.id:null).catch(n=>(r.debug("Error getting user ID from subscription identifier:",n),null))}static async updateUserSession(e,t,i){const n=new Q(Q.ONESIGNAL_ID,t),o={refresh_device_metadata:!0,deltas:{session_count:1}};y.enforceAppId(e),y.enforceAlias(n);try{await se.updateUser({appId:e,subscriptionId:i},n,o)}catch(a){r.debug("Error updating user session:",a)}}static async sendSessionDuration(e,t,i,n,o){const a={refresh_device_metadata:!0,deltas:{session_time:n}},c=new Q(Q.ONESIGNAL_ID,t),d={id:"os__session_duration",app_id:e,session_time:n,notification_ids:o.notificationIds,subscription:{id:i,type:Ve.getSubscriptionType()},onesignal_id:t};d.direct=o.type===be.Direct;try{await se.updateUser({appId:e,subscriptionId:i},c,a),d.notification_ids&&d.notification_ids.length>0&&await Rt.sendOutcome(d)}catch(l){r.debug("Error sending session duration:",l)}}}class gi{static jsonpLib(e,t){es(e,null,t)}static async downloadServerAppConfig(e){return x.getWindowEnv()===Y.Host?await new Promise((t,i)=>{gi.jsonpLib(`${x.getOneSignalApiUrl().toString()}/sync/${e}/web`,(n,o)=>{n?i(n):o.success?t(o):i(o)})}):await ui.downloadServerAppConfig(e)}}const pi={reportingThreshold:30,enableOnSessionForUnsubcribed:!1,enableOnFocus:!0},de={pageViews:1,timeDelay:0},oe={actionMessage:"We'd like to show you notifications for the latest news and updates.",acceptButton:"Allow",cancelButton:"Cancel",errorButton:"Try Again",categoryDefaults:{updateMessage:"Update your push notification subscription preferences.",positiveUpdateButton:"Save Preferences",negativeUpdateButton:"Cancel"},savingText:"Saving...",confirmMessage:"Thank You!"},hi={type:f.Push,text:{actionMessage:oe.actionMessage,acceptButton:oe.acceptButton,cancelButton:oe.cancelButton},autoPrompt:!1,delay:de};var Lt=(s=>(s.TypicalSite="typical",s.WordPress="wordpress",s.Shopify="shopify",s.Blogger="blogger",s.Magento="magento",s.Drupal="drupal",s.SquareSpace="squarespace",s.Joomla="joomla",s.Weebly="weebly",s.Wix="wix",s.Custom="custom",s))(Lt||{});class Se{static convertTagsApiToBooleans(e){const t={};return Object.keys(e).forEach(i=>{t[i]=e[i]==="1"}),t}static convertTagsBooleansToApi(e){const t={};return Object.keys(e).forEach(i=>{t[i]=e[i]===!0?"1":"0"}),t}static getObjectDifference(e,t){const i={};return Object.keys(e).forEach(n=>{t[n]!==e[n]&&(i[n]=e[n])}),i}static markAllTagsAsSpecified(e,t){e.forEach(i=>{i.checked=t})}static isTagObjectEmpty(e){return Object.keys(e).length===0}static getCheckedTagCategories(e,t){if(!t)return e;if(Se.isTagObjectEmpty(t)){const o=Jt(e);return Se.markAllTagsAsSpecified(o,!0),o}return Jt(e).map(o=>{const a=t[o.tag];return o.checked=Se.getCheckedStatusForTagValue(a),o})}static getCheckedStatusForTagValue(e){return e===void 0?!0:e}static limitCategoriesToMaxCount(e,t){let i=Jt(e);return i=e.slice(0,t),i}}class at{static upgradeConfigToVersionTwo(e){at.isPromptOptionsVersion0(e.promptOptions)&&(e.promptOptions=at.convertConfigToVersionOne(e.promptOptions)),at.isSlidedownConfigVersion1(e.promptOptions?.slidedown)&&e.promptOptions?.slidedown&&(e.promptOptions.slidedown=at.convertConfigToVersionTwo(e.promptOptions?.slidedown))}static convertConfigToVersionOne(e){e.slidedown||(e.slidedown={});const{acceptButtonText:t,cancelButtonText:i,actionMessage:n}=e.slidedown,o=e.acceptButtonText||e.acceptButton,a=e.cancelButtonText||e.cancelButton;return e.slidedown.acceptButtonText=t||o,e.slidedown.cancelButtonText=i||a,e.slidedown.actionMessage=n||e.actionMessage,e}static convertConfigToVersionTwo(e){const t=pe.isCategorySlidedownConfiguredVersion1(e)?f.Category:f.Push;let i,n;return t===f.Category&&(i=e.categories?.positiveUpdateButton,n=e.categories?.negativeUpdateButton),{prompts:[...e.prompts||[],{type:t,autoPrompt:e.autoPrompt,text:{actionMessage:e.actionMessage,acceptButton:e.acceptButton||e.acceptButtonText,cancelButton:e.cancelButton||e.cancelButtonText,positiveUpdateButton:i,negativeUpdateButton:n,updateMessage:e?.categories?.updateMessage},delay:{pageViews:e.pageViews,timeDelay:e.timeDelay},categories:e?.categories?.tags}]}}static isPromptOptionsVersion0(e){if(e){const t=["acceptButtonText","cancelButtonText","actionMessage"];for(let i=0;i Web Configuration to find this option."):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. Please visit the OneSignal dashboard's Settings > Web Configuration to find this option.`)}static checkRestrictedOrigin(e){if(e.restrictedOriginEnabled&&x.getWindowEnv()===Y.Host&&!this.doesCurrentOriginMatchConfigOrigin(e.origin))throw new ge(me.WrongSiteUrl,{siteUrl:e.origin})}static doesCurrentOriginMatchConfigOrigin(e){try{return location.origin===new URL(e).origin}catch{return!1}}static getIntegrationCapabilities(e){switch(e){case Lt.Custom:case Lt.WordPress:return{configuration:1};default:return{configuration:0}}}static getMergedConfig(e,t){const i=this.getConfigIntegrationKind(t),n=this.hasUnsupportedSubdomainForConfigIntegrationKind(i,e,t),o=this.getUserConfigForConfigIntegrationKind(i,e,t);return{appId:t.app_id,hasUnsupportedSubdomain:n,siteName:t.config.siteInfo.name,origin:t.config.origin,restrictedOriginEnabled:t.features.restrict_origin&&t.features.restrict_origin.enable,safariWebId:t.config.safari_web_id,vapidPublicKey:t.config.vapid_public_key,onesignalVapidPublicKey:t.config.onesignal_vapid_public_key,userConfig:o,enableOnSession:y.valueOrDefault(t.features.enable_on_session,pi.enableOnSessionForUnsubcribed),sessionThreshold:y.valueOrDefault(t.features.session_threshold,pi.reportingThreshold),enableSessionDuration:y.valueOrDefault(t.features.web_on_focus_enabled,pi.enableOnFocus)}}static getConfigIntegrationKind(e){return e.config.integration?e.config.integration.kind:Lt.Custom}static getCustomLinkConfig(e){const t={enabled:!1,style:"button",size:"medium",unsubscribeEnabled:!1,text:{explanation:"",subscribe:"",unsubscribe:""},color:{button:"",text:""}};if(!e||!e.config||!e.config.staticPrompts||!e.config.staticPrompts.customlink||!e.config.staticPrompts.customlink.enabled)return t;const i=e.config.staticPrompts.customlink;return{enabled:i.enabled,style:i.style,size:i.size,unsubscribeEnabled:i.unsubscribeEnabled,text:i.text?{subscribe:i.text.subscribe,unsubscribe:i.text.unsubscribe,explanation:i.text.explanation}:t.text,color:i.color?{button:i.color.button,text:i.color.text}:t.color}}static injectDefaultsIntoPromptOptions(e,t,i){let n={enabled:!1};e&&e.customlink&&(n=e.customlink);const o=t.customlink,a={...e,customlink:{enabled:y.getValueOrDefault(n.enabled,o.enabled),style:y.getValueOrDefault(n.style,o.style),size:y.getValueOrDefault(n.size,o.size),unsubscribeEnabled:y.getValueOrDefault(n.unsubscribeEnabled,o.unsubscribeEnabled),text:{subscribe:y.getValueOrDefault(n.text?n.text.subscribe:void 0,o.text.subscribe),unsubscribe:y.getValueOrDefault(n.text?n.text.unsubscribe:void 0,o.text.unsubscribe),explanation:y.getValueOrDefault(n.text?n.text.explanation:void 0,o.text.explanation)},color:{button:y.getValueOrDefault(n.color?n.color.button:void 0,o.color.button),text:y.getValueOrDefault(n.color?n.color.text:void 0,o.color.text)}}};return a.slidedown?a.slidedown.prompts=a.slidedown?.prompts?.map(c=>{if(c.type=y.getValueOrDefault(c.type,f.Push),c.type===f.Category&&(c.text={...c.text,positiveUpdateButton:y.getValueOrDefault(c.text?.positiveUpdateButton,oe.categoryDefaults.positiveUpdateButton),negativeUpdateButton:y.getValueOrDefault(c.text?.negativeUpdateButton,oe.categoryDefaults.negativeUpdateButton),updateMessage:y.getValueOrDefault(c.text?.updateMessage,oe.categoryDefaults.updateMessage)}),c.text={...c.text,actionMessage:y.getValueOrDefault(c.text?.actionMessage,oe.actionMessage),acceptButton:y.getValueOrDefault(c.text?.acceptButton,oe.acceptButton),cancelButton:y.getValueOrDefault(c.text?.cancelButton,oe.cancelButton),confirmMessage:y.getValueOrDefault(c.text?.confirmMessage,oe.confirmMessage)},c.autoPrompt=y.getValueOrDefault(c.autoPrompt,!0),c.delay={pageViews:y.getValueOrDefault(c.delay?.pageViews,de.pageViews),timeDelay:y.getValueOrDefault(c.delay?.timeDelay,de.timeDelay)},c.categories){const{categories:d}=c;c.categories=Se.limitCategoriesToMaxCount(d,ts)}return c}):(a.slidedown={prompts:[]},a.slidedown.prompts=[hi]),a.native?(a.native.enabled=!!a.native.enabled,a.native.autoPrompt=a.native.hasOwnProperty("autoPrompt")?!!a.native.enabled&&!!a.native.autoPrompt:!!a.native.enabled,a.native.pageViews=y.getValueOrDefault(a.native.pageViews,de.pageViews),a.native.timeDelay=y.getValueOrDefault(a.native.timeDelay,de.timeDelay)):a.native={enabled:!1,autoPrompt:!1,pageViews:de.pageViews,timeDelay:de.timeDelay},i.autoRegister===!0&&(a.native.enabled=!0,a.native.autoPrompt=!0),a.autoPrompt=a.native.autoPrompt||pe.isSlidedownAutoPromptConfigured(a.slidedown.prompts),a}static getPromptOptionsForDashboardConfiguration(e){const t=e.config.staticPrompts,i=t.native?{enabled:t.native.enabled,autoPrompt:t.native.enabled&&t.native.autoPrompt!==!1,pageViews:y.getValueOrDefault(t.native.pageViews,de.pageViews),timeDelay:y.getValueOrDefault(t.native.timeDelay,de.timeDelay)}:{enabled:!1,autoPrompt:!1,pageViews:de.pageViews,timeDelay:de.timeDelay},{prompts:n}=t.slidedown;return{autoPrompt:i.autoPrompt||pe.isSlidedownAutoPromptConfigured(n),native:i,slidedown:{prompts:n},fullscreen:{enabled:t.fullscreen.enabled,actionMessage:t.fullscreen.actionMessage,acceptButton:t.fullscreen.acceptButton,cancelButton:t.fullscreen.cancelButton,title:t.fullscreen.title,message:t.fullscreen.message,caption:t.fullscreen.caption,autoAcceptTitle:t.fullscreen.autoAcceptTitle},customlink:this.getCustomLinkConfig(e)}}static getServiceWorkerValues(e,t){const i=e.serviceWorkerOverrideForTypical,n=i?y.getValueOrDefault(e.path,t.config.serviceWorker.path):t.config.serviceWorker.path,o=i?y.getValueOrDefault(e.serviceWorkerParam,{scope:t.config.serviceWorker.registrationScope}):{scope:t.config.serviceWorker.registrationScope},a=i?y.getValueOrDefault(e.serviceWorkerPath,t.config.serviceWorker.workerName):t.config.serviceWorker.workerName;return{path:n,serviceWorkerParam:o,serviceWorkerPath:a}}static getUserConfigForConfigIntegrationKind(e,t,i){switch(this.getIntegrationCapabilities(e).configuration){case 0:{const{path:o,serviceWorkerPath:a,serviceWorkerParam:c}=this.getServiceWorkerValues(t,i);return{appId:i.app_id,autoRegister:!1,autoResubscribe:i.config.autoResubscribe,path:o,serviceWorkerPath:a,serviceWorkerParam:c,subdomainName:i.config.siteInfo.proxyOrigin,promptOptions:this.getPromptOptionsForDashboardConfiguration(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,allowLocalhostAsSecureOrigin:i.config.setupBehavior?i.config.setupBehavior.allowLocalhostAsSecureOrigin: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 o={scope:"/"},c={...t,promptOptions:this.injectDefaultsIntoPromptOptions(t.promptOptions,i.config.staticPrompts,t),serviceWorkerParam:t.serviceWorkerParam?t.serviceWorkerParam:o,serviceWorkerPath:t.serviceWorkerPath?t.serviceWorkerPath:"OneSignalSDKWorker.js",path:t.path?t.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 t.hasOwnProperty("autoResubscribe")?c.autoResubscribe=!!t.autoResubscribe:t.hasOwnProperty("autoRegister")?c.autoResubscribe=!!t.autoRegister:c.autoResubscribe=!!i.config.autoResubscribe,c}}}static hasUnsupportedSubdomainForConfigIntegrationKind(e,t,i){switch(this.getIntegrationCapabilities(e).configuration){case 0:return i.config.siteInfo.proxyOriginEnabled;case 1:return!!t.subdomainName}}}class is{async getAppConfig(e){return await ji.getAppConfig(e,gi.downloadServerAppConfig)}getMergedConfig(e,t){return ji.getMergedConfig(e,t)}}class ee{static switchingUsersPromise=Promise.resolve();static async login(e,t){await(this.switchingUsersPromise=ee._login(e,t))}static async _login(e,t){const i=Ge.getConsentRequired(),n=await u.getConsentGiven();if(i&&!n)throw new S("Login: Consent required but not given, skipping login");try{O.coreDirector.forceDeltaQueueProcessingOnAllExecutors(),t&&await u.setJWTToken(t);const o=O.coreDirector.getIdentityModel(),a=o?.onesignalId;if(!o)throw new S("Login: No identity model found");const c=o?.data?.external_id;if(c===e){r.debug("Login: External ID already set, skipping login");return}const d=await O.coreDirector.getPushSubscriptionModel();let l;d&&ne(d.data)&&(l=d.data.id);const p=ee.isIdentified(o.data);ee.setExternalId(o,e);let b;if(!p)b=await K.getAllUserData();else{b={identity:{external_id:e}};const w=await O.coreDirector.getPushSubscriptionModel();w&&(b.subscriptions=[w.data])}await O.coreDirector.resetModelRepoAndCache(),await K.initializeUser(!0);try{const T=(await ee.identifyOrUpsertUser(b,p,l))?.identity?.onesignal_id;if(!T){r.info("Caching login call, waiting on network or subscription creation.");return}await ee.fetchAndHydrate(T,e)}catch(w){if(r.error(`Login: Error while identifying/upserting user: ${w.message}`),a){r.debug("Login: Restoring old user data");try{await ee.fetchAndHydrate(a,c)}catch(T){r.error(`Login: Error while restoring old user data: ${T.message}`)}}throw w}}catch(o){r.error(o)}}static async logout(){await(this.switchingUsersPromise=ee._logout())}static async _logout(){const e=O.coreDirector?.getIdentityModel();if(!e||!e.data||!e.data.external_id){r.debug("Logout: User is not logged in, skipping logout");return}O.coreDirector.forceDeltaQueueProcessingOnAllExecutors(),K.resetUserMetaProperties();const t=await O.coreDirector.getPushSubscriptionModel();if(t?.setExternalId(void 0),await O.coreDirector.resetModelRepoAndCache(),t===void 0){await K.initializeUser(!0);return}O.coreDirector.add(E.Subscriptions,t,!1),await K.initializeUser(!1)}static setExternalId(e,t){if(h("LoginManager.setExternalId",{externalId:t}),!e)throw new S("login: no identity model found");e.set("external_id",t,!1)}static isIdentified(e){return h("LoginManager.isIdentified",{identity:e}),e.external_id!==void 0}static async identifyOrUpsertUser(e,t,i){h("LoginManager.identifyOrUpsertUser",{userData:e,isIdentified:t,subscriptionId:i});let n;return t?n=await this.upsertUser(e,i):n=await this.identifyUser(e,i),n}static async upsertUser(e,t,i=5){if(h("LoginManager.upsertUser",{userData:e,subscriptionId:t}),i===0)throw new S("Login: upsertUser failed: max retries reached");const n=await L.getAppId(),o=JSON.parse(JSON.stringify(e));this.stripAliasesOtherThanExternalId(e);const a=await se.createUser({appId:n,subscriptionId:t},e),c=a?.result,d=a?.status;if(d>=200&&d<300){const l=e.identity?.onesignal_id,p=O.coreDirector.getNewRecordsState();p||r.error("UpsertUser: NewRecordsState is undefined"),l&&p?.add(l);const b=e.subscriptions?.[0]?.token,w=c.subscriptions?.find(T=>T.token===b);w&&ne(w)&&p?.add(w.id),r.info("Successfully created user",c)}else if(d>=400&&d<500)r.error("Malformed request",c);else if(d>=500)return r.error("Server error. Retrying..."),await He(oi[i]),this.upsertUser(o,t,i-1);return c}static async identifyUser(e,t,i=5){if(h("LoginManager.identifyUser",{userData:e,pushSubscriptionId:t}),i===0)throw new S("Login: identifyUser failed: max retries reached");const{onesignal_id:n}=e.identity,o=JSON.parse(JSON.stringify(e));this.stripAliasesOtherThanExternalId(e);const{identity:a}=e;if(!a)throw new S("identifyUser failed: no identity found");if(!n)return O.coreDirector.getIdentityModel()?.set(Q.EXTERNAL_ID,a.external_id,!1),e;const c=await L.getAppId(),d=new Q(Q.ONESIGNAL_ID,n),l=await se.addAlias({appId:c},d,a),p=l?.status;if(p>=200&&p<300){r.info("identifyUser succeeded");const w=O.coreDirector.getNewRecordsState();w||r.error("IdentifyUser: NewRecordsState is undefined"),w?.add(n,!0)}else{if(p===409&&t)return await this.transferSubscription(c,t,a);if(p>=400&&p<500)throw new S(`identifyUser: malformed request: ${JSON.stringify(l?.result)}`);if(p>=500)return r.error("identifyUser failed: server error. Retrying..."),await He(oi[i]),this.identifyUser(o,t,i-1)}return{identity:l?.result?.identity}}static async fetchAndHydrate(e,t){h("LoginManager.fetchAndHydrate",{onesignalId:e,externalId:t});const i=await se.getUser({appId:await L.getAppId()},new Q(Q.ONESIGNAL_ID,e));O.coreDirector.hydrateUser(i?.result,t)}static stripAliasesOtherThanExternalId(e){h("LoginManager.stripAliasesOtherThanExternalId",{userData:e});const{identity:t}=e;if(!t)throw new S("stripAliasesOtherThanExternalId failed: no identity found");const{external_id:i}=t;if(!i)throw new S("stripAliasesOtherThanExternalId failed: no external_id found");const n={external_id:i};e.identity=n}static async transferSubscription(e,t,i){r.error("^^^ Handling 409 HTTP response reported by the browser above. This is an expected result when the User already exists. Push subscription is being transferred the existing User.");const o=await se.transferSubscription({appId:e},t,i,!1),a=o?.status,c=o?.result;if(a&&a>=200&&a<300)return r.info("transferSubscription succeeded"),{identity:c?.identity};throw new S(`transferSubscription failed: ${JSON.stringify(c)}}`)}}class wt{static async getRegistration(e){try{const t=location.origin+e;return await navigator.serviceWorker.getRegistration(t)}catch(t){r.warn("[Service Worker Status] Error Checking service worker registration",e,t);return}}static getAvailableServiceWorker(e){const t=e.active||e.installing||e.waiting;return t||r.warn("Could not find an available ServiceWorker instance!"),t}static waitUntilActive(e){return new Promise(t=>{const i=e.installing||e.waiting;i&&i.addEventListener("statechange",()=>{r.debug("OneSignal Service Worker state changed:",i.state),e.active&&t()}),e.active&&t()})}}class Bt extends S{status;statusText;constructor(e,t){super("Registration of a Service Worker failed."),this.status=e,this.statusText=t,Object.setPrototypeOf(this,Bt.prototype)}}class ke{static debug(...e){self.shouldLog&&console.debug(...e)}static trace(...e){self.shouldLog&&console.trace(...e)}static info(...e){self.shouldLog&&console.info(...e)}static warn(...e){self.shouldLog&&console.warn(...e)}static error(...e){self.shouldLog&&console.error(...e)}}function Gi(s,e){const t=e*1e3;let i,n=()=>{};return{promise:new Promise((a,c)=>{let d=!1;i=self.setTimeout(async()=>{d=!0;try{await s(),a()}catch(l){ke.error("Failed to execute callback",l),c()}},t),n=()=>{ke.debug("Cancel called"),self.clearTimeout(i),d||a()}}),cancel:n}}const ns="sendOutcome",ss="sendUniqueOutcome";class bt{outcomeName;config;appId;isUnique;constructor(e,t,i,n){this.outcomeName=i,this.config=t,this.appId=e,this.isUnique=n}async getAttribution(){return await bt.getAttribution(this.config)}async beforeOutcomeSend(){const e=this.isUnique?ss:ns;return h(e,this.outcomeName),this.config?this.outcomeName?(await ce(),await OneSignal.context.subscriptionManager.isPushNotificationsEnabled()?!0:(r.warn("Reporting outcomes is supported only for subscribed users."),!1)):(r.error("Outcome name is required"),!1):(r.debug("Outcomes feature not supported by main application yet."),!1)}async getAttributedNotifsByUniqueOutcomeName(){return(await u.getAll("SentUniqueOutcome")).filter(t=>t.outcomeName===this.outcomeName).reduce((t,i)=>{const n=i.notificationIds||[];return[...t,...n]},[])}async getNotifsToAttributeWithUniqueOutcome(e){const t=await this.getAttributedNotifsByUniqueOutcomeName();return e.filter(i=>t.indexOf(i)===-1)}shouldSendUnique(e,t){return e.type===be.Unattributed?!0:t.length>0}async saveSentUniqueOutcome(e){const t=this.outcomeName,i=await u.get("SentUniqueOutcome",t),n=await u.getCurrentSession(),a=[...i?i.notificationIds:[],...e],c=n?n.startTimestamp:null;await u.put("SentUniqueOutcome",{outcomeName:t,notificationIds:a,sentDuringSession:c})}async wasSentDuringSession(){const e=await u.get("SentUniqueOutcome",this.outcomeName);if(!e)return!1;const t=await u.getCurrentSession(),i=t&&e.sentDuringSession===t.startTimestamp,n=!t&&!!e.sentDuringSession;return i||n}async send(e){const{type:t,notificationIds:i,weight:n}=e;switch(t){case be.Direct:this.isUnique&&await this.saveSentUniqueOutcome(i),await OneSignal.context.updateManager.sendOutcomeDirect(this.appId,i,this.outcomeName,n);return;case be.Indirect:this.isUnique&&await this.saveSentUniqueOutcome(i),await OneSignal.context.updateManager.sendOutcomeInfluenced(this.appId,i,this.outcomeName,n);return;case be.Unattributed:if(this.isUnique){if(await this.wasSentDuringSession()){r.warn("(Unattributed) unique outcome was already sent during this session");return}await this.saveSentUniqueOutcome([])}await OneSignal.context.updateManager.sendOutcomeUnattributed(this.appId,this.outcomeName,n);return;default:r.warn("You are on a free plan. Please upgrade to use this functionality.");return}}static async getAttribution(e){if(e.direct&&e.direct.enabled){const t=await u.getAllNotificationClickedForOutcomes();if(t.length>0)return{type:be.Direct,notificationIds:[t[0].notificationId]}}if(e.indirect&&e.indirect.enabled){const t=e.indirect.influencedTimePeriodMin*60*1e3,n=new Date(new Date().getTime()-t).getTime(),o=await u.getAllNotificationReceivedForOutcomes();if(r.debug(` Found total of ${o.length} received notifications`),o.length>0){const a=e.indirect.influencedNotificationsLimit,c=y.sortArrayOfObjects(o,p=>p.timestamp,!0,!1),d=c.filter(p=>p.timestamp>=n).slice(0,a).map(p=>p.notificationId);r.debug(` Total of ${d.length} received notifications are within reporting window.`);const l=c.filter(p=>d.indexOf(p.notificationId)===-1).map(p=>p.notificationId);if(l.forEach(p=>u.remove(Ct,p)),r.debug(` ${l.length} received notifications will be deleted.`),d.length>0)return{type:be.Indirect,notificationIds:d}}}return e.unattributed&&e.unattributed.enabled?{type:be.Unattributed,notificationIds:[]}:{type:be.NotSupported,notificationIds:[]}}}class ye{static getServiceWorkerHref(e,t,i){return ye.appendServiceWorkerParams(e.workerPath.getFullPath(),t,i)}static appendServiceWorkerParams(e,t,i){const n=new URL(e,B.getBaseUrl()).href,o=y.encodeHashAsUriComponent({appId:t}),a=y.encodeHashAsUriComponent({sdkVersion:i});return`${n}?${o}&${a}`}static async upsertSession(e,t,i,n,o,a,c){const d=await u.getCurrentSession();if(!d){const w=Oi({appId:e}),T=await u.getLastNotificationClickedForOutcomes(e);T&&(w.notificationId=T.notificationId),await u.upsertSession(w),await ye.sendOnSessionCallIfNotPlayerCreate(e,t,i,a,w);return}if(d.status===Xe.Active){ke.debug("Session already active",d);return}if(!d.lastDeactivatedTimestamp){ke.debug("Session is in invalid state",d);return}const l=new Date().getTime();if(ye.timeInSecondsBetweenTimestamps(l,d.lastDeactivatedTimestamp)<=n){d.status=Xe.Active,d.lastActivatedTimestamp=l,d.lastDeactivatedTimestamp=null,await u.upsertSession(d);return}await ye.finalizeSession(e,t,i,d,o,c);const b=Oi({appId:e});await u.upsertSession(b),await ye.sendOnSessionCallIfNotPlayerCreate(e,t,i,a,b)}static async deactivateSession(e,t,i,n,o,a){const c=await u.getCurrentSession();if(!c){ke.debug("No active session found. Cannot deactivate.");return}const d=()=>ye.finalizeSession(e,t,i,c,o,a);if(c.status===Xe.Inactive)return Gi(d,n);if(c.status!==Xe.Active){ke.warn(`Session in invalid state ${c.status}. Cannot deactivate.`);return}const l=new Date().getTime(),p=ye.timeInSecondsBetweenTimestamps(l,c.lastActivatedTimestamp);c.lastDeactivatedTimestamp=l,c.accumulatedDuration+=p,c.status=Xe.Inactive;const b=Gi(d,n);return await u.upsertSession(c),b}static async sendOnSessionCallIfNotPlayerCreate(e,t,i,n,o){n!==Oe.UserCreate&&(u.upsertSession(o),u.resetSentUniqueOutcomes(),await ui.updateUserSession(e,t,i))}static async finalizeSession(e,t,i,n,o,a){if(ke.debug("Finalize session",`started: ${new Date(n.startTimestamp)}`,`duration: ${n.accumulatedDuration}s`),o){ke.debug(`send on_focus reporting session duration -> ${n.accumulatedDuration}s`);const c=await bt.getAttribution(a);ke.debug("send on_focus with attribution",c),await ui.sendSessionDuration(e,t,i,n.accumulatedDuration,c)}await Promise.all([u.cleanupCurrentSession(),u.removeAllNotificationClickedForOutcomes()]),ke.debug("Finalize session finished",`started: ${new Date(n.startTimestamp)}`)}static timeInSecondsBetweenTimestamps(e,t){return e<=t?0:Math.floor((e-t)/1e3)}}var Ne=(s=>(s.OneSignalWorker="OneSignal Worker",s.ThirdParty="3rd Party",s.None="None",s))(Ne||{}),ve=(s=>(s.WorkerVersion="GetWorkerVersion",s.Subscribe="Subscribe",s.SubscribeNew="SubscribeNew",s.NotificationWillDisplay="notification.willDisplay",s.NotificationClicked="notification.clicked",s.NotificationDismissed="notification.dismissed",s.RedirectPage="command.redirect",s.SessionUpsert="os.session.upsert",s.SessionDeactivate="os.session.deactivate",s.AreYouVisible="os.page_focused_request",s.AreYouVisibleResponse="os.page_focused_response",s.SetLogging="os.set_sw_logging",s))(ve||{});class os{replies;constructor(){this.replies={}}addListener(e,t,i){const n={callback:t,onceListenerOnly:i},o=this.replies[e.toString()];o?o.push(n):this.replies[e.toString()]=[n]}findListenersForMessage(e){return this.replies[e.toString()]||[]}deleteListenerRecords(e){this.replies[e.toString()]=null}deleteAllListenerRecords(){this.replies={}}deleteListenerRecord(e,t){const i=this.replies[e.toString()];if(i!=null)for(let n=i.length-1;n>=0;n--)i[n]===t&&i.splice(n,1)}}class as{context;replies;constructor(e,t=new os){this.context=e,this.replies=t}async broadcast(e,t){if(x.getWindowEnv()!==Y.ServiceWorker)return;const i=await self.clients.matchAll({type:"window",includeUncontrolled:!0});for(const n of i)r.debug(`[Worker Messenger] [SW -> Page] Broadcasting '${e.toString()}' to window client ${n.url}.`),n.postMessage({command:e,payload:t})}async unicast(e,t,i){if(x.getWindowEnv()===Y.ServiceWorker)if(i)r.debug(`[Worker Messenger] [SW -> Page] Unicasting '${e.toString()}' to window client ${i.url}.`),i.postMessage({command:e,payload:t});else throw new I("windowClient",v.Empty);else r.debug(`[Worker Messenger] [Page -> SW] Unicasting '${e.toString()}' to service worker.`),this.directPostMessageToSW(e,t)}async directPostMessageToSW(e,t){r.debug(`[Worker Messenger] [Page -> SW] Direct command '${e.toString()}' to service worker.`);const i=await this.context?.serviceWorkerManager.getOneSignalRegistration();if(!i){r.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!");return}const n=wt.getAvailableServiceWorker(i);if(!n){r.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorker to postMessage!");return}n.postMessage({command:e,payload:t})}async listen(){if(!R.supportsServiceWorkers())return;x.getWindowEnv()===Y.ServiceWorker?(self.addEventListener("message",this.onWorkerMessageReceivedFromPage.bind(this)),r.debug("[Worker Messenger] Service worker is now listening for messages.")):await this.listenForPage()}async listenForPage(){navigator.serviceWorker.addEventListener("message",this.onPageMessageReceivedFromServiceWorker.bind(this)),r.debug(`(${location.origin}) [Worker Messenger] Page is now listening for messages.`)}onWorkerMessageReceivedFromPage(e){const t=e.data;if(!t||!t.command)return;const i=this.replies.findListenersForMessage(t.command),n=[],o=[];r.debug("[Worker Messenger] Service worker received message:",e.data);for(const a of i)a.onceListenerOnly&&n.push(a),o.push(a);for(let a=n.length-1;a>=0;a--){const c=n[a];this.replies.deleteListenerRecord(t.command,c)}for(const a of o)a.callback.apply(null,[t.payload])}onPageMessageReceivedFromServiceWorker(e){const t=e.data;if(!t||!t.command)return;const i=this.replies.findListenersForMessage(t.command),n=[],o=[];r.debug("[Worker Messenger] Page received message:",e.data);for(const a of i)a.onceListenerOnly&&n.push(a),o.push(a);for(let a=n.length-1;a>=0;a--){const c=n[a];this.replies.deleteListenerRecord(t.command,c)}for(const a of o)a.callback.apply(null,[t.payload])}on(e,t){this.replies.addListener(e,t,!1)}once(e,t){this.replies.addListener(e,t,!0)}off(e){e?this.replies.deleteListenerRecords(e):this.replies.deleteAllListenerRecords()}}class ze{static QUERY_STRING="?";path;constructor(e){if(!e)throw new I("path",v.Empty);this.path=e.trim()}getQueryString(){const e=this.path.indexOf("?");return e===-1?null:this.path.length>e?this.path.substring(e+1):null}getWithoutQueryString(){return this.path.split(ze.QUERY_STRING)[0]}getFileName(){return this.getWithoutQueryString().split("\\").pop()?.split("/").pop()}getFileNameWithQuery(){return this.path.split("\\").pop()?.split("/").pop()}getFullPath(){return this.path}getPathWithoutFileName(){const e=this.getWithoutQueryString(),t=e.lastIndexOf(this.getFileName());let i=e.substring(0,t);return i=i.replace(/[\\/]$/,""),i}}class fi{context;config;constructor(e,t){this.context=e,this.config=t}async getRegistration(){return wt.getRegistration(this.config.registrationOptions.scope)}async getOneSignalRegistration(){if(await this.getActiveState()===Ne.OneSignalWorker)return this.getRegistration()}async getActiveState(){const e=await this.getRegistration();if(!e)return Ne.None;const t=fi.activeSwFileName(e);return this.swActiveStateByFileName(t)}static activeSwFileName(e){const t=wt.getAvailableServiceWorker(e);if(!t)return null;const i=new URL(t.scriptURL).pathname,n=new ze(i).getFileName();if(n=="akam-sw.js"){const a=new URLSearchParams(new URL(t.scriptURL).search).get("othersw");if(a)return r.debug("Found a ServiceWorker under Akamai's akam-sw.js?othersw=",a),new ze(new URL(a).pathname).getFileName()}return n}swActiveStateByFileName(e){return e?e==this.config.workerPath.getFileName()||e=="OneSignalSDK.sw.js"?Ne.OneSignalWorker:Ne.ThirdParty:Ne.None}async getWorkerVersion(){return new Promise(async e=>{this.context.workerMessenger.once(ve.WorkerVersion,t=>{e(t)}),await this.context.workerMessenger.unicast(ve.WorkerVersion)})}async shouldInstallWorker(){if(!R.supportsServiceWorkers()||!OneSignal.config)return!1;const e=await this.getActiveState();if(r.debug("[shouldInstallWorker] workerState",e),e===Ne.None||e===Ne.ThirdParty){const i=await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.config.safariWebId)==="granted";return i&&r.info("[shouldInstallWorker] Notification Permissions enabled, will install ServiceWorker"),i}return await this.haveParamsChanged()?!0:this.workerNeedsUpdate()}async haveParamsChanged(){const e=await this.getRegistration();if(!e)return r.info("[changedServiceWorkerParams] workerRegistration not found at scope",this.config.registrationOptions.scope),!0;const t=new URL(e.scope).pathname,i=this.config.registrationOptions.scope;if(t!=i)return r.info("[changedServiceWorkerParams] ServiceWorker scope changing",{a_old:t,b_new:i}),!0;const n=wt.getAvailableServiceWorker(e),o=ye.getServiceWorkerHref(this.config,this.context.appConfig.appId,R.version());return n?.scriptURL?o!==n.scriptURL?(r.info("[changedServiceWorkerParams] ServiceWorker href changing:",{a_old:n?.scriptURL,b_new:o}),!0):!1:!0}async workerNeedsUpdate(){r.info("[Service Worker Update] Checking service worker version...");let e;try{e=await y.timeoutPromise(this.getWorkerVersion(),2e3)}catch{return r.info("[Service Worker Update] Worker did not reply to version query; assuming older version and updating."),!0}return e!==R.version()?(r.info(`[Service Worker Update] Updating service worker from ${e} --> ${R.version()}.`),!0):(r.info(`[Service Worker Update] Service worker version is current at ${e} (no update required).`),!1)}async establishServiceWorkerChannel(){r.debug("establishServiceWorkerChannel");const e=this.context.workerMessenger;e.off(),e.on(ve.NotificationWillDisplay,async i=>{r.debug(location.origin,"Received notification display event from service worker.");const n={notification:i.notification,preventDefault:function(){throw new Error("Browser does not support preventing display.")}};await P.trigger(OneSignal.EVENTS.NOTIFICATION_WILL_DISPLAY,n)}),e.on(ve.NotificationClicked,async i=>{OneSignal.emitter.numberOfListeners(OneSignal.EVENTS.NOTIFICATION_CLICKED)===0?(r.debug("notification.clicked event received, but no event listeners; storing event in IndexedDb for later retrieval."),i.result.url,await u.putNotificationClickedEventPendingUrlOpening(i)):await J.triggerNotificationClick(i)}),e.on(ve.NotificationDismissed,async i=>{await P.trigger(OneSignal.EVENTS.NOTIFICATION_DISMISSED,i)});const t=B.isSafari();e.on(ve.AreYouVisible,async i=>{if(t){const n={timestamp:i.timestamp,focused:document.hasFocus()};await e.directPostMessageToSW(ve.AreYouVisibleResponse,n)}})}async installWorker(){if(!await this.shouldInstallWorker())return this.getOneSignalRegistration();r.info("Installing worker..."),await this.getActiveState()===Ne.ThirdParty&&r.info("[Service Worker Installation] 3rd party service worker detected.");const t=ye.getServiceWorkerHref(this.config,this.context.appConfig.appId,R.version()),i=`${B.getBaseUrl()}${this.config.registrationOptions.scope}`;r.info(`[Service Worker Installation] Installing service worker ${t} ${i}.`);let n;try{n=await navigator.serviceWorker.register(t,{scope:i,type:void 0})}catch(o){r.error(`[Service Worker Installation] Installing service worker failed ${o}`),n=await this.fallbackToUserModelBetaWorker()}return r.debug("[Service Worker Installation] Service worker installed. Waiting for activation"),await wt.waitUntilActive(n),r.debug("[Service Worker Installation] Service worker active"),await this.establishServiceWorkerChannel(),n}async fallbackToUserModelBetaWorker(){const e="OneSignalSDK.sw.js",t={workerPath:new ze(`/${e}`),registrationOptions:this.config.registrationOptions},i=ye.getServiceWorkerHref(t,this.context.appConfig.appId,R.version()),n=`${B.getBaseUrl()}${this.config.registrationOptions.scope}`;r.info(`[Service Worker Installation] Attempting to install v16 Beta Worker ${i} ${n}.`);try{const o=await navigator.serviceWorker.register(i,{scope:n}),a=` [Service Worker Installation] Successfully installed v16 Beta Worker. Deprecation warning: support for the v16 beta worker name of ${e} will be removed May 5 2024. We have decided to keep the v15 name. To avoid breaking changes for your users, please host both worker files: OneSignalSDK.sw.js & OneSignalSDKWorker.js. `;return r.error(a),o}catch(o){const a=await fetch(i);throw a.status===403||a.status===404?new Bt(a.status,a.statusText):o}}}var ae=(s=>(s.Default="default",s.Granted="granted",s.Denied="denied",s))(ae||{}),mi=(s=>(s[s.DestroySubscription=0]="DestroySubscription",s[s.MarkUnsubscribed=1]="MarkUnsubscribed",s))(mi||{});class St extends S{constructor(){super("This code is not implemented yet."),Object.setPrototypeOf(this,St.prototype)}}var Ke=(s=>(s[s.Blocked=0]="Blocked",s[s.Dismissed=1]="Dismissed",s[s.Default=2]="Default",s))(Ke||{});class We extends S{reason;constructor(e){let t;switch(e){case 1:t="The user dismissed the permission prompt.";break;case 0:t="Notification permissions are blocked.";break;case 2:t="Notification permissions have not been granted yet.";break}super(t),this.reason=e,Object.setPrototypeOf(this,We.prototype)}}var qi=(s=>(s[s.InvalidSafariSetup=0]="InvalidSafariSetup",s[s.Blocked=1]="Blocked",s[s.Dismissed=2]="Dismissed",s))(qi||{});class wi extends S{constructor(e){let t;switch(e){case 0:t="The Safari site URL, icon size, or push certificate is invalid, or Safari is in a private session.";break;case 1:t="Notification permissions are blocked.";break;case 2:t="The notification permission prompt was dismissed.";break}super(t),Object.setPrototypeOf(this,wi.prototype)}}class Qe{w3cEndpoint;w3cP256dh;w3cAuth;safariDeviceToken;static setFromW3cSubscription(e){const t=new Qe;if(e&&(t.w3cEndpoint=new URL(e.endpoint),e.getKey)){let i=null;try{i=e.getKey("p256dh")}catch{}let n=null;try{n=e.getKey("auth")}catch{}if(i){const o=btoa(String.fromCharCode.apply(null,new Uint8Array(i)));t.w3cP256dh=o}if(n){const o=btoa(String.fromCharCode.apply(null,new Uint8Array(n)));t.w3cAuth=o}}return t}setFromSafariSubscription(e){e&&(this.safariDeviceToken=e)}serialize(){return{w3cEndpoint:this.w3cEndpoint?this.w3cEndpoint.toString():null,w3cP256dh:this.w3cP256dh,w3cAuth:this.w3cAuth,safariDeviceToken:this.safariDeviceToken}}static deserialize(e){const t=new Qe;if(!e)return t;try{t.w3cEndpoint=new URL(e.w3cEndpoint)}catch{}return t.w3cP256dh=e.w3cP256dh,t.w3cAuth=e.w3cAuth,t.safariDeviceToken=e.safariDeviceToken,t}}const rs="99999999-9999-9999-9999-999999999999";class Ue{context;config;safariPermissionPromptFailed=!1;constructor(e,t){this.context=e,this.config=t}async isPushNotificationsEnabled(){const e=await this.getSubscriptionState();return e.subscribed&&!e.optedOut}async isOptedIn(){const e=await this.getSubscriptionState();return await OneSignal.context.permissionManager.getPermissionStatus()==="granted"&&!e.optedOut}async isOptedOut(e){h("isOptedOut",e);const{optedOut:t}=await u.getSubscription();return yn(e,t),t}async subscribe(e){const t=x.getWindowEnv();let i;switch(t){case Y.ServiceWorker:i=await this.subscribeFcmFromWorker(e);break;case Y.Host:if(await OneSignal.context.permissionManager.getPermissionStatus()===ae.Denied)throw new We(Ke.Blocked);if(R.useSafariLegacyPush()){i=await this.subscribeSafari(),await this._updatePushSubscriptionModelWithRawSubscription(i),r.info("Installing SW on Safari");try{await this.context.serviceWorkerManager.installWorker(),r.info("SW on Safari successfully installed")}catch{r.error("SW on Safari failed to install.")}}else i=await this.subscribeFcmFromPage(e),await this._updatePushSubscriptionModelWithRawSubscription(i);break;default:throw new Me(Ae.UnsupportedEnvironment)}return i}async _updatePushSubscriptionModelWithRawSubscription(e){const t=await OneSignal.coreDirector.getPushSubscriptionModel();if(t){const i=new Ve(e).serialize(),n=Object.keys(i);for(let o=0;onew Promise(i=>{window.safari.pushNotification.requestPermission(t,this.config.safariWebId,{app_id:this.config.appId},n=>{n&&n.deviceToken?i(n.deviceToken.toLowerCase()):i(null)})});return this.safariPermissionPromptFailed?e(`${x.getOneSignalApiUrl().toString()}/safari`):e(`${x.getOneSignalApiUrl().toString()}/safari/apps/${this.config.appId}`)}async subscribeSafari(){const e=new Qe;if(!this.config.safariWebId)throw new ge(me.MissingSafariWebId);const{deviceToken:t}=window.safari.pushNotification.permission(this.config.safariWebId);if(t)return e.setFromSafariSubscription(t.toLowerCase()),e;P.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);const i=await this.subscribeSafariPromptPermission();if(Ee.triggerNotificationPermissionChanged(),i)e.setFromSafariSubscription(i);else throw this.safariPermissionPromptFailed=!0,new wi(qi.InvalidSafariSetup);return e}async subscribeFcmFromPage(e){if(x.getWindowEnv()===Y.Host&&Notification.permission===ae.Default){await P.trigger(OneSignal.EVENTS.PERMISSION_PROMPT_DISPLAYED);const i=await Ue.requestPresubscribeNotificationPermission(),n=i===ae.Default;switch(await Ee.triggerNotificationPermissionChanged(n),i){case ae.Default:throw r.debug("Exiting subscription and not registering worker because the permission was dismissed."),OneSignal._sessionInitAlreadyRunning=!1,new We(Ke.Dismissed);case ae.Denied:throw r.debug("Exiting subscription and not registering worker because the permission was blocked."),OneSignal._sessionInitAlreadyRunning=!1,new We(Ke.Blocked)}}let t;try{t=await this.context.serviceWorkerManager.installWorker()}catch(i){throw i instanceof Bt&&(i.status===403?await this.context.subscriptionManager.registerFailedSubscription(we.ServiceWorkerStatus403,this.context):i.status===404&&await this.context.subscriptionManager.registerFailedSubscription(we.ServiceWorkerStatus404,this.context)),i}if(!t)throw new Error("OneSignal service worker not found!");return r.debug("[Subscription Manager] Service worker is ready to continue subscribing."),await this.subscribeWithVapidKey(t.pushManager,e)}async subscribeFcmFromWorker(e){const t=self.registration;if(!t.active&&N().name!=="firefox")throw new Me(Ae.ServiceWorkerNotActivated);const i=await t.pushManager.permissionState({userVisibleOnly:!0});if(i==="denied")throw new We(Ke.Blocked);if(i==="prompt")throw new We(Ke.Default);return await this.subscribeWithVapidKey(t.pushManager,e)}getVapidKeyForBrowser(){let e;if(N().name==="firefox"?e=this.config.onesignalVapidPublicKey:e=this.config.vapidPublicKey,e)return xn(e).buffer}async subscribeWithVapidKey(e,t){const i=await e.getSubscription();switch(t){case ht.ResubscribeExisting:if(!i)break;i.options?r.debug("[Subscription Manager] An existing push subscription exists and it's options is not null."):(r.debug("[Subscription Manager] An existing push subscription exists and options is null. Unsubscribing from push first now."),await Ue.doPushUnsubscribe(i));break;case ht.SubscribeNew:i&&await Ue.doPushUnsubscribe(i);break}const[n,o]=await Ue.doPushSubscribe(e,this.getVapidKeyForBrowser());return await Ue.updateSubscriptionTime(o,n.expirationTime),Qe.setFromW3cSubscription(n)}static async updateSubscriptionTime(e,t){const i=await u.getSubscription();e&&(i.createdAt=new Date().getTime()),i.expirationTime=t,await u.setSubscription(i)}static async doPushUnsubscribe(e){r.debug("[Subscription Manager] Unsubscribing existing push subscription.");const t=await e.unsubscribe();return r.debug(`[Subscription Manager] Unsubscribing existing push subscription result: ${t}`),t}static async doPushSubscribe(e,t){if(!t)throw new Error("Missing required 'applicationServerKey' to subscribe for push notifications!");const i={userVisibleOnly:!0,applicationServerKey:t};r.debug("[Subscription Manager] Subscribing to web push with these options:",i);try{const n=await e.getSubscription();return[await e.subscribe(i),!n]}catch(n){if(n.name=="InvalidStateError"){r.warn("[Subscription Manager] Couldn't re-subscribe due to applicationServerKey changing, unsubscribe and attempting to subscribe with new key.",n);const o=await e.getSubscription();return o&&await Ue.doPushUnsubscribe(o),[await e.subscribe(i),!0]}else throw n}}async isSubscriptionExpiring(){if(await this.context.serviceWorkerManager.getActiveState()!==Ne.OneSignalWorker)return!1;const t=await this.context.serviceWorkerManager.getOneSignalRegistration();if(!t||!t.pushManager)return!1;const i=await t.pushManager.getSubscription();if(!i||!i.expirationTime)return!1;let{createdAt:n}=await u.getSubscription();n||(n=new Date().getTime()+31536e6);const o=n+(i.expirationTime-n)/2;return!!i.expirationTime&&(new Date().getTime()>=i.expirationTime||new Date().getTime()>=o)}async getSubscriptionState(){switch(x.getWindowEnv()){case Y.ServiceWorker:{const t=await self.registration.pushManager.getSubscription(),{optedOut:i}=await u.getSubscription();return{subscribed:!!t,optedOut:!!i}}default:return this.getSubscriptionStateFromBrowserContext()}}async getSubscriptionStateFromBrowserContext(){const{optedOut:e,subscriptionToken:t}=await u.getSubscription(),i=await OneSignal.coreDirector.getPushSubscriptionModel(),n=ne(i?.data)&&!!i?.onesignalId;if(R.useSafariLegacyPush()){const d=window.safari?.pushNotification?.permission(this.config.safariWebId);return{subscribed:!!(n&&t&&d?.permission==="granted"&&d?.deviceToken),optedOut:!!e}}const o=await this.context.serviceWorkerManager.getOneSignalRegistration(),a=await this.context.permissionManager.getNotificationPermission(this.context.appConfig.safariWebId);return o?{subscribed:!!(n&&t&&a===ae.Granted),optedOut:!!e}:{subscribed:!1,optedOut:!!e}}async registerFailedSubscription(e,t){t.pageViewManager.isFirstPageView()&&(t.subscriptionManager.registerSubscription(new Qe,e),t.pageViewManager.incrementPageViewCount())}}class zi{static getServiceWorkerManager(e){const t=e.appConfig,i={workerPath:new ze("OneSignalSDKWorker.js"),registrationOptions:{scope:"/"}};return t.userConfig&&(t.userConfig.path&&(i.workerPath=new ze(`${t.userConfig.path}${t.userConfig.serviceWorkerPath}`)),t.userConfig.serviceWorkerParam&&(i.registrationOptions=t.userConfig.serviceWorkerParam)),new fi(e,i)}static getSubscriptionManager(e){const t=e.appConfig,i={safariWebId:t.safariWebId,appId:t.appId,vapidPublicKey:t.vapidPublicKey,onesignalVapidPublicKey:t.onesignalVapidPublicKey};return new Ue(e,i)}}class Vt{static SESSION_STORAGE_KEY_NAME="onesignal-pageview-count";incrementedPageViewCount=!1;getPageViewCount(){try{const e=sessionStorage.getItem(Vt.SESSION_STORAGE_KEY_NAME),t=e?parseInt(e):0;return isNaN(t)?0:t}catch{return 0}}setPageViewCount(e){try{sessionStorage.setItem(Vt.SESSION_STORAGE_KEY_NAME,e.toString())}catch{}}incrementPageViewCount(){if(this.incrementedPageViewCount)return;const e=this.getPageViewCount()+1,t=this.getLocalPageViewCount()+1;this.setPageViewCount(e),this.setLocalPageViewCount(t),this.incrementedPageViewCount=!0,r.debug(`Incremented page view count: newCountSingleTab: ${e}, newCountAccrossTabs: ${t}.`)}simulatePageNavigationOrRefresh(){this.incrementedPageViewCount=!1}isFirstPageView(){return this.getPageViewCount()===1}getLocalPageViewCount(){return Ge.getLocalPageViewCount()}setLocalPageViewCount(e){Ge.setLocalPageViewCount(e)}}class bi{static get STORED_PERMISSION_KEY(){return"storedNotificationPermission"}async getPermissionStatus(){if(!OneSignal.context)throw new S("OneSignal.context is undefined. Make sure to call OneSignal.init() before calling getPermissionStatus().");return await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.config.safariWebId)}async getNotificationPermission(e){return R.useSafariLegacyPush()?bi.getLegacySafariNotificationPermission(e):this.getW3cNotificationPermission()}static getLegacySafariNotificationPermission(e){if(e)return window.safari.pushNotification.permission(e).permission;throw new I("safariWebId",v.Empty)}getW3cNotificationPermission(){return Notification.permission}}class cs{context;onSessionSent;constructor(e){this.context=e,this.onSessionSent=e.pageViewManager.getPageViewCount()>1}async sendPushDeviceRecordUpdate(){if(!_.singletonInstance?.hasOneSignalId){r.debug("Not sending the update because user is not registered with OneSignal (no onesignal_id)");return}this.onSessionSent||await this.sendOnSessionUpdate()}async sendOnSessionUpdate(){if(this.onSessionSent||!this.context.pageViewManager.isFirstPageView())return;if(!await this.context.subscriptionManager.isAlreadyRegisteredWithOneSignal()){r.debug("Not sending the on session because user is not registered with OneSignal (no device id)");return}if(!((await OneSignal.coreDirector.getPushSubscriptionModel())?.data.notification_types!==we.Subscribed&&OneSignal.config?.enableOnSession!==!0))try{this.context.sessionManager.upsertSession(Oe.UserNewSession),this.onSessionSent=!0}catch(i){r.error(`Failed to update user session. Error "${i.message}" ${i.stack}`)}}async sendOutcomeDirect(e,t,i,n){h("sendOutcomeDirect");const o=await OneSignal.coreDirector.getPushSubscriptionModel();if(o&&ne(o?.data)){const a={id:i,app_id:e,notification_ids:t,direct:!0,subscription:{id:o.data.id,type:Ve.getSubscriptionType()}};n!==void 0&&(a.weight=n),await Rt.sendOutcome(a);return}r.warn("Send outcome aborted because pushSubscriptionModel is not available.")}async sendOutcomeInfluenced(e,t,i,n){h("sendOutcomeInfluenced");const o=await OneSignal.coreDirector.getPushSubscriptionModel();if(o&&ne(o?.data)){const a={id:i,app_id:e,notification_ids:t,direct:!1,subscription:{id:o.data.id,type:Ve.getSubscriptionType()}};n!==void 0&&(a.weight=n),await Rt.sendOutcome(a);return}r.warn("Send outcome aborted because pushSubscriptionModel is not available.")}async sendOutcomeUnattributed(e,t,i){h("sendOutcomeUnattributed");const n=await OneSignal.coreDirector.getPushSubscriptionModel();if(n&&ne(n?.data)){const o={id:t,app_id:e,subscription:{id:n.data.id,type:Ve.getSubscriptionType()}};i!==void 0&&(o.weight=i),await Rt.sendOutcome(o);return}r.warn("Send outcome aborted because pushSubscriptionModel is not available.")}}class ls{context;onSessionSent=!1;constructor(e){this.context=e}async notifySWToUpsertSession(e,t,i){const n={onesignalId:e,subscriptionId:t,appId:this.context.appConfig.appId,sessionThreshold:this.context.appConfig.sessionThreshold||0,enableSessionDuration:!!this.context.appConfig.enableSessionDuration,sessionOrigin:i,isSafari:B.isSafari(),outcomesConfig:this.context.appConfig.userConfig.outcomes};this.context.environmentInfo?.isBrowserAndSupportsServiceWorkers?(r.debug("Notify SW to upsert session"),await this.context.workerMessenger.unicast(ve.SessionUpsert,n)):r.debug("Notify upsert: do nothing")}async notifySWToDeactivateSession(e,t,i){const n={appId:this.context.appConfig.appId,subscriptionId:t,onesignalId:e,sessionThreshold:this.context.appConfig.sessionThreshold,enableSessionDuration:this.context.appConfig.enableSessionDuration,sessionOrigin:i,isSafari:B.isSafari(),outcomesConfig:this.context.appConfig.userConfig.outcomes};this.context.environmentInfo?.isBrowserAndSupportsServiceWorkers?(r.debug("Notify SW to deactivate session"),await this.context.workerMessenger.unicast(ve.SessionDeactivate,n)):r.debug("Notify deactivate: do nothing")}async _getOneSignalAndSubscriptionIds(){const e=OneSignal.coreDirector.getIdentityModel(),t=await OneSignal.coreDirector.getPushSubscriptionModel();if(!e||!e.onesignalId)throw new S("Abort _getOneSignalAndSubscriptionIds: no identity");if(!t||!ne(t.data))throw new S("Abort _getOneSignalAndSubscriptionIds: no subscription");const{onesignalId:i}=e,{id:n}=t.data;return{onesignalId:i,subscriptionId:n}}async handleVisibilityChange(){if(await ee.switchingUsersPromise,!!_.singletonInstance?.hasOneSignalId)try{const e=document.visibilityState,{onesignalId:t,subscriptionId:i}=await this._getOneSignalAndSubscriptionIds();if(e==="visible"){this.setupOnFocusAndOnBlurForSession(),r.debug("handleVisibilityChange","visible",`hasFocus: ${document.hasFocus()}`),document.hasFocus()&&await this.notifySWToUpsertSession(t,i,Oe.VisibilityVisible);return}if(e==="hidden"){r.debug("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),await this.notifySWToDeactivateSession(t,i,Oe.VisibilityHidden);return}r.warn("Unhandled visibility state happened",e)}catch(e){r.error("Error handling visibility change:",e)}}async handleOnBeforeUnload(){if(await ee.switchingUsersPromise,!!_.singletonInstance?.hasOneSignalId)try{const{onesignalId:e,subscriptionId:t}=await this._getOneSignalAndSubscriptionIds(),i={appId:this.context.appConfig.appId,onesignalId:e,subscriptionId:t,sessionThreshold:this.context.appConfig.sessionThreshold,enableSessionDuration:this.context.appConfig.enableSessionDuration,sessionOrigin:Oe.BeforeUnload,isSafari:B.isSafari(),outcomesConfig:this.context.appConfig.userConfig.outcomes};r.debug("Notify SW to deactivate session (beforeunload)"),this.context.workerMessenger.directPostMessageToSW(ve.SessionDeactivate,i)}catch(e){r.error("Error handling onbeforeunload:",e)}}async handleOnFocus(e){if(await ee.switchingUsersPromise,r.debug("handleOnFocus",e),!!_.singletonInstance?.hasOneSignalId)try{if(e.target!==window)return;const{onesignalId:t,subscriptionId:i}=await this._getOneSignalAndSubscriptionIds();await this.notifySWToUpsertSession(t,i,Oe.Focus)}catch(t){r.error("Error handling focus:",t)}}async handleOnBlur(e){if(await ee.switchingUsersPromise,r.debug("handleOnBlur",e),!!_.singletonInstance?.hasOneSignalId)try{if(e.target!==window)return;const{onesignalId:t,subscriptionId:i}=await this._getOneSignalAndSubscriptionIds();await this.notifySWToDeactivateSession(t,i,Oe.Blur)}catch(t){r.error("Error handling blur:",t)}}async upsertSession(e){if(await ee.switchingUsersPromise,_.singletonInstance?.hasOneSignalId){const{onesignalId:t,subscriptionId:i}=await this._getOneSignalAndSubscriptionIds();await this.notifySWToUpsertSession(t,i,e)}this.context.environmentInfo?.isBrowserAndSupportsServiceWorkers?this.setupSessionEventListeners():(this.onSessionSent=e===Oe.UserCreate,OneSignal.emitter.emit(OneSignal.EVENTS.SESSION_STARTED))}setupSessionEventListeners(){if(!this.context.environmentInfo?.isBrowserAndSupportsServiceWorkers){r.debug("Not setting session event listeners. No service worker possible.");return}this.setupOnFocusAndOnBlurForSession(),OneSignal.cache.isVisibilityChangeEventSetup||(document.addEventListener("visibilitychange",this.handleVisibilityChange.bind(this),!0),OneSignal.cache.isVisibilityChangeEventSetup=!0),OneSignal.cache.isBeforeUnloadEventSetup||(window.addEventListener("beforeunload",e=>{this.handleOnBeforeUnload(),delete e.returnValue},!0),OneSignal.cache.isBeforeUnloadEventSetup=!0)}setupOnFocusAndOnBlurForSession(){r.debug("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||!this.context.pageViewManager.isFirstPageView())return;const i=OneSignal.coreDirector.getIdentityModel()?.data?.id;if(!i){r.debug("Not sending the on session because user is not registered with OneSignal (no onesignal id)");return}const n=await OneSignal.coreDirector.getPushSubscriptionModel();if(n?.data.notification_types!==we.Subscribed&&OneSignal.config?.enableOnSession!==!0)return;let o;ne(n?.data)&&(o=n?.data.id);try{const a=new Q(Q.ONESIGNAL_ID,i),c={refresh_device_metadata:!0,deltas:{session_count:1}},d=await L.getAppId();y.enforceAppId(d),y.enforceAlias(a);try{await se.updateUser({appId:d,subscriptionId:o},a,c),this.onSessionSent=!0}catch(l){r.debug("Error updating user session:",l)}}catch(a){r.error(`Failed to update user session. Error "${a.message}" ${a.stack}`)}}}var te=(s=>(s.Push="push",s.NonPush="nonPush",s))(te||{}),Si=(s=>(s.PromptDismissCount="promptDismissCount",s.NonPushPromptsDismissCount="nonPushPromptsDismissCount",s))(Si||{}),yt=(s=>(s.OneSignalNotificationPrompt="onesignal-notification-prompt",s.OneSignalNonPushPrompt="onesignal-non-push-prompt",s))(yt||{});class _e{static isLocalStorageSupported(){try{return typeof localStorage>"u"?!1:(localStorage.getItem("test"),!0)}catch{return!1}}static setItem(e,t,i){if(!_e.isLocalStorageSupported())return;const n=typeof i<"u"?i*60*1e3:0,o={value:JSON.stringify(t),timestamp:typeof i<"u"?new Date().getTime()+n:void 0};localStorage.setItem(e,JSON.stringify(o))}static getItem(e){if(!_e.isLocalStorageSupported())return null;const t=localStorage.getItem(e);let i;try{i=JSON.parse(t)}catch{return null}if(i===null)return null;if(i.timestamp&&new Date().getTime()>=i.timestamp)return localStorage.removeItem(e),null;let n=i.value;try{n=JSON.parse(i.value)}catch{return n}return n}static removeItem(e){if(!_e.isLocalStorageSupported())return null;localStorage.removeItem(e)}}const ds={[te.Push]:Si.PromptDismissCount,[te.NonPush]:Si.NonPushPromptsDismissCount},us={[te.Push]:yt.OneSignalNotificationPrompt,[te.NonPush]:yt.OneSignalNonPushPrompt};class Fe{static async markPromptDismissedWithType(e){const t=ds[e],i=us[e];let n=await u.get("Options",t);n||(n=0),n+=1;let o=3;n==2?o=7:n>2&&(o=30),r.debug(`(${x.getWindowEnv().toString()}) OneSignal: User dismissed the ${e} notification prompt; reprompt after ${o} days.`),await u.put("Options",{key:t,value:n});const a=o*24*60;return _e.setItem(i,"dismissed",a)}static wasPromptOfTypeDismissed(e){switch(e){case te.Push:return _e.getItem(yt.OneSignalNotificationPrompt)==="dismissed";case te.NonPush:return _e.getItem(yt.OneSignalNonPushPrompt)==="dismissed"}return!1}}class Ie{constructor(e,t,i,n="shown",o=["opacity","transform"],a,c=500){this.selector=e,this.showClass=t,this.hideClass=i,this.state=n,this.targetTransitionEvents=o,this.nestedContentSelector=a,this.transitionCheckTimeout=c}show(){return this.hidden?new Promise(e=>{this.state="showing",P.trigger(Ie.EVENTS.SHOWING,this);const t=this.element;if(t?(this.hideClass&&le(t,this.hideClass),this.showClass&&m(t,this.showClass)):r.error(`(show) could not find animated element with selector ${this.selector}`),this.targetTransitionEvents.length==0)return e(this);{const i=setTimeout(()=>{r.debug(`Element did not completely show (state: ${this.state}).`)},this.transitionCheckTimeout);fe(this.element,"transitionend",(n,o)=>{if(n.target===this.element&&Le(this.targetTransitionEvents,n.propertyName))return clearTimeout(i),o(),this.state="shown",P.trigger(Ie.EVENTS.SHOWN,this),e(this)},!0)}}):Promise.resolve(this)}hide(){return this.shown?new Promise(e=>{this.state="hiding",P.trigger(Ie.EVENTS.HIDING,this);const t=this.element;if(t?(this.showClass&&le(t,this.showClass),this.hideClass&&m(t,this.hideClass)):r.error(`(hide) could not find animated element with selector ${this.selector}`),this.targetTransitionEvents.length==0)return e(this);fe(this.element,"transitionend",(i,n)=>{const o=setTimeout(()=>{r.debug(`Element did not completely hide (state: ${this.state}).`)},this.transitionCheckTimeout);if(i.target===this.element&&Le(this.targetTransitionEvents,i.propertyName))return clearTimeout(o),n(),this.state="hidden",P.trigger(Ie.EVENTS.HIDDEN,this),e(this)},!0)}):Promise.resolve(this)}waitUntilShown(){return this.state==="shown"?Promise.resolve(this):new Promise(e=>{OneSignal.emitter.once(Ie.EVENTS.SHOWN,t=>{if(t===this)return e(this)})})}waitUntilHidden(){return this.state==="hidden"?Promise.resolve(this):new Promise(e=>{OneSignal.emitter.once(Ie.EVENTS.HIDDEN,t=>{if(t===this)return e(this)})})}static get EVENTS(){return{SHOWING:"animatedElementShowing",SHOWN:"animatedElementShown",HIDING:"animatedElementHiding",HIDDEN:"animatedElementHidden"}}get content(){if(!this.element)return"";if(this.nestedContentSelector){const e=this.element.querySelector(this.nestedContentSelector);return e?e.innerHTML:""}else return this.element.innerHTML}set content(e){if(this.element)if(this.nestedContentSelector){const t=this.element.querySelector(this.nestedContentSelector);t&&(t.textContent=e)}else this.element.textContent=e}get element(){return document.querySelector(this.selector)}get showing(){return this.state==="showing"}get shown(){return this.state==="shown"}get hiding(){return this.state==="hiding"}get hidden(){return this.state==="hidden"}}class he extends Ie{constructor(e,t,i,n,o,a="shown",c="active",d=["opacity","transform"],l){super(e,t,i,a,d),this.selector=e,this.showClass=t,this.hideClass=i,this.activeClass=n,this.inactiveClass=o,this.state=a,this.activeState=c,this.targetTransitionEvents=d,this.nestedContentSelector=l}activate(){return!this.inactive||!this.shown?Promise.resolve(this):new Promise(e=>{this.activeState="activating",P.trigger(he.EVENTS.ACTIVATING,this);const t=this.element;if(t?(this.inactiveClass&&le(t,this.inactiveClass),this.activeClass&&m(t,this.activeClass)):r.error("Could not find active animated element"),this.shown){if(this.targetTransitionEvents.length==0)return e(this);{const i=setTimeout(()=>{r.debug(`Element did not completely activate (state: ${this.state}, activeState: ${this.activeState}).`)},this.transitionCheckTimeout);fe(this.element,"transitionend",(n,o)=>{if(n.target===this.element&&Le(this.targetTransitionEvents,n.propertyName))return clearTimeout(i),o(),this.activeState="active",P.trigger(he.EVENTS.ACTIVE,this),e(this)},!0)}}else return r.debug("Ending activate() transition (alternative)."),this.activeState="active",P.trigger(he.EVENTS.ACTIVE,this),e(this)})}inactivate(){return this.active?new Promise(e=>{this.activeState="inactivating",P.trigger(he.EVENTS.INACTIVATING,this);const t=this.element;if(t?(this.activeClass&&le(t,this.activeClass),this.inactiveClass&&m(t,this.inactiveClass)):r.error("Could not find active animated element"),this.shown){if(this.targetTransitionEvents.length==0)return e(this);{const i=setTimeout(()=>{r.debug(`Element did not completely inactivate (state: ${this.state}, activeState: ${this.activeState}).`)},this.transitionCheckTimeout);fe(this.element,"transitionend",(n,o)=>{if(n.target===this.element&&Le(this.targetTransitionEvents,n.propertyName))return clearTimeout(i),o(),this.activeState="inactive",P.trigger(he.EVENTS.INACTIVE,this),e(this)},!0)}}else return this.activeState="inactive",P.trigger(he.EVENTS.INACTIVE,this),e(this)}):Promise.resolve(this)}waitUntilActive(){return this.active?Promise.resolve(this):new Promise(e=>{OneSignal.emitter.once(he.EVENTS.ACTIVE,t=>{if(t===this)return e(this)})})}waitUntilInactive(){return this.inactive?Promise.resolve(this):new Promise(e=>{OneSignal.emitter.once(he.EVENTS.INACTIVE,t=>{if(t===this)return e(this)})})}static get EVENTS(){return{...Ie.EVENTS,ACTIVATING:"activeAnimatedElementActivating",ACTIVE:"activeAnimatedElementActive",INACTIVATING:"activeAnimatedElementInactivating",INACTIVE:"activeAnimatedElementInactive"}}get activating(){return this.activeState==="activating"}get active(){return this.activeState==="active"}get inactivating(){return this.activeState==="inactivating"}get inactive(){return this.activeState==="inactive"}}class gs extends he{constructor(){super(".onesignal-bell-launcher-badge","onesignal-bell-launcher-badge-opened",null,"onesignal-bell-launcher-badge-active",null,"hidden")}increment(){if(!isNaN(this.content)){let e=+this.content;e+=1,this.content=e.toString()}}show(){const e=super.show();return OneSignal.notifyButton.setCustomColorsIfSpecified(),e}decrement(){if(!isNaN(this.content)){let e=+this.content;e-=1,e>0?this.content=e.toString():this.content=""}}}class ue extends Ie{bell;contentType;queued;constructor(e){super(".onesignal-bell-launcher-message","onesignal-bell-launcher-message-opened",void 0,"hidden",["opacity","transform"],".onesignal-bell-launcher-message-body"),this.bell=e,this.contentType="",this.queued=[]}static get TIMEOUT(){return 2500}static get TYPES(){return{TIP:"tip",MESSAGE:"message",QUEUED:"queued"}}display(e,t,i=0){return r.debug(`Calling display(${e}, ${t}, ${i}).`),(this.shown?this.hide():et()).then(()=>{this.content=ft.decodeHtmlEntities(t),this.contentType=e}).then(()=>this.show()).then(()=>Pt(i)).then(()=>this.hide()).then(()=>{this.content=this.getTipForState(),this.contentType="tip"})}getTipForState(){return this.bell.state===C.STATES.UNSUBSCRIBED?this.bell.options.text["tip.state.unsubscribed"]:this.bell.state===C.STATES.SUBSCRIBED?this.bell.options.text["tip.state.subscribed"]:this.bell.state===C.STATES.BLOCKED?this.bell.options.text["tip.state.blocked"]:""}enqueue(e){return this.queued.push(ft.decodeHtmlEntities(e)),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(e){const t=this.queued.pop(e);return new Promise(i=>{this.bell.badge.shown?this.bell.badge.hide().then(()=>this.bell.badge.decrement()).then(n=>n>0?this.bell.badge.show():Promise.resolve(this)).then(i(t)):(this.bell.badge.decrement(),i(t))})}}class ps extends he{events;bell;constructor(e){super(".onesignal-bell-launcher-button",void 0,void 0,"onesignal-bell-launcher-button-active",void 0,"shown",""),this.bell=e,this.events={mouse:"bell.launcher.button.mouse"};const t=this.element;t&&(t.addEventListener("touchstart",()=>{this.onHovering(),this.onTap()},{passive:!0}),t.addEventListener("mouseenter",()=>{this.onHovering()}),t.addEventListener("mouseleave",()=>{this.onHovered()}),t.addEventListener("touchmove",()=>{this.onHovered()},{passive:!0}),t.addEventListener("mousedown",()=>{this.onTap()}),t.addEventListener("mouseup",()=>{this.onEndTap()}),t.addEventListener("click",()=>{this.onHovered(),this.onClick()}))}onHovering(){(F.isEmpty(this.events.mouse)||F.getLast(this.events.mouse)==="out")&&P.trigger(C.EVENTS.HOVERING),F.put(this.events.mouse,"over")}onHovered(){F.put(this.events.mouse,"out"),P.trigger(C.EVENTS.HOVERED)}onTap(){this.pulse(),this.activate(),this.bell.badge.activate()}onEndTap(){this.inactivate(),this.bell.badge.inactivate()}onClick(){if(P.trigger(C.EVENTS.BELL_CLICK),P.trigger(C.EVENTS.LAUNCHER_CLICK),this.bell.message.shown&&this.bell.message.contentType==ue.TYPES.MESSAGE)return;const e=F.getLast("subscription.optedOut");return this.bell.unsubscribed?e?this.bell.launcher.activateIfInactive().then(()=>{this.bell.showDialogProcedure()}):($.registerForPushNotifications(),this.bell._ignoreSubscriptionState=!0,OneSignal.emitter.once(OneSignal.EVENTS.SUBSCRIPTION_CHANGED,()=>{this.bell.message.display(ue.TYPES.MESSAGE,this.bell.options.text["message.action.subscribed"],ue.TIMEOUT).then(()=>{this.bell._ignoreSubscriptionState=!1,this.bell.launcher.inactivate()})})):this.bell.subscribed?this.bell.launcher.activateIfInactive().then(()=>{this.bell.showDialogProcedure()}):this.bell.blocked&&this.bell.launcher.activateIfInactive().then(()=>{this.bell.showDialogProcedure()}),this.bell.message.hide()}pulse(){Re(".pulse-ring"),this.element&&ie(this.element,"beforeend",'
'),this.bell.setCustomColorsIfSpecified()}}class hs extends Ie{bell;subscribeButtonId;unsubscribeButtonId;notificationIcons;constructor(e){super(".onesignal-bell-launcher-dialog","onesignal-bell-launcher-dialog-opened",void 0,"hidden",["opacity","transform"],".onesignal-bell-launcher-dialog-body"),this.bell=e,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.subscriptionManager.isPushNotificationsEnabled().then(e=>{this.nestedContentSelector&&In(this.nestedContentSelector);let t="Nothing to show.",i="";if(this.bell.options.showCredit&&(i='
Powered by OneSignal
'),this.bell.state===C.STATES.SUBSCRIBED&&e===!0||this.bell.state===C.STATES.UNSUBSCRIBED&&e===!1){let n="";const o=Qt(this.notificationIcons);o!="default-icon"?n=`
`:n='
';let a="";this.bell.state!==C.STATES.SUBSCRIBED?a=``:a=``,t=`

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

${n}
${a}
${i}`}else if(this.bell.state===C.STATES.BLOCKED){let n=null;N().name==="chrome"?!N().mobile&&!N().tablet&&(n="/bell/chrome-unblock.jpg"):N().name==="firefox"?n="/bell/firefox-unblock.jpg":N().name=="safari"?n="/bell/safari-unblock.jpg":N().name==="msedge"&&(n="/bell/edge-unblock.png");let o="";n&&(n=x.getOneSignalStaticResourcesUrl()+n,o=``),(N().mobile||N().tablet)&&N().name==="chrome"&&(o="
  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.
"),t=`

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

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

${o}
${i}`}this.nestedContentSelector&&ie(this.nestedContentSelector,"beforeend",t),this.subscribeButton&&this.subscribeButton.addEventListener("click",()=>{OneSignal.__doNotShowWelcomeNotification=!1,P.trigger(C.EVENTS.SUBSCRIBE_CLICK)}),this.unsubscribeButton&&this.unsubscribeButton.addEventListener("click",()=>P.trigger(C.EVENTS.UNSUBSCRIBE_CLICK)),this.bell.setCustomColorsIfSpecified()})}}class fs extends he{bell;wasInactive;constructor(e){super(".onesignal-bell-launcher","onesignal-bell-launcher-active",void 0,void 0,"onesignal-bell-launcher-inactive","hidden","active"),this.bell=e,this.wasInactive=!1}async resize(e){if(!this.element)throw new Me(Ae.MissingDomElement);if(e==="small"&&qt(this.element,"onesignal-bell-launcher-sm")||e==="medium"&&qt(this.element,"onesignal-bell-launcher-md")||e==="large"&&qt(this.element,"onesignal-bell-launcher-lg"))return Promise.resolve(this);if(le(this.element,"onesignal-bell-launcher-sm"),le(this.element,"onesignal-bell-launcher-md"),le(this.element,"onesignal-bell-launcher-lg"),e==="small")m(this.element,"onesignal-bell-launcher-sm");else if(e==="medium")m(this.element,"onesignal-bell-launcher-md");else if(e==="large")m(this.element,"onesignal-bell-launcher-lg");else throw new Error("Invalid OneSignal bell size "+e);return this.shown?await new Promise(t=>{if(this.targetTransitionEvents.length==0)return t(this);{const i=setTimeout(()=>{r.debug(`Launcher did not completely resize (state: ${this.state}, activeState: ${this.activeState}).`)},this.transitionCheckTimeout);fe(this.element,"transitionend",(n,o)=>{if(n.target===this.element&&Le(this.targetTransitionEvents,n.propertyName))return clearTimeout(i),o(),t(this)},!0)}}):this}activateIfInactive(){return this.inactive?(this.wasInactive=!0,this.activate()):et()}inactivateIfWasInactive(){return this.wasInactive?(this.wasInactive=!1,this.inactivate()):et()}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)])}}const ms='';class C{options;state=C.STATES.UNINITIALIZED;_ignoreSubscriptionState=!1;hovering=!1;initialized=!1;_launcher;_button;_badge;_message;_dialog;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(e,t){this.options={enable:e.enable||!1,size:e.size||this.DEFAULT_SIZE,position:e.position||this.DEFAULT_POSITION,theme:e.theme||this.DEFAULT_THEME,showLauncherAfter:e.showLauncherAfter||10,showBadgeAfter:e.showBadgeAfter||300,text:this.setDefaultTextOptions(e.text||{}),prenotify:e.prenotify,showCredit:e.showCredit,colors:e.colors,offset:e.offset},t&&(this._launcher=t),this.options.enable&&(this.validateOptions(this.options),this.state=C.STATES.UNINITIALIZED,this._ignoreSubscriptionState=!1,this.installEventHooks(),this.updateState())}showDialogProcedure(){this.dialog.shown||this.dialog.show().then(()=>{fe(document,"click",(e,t)=>{this.dialog.element.contains(e.target)||(t(),this.dialog.shown&&this.dialog.hide().then(()=>{this.launcher.inactivateIfWasInactive()}))},!0)})}validateOptions(e){if(!e.size||!Le(["small","medium","large"],e.size))throw new Error(`Invalid size ${e.size} for notify button. Choose among 'small', 'medium', or 'large'.`);if(!e.position||!Le(["bottom-left","bottom-right"],e.position))throw new Error(`Invalid position ${e.position} for notify button. Choose either 'bottom-left', or 'bottom-right'.`);if(!e.theme||!Le(["default","inverse"],e.theme))throw new Error(`Invalid theme ${e.theme} for notify button. Choose either 'default', or 'inverse'.`);if(!e.showLauncherAfter||e.showLauncherAfter<0)throw new Error(`Invalid delay duration of ${this.options.showLauncherAfter} for showing the notify button. Choose a value above 0.`);if(!e.showBadgeAfter||e.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(e){return{"tip.state.unsubscribed":e["tip.state.unsubscribed"]||"Subscribe to notifications","tip.state.subscribed":e["tip.state.subscribed"]||"You're subscribed to notifications","tip.state.blocked":e["tip.state.blocked"]||"You've blocked notifications","message.prenotify":e["message.prenotify"]||"Click to subscribe to notifications","message.action.subscribed":e["message.action.subscribed"]||"Thanks for subscribing!","message.action.resubscribed":e["message.action.resubscribed"]||"You're subscribed to notifications","message.action.subscribing":e["message.action.subscribing"]||"Click {{prompt.native.grant}} to receive notifications","message.action.unsubscribed":e["message.action.unsubscribed"]||"You won't receive notifications again","dialog.main.title":e["dialog.main.title"]||"Manage Site Notifications","dialog.main.button.subscribe":e["dialog.main.button.subscribe"]||"SUBSCRIBE","dialog.main.button.unsubscribe":e["dialog.main.button.unsubscribe"]||"UNSUBSCRIBE","dialog.blocked.title":e["dialog.blocked.title"]||"Unblock Notifications","dialog.blocked.message":e["dialog.blocked.message"]||"Follow these instructions to allow notifications:"}}installEventHooks(){O.emitter.on(C.EVENTS.SUBSCRIBE_CLICK,()=>{this.dialog.subscribeButton.disabled=!0,this._ignoreSubscriptionState=!0,O.User.PushSubscription.optIn().then(()=>(this.dialog.subscribeButton.disabled=!1,this.dialog.hide())).then(()=>this.message.display(ue.TYPES.MESSAGE,this.options.text["message.action.resubscribed"],ue.TIMEOUT)).then(()=>(this._ignoreSubscriptionState=!1,this.launcher.clearIfWasInactive(),this.launcher.inactivate())).then(()=>this.updateState()).catch(e=>{throw e})}),O.emitter.on(C.EVENTS.UNSUBSCRIBE_CLICK,()=>{this.dialog.unsubscribeButton.disabled=!0,O.User.PushSubscription.optOut().then(()=>(this.dialog.unsubscribeButton.disabled=!1,this.dialog.hide())).then(()=>(this.launcher.clearIfWasInactive(),this.launcher.activate())).then(()=>this.message.display(ue.TYPES.MESSAGE,this.options.text["message.action.unsubscribed"],ue.TIMEOUT)).then(()=>this.updateState())}),O.emitter.on(C.EVENTS.HOVERING,()=>{if(this.hovering=!0,this.launcher.activateIfInactive(),this.message.shown||this.dialog.shown){this.hovering=!1;return}if(this.message.contentType===ue.TYPES.MESSAGE){this.hovering=!1;return}new Promise(e=>{if(this.message.queued.length>0)return this.message.dequeue().then(t=>{this.message.content=t,this.message.contentType=ue.TYPES.QUEUED,e()});this.message.content=ft.decodeHtmlEntities(this.message.getTipForState()),this.message.contentType=ue.TYPES.TIP,e()}).then(()=>this.message.show()).then(()=>{this.hovering=!1}).catch(e=>{r.error(e)})}),O.emitter.on(C.EVENTS.HOVERED,()=>{this.message.contentType!==ue.TYPES.MESSAGE&&this.dialog.hidden&&(this.hovering&&(this.hovering=!1,this.message.waitUntilShown().then(()=>Pt(ue.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)}))}),O.emitter.on(O.EVENTS.SUBSCRIPTION_CHANGED,async e=>{if(e.current.optedIn&&(this.badge.shown&&this.options.prenotify&&this.badge.hide(),this.dialog.notificationIcons===null)){const n=await L.getNotificationIcons();this.dialog.notificationIcons=n}const t=await O.context.permissionManager.getPermissionStatus();let i;e.current.optedIn?i=C.STATES.SUBSCRIBED:t===ae.Denied?i=C.STATES.BLOCKED:i=C.STATES.UNSUBSCRIBED,this.setState(i,this._ignoreSubscriptionState)}),O.emitter.on(C.EVENTS.STATE_CHANGED,e=>{this.launcher.element&&(e.to===C.STATES.SUBSCRIBED?this.launcher.inactivate():(e.to===C.STATES.UNSUBSCRIBED||C.STATES.BLOCKED)&&this.launcher.activate())}),O.emitter.on(O.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,()=>{this.updateState()})}addDefaultClasses(){const e=this.container;if(this.options.position==="bottom-left")e&&m(e,"onesignal-bell-container-bottom-left"),m(this.launcher.selector,"onesignal-bell-launcher-bottom-left");else if(this.options.position==="bottom-right")e&&m(e,"onesignal-bell-container-bottom-right"),m(this.launcher.selector,"onesignal-bell-launcher-bottom-right");else throw new Error(`Invalid OneSignal notify button position ${this.options.position}`);if(this.options.theme==="default")m(this.launcher.selector,"onesignal-bell-launcher-theme-default");else if(this.options.theme==="inverse")m(this.launcher.selector,"onesignal-bell-launcher-theme-inverse");else throw new Error(`Invalid OneSignal notify button theme ${this.options.theme}`)}async create(){if(!this.options.enable)return;if(await O.context.dynamicResourceLoader.loadSdkStylesheet()!==Dt.Loaded){r.debug("Not showing notify button because styles failed to load.");return}this.container&&Re("#onesignal-bell-container"),ie("body","beforeend",'
'),this.container&&ie(this.container,"beforeend",'
'),ie(this.launcher.selector,"beforeend",'
'),ie(this.launcher.selector,"beforeend",'
'),ie(this.launcher.selector,"beforeend",'
'),ie(this.message.selector,"beforeend",'
'),ie(this.launcher.selector,"beforeend",'
'),ie(this.dialog.selector,"beforeend",'
'),ie(this.button.selector,"beforeend",ms);const t=await O.context.subscriptionManager.isPushNotificationsEnabled();Fe.wasPromptOfTypeDismissed(te.Push);const i=t?"small":this.options.size||this.DEFAULT_SIZE;await this.launcher.resize(i),this.addDefaultClasses(),this.applyOffsetIfSpecified(),this.setCustomColorsIfSpecified(),this.patchSafariSvgFilterBug(),r.info("Showing the notify button."),await(t?this.launcher.inactivate():et()).then(()=>t&&this.dialog.notificationIcons===null?L.getNotificationIcons().then(n=>{this.dialog.notificationIcons=n}):et()).then(()=>Pt(this.options.showLauncherAfter||0)).then(()=>this.launcher.show()).then(()=>Pt(this.options.showBadgeAfter||0)).then(()=>this.options.prenotify&&!t&&O._isNewVisitor?this.message.enqueue(this.options.text["message.prenotify"]).then(()=>this.badge.show()):et()).then(()=>this.initialized=!0)}patchSafariSvgFilterBug(){if(!(N().name=="safari"&&Number(N().version)>=9.1)){const e="drop-shadow(0 2px 4px rgba(34,36,38,0.35));",t="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: ${e}; -webkit-filter: ${e};`),this.badge.element.setAttribute("style",`filter: ${t}; -webkit-filter: ${t};`),this.dialog.element.setAttribute("style",`filter: ${i}; -webkit-filter: ${i};`)}N().name=="safari"&&this.badge.element.setAttribute("style","display: none;")}applyOffsetIfSpecified(){const e=this.options.offset;if(e){const t=this.launcher.element;if(!t){r.error("Could not find bell dom element");return}t.style.cssText="",e.bottom&&(t.style.cssText+=`bottom: ${e.bottom};`),this.options.position==="bottom-right"?e.right&&(t.style.cssText+=`right: ${e.right};`):this.options.position==="bottom-left"&&e.left&&(t.style.cssText+=`left: ${e.left};`)}}setCustomColorsIfSpecified(){const e=this.dialog.element.querySelector("button.action"),t=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(e?C.STATES.SUBSCRIBED:C.STATES.UNSUBSCRIBED),t===ae.Denied&&this.setState(C.STATES.BLOCKED)}).catch(e=>{r.error(e)})}setState(e,t=!1){const i=this.state;this.state=e,i!==e&&!t&&P.trigger(C.EVENTS.STATE_CHANGED,{from:i,to:e})}get container(){return document.querySelector("#onesignal-bell-container")}get graphic(){return this.button.element.querySelector("svg")}get launcher(){return this._launcher||(this._launcher=new fs(this)),this._launcher}get button(){return this._button||(this._button=new ps(this)),this._button}get badge(){return this._badge||(this._badge=new gs),this._badge}get message(){return this._message||(this._message=new ue(this)),this._message}get dialog(){return this._dialog||(this._dialog=new hs(this)),this._dialog}get subscribed(){return this.state===C.STATES.SUBSCRIBED}get unsubscribed(){return this.state===C.STATES.UNSUBSCRIBED}get blocked(){return this.state===C.STATES.BLOCKED}}class ${static async internalInit(){r.debug("Called internalInit()"),await OneSignal.context.serviceWorkerManager.installWorker();const e=OneSignal.context.sessionManager;if(OneSignal.emitter.on(OneSignal.EVENTS.SESSION_STARTED,e.sendOnSessionUpdateFromPage.bind(e)),OneSignal.context.pageViewManager.incrementPageViewCount(),document.visibilityState!=="visible"){$.postponeSessionInitUntilPageIsInFocus();return}await $.sessionInit()}static postponeSessionInitUntilPageIsInFocus(){fe(document,"visibilitychange",(e,t)=>{document.visibilityState==="visible"&&(t(),$.sessionInit())},!0)}static async sessionInit(){if(r.debug("Called sessionInit()"),OneSignal._sessionInitAlreadyRunning){r.debug("Returning from sessionInit because it has already been called.");return}OneSignal._sessionInitAlreadyRunning=!0;try{await $.doInitialize()}catch(n){if(n instanceof ge)return;throw n}const e=await OneSignal.context.subscriptionManager.isOptedOut(),t=await u.getSubscription();t.optedOut=e,await u.setSubscription(t),await $.handleAutoResubscribe(e);const i=await OneSignal.context.subscriptionManager.isPushNotificationsEnabled();await u.setIsPushEnabled(!!i),OneSignal.config.userConfig.promptOptions.autoPrompt&&!e&&OneSignal.context.promptsManager.spawnAutoPrompts(),OneSignal._sessionInitAlreadyRunning=!1,await P.trigger(OneSignal.EVENTS.SDK_INITIALIZED)}static async registerForPushNotifications(){await ot.registerForPush()}static async onSdkInitialized(){const e=await $.processExpiringSubscriptions();await OneSignal.context.subscriptionManager.isAlreadyRegisteredWithOneSignal()?(OneSignal.context.sessionManager.setupSessionEventListeners(),e||await OneSignal.context.updateManager.sendOnSessionUpdate()):!OneSignal.config.userConfig.promptOptions.autoPrompt&&!OneSignal.config.userConfig.autoResubscribe&&await OneSignal.context.updateManager.sendOnSessionUpdate(),await P.trigger(OneSignal.EVENTS.SDK_INITIALIZED_PUBLIC)}static async storeInitialValues(){const e=await OneSignal.context.subscriptionManager.isPushNotificationsEnabled(),t=await OneSignal.context.permissionManager.getPermissionStatus(),i=await OneSignal.context.subscriptionManager.isOptedOut();F.put("subscription.optedOut",i),await u.put("Options",{key:"isPushEnabled",value:e}),await u.put("Options",{key:"notificationPermission",value:t})}static async setWelcomeNotificationFlag(){await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.context.appConfig.safariWebId)===ae.Granted&&(OneSignal.__doNotShowWelcomeNotification=!0)}static async establishServiceWorkerChannel(){if(navigator.serviceWorker&&window.isSecureContext)try{await OneSignal.context.serviceWorkerManager.establishServiceWorkerChannel()}catch(e){r.error(e)}}static async processExpiringSubscriptions(){const e=OneSignal.context;if(r.debug("Checking subscription expiration..."),!await e.subscriptionManager.isSubscriptionExpiring())return r.debug("Subscription is not considered expired."),!1;r.debug("Subscription is considered expiring.");const i=await e.subscriptionManager.subscribe(ht.SubscribeNew);return await e.subscriptionManager.registerSubscription(i),!0}static async doInitialize(){const e=[];e.push($.storeInitialValues()),e.push($.installNativePromptPermissionChangedHook()),e.push($.setWelcomeNotificationFlag()),e.push($.establishServiceWorkerChannel()),e.push($.showNotifyButton()),e.push($.showPromptsFromWebConfigEditor());try{await Promise.all(e)}catch(t){throw r.error(t),new ge(me.Unknown)}}static async showNotifyButton(){if(R.isBrowser()&&!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 e=OneSignal.config.userConfig.notifyButton.displayPredicate;e&&typeof e=="function"?OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED,async()=>{await Promise.resolve(OneSignal.config.userConfig.notifyButton.displayPredicate())!==!1?(OneSignal.notifyButton=new C(OneSignal.config.userConfig.notifyButton),OneSignal.notifyButton.create()):r.debug("Notify button display predicate returned false so not showing the notify button.")}):(OneSignal.notifyButton=new C(OneSignal.config.userConfig.notifyButton),OneSignal.notifyButton.create())}}static async showPromptsFromWebConfigEditor(){const e=OneSignal.config;e.userConfig.promptOptions&&await new Fi(e.userConfig.promptOptions.customlink).initialize()}static async installNativePromptPermissionChangedHook(){try{if(navigator.permissions){const e=await navigator.permissions.query({name:"notifications"});e.onchange=function(){Sn()}}}catch(e){r.warn(`Could not install native notification permission change hook w/ error: ${e}`)}}static async saveInitOptions(){const e=[],t=OneSignal.config.userConfig.persistNotification;e.push(u.put("Options",{key:"persistNotification",value:t??!0}));const i=OneSignal.config.userConfig.webhooks;return["notification.willDisplay","notification.clicked","notification.dismissed"].forEach(n=>{i&&i[n]?e.push(u.put("Options",{key:`webhooks.${n}`,value:i[n]})):e.push(u.put("Options",{key:`webhooks.${n}`,value:!1}))}),i&&i.cors?e.push(u.put("Options",{key:"webhooks.cors",value:!0})):e.push(u.put("Options",{key:"webhooks.cors",value:!1})),OneSignal.config.userConfig.notificationClickHandlerMatch?e.push(u.put("Options",{key:"notificationClickHandlerMatch",value:OneSignal.config.userConfig.notificationClickHandlerMatch})):e.push(u.put("Options",{key:"notificationClickHandlerMatch",value:"exact"})),OneSignal.config.userConfig.notificationClickHandlerAction?e.push(u.put("Options",{key:"notificationClickHandlerAction",value:OneSignal.config.userConfig.notificationClickHandlerAction})):e.push(u.put("Options",{key:"notificationClickHandlerAction",value:"navigate"})),Promise.all(e)}static async initSaveState(e){const t=await L.getAppId(),i=OneSignal.config;await u.put("Ids",{type:"appId",id:t});const n=e||i.siteName||document.title||"Notification";await u.put("Options",{key:"pageTitle",value:n}),r.info(`OneSignal: Set pageTitle to be '${n}'.`)}static async handleAutoResubscribe(e){r.info("handleAutoResubscribe",{autoResubscribe:OneSignal.config.userConfig.autoResubscribe,isOptedOut:e}),OneSignal.config.userConfig.autoResubscribe&&!e&&await OneSignal.context.permissionManager.getNotificationPermission(OneSignal.context.appConfig.safariWebId)==ae.Granted&&await ot.registerForPush()}static errorIfInitAlreadyCalled(){if(OneSignal._initCalled)throw new ge(me.MultipleInitialization);OneSignal._initCalled=!0}}function Ki(s){return` `}function ws(s="#FFFFFF"){return``}function bs(s){const{icon:e,messageText:t,positiveButtonText:i,negativeButtonText:n}=s,o=e===U.defaultIcon?zn:e,a=e===U.defaultIcon?U.defaultIcon:"",c=document.createElement("div"),d=document.createElement("div"),l=document.createElement("div"),p=document.createElement("div"),b=document.createElement("div"),w=document.createElement("div"),T=document.createElement("button"),M=document.createElement("button"),Ye=document.createElement("div"),ct=document.createElement("div"),lt=document.createElement("img");return m(d,U.body),m(p,U.icon),m(l,U.message),m(w,U.footer),m(Ye,U.clearfix),m(ct,U.clearfix),m(T,nt.alignRight),m(T,nt.primary),m(T,nt.slidedownButton),m(M,nt.alignRight),m(M,nt.secondary),m(M,nt.slidedownButton),c.id=k.normalSlidedown,d.id=k.body,b.id=k.loadingContainer,T.id=k.allowButton,M.id=k.cancelButton,w.id=k.footer,a&&m(lt,a),lt.setAttribute("alt","notification icon"),lt.setAttribute("src",o||""),l.innerText=t||"",T.innerText=i||"",M.innerText=n||"",p.appendChild(lt),d.appendChild(p),d.appendChild(l),d.appendChild(Ye),d.appendChild(b),w.appendChild(T),w.appendChild(M),w.appendChild(ct),c.appendChild(d),c.appendChild(w),c}var Wt=(s=>(s.Stylesheet="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.min.css",s.Main="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput.min.js",s.Utils="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js",s))(Wt||{}),_t=(s=>(s.Stylesheet="sha512-yye/u0ehQsrVrfSd6biT17t39Rg9kNc+vENcCXZuMz2a+LWFGvXUnYuWUW6pbfYj1jcBb/C39UZw2ciQvwDDvg==",s.Main="sha512-OnkjbJ4TwPpgSmjXACCb5J4cJwi880VRe+vWpPDlr8M38/L3slN5uUAeOeWU2jN+4vN0gImCXFGdJmc0wO4Mig==",s.Utils="sha512-bUcJxlqkiGA3cmoYPuZaLRsyc5ChG9APG4ajom2AXKSlBtOmx4kLV3c8uv/6uSz43FMjI4Q2QI21+D223rT76w==",s))(_t||{});class re{smsInputFieldIsValid=!0;emailInputFieldIsValid=!0;promptOptions;itiOneSignal;constructor(e){this.promptOptions=e}generateHtml(){const e=document.createElement("div");m(e,H.channelCaptureContainer),e.id=H.channelCaptureContainer;let t,i,n;switch(this.promptOptions.type){case f.Sms:t=this.promptOptions.text.smsLabel||"Phone Number",i=this.getInputWithValidationElement(f.Sms,t),e.appendChild(i);break;case f.Email:t=this.promptOptions.text.emailLabel||"Email",n=this.getInputWithValidationElement(f.Email,t),e.appendChild(n);break;case f.SmsAndEmail:t=this.promptOptions.text.emailLabel||"Email",n=this.getInputWithValidationElement(f.Email,t),e.appendChild(n),t=this.promptOptions.text.smsLabel||"Phone Number",i=this.getInputWithValidationElement(f.Sms,t),e.appendChild(i);break}return e}getValidationElementWithMessage(e){const t=document.createElement("div"),i=document.createElement("img"),n=document.createElement("p");return n.innerText=e,i.setAttribute("src",Kn),t.appendChild(i),t.appendChild(n),t}getInputWithValidationElement(e,t){const i=this.getTypeSpecificVariablesForValidationElemGeneration(e),n=document.createElement("label"),o=document.createElement("input"),a=document.createElement("div"),c=document.createElement("div"),d=this.getValidationElementWithMessage(i.message),l=document.createElement("div");return a.setAttribute("style","clear:both"),c.setAttribute("style","clear:both"),m(d,H.onesignalValidationElementHidden),m(d,H.onesignalValidationElement),d.id=i.validationElementId,n.title=t,n.innerText=t,n.htmlFor=i.inputElementId,o.type=i.domElementType,o.id=i.inputElementId,o.tabIndex=i.tabIndex,m(o,i.inputClass),m(l,H.inputWithValidationElement),l.id=i.wrappingDivId,l.appendChild(n),l.appendChild(a),l.appendChild(o),l.appendChild(c),l.appendChild(d),l}getTypeSpecificVariablesForValidationElemGeneration(e){if(e===f.Email)return{message:"Please enter a valid email",domElementType:"email",validationElementId:z.onesignalEmailValidationElement,inputElementId:z.onesignalEmailInput,inputClass:H.onesignalEmailInput,wrappingDivId:z.emailInputWithValidationElement,tabIndex:1};if(e===f.Sms)return{message:"Please enter a valid phone number",domElementType:"tel",validationElementId:z.onesignalSmsValidationElement,inputElementId:z.onesignalSmsInput,inputClass:H.onesignalSmsInput,wrappingDivId:z.smsInputWithValidationElement,tabIndex:2};throw new Error("invalid channel type for input validation")}initializePhoneInputLibrary(){const e=V(`#${z.onesignalSmsInput}`);e&&window.intlTelInput?this.itiOneSignal=window.intlTelInput(e,{autoPlaceholder:"off",separateDialCode:!0}):r.error("OneSignal: there was a problem initializing International Telephone Input")}addSmsInputEventListeners(){const e=V(`#${z.onesignalSmsInput}`);e.addEventListener("keyup",t=>{this.smsInputFieldIsValid=this.itiOneSignal.isValidNumber()||e?.value==="",t.key==="Enter"&&document.getElementById(k.allowButton)?.click(),this.updateValidationOnSmsInputChange()}),e.addEventListener("blur",()=>{this.smsInputFieldIsValid=this.itiOneSignal.isValidNumber()||e?.value==="",this.updateValidationOnSmsInputChange()})}addEmailInputEventListeners(){const e=V(`#${z.onesignalEmailInput}`);e.addEventListener("keyup",t=>{const i=e?.value;this.emailInputFieldIsValid=re.validateEmailInputWithReturnVal(i),t.key==="Enter"&&document.getElementById(k.allowButton)?.click(),this.updateValidationOnEmailInputChange()})}updateValidationOnSmsInputChange(){const e=V(`#${z.smsInputWithValidationElement}`),t=V(`#${z.onesignalSmsValidationElement}`);le(e,H.onesignalErrorInput),m(t,H.onesignalValidationElementHidden)}updateValidationOnEmailInputChange(){const e=V(`#${z.emailInputWithValidationElement}`),t=V(`#${z.onesignalEmailValidationElement}`);le(e,H.onesignalErrorInput),m(t,H.onesignalValidationElementHidden)}async loadPhoneLibraryScripts(){if(OneSignal._didLoadITILibrary)return;const e=document.createElement("script"),t=document.createElement("script"),i=document.createElement("link");e.src=Wt.Main,t.src=Wt.Utils,i.href=Wt.Stylesheet,i.rel="stylesheet",e.integrity=_t.Main,t.integrity=_t.Utils,i.integrity=_t.Stylesheet,e.crossOrigin="anonymous",t.crossOrigin="anonymous",i.crossOrigin="anonymous",document.head.appendChild(e),document.head.appendChild(t),document.head.appendChild(i);const n=new Promise(a=>{e.onload=()=>{a()}}),o=new Promise(a=>{t.onload=()=>{a()}});await Promise.all([n,o]),OneSignal._didLoadITILibrary=!0}async mount(){const e=re.isUsingSmsInputField(this.promptOptions.type),t=re.isUsingEmailInputField(this.promptOptions.type);e&&await this.loadPhoneLibraryScripts();const i=this.generateHtml();V(`#${k.body}`).appendChild(i),e&&(this.initializePhoneInputLibrary(),this.addSmsInputEventListeners()),t&&this.addEmailInputEventListeners()}isEmailInputFieldEmpty(){return this.getValueFromEmailInput()===""}isSmsInputFieldEmpty(){return this.getValueFromSmsInput()===""}getValueFromEmailInput(){return V(`#${z.onesignalEmailInput}`)?.value||""}getValueFromSmsInput(){return this.itiOneSignal.getNumber(intlTelInputUtils.numberFormat.E164)||""}static showSmsInputError(e){const t=document.querySelector(`#${z.onesignalSmsValidationElement}`),i=document.querySelector(`#${z.smsInputWithValidationElement}`);if(!t||!i){r.error("OneSignal: couldn't find slidedown validation element");return}e?(t.classList.remove(H.onesignalValidationElementHidden),i.classList.add(H.onesignalErrorInput)):(t.classList.add(H.onesignalValidationElementHidden),i.classList.remove(H.onesignalErrorInput))}static showEmailInputError(e){const t=document.querySelector(`#${z.onesignalEmailValidationElement}`),i=document.querySelector(`#${z.emailInputWithValidationElement}`);if(!t||!i){r.error("OneSignal: couldn't find slidedown validation element");return}e?(t.classList.remove(H.onesignalValidationElementHidden),i.classList.add(H.onesignalErrorInput)):(t.classList.add(H.onesignalValidationElementHidden),i.classList.remove(H.onesignalErrorInput))}static resetInputErrorStates(e){switch(e){case f.Sms:re.showSmsInputError(!1);break;case f.Email:re.showEmailInputError(!1);break;case f.SmsAndEmail:re.showSmsInputError(!1),re.showEmailInputError(!1);break}}static validateEmailInputWithReturnVal(e){return/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(e||"")||e===""}static isUsingSmsInputField(e){return e===f.Sms||e===f.SmsAndEmail}static isUsingEmailInputField(e){return e===f.Email||e===f.SmsAndEmail}}var xe=(s=>(s[s.InvalidSms=0]="InvalidSms",s[s.InvalidEmail=1]="InvalidEmail",s[s.InvalidEmailAndSms=2]="InvalidEmailAndSms",s))(xe||{});class Je extends S{description;reason;constructor(e){let t;switch(e){case 1:t="Invalid email";break;case 0:t="Invalid sms";break;case 2:t="Invalid email & sms";break}super(t),this.description=xe[e],this.reason=e,Object.setPrototypeOf(this,Je.prototype)}}class j{options;notificationIcons;channelCaptureContainer;isShowingFailureState;tagCategories;savingButton=oe.savingText;errorButton=oe.errorButton;updateMessage;positiveUpdateButton;negativeUpdateButton;constructor(e){switch(this.options=e,this.options.text.actionMessage=e.text.actionMessage.substring(0,90),this.options.text.acceptButton=e.text.acceptButton.substring(0,16),this.options.text.cancelButton=e.text.cancelButton.substring(0,16),this.notificationIcons=null,this.channelCaptureContainer=null,this.isShowingFailureState=!1,e.type){case f.Category: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=e.categories,this.errorButton=y.getValueOrDefault(this.options.text.positiveUpdateButton,oe.errorButton);break;case f.Sms:case f.Email:case f.SmsAndEmail:this.errorButton=y.getValueOrDefault(this.options.text.acceptButton,oe.errorButton);break}}async create(e){if(this.notificationIcons===null){const t=await L.getNotificationIcons();this.notificationIcons=t,this.container.className.includes(U.container)&&Re(`#${k.container}`);const i=e&&this.tagCategories?this.positiveUpdateButton:this.options.text.acceptButton,n=e&&this.tagCategories?this.negativeUpdateButton:this.options.text.cancelButton,o=e&&this.tagCategories?this.updateMessage:this.options.text.actionMessage,a=this.options.icon||this.getPlatformNotificationIcon(),c=bs({messageText:o,icon:a,positiveButtonText:i,negativeButtonText:n}),d=document.createElement("div"),l=document.createElement("div");d.id=k.container,m(d,U.container),m(d,U.reset),V("body").appendChild(d),l.id=k.dialog,m(l,U.dialog),l.appendChild(c),this.container.appendChild(l),m(this.container,N().mobile?U.slideUp:U.slideDown),this.allowButton.addEventListener("click",this.onSlidedownAllowed.bind(this)),this.cancelButton.addEventListener("click",this.onSlidedownCanceled.bind(this))}}static async triggerSlidedownEvent(e){await P.trigger(e)}async onSlidedownAllowed(e){await j.triggerSlidedownEvent(j.EVENTS.ALLOW_CLICK)}onSlidedownCanceled(e){j.triggerSlidedownEvent(j.EVENTS.CANCEL_CLICK),this.close(),j.triggerSlidedownEvent(j.EVENTS.CLOSED)}close(){m(this.container,U.closeSlidedown),fe(this.dialog,"animationend",(e,t)=>{e.target===this.dialog&&(e.animationName==="slideDownExit"||e.animationName==="slideUpExit")&&(Re(`#${k.container}`),t())},!0)}setSaveState(){this.allowButton.disabled=!0,this.allowButton.textContent=null,this.allowButton.insertAdjacentElement("beforeend",this.getTextSpan(this.savingButton)),this.allowButton.insertAdjacentElement("beforeend",this.getIndicatorHolder()),ie(this.buttonIndicatorHolder,"beforeend",Ki(_i.whiteLoadingIndicator)),m(this.allowButton,"disabled"),m(this.allowButton,U.savingStateButton)}removeSaveState(){this.allowButton.textContent=this.positiveUpdateButton,Re(`#${U.buttonIndicatorHolder}`),this.allowButton.disabled=!1,le(this.allowButton,"disabled"),le(this.allowButton,U.savingStateButton)}setFailureState(){this.allowButton.textContent=null,this.allowButton.insertAdjacentElement("beforeend",this.getTextSpan(this.errorButton)),this.options.type===f.Category&&(this.allowButton.insertAdjacentElement("beforeend",this.getIndicatorHolder()),ie(this.buttonIndicatorHolder,"beforeend",ws()),m(this.allowButton,"onesignal-error-state-button")),this.isShowingFailureState=!0}setFailureStateForInvalidChannelInput(e){switch(e){case xe.InvalidSms:re.showSmsInputError(!0);break;case xe.InvalidEmail:re.showEmailInputError(!0);break;case xe.InvalidEmailAndSms:re.showSmsInputError(!0),re.showEmailInputError(!0);break}}removeFailureState(){Re("#onesignal-button-indicator-holder"),le(this.allowButton,"onesignal-error-state-button"),pe.isSlidedownPushDependent(this.options.type)||re.resetInputErrorStates(this.options.type),this.isShowingFailureState=!1}getPlatformNotificationIcon(){return Qt(this.notificationIcons)}getIndicatorHolder(){const e=document.createElement("div");return e.id=k.buttonIndicatorHolder,m(e,U.buttonIndicatorHolder),e}getTextSpan(e){const t=document.createElement("span");return t.textContent=e,t}get container(){return V(`#${k.container}`)}get dialog(){return V(`#${k.dialog}`)}get allowButton(){return V(`#${k.allowButton}`)}get cancelButton(){return V(`#${k.cancelButton}`)}get buttonIndicatorHolder(){return V(`#${k.buttonIndicatorHolder}`)}get slidedownFooter(){return V(`#${k.footer}`)}static get EVENTS(){return{ALLOW_CLICK:"slidedownAllowClick",CANCEL_CLICK:"slidedownCancelClick",SHOWN:"slidedownShown",CLOSED:"slidedownClosed",QUEUED:"slidedownQueued"}}}function Ss(){const s=OneSignal.notifyButton;s&&s.options.enable&&OneSignal.notifyButton.launcher.state!=="hidden"&&OneSignal.notifyButton.launcher.waitUntilShown().then(()=>{OneSignal.notifyButton.launcher.hide()}),OneSignal.emitter.once(j.EVENTS.CLOSED,()=>{OneSignal.notifyButton&&OneSignal.notifyButton.options.enable&&OneSignal.notifyButton.launcher.show()})}class ys{isNativePromptShowing;context;eventHooksInstalled;constructor(e){this.isNativePromptShowing=!1,this.context=e,this.eventHooksInstalled=!1}shouldForceSlidedownOverNative(){const{environmentInfo:e}=OneSignal,{browserType:t,browserVersion:i,requiresUserInteraction:n}=e;return t==="chrome"&&Number(i)>=63&&(N().tablet||N().mobile)||n}async spawnAutoPrompts(){const e=OneSignal.config.userConfig.promptOptions,t=this.shouldForceSlidedownOverNative(),i=this.getDelayedPromptOptions(e,f.Native),n=this.isPageViewConditionMet(i),o=i.enabled&&n,a=t&&o;if(o&&!a){this.internalShowDelayedPrompt(f.Native,i.timeDelay||0);return}const c=!!pe.getFirstSlidedownPromptOptionsWithType(e.slidedown?.prompts,f.Push);a&&!c&&this.internalShowDelayedPrompt(f.Push,i.timeDelay||0);const d=e.slidedown?.prompts;if(d&&d?.length>0)for(let l=0;l0&&await He(t*1e3),e){case f.Native:await this.internalShowNativePrompt();break;case f.Push:await this.internalShowSlidedownPrompt(i);break;case f.Category:await this.internalShowCategorySlidedown(i);break;case f.Sms:await this.internalShowSmsSlidedown(i);break;case f.Email:await this.internalShowEmailSlidedown(i);break;case f.SmsAndEmail:await this.internalShowSmsAndEmailSlidedown(i);break;default:r.error("Invalid Delayed Prompt type")}}async internalShowNativePrompt(){if(B.logMethodCall("internalShowNativePrompt"),this.isNativePromptShowing){r.debug("Already showing autoprompt. Abort showing a native prompt.");return}this.isNativePromptShowing=!0,await $.registerForPushNotifications(),this.isNativePromptShowing=!1,Fe.markPromptDismissedWithType(te.Push)}async internalShowSlidedownPrompt(e={force:!1}){if(B.logMethodCall("internalShowSlidedownPrompt"),e.slidedownPromptOptions||(e.slidedownPromptOptions=hi),await this.context.dynamicResourceLoader.loadSdkStylesheet()!==Dt.Loaded){r.debug("Not showing slidedown permission message because styles failed to load.");return}this.eventHooksInstalled||this.installEventHooksForSlidedown(),await this.context.slidedownManager.createSlidedown(e)}async internalShowCategorySlidedown(e){B.logMethodCall("internalShowCategorySlidedown"),await this.internalShowParticularSlidedown(f.Category,e)}async internalShowSmsSlidedown(e){B.logMethodCall("internalShowSmsSlidedown"),await this.internalShowParticularSlidedown(f.Sms,e)}async internalShowEmailSlidedown(e){B.logMethodCall("internalShowEmailSlidedown"),await this.internalShowParticularSlidedown(f.Email,e)}async internalShowSmsAndEmailSlidedown(e){B.logMethodCall("internalShowSmsAndEmailSlidedown"),await this.internalShowParticularSlidedown(f.SmsAndEmail,e)}async internalShowParticularSlidedown(e,t){const i=this.context.appConfig.userConfig.promptOptions?.slidedown?.prompts,n=t?.slidedownPromptOptions||pe.getFirstSlidedownPromptOptionsWithType(i,e);if(!n)if(e!==f.Push){r.error(`OneSignal: slidedown of type '${e}' couldn't be shown. Check your configuration on the OneSignal dashboard or your custom code initialization.`);return}else r.warn("The OneSignal 'push' slidedown will be shown with default text settings. To customize, see the OneSignal documentation.");await this.internalShowSlidedownPrompt({...t,slidedownPromptOptions:n})}installEventHooksForSlidedown(){this.eventHooksInstalled=!0,OneSignal.emitter.on(j.EVENTS.SHOWN,()=>{this.context.slidedownManager.setIsSlidedownShowing(!0)}),OneSignal.emitter.on(j.EVENTS.CLOSED,()=>{this.context.slidedownManager.setIsSlidedownShowing(!1),this.context.slidedownManager.showQueued()}),OneSignal.emitter.on(j.EVENTS.ALLOW_CLICK,async()=>{await this.context.slidedownManager.handleAllowClick(),P.trigger(OneSignal.EVENTS.TEST_FINISHED_ALLOW_CLICK_HANDLING)}),OneSignal.emitter.on(j.EVENTS.CANCEL_CLICK,()=>{if(!this.context.slidedownManager.slidedown)return;switch(this.context.slidedownManager.slidedown?.options.type){case f.Push:case f.Category:r.debug("Setting flag to not show the slidedown to the user again."),Fe.markPromptDismissedWithType(te.Push);break;default:r.debug("Setting flag to not show the slidedown to the user again."),Fe.markPromptDismissedWithType(te.NonPush);break}})}isPageViewConditionMet(e){return!e||typeof e.pageViews>"u"||!e.autoPrompt||!e.enabled?!1:this.context.pageViewManager.getLocalPageViewCount()>=e.pageViews}getDelayedPromptOptions(e,t){const i={enabled:!1,autoPrompt:!1,timeDelay:de.timeDelay,pageViews:de.pageViews};if(!e||!e.native||!e.slidedown)return i;switch(t){case f.Native:{const n=e.native;return{enabled:n?.enabled,autoPrompt:n?.autoPrompt,timeDelay:n?.timeDelay,pageViews:n?.pageViews}}case f.Push:case f.Category:case f.Email:case f.Sms:case f.SmsAndEmail:{const{userConfig:n}=this.context.appConfig,o=pe.getFirstSlidedownPromptOptionsWithType(n.promptOptions?.slidedown?.prompts||[],t);return{enabled:!!o,autoPrompt:!!o?.autoPrompt,timeDelay:o?.delay?.timeDelay,pageViews:o?.delay?.pageViews}}default:return i}}}class Qi{mount(e,t){const i=this.generateHtml(e,t);V(`#${k.body}`).appendChild(i),this.taggingContainer&&this.taggingContainer.addEventListener("change",this.toggleCheckedTag);const o=V(`#${k.allowButton}`);o.disabled=!1,le(o,"disabled"),Re(`#${k.loadingContainer}`)}load(){const e=V(`#${k.loadingContainer}`),t=V(`#${k.allowButton}`),i=document.createElement("div");m(e,`${U.loadingContainer}`),m(i,Te.loadingMessage),m(t,"disabled"),ie(e,"beforeend",Ki(_i.greyLoadingIndicator)),i.innerText=Qn.fetchingPreferences,e.appendChild(i),t.disabled=!0}generateHtml(e,t){const i=Se.getCheckedTagCategories(e,t),n=i.filter(l=>i.indexOf(l)%2===0),o=i.filter(l=>i.indexOf(l)%2),a=document.createElement("div"),c=document.createElement("div"),d=document.createElement("div");return m(a,Te.taggingContainerCol),m(c,Te.taggingContainerCol),m(d,Te.taggingContainer),d.id=qn.taggingContainer,n.forEach(l=>{a.appendChild(this.getCategoryLabelElement(l))}),o.forEach(l=>{c.appendChild(this.getCategoryLabelElement(l))}),d.appendChild(a),d.appendChild(c),d}getCategoryLabelElement(e){const{label:t}=e,i=document.createElement("label"),n=document.createElement("span"),o=document.createElement("input"),a=document.createElement("span"),c=document.createElement("div"),d=document.createElement("div");return m(i,Te.categoryLabel),m(n,Te.categoryLabelText),m(o,Te.categoryLabelInput),m(a,Te.checkmark),i.title=t,n.innerText=t,o.type="checkbox",o.value=e.tag,o.checked=!!e.checked,i.appendChild(n),i.appendChild(o),i.appendChild(a),c.setAttribute("style","clear:both"),d.appendChild(i),d.appendChild(c),d}get taggingContainer(){const e=`#${k.body} > div.${Te.taggingContainer}`;return V(e)}toggleCheckedTag(e){const t=e.target;if(t&&t.getAttribute("type")==="checkbox"){const i=t.checked;t.setAttribute("checked",i.toString())}}static getValuesFromTaggingContainer(){const e=`#${k.body} > div.${Te.taggingContainer}> div > div > label > input[type=checkbox]`,t=document.querySelectorAll(e),i={};return t.forEach(n=>{i[n.value]=n.checked}),i}}class yi extends S{constructor(e){super(`The permission message of type ${e||"unknown"} was previously dismissed.`),Object.setPrototypeOf(this,yi.prototype)}}class rt{message;constructor(e){this.message=e}async show(){const e=document.createElement("div"),t=document.createElement("p");t.innerText=this.message,e.appendChild(t);const i=document.createElement("div"),n=document.createElement("div");i.id=k.container,e.id=Gn.toastText,m(e,jn.toastText),m(i,U.container),m(i,U.reset),V("body").appendChild(i),n.id=k.dialog,m(n,U.dialog),n.appendChild(e),this.container.appendChild(n),m(this.container,N().mobile?U.slideUp:U.slideDown),rt.triggerSlidedownEvent(rt.EVENTS.SHOWN)}static async triggerSlidedownEvent(e){await P.trigger(e)}close(){m(this.container,U.closeSlidedown),fe(this.dialog,"animationend",(e,t)=>{e.target===this.dialog&&(e.animationName==="slideDownExit"||e.animationName==="slideUpExit")&&(Re(`#${k.container}`),t())},!0)}get container(){return V(`#${k.container}`)}get dialog(){return V(`#${k.dialog}`)}static get EVENTS(){return{SHOWN:"toastShown",CLOSED:"toastClosed"}}}class vi extends S{constructor(){super("This operation can only be performed when the user is not subscribed."),Object.setPrototypeOf(this,vi.prototype)}}class vt extends S{constructor(e){super(`This operation can only be performed when the channel '${e}' does not yet exist.`),Object.setPrototypeOf(this,vt.prototype)}}class vs{context;slidedownQueue;isSlidedownShowing;slidedown;constructor(e){this.context=e,this.slidedownQueue=[],this.isSlidedownShowing=!1}async checkIfSlidedownShouldBeShown(e){const t=await OneSignal.context.permissionManager.getPermissionStatus()===ae.Denied;let i;const n=await OneSignal.context.subscriptionManager.getSubscriptionState(),{subscribed:o,optedOut:a}=n,c=e.slidedownPromptOptions?.type;let d=!1;if(c&&(d=pe.isSlidedownPushDependent(c)),d){if(o)return e.isInUpdateMode?!0:(r.info(new vi),!1);if(i=Fe.wasPromptOfTypeDismissed(te.Push),a)throw new At(xt.OptedOut);if(t)return r.info(new We(Ke.Blocked)),!1}else{if(!e.force){const l=await OneSignal.coreDirector.hasSms(),p=await OneSignal.coreDirector.hasEmail(),b=l&&p;if(l&&c===f.Sms)return r.info(new vt(f.Sms)),!1;if(p&&c===f.Email)return r.info(new vt(f.Email)),!1;if(b&&c===f.SmsAndEmail)return r.info(new vt(f.SmsAndEmail)),!1}i=Fe.wasPromptOfTypeDismissed(te.NonPush)}return i&&!e.force&&!e.isInUpdateMode?(r.info(new yi(c)),!1):!0}registerForPush(){$.registerForPushNotifications()}async handleAllowForCategoryType(){if(!this.slidedown)throw new S("SlidedownManager: handleAllowForCategoryType: this.slidedown is undefined");const e=Qi.getValuesFromTaggingContainer();this.context.tagManager.storeTagValuesToUpdate(e),this.registerForPush(),await this.context.tagManager.sendTags(!0)}async handleAllowForEmailType(){if(!this.slidedown)throw new S("SlidedownManager: handleAllowForEmailType: this.slidedown is undefined");const e=this.slidedown.channelCaptureContainer?.emailInputFieldIsValid,t=this.slidedown.channelCaptureContainer?.isEmailInputFieldEmpty();if(!e||t)throw new Je(xe.InvalidEmail);const i=this.slidedown.channelCaptureContainer?.getValueFromEmailInput();this.updateEmail(i)}async handleAllowForSmsType(){if(!this.slidedown)throw new S("SlidedownManager: handleAllowForSmsType: this.slidedown is undefined");const e=this.slidedown.channelCaptureContainer?.smsInputFieldIsValid,t=this.slidedown.channelCaptureContainer?.isSmsInputFieldEmpty();if(!e||t)throw new Je(xe.InvalidSms);const i=this.slidedown.channelCaptureContainer?.getValueFromSmsInput();this.updateSMS(i)}async handleAllowForSmsAndEmailType(){if(!this.slidedown)throw new S("SlidedownManager: handleAllowForSmsAndEmailType: this.slidedown is undefined");const e=this.slidedown.channelCaptureContainer?.smsInputFieldIsValid,t=this.slidedown.channelCaptureContainer?.emailInputFieldIsValid,i=this.slidedown.channelCaptureContainer?.isEmailInputFieldEmpty(),n=this.slidedown.channelCaptureContainer?.isSmsInputFieldEmpty();if(!e&&!t||i&&n)throw new Je(xe.InvalidEmailAndSms);const c=this.slidedown.channelCaptureContainer?.getValueFromEmailInput(),d=this.slidedown.channelCaptureContainer?.getValueFromSmsInput();if(t)i||this.updateEmail(c);else throw new Je(xe.InvalidEmail);if(e)n||this.updateSMS(d);else throw new Je(xe.InvalidSms)}updateEmail(e){e&&OneSignal.User.addEmail(e)}updateSMS(e){e&&OneSignal.User.addSms(e)}async showConfirmationToast(){if(!this.slidedown)throw new S("SlidedownManager: showConfirmationToast: this.slidedown is undefined");const e=this.slidedown.options.text.confirmMessage;if(!e)return;await He(1e3);const t=new rt(e);await t.show(),await He(5e3),t.close(),rt.triggerSlidedownEvent(rt.EVENTS.CLOSED)}async mountAuxiliaryContainers(e){switch(e.slidedownPromptOptions?.type){case f.Category:this.mountTaggingContainer(e);break;case f.Email:case f.Sms:case f.SmsAndEmail:await this.mountChannelCaptureContainer(e);break}}async mountTaggingContainer(e){B.logMethodCall("mountTaggingContainer");try{let t={};const i=new Qi,n=e.slidedownPromptOptions?.categories;if(!n)throw new Error("Categories not defined");const a=OneSignal.coreDirector.getPropertiesModel()?.data.tags;e.isInUpdateMode&&a?(this.context.tagManager.storeRemotePlayerTags(a),t=Se.convertTagsApiToBooleans(a)):Se.markAllTagsAsSpecified(n,!0),i.mount(n,t)}catch(t){r.error("OneSignal: Attempted to create tagging container with error",t)}}async mountChannelCaptureContainer(e){B.logMethodCall("mountChannelCaptureContainer");try{if(e.slidedownPromptOptions){const t=new re(e.slidedownPromptOptions);t.mount(),this.slidedown&&(this.slidedown.channelCaptureContainer=t)}}catch(t){r.error("OneSignal: Attempted to create channel capture container with error",t)}}async handleAllowClick(){if(!this.slidedown)throw new S("SlidedownManager: handleAllowClick: this.slidedown is undefined");const e=this.slidedown.options.type;this.slidedown.isShowingFailureState&&this.slidedown.removeFailureState();try{switch(e){case f.Push:this.registerForPush();break;case f.Category:await this.handleAllowForCategoryType();break;case f.Email:await this.handleAllowForEmailType();break;case f.Sms:await this.handleAllowForSmsType();break;case f.SmsAndEmail:await this.handleAllowForSmsAndEmailType();break;default:break}}catch(t){r.warn("OneSignal Slidedown failed to update:",t),this.slidedown.removeSaveState(),this.slidedown.setFailureState(),t.reason!==void 0&&this.slidedown.setFailureStateForInvalidChannelInput(t.reason);return}switch(this.slidedown&&(this.slidedown.close(),pe.isSlidedownPushDependent(e)||await this.showConfirmationToast(),await He(1e3),j.triggerSlidedownEvent(j.EVENTS.CLOSED)),e){case f.Push:case f.Category:r.debug("Setting flag to not show the slidedown to the user again."),Fe.markPromptDismissedWithType(te.Push);break;default:r.debug("Setting flag to not show the slidedown to the user again."),Fe.markPromptDismissedWithType(te.NonPush);break}}setIsSlidedownShowing(e){this.isSlidedownShowing=e}async showQueued(){if(this.slidedownQueue.length>0){const e=this.dequeue();e&&await this.createSlidedown(e)}}enqueue(e){this.slidedownQueue.push(e),j.triggerSlidedownEvent(j.EVENTS.QUEUED)}dequeue(){return this.slidedownQueue.shift()}async createSlidedown(e){B.logMethodCall("createSlidedown");try{if(!await this.checkIfSlidedownShouldBeShown(e))return}catch(t){r.warn("checkIfSlidedownShouldBeShown returned an error",t);return}if(Ss(),this.isSlidedownShowing){this.enqueue(e);return}try{this.setIsSlidedownShowing(!0);const t=e.slidedownPromptOptions||hi;this.slidedown=new j(t),await this.slidedown.create(e.isInUpdateMode),await this.mountAuxiliaryContainers(e),r.debug("Showing OneSignal Slidedown"),j.triggerSlidedownEvent(j.EVENTS.SHOWN)}catch(t){r.error("There was an error showing the OneSignal Slidedown:",t),this.setIsSlidedownShowing(!1),this.slidedown?.close()}}}class Is{tagsFromTaggingContainer={};context;remoteTags={};constructor(e){this.context=e}async sendTags(){r.info("Category Slidedown Local Tags:",this.tagsFromTaggingContainer);const e=Se.convertTagsBooleansToApi(this.tagsFromTaggingContainer),t=Se.getObjectDifference(e,this.remoteTags);return Se.isTagObjectEmpty(t)?(r.warn("OneSignal: no change detected in Category preferences. Skipping tag update."),t):await OneSignal.User.addTags(t)}storeTagValuesToUpdate(e){this.tagsFromTaggingContainer=e}storeRemotePlayerTags(e){this.context.tagManager.remoteTags=e}}class Os{appConfig;environmentInfo;dynamicResourceLoader;subscriptionManager;serviceWorkerManager;workerMessenger;pageViewManager;permissionManager;updateManager;promptsManager;sessionManager;tagManager;slidedownManager;constructor(e){this.appConfig=e,typeof OneSignal<"u"&&OneSignal.environmentInfo&&(this.environmentInfo=OneSignal.environmentInfo),this.subscriptionManager=zi.getSubscriptionManager(this),this.serviceWorkerManager=zi.getServiceWorkerManager(this),this.pageViewManager=new Vt,this.permissionManager=new bi,this.workerMessenger=new as(this),this.updateManager=new cs(this),this.sessionManager=new ls(this),this.tagManager=new Is(this),this.slidedownManager=new vs(this),this.promptsManager=new ys(this),this.dynamicResourceLoader=new ci}}class Es{static processItem(e,t){if(typeof t=="function")return t(e);throw new S("Only accepts function type!")}}class Cs{setLogLevel(e){r.setLevel(e)}}class Ji extends Ut{constructor(e){super(),this._permissionNative=e,this._permission=e===ae.Granted,O.emitter.on(O.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,t=>{this._permissionNative=t,this._permission=t===ae.Granted})}_permission;get permissionNative(){return this._permissionNative}get permission(){return this._permission}async setDefaultUrl(e){if(h("setDefaultUrl",e),typeof e>"u")throw new I("url",v.Empty);if(typeof e!="string")throw new I("url",v.WrongType);if(!Mt.isValidUrl(e,{allowNull:!0}))throw new I("url",v.Malformed);await ce(),h("setDefaultNotificationUrl",e);const t=await u.getAppState();t.defaultNotificationUrl=e,await u.setAppState(t)}async setDefaultTitle(e){if(h("setDefaultTitle",e),typeof e>"u")throw new I("title",v.Empty);if(typeof e!="string")throw new I("title",v.WrongType);await ce();const t=await u.getAppState();t.defaultNotificationTitle=e,await u.setAppState(t)}isPushSupported(){return h("isPushNotificationsSupported"),!0}async requestPermission(){await ce(),await O.context.promptsManager.internalShowNativePrompt()}addEventListener(e,t){O.emitter.on(e,t),e==="click"&&J.fireStoredNotificationClicks()}removeEventListener(e,t){O.emitter.off(e,t)}}const Ts={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 Ps{async sendOutcome(e,t){const i=OneSignal.config.userConfig.outcomes;if(!i){r.error(`Could not send ${e}. No outcomes config found.`);return}const n=new bt(OneSignal.config.appId,i,e,!1);if(typeof t<"u"&&typeof t!="number"){r.error("Outcome weight can only be a number if present.");return}if(!await n.beforeOutcomeSend())return;const o=await n.getAttribution();await n.send({type:o.type,notificationIds:o.notificationIds,weight:t})}async sendUniqueOutcome(e){const t=OneSignal.config.userConfig.outcomes;if(!t){r.error(`Could not send ${e}. No outcomes config found.`);return}const i=new bt(OneSignal.config.appId,t,e,!0);if(!await i.beforeOutcomeSend())return;const n=await i.getAttribution();if(n.type===be.NotSupported){r.warn("You are on a free plan. Please upgrade to use this functionality.");return}const{notificationIds:o}=n,a=await i.getNotifsToAttributeWithUniqueOutcome(o);if(!i.shouldSendUnique(n,a)){r.warn(`'${e}' was already reported for all notifications.`);return}await i.send({type:n.type,notificationIds:a})}}class ks extends Ut{constructor(){super()}async promptPush(e){await ce(),await O.context.promptsManager.internalShowParticularSlidedown(f.Push,e)}async promptPushCategories(e){await ce();const t=await O.context.subscriptionManager.isPushNotificationsEnabled();await O.context.promptsManager.internalShowCategorySlidedown({...e,isInUpdateMode:t})}async promptSms(e){await ce(),await O.context.promptsManager.internalShowSmsSlidedown({...e})}async promptEmail(e){await ce(),await O.context.promptsManager.internalShowEmailSlidedown({...e})}async promptSmsAndEmail(e){await ce(),await O.context.promptsManager.internalShowSmsAndEmailSlidedown({...e})}addEventListener(e,t){O.emitter.on(e,t)}removeEventListener(e,t){O.emitter.off(e,t)}}let O=class D{static EVENTS=Ts;static async _initializeCoreModuleAndOSNamespaces(){const e=new Hn;await e.initPromise,D.coreDirector=new Yn(e);const t=await u.getSubscription(),i=await D.context.permissionManager.getPermissionStatus();D.User=new st(!0,t,i),this.Notifications=new Ji(i)}static async _initializeConfig(e){const t=await new is().getAppConfig(e);r.debug("OneSignal: Final web app config:",t),D.config=t,D.environmentInfo=li.getEnvironmentInfo(),D.context=new Os(t),D.config=D.context.appConfig}static async login(e,t){if(h("login",{externalId:e,jwtToken:t}),typeof e>"u")throw new I("externalId",v.Empty);if(typeof e!="string")throw new I("externalId",v.WrongType);if(t!==void 0&&typeof t!="string")throw new I("jwtToken",v.WrongType);await ee.login(e,t)}static async logout(){h("logout"),await ee.logout()}static async init(e){if(h("init"),r.debug(`Browser Environment: ${N().name} ${N().version}`),Ge.removeLegacySubscriptionOptions(),$.errorIfInitAlreadyCalled(),await D._initializeConfig(e),!D.config)throw new Error("OneSignal config not initialized!");if(N().name=="safari"&&!D.config.safariWebId){r.warn(new ge(me.MissingSafariWebId));return}if(await D._initializeCoreModuleAndOSNamespaces(),Ge.getConsentRequired()&&!await u.getConsentGiven()){D.pendingInit=!0;return}await D._delayedInit()}static async _delayedInit(){D.pendingInit=!1,D.context.workerMessenger.listen();async function e(){D.__initAlreadyCalled||(D.__initAlreadyCalled=!0,D.emitter.on(D.EVENTS.NOTIFICATION_PERMISSION_CHANGED_AS_STRING,J.onNotificationPermissionChange),D.emitter.on(D.EVENTS.SUBSCRIPTION_CHANGED,J._onSubscriptionChanged),D.emitter.on(D.EVENTS.SDK_INITIALIZED,$.onSdkInitialized),window.addEventListener("focus",()=>{L.checkAndTriggerNotificationPermissionChanged()}),await $.initSaveState(),await $.saveInitOptions(),await $.internalInit())}document.readyState==="complete"||document.readyState==="interactive"?await e():(r.debug("OneSignal: Waiting for DOMContentLoaded or readyStateChange event before continuing initialization..."),window.addEventListener("DOMContentLoaded",()=>{e()}),document.onreadystatechange=()=>{(document.readyState==="complete"||document.readyState==="interactive")&&e()})}static async setConsentGiven(e){if(h("setConsentGiven",{consent:e}),typeof e>"u")throw new I("consent",v.Empty);if(typeof e!="boolean")throw new I("consent",v.WrongType);await u.setConsentGiven(e),e&&D.pendingInit&&await D._delayedInit()}static async setConsentRequired(e){if(h("setConsentRequired",{requiresConsent:e}),typeof e>"u")throw new I("requiresConsent",v.Empty);if(typeof e!="boolean")throw new I("requiresConsent",v.WrongType);Ge.setConsentRequired(e)}static async push(e){return Es.processItem(D,e)}static __doNotShowWelcomeNotification;static VERSION=R.version();static _VERSION=R.version();static sdkEnvironment=x;static environmentInfo;static config=null;static _sessionInitAlreadyRunning=!1;static _isNewVisitor=!1;static timedLocalStorage=_e;static initialized=!1;static _didLoadITILibrary=!1;static notifyButton=null;static environment=R;static database=u;static event=P;static pendingInit=!0;static emitter=new Ot;static cache={};static _LOGGING=!1;static LOGGING=!1;static _initCalled=!1;static __initAlreadyCalled=!1;static context;static coreDirector;static _notifications;static get Notifications(){return this._notifications||(this._notifications=new Ji),this._notifications}static set Notifications(e){this._notifications=e}static Slidedown=new ks;static Session=new Ps;static User=new st(!1);static Debug=new Cs};r.info(`OneSignal Web SDK loaded (version ${O._VERSION}, ${x.getWindowEnv().toString()} environment).`),r.debug(`Current Page URL: ${typeof location>"u"?"NodeJS":location.href}`);class Ns{static async processOneSignalDeferredArray(e){for(const t of e)try{await O.push(t)}catch(i){r.error(i)}}}function xs(){if(On(),Kt()>1){r.warn("OneSignal: The web push SDK is included more than once. For optimal performance, please include our SDK only once on your page."),r.debug(`OneSignal: Exiting from SDK initialization to prevent double-initialization errors. Occurred ${Kt()} times.`);return}window.OneSignal=O,window.OneSignalDeferred=window.OneSignalDeferred??[];const s=Ns.processOneSignalDeferredArray(window.OneSignalDeferred);Object.defineProperty(window.OneSignalDeferred,"push",{value:async function(e){await s,O.push(e)}})}xs()})(); //# sourceMappingURL=OneSignalSDK.page.es6.js.map