!function(e){var t={};function i(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}i.m=e,i.c=t,i.d=function(e,t,s){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(s,r,function(t){return e[t]}.bind(null,r));return s},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=14)}([function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s="[WebEmarsysSDK]",r=()=>{},n=(e,t)=>(...i)=>{console[t](e,...i)};const a={trace:r,debug:r,info:r,warn:r,error:r,log:r},o={NoopLogFn:r,enableLogger:function(e,t=s){const i=["trace","debug","info","warn","error","log"];if(e)for(const e of i)a[e]=n(t,e);else for(const e of i)a[e]=r},SdkContext:s,SwContext:"[WebEmarsysSW]",Logger:a};t.default=o},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEVICE_REGISTRATION_STATUS_UNREGISTERED=t.DEVICE_REGISTRATION_STATUS_REGISTERED=t.KEY_DEVICE_REGISTRATION_STATUS=t.EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG=t.EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG=t.EVENT_ON_UPDATE_INBOX_MESSAGES=t.EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE=t.EVENT_ON_PUSH_DELIVERY=t.EVENT_ON_SW_INIT_ERROR=t.EVENT_ON_PERMISSION_GRANTED=t.EVENT_ON_PERMISSION_DENIED=t.EVENT_ON_PERMISSION_PROMPT=t.EVENT_ON_UNSUBSCRIBE=t.EVENT_ON_SUBSCRIBE=t.EVENT_ON_READY=t.PERMISSION_PROMPT=t.PERMISSION_GRANTED=t.PERMISSION_DENIED=t.indexedDbVersion=t.indexedDbName=t.meCustomEvent=t.meOpen=t.meLogout=t.meLogin=t.lsKeyLastContactFieldId=t.lsKeyLastLoginToken=t.lsKeyLastLoginTime=t.dbKeyLastUsedAt=t.dbKeyLoggingEnabled=t.dbKeyTimezone=t.dbKeyLanguage=t.dbKeyOsVersion=t.dbKeyDeviceModel=t.dbKeyApplicationVersion=t.dbKeyPlatform=t.dbKeyContactFieldValue=t.dbKeyContactFieldId=t.dbKeyPushToken=t.dbKeyServiceWorkerVersion=t.dbKeySdkVersion=t.dbKeyRefreshToken=t.dbKeyContactToken=t.dbKeyXClientState=t.dbKeyBrowserIds=t.dbKeyBrowserId=t.dbKeyInitParams=t.dbKeyLastPermissionStatus=t.dbKeyPushPackageServiceUrl=t.dbKeyWebsitePushId=t.dbKeyApplicationServerPublicKey=t.dbKeyServiceWorkerScope=t.dbKeyServiceWorkerUrl=t.dbKeyMeDeviceEventServiceApiBaseUrl=t.dbKeyMeClientServiceApiBaseUrl=t.dbKeyApplicationCode=t.dbKeyDefaultNotificationIcon=t.dbKeyDefaultNotificationTitle=t.applicationPassword=t.pushActionsProperty=t.pushImageProperty=t.pushIconProperty=t.pushLinkProperty=t.pushTitleProperty=t.loginOverloadProtectionTime=t.defaultApplicationVersion=t.defaultSafariPushPackageServiceUrl=t.defaultDeviceEventServiceApiBaseUrl=t.defaultClientServiceApiBaseUrl=void 0,t.defaultClientServiceApiBaseUrl="https://me-client.eservice.emarsys.net/v3",t.defaultDeviceEventServiceApiBaseUrl="https://mobile-events.eservice.emarsys.net/v3",t.defaultSafariPushPackageServiceUrl="https://me-client.eservice.emarsys.net",t.defaultApplicationVersion="0.0.0",t.loginOverloadProtectionTime=36e5,t.pushTitleProperty="title",t.pushLinkProperty="link",t.pushIconProperty="icon",t.pushImageProperty="image",t.pushActionsProperty="actions",t.applicationPassword="not-used",t.dbKeyDefaultNotificationTitle="pushDefaultNotificationTitle",t.dbKeyDefaultNotificationIcon="pushDefaultNotificationIcon",t.dbKeyApplicationCode="emarsysApplicationCode",t.dbKeyMeClientServiceApiBaseUrl="meClientServiceApiBaseUrl",t.dbKeyMeDeviceEventServiceApiBaseUrl="meDeviceEventServiceApiBaseUrl",t.dbKeyServiceWorkerUrl="serviceWorkerUrl",t.dbKeyServiceWorkerScope="serviceWorkerScope",t.dbKeyApplicationServerPublicKey="applicationServerPublicKey",t.dbKeyWebsitePushId="websitePushId",t.dbKeyPushPackageServiceUrl="pushPackageServiceUrl",t.dbKeyLastPermissionStatus="lastPermissionStatus",t.dbKeyInitParams="initParams",t.dbKeyBrowserId="browserId",t.dbKeyBrowserIds="browserIds",t.dbKeyXClientState="xClientState",t.dbKeyContactToken="contactToken",t.dbKeyRefreshToken="refreshToken",t.dbKeySdkVersion="sdkVersion",t.dbKeyServiceWorkerVersion="serviceWorkerVersion",t.dbKeyPushToken="pushToken",t.dbKeyContactFieldId="contactFieldId",t.dbKeyContactFieldValue="contactFieldValue",t.dbKeyPlatform="platform",t.dbKeyApplicationVersion="applicationVersion",t.dbKeyDeviceModel="deviceModel",t.dbKeyOsVersion="osVersion",t.dbKeyLanguage="language",t.dbKeyTimezone="timezone",t.dbKeyLoggingEnabled="loggingEnabled",t.dbKeyLastUsedAt="lastUsedAt",t.lsKeyLastLoginTime="emarsysWebpushLastLoginTime",t.lsKeyLastLoginToken="emarsysWebpushLastLoginToken",t.lsKeyLastContactFieldId="emarsysWebpushLastContactFieldId",t.meLogin="/users/login",t.meLogout="/users/logout",t.meOpen="/events/message_open",t.meCustomEvent="/events/",t.indexedDbName="EMARSYS_WEBPUSH_STORE",t.indexedDbVersion=1,t.PERMISSION_DENIED="denied",t.PERMISSION_GRANTED="granted",t.PERMISSION_PROMPT="default",t.EVENT_ON_READY="onReady",t.EVENT_ON_SUBSCRIBE="onSubscribe",t.EVENT_ON_UNSUBSCRIBE="onUnsubscribe",t.EVENT_ON_PERMISSION_PROMPT="onPermissionPrompt",t.EVENT_ON_PERMISSION_DENIED="onPermissionDenied",t.EVENT_ON_PERMISSION_GRANTED="onPermissionGranted",t.EVENT_ON_SW_INIT_ERROR="onSWInitError",t.EVENT_ON_PUSH_DELIVERY="onPushDelivery",t.EVENT_ON_PUT_NEW_MESSAGE_TO_INBOX_STORE="onPutNewMessageToInboxStore",t.EVENT_ON_UPDATE_INBOX_MESSAGES="onUpdateInboxMessages",t.EVENT_ON_SHOW_NOTIFICATION_PERMISSION_DIALOG="onShowNotificationPermissionDialog",t.EVENT_ON_HIDE_NOTIFICATION_PERMISSION_DIALOG="onHideNotificationPermissionDialog",t.KEY_DEVICE_REGISTRATION_STATUS="registrationStatus",t.DEVICE_REGISTRATION_STATUS_REGISTERED="registered",t.DEVICE_REGISTRATION_STATUS_UNREGISTERED="unregistered"},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.determineServiceWorkerScope=t.isEmptyObject=t.toContactInfo=t.isValidPayload=t.payloadMessageDataProperties=t.checkDevice=t.isDeviceRegistered=t.urlB64ToString=t.urlB64ToUint8Array=t.getGlobal=t.getVersion=void 0;const a=n(i(4));function o(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");return atob(t)}async function c(e){if(!await e.getClientId())return{exists:!1};const t=await e.getClientState();if(!t)return{exists:!1};const i=a.decode(t);if(!i)return{exists:!1};return{exists:!0,pushTokenExists:null!==(i.pushToken||null),identified:null!==(i.contactField||null)}}t.getVersion=function(){return"3.6.0"},t.getGlobal=function(){return Function("return this")()},t.urlB64ToUint8Array=function(e){const t=o(e),i=new Uint8Array(t.length);for(let e=0;e!!i[e]&&typeof i[e]===t.payloadMessageDataProperties[e])).reduce(((e,t)=>e&&t),!0)},t.toContactInfo=function(e){if(void 0!==e&&3===Object.keys(e).length)return e},t.isEmptyObject=e=>{if(null===e)return!0;if(void 0===e)return!0;for(const t in e)return!1;return!0},t.determineServiceWorkerScope=function(e){return e?e.scope:void 0}},function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StorageWithLog=void 0;const r=s(i(0)),{Logger:n}=r.default;t.StorageWithLog=class{constructor(e){this.storage=e}log(e,t,i){const{level:s="error",message:r=t}=i||{};return e||n[s](r),e}async getClientId(e){const t=await this.storage.getClientId();return this.log(t,"Error: No client ID set for the browser!",e)}async getContactToken(e){const t=await this.storage.getContactToken();return this.log(t,"Error: No contact token set!",e)}async getClientState(e){const t=await this.storage.getClientState();return this.log(t,"Error: No client state set!",e)}async getRefreshToken(e){const t=await this.storage.getRefreshToken();return this.log(t,"Unable to refresh contact token a refresh-token is missing!",e)}}},function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=void 0;const r=i(2),n=s(i(0));t.decode=function(e,t){const i=!0===(t||{}).header?0:1;try{return JSON.parse(r.urlB64ToString(e.split(".")[i]))}catch(e){return n.default.Logger.error("Error decoding token",e),null}}},function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MEDeviceEventService=void 0;const r=s(i(0)),n=i(3),{Logger:a}=r.default,o=[200,204];class c{constructor(e,t,i){this.storage=i,this.storageWithLog=new n.StorageWithLog(i),this.baseUrl=e+"/apps",this.desRequest=t}async postEvents(e){const t=await this.storageWithLog.getClientId(),i=await this.storageWithLog.getContactToken(),s=await this.storageWithLog.getClientState();if(!t||!i||!s)return{success:!1};const r=await this.apiEndpoint("client/events"),n=await this.desRequest.post(r,e,{clientId:t,clientState:s,contactToken:i});if(o.includes(n.status))return{success:!0,statusCode:n.status};{const e=await n.json();return a.warn("Error posting events to device event service",n.status,JSON.stringify(e)),{success:!1,statusCode:n.status}}}async apiEndpoint(e){const t=await this.storage.getAppCode();return`${this.baseUrl}/${t}/${e}`}static create(e,t,i){return new c(e,t,i)}}t.MEDeviceEventService=c},function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MEClientService=void 0;const r=s(i(0)),n=i(3),{Logger:a}=r.default;class o{constructor(e,t,i){this.storage=i,this.storageWithLog=new n.StorageWithLog(i),this.baseUrl=e+"/domains",this.meClientServiceRequest=t}async storeClientDetails(){const e=await this.storageWithLog.getClientId();if(!e)return!1;const t=await this.apiEndpoint("client"),i=await this.storage.getClientState(),s=await this.getClientDetails(),r=await this.meClientServiceRequest.post(t,s,{clientId:e,clientState:i});if(204===r.status)return await this.saveClientState(r),!0;{const e=await r.json();return a.error("Error storing client info",r.status,JSON.stringify(e)),!1}}async linkClientToContact(e){const t=await this.storageWithLog.getClientId(),i=await this.storageWithLog.getClientState({level:"info"});if(!t||!i)return!1;const{anonymous:s,body:r}=this.toContactRequestBodyData(e),n=`${await this.apiEndpoint("client/contact")}${s?"?anonymous=true":""}`,o=await this.meClientServiceRequest.post(n,r,{clientId:t,clientState:i});if(200===o.status){await this.saveClientState(o);const e=await o.json();return e.contactToken&&e.refreshToken?(await Promise.all([this.storage.setContactToken(e.contactToken),this.storage.setRefreshToken(e.refreshToken)]),!0):(a.error("At least one of the expected response parts missing!"),!1)}{const e=await o.json();return a.error("Error linking contact to client",o.status,JSON.stringify(e)),!1}}async generateAccessToken(){const e=await this.storageWithLog.getClientId(),t=await this.storageWithLog.getRefreshToken(),i=await this.storageWithLog.getClientState();if(!e||!t||!i)return!1;const s=await this.apiEndpoint("client/contact-token"),r={refreshToken:t},n=await this.meClientServiceRequest.post(s,r,{clientId:e,clientState:i});if(200===n.status){const e=await n.json();return e.contactToken?(await this.storage.setContactToken(e.contactToken),!0):(a.error("ContactToken is not part of response body!"),!1)}{const e=await n.json();return a.log("Error refreshing the contact token",n.status,JSON.stringify(e)),!1}}async registerPushToken(e){const t=await this.storageWithLog.getClientId(),i=await this.storageWithLog.getClientState(),s=await this.storageWithLog.getContactToken({message:"Unable to register subscription as contactToken is missing!"});if(!t||!i||!s)return!1;const r=await this.apiEndpoint("client/push-token"),n={pushToken:e},o=await this.meClientServiceRequest.put(r,n,{clientId:t,clientState:i,contactToken:s});if(204===o.status)return await this.saveClientState(o),!0;{const e=await o.json();return a.error("Error registering the subscription",o.status,JSON.stringify(e)),!1}}async removePushToken(){a.info("Remove push token");const e=await this.storageWithLog.getClientId(),t=await this.storageWithLog.getClientState({level:"info"}),i=await this.storageWithLog.getContactToken({level:"info"});if(!e||!t||!i)return!1;const s=await this.apiEndpoint("client/push-token"),r=await this.meClientServiceRequest.delete(s,{},{clientId:e,clientState:t,contactToken:i});if(204===r.status)return await this.saveClientState(r),!0;{const e=await r.json();return a.error("Error removing a subscription",r.status,JSON.stringify(e)),!0}}async apiEndpoint(e){const t=await this.storage.getAppCode();return`${this.baseUrl}/${t}/${e}`}async saveClientState(e){const t=e.headers.get("x-client-state");t?await this.storage.setClientState(t):a.error("Error: X-Client-State not found in response header!")}async getClientDetails(){const e=await this.storage.getPlatform();if(e){return{platform:e,applicationVersion:await this.storage.getApplicationVersion(),deviceModel:await this.storage.getDeviceModel(),osVersion:await this.storage.getOsVersion(),sdkVersion:await this.storage.getSdkVersion(),language:await this.storage.getLanguage(),timezone:await this.storage.getTimezone()}}throw new Error("platform not found in storage!")}toContactRequestBodyData(e){return e?"openIdToken"in e?{body:{contactFieldId:e.fieldId,openIdToken:e.openIdToken},anonymous:!1}:{body:{contactFieldId:e.fieldId,contactFieldValue:e.fieldValue,contactFieldEncrypted:e.encrypted},anonymous:!1}:{body:{},anonymous:!0}}static create(e,t,i){return new o(e,t,i)}}t.MEClientService=o},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MEV3ApiRequest=void 0;const s={"Content-Type":"application/json"};class r{constructor(){this.requestOrder=0}post(e,t,i){const s=this.createPostRequestInit(t,i);return fetch(e,s)}put(e,t,i){const s=this.createPutRequestInit(t,i);return fetch(e,s)}delete(e,t,i){const s=this.createDeleteRequestInit(t,i);return fetch(e,s)}createPostRequestInit(e,t){return this.createRequestInit("POST",e,t)}createPutRequestInit(e,t){return this.createRequestInit("PUT",e,t)}createDeleteRequestInit(e,t){return this.createRequestInit("DELETE",e,t)}createRequestInit(e,t,i){return{method:e,headers:this.buildHeaders(i),mode:"cors",cache:"default",body:JSON.stringify(t)}}buildHeaders(e){const t=new Headers;return Object.keys(s).forEach((e=>{t.append(e,s[e])})),t.append("x-client-id",e.clientId),e.clientState&&t.append("x-client-state",e.clientState),e.contactToken&&t.append("x-contact-token",e.contactToken),t.append("x-request-order",""+this.requestOrder),this.requestOrder+=1,t}static create(){return new r}}t.MEV3ApiRequest=r},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.MEWebPushDb=void 0;const a=n(i(1));class o{constructor(e){this.indexDb=e}getDefaultNotificationTitle(e){return this.indexDb.getDBValueOrDefault(a.dbKeyDefaultNotificationTitle,e)}getDefaultNotificationIcon(e){return this.indexDb.getDBValueOrDefault(a.dbKeyDefaultNotificationIcon,e)}async getClientIdForAppCode(e){if(void 0!==e){return(await this.getBrowserIdsFromDb())[e.toUpperCase()]}}getClientIds(){return this.getBrowserIdsFromDb()}async getBrowserIdsFromDb(){let e=await this.indexDb.getDBValueOrDefault(a.dbKeyBrowserIds),t={};if(void 0!==e)try{t=JSON.parse(e)}catch(e){}return t=await this.addLegacyBrowserId(t),t}async addLegacyBrowserId(e){const t=await this.indexDb.getDBValueOrDefault(a.dbKeyBrowserId);if(void 0!==t){e[t.split("_")[0].toUpperCase()]=t,await this.indexDb.setDBValue(a.dbKeyBrowserIds,JSON.stringify(e)),await this.indexDb.setDBValue(a.dbKeyBrowserId,void 0)}return e}async getInitParams(){const e=await this.indexDb.getDBValueOrDefault(a.dbKeyInitParams);return e?JSON.parse(e):void 0}getMeClientServiceApiBaseUrl(){return this.indexDb.getDBValue(a.dbKeyMeClientServiceApiBaseUrl)}getMeDeviceEventServiceApiBaseUrl(){return this.indexDb.getDBValue(a.dbKeyMeDeviceEventServiceApiBaseUrl)}async getClientId(){const e=await this.getAppCode();return this.getClientIdForAppCode(e)}getClientState(){return this.indexDb.getDBValueOrDefault(a.dbKeyXClientState)}getRefreshToken(){return this.indexDb.getDBValueOrDefault(a.dbKeyRefreshToken)}getContactToken(){return this.indexDb.getDBValueOrDefault(a.dbKeyContactToken)}async getAppCode(){return this.appCode||(this.appCode=await this.indexDb.getDBValueOrDefault(a.dbKeyApplicationCode)),this.appCode}async getWebsitePushId(){return this.indexDb.getDBValueOrDefault(a.dbKeyWebsitePushId)}async getLastPermissionStatus(){return this.indexDb.getDBValueOrDefault(a.dbKeyLastPermissionStatus).then((e=>e))}async getApplicationServerPublicKey(){return this.indexDb.getDBValueOrDefault(a.dbKeyApplicationServerPublicKey)}async getServiceWorkerUrl(){return this.indexDb.getDBValueOrDefault(a.dbKeyServiceWorkerUrl)}async getServiceWorkerScope(){return this.indexDb.getDBValueOrDefault(a.dbKeyServiceWorkerScope)}async getSdkVersion(){return this.indexDb.getDBValueOrDefault(a.dbKeySdkVersion)}async getServiceWorkerVersion(){return this.indexDb.getDBValueOrDefault(a.dbKeyServiceWorkerVersion)}async getPushToken(){return this.indexDb.getDBValueOrDefault(a.dbKeyPushToken)}async getContactFieldId(){const e=await this.indexDb.getDBValueOrDefault(a.dbKeyContactFieldId);return e?Number(e):void 0}async getContactFieldValue(){return this.indexDb.getDBValueOrDefault(a.dbKeyContactFieldValue)}async getPushPackageServiceUrl(){return this.indexDb.getDBValueOrDefault(a.dbKeyPushPackageServiceUrl)}async getPlatform(){return this.indexDb.getDBValueOrDefault(a.dbKeyPlatform)}async getApplicationVersion(){return this.indexDb.getDBValueOrDefault(a.dbKeyApplicationVersion)}async getDeviceModel(){return this.indexDb.getDBValueOrDefault(a.dbKeyDeviceModel)}async getOsVersion(){return this.indexDb.getDBValueOrDefault(a.dbKeyOsVersion)}async getLanguage(){return this.indexDb.getDBValueOrDefault(a.dbKeyLanguage)}async getTimezone(){return this.indexDb.getDBValueOrDefault(a.dbKeyTimezone)}async getLoggingEnabled(){const e=await this.indexDb.getDBValueOrDefault(a.dbKeyLoggingEnabled);return"true"===(null==e?void 0:e.toLowerCase())}async setTimezone(e){await this.indexDb.setDBValue(a.dbKeyTimezone,e)}async setLanguage(e){await this.indexDb.setDBValue(a.dbKeyLanguage,e)}async setOsVersion(e){await this.indexDb.setDBValue(a.dbKeyOsVersion,e)}async setDeviceModel(e){await this.indexDb.setDBValue(a.dbKeyDeviceModel,e)}async setApplicationVersion(e){await this.indexDb.setDBValue(a.dbKeyApplicationVersion,e)}async setPlatform(e){await this.indexDb.setDBValue(a.dbKeyPlatform,e)}async setPushPackageServiceUrl(e){await this.indexDb.setDBValue(a.dbKeyPushPackageServiceUrl,e)}async setContactFieldValue(e){await this.indexDb.setDBValue(a.dbKeyContactFieldValue,e)}async setContactFieldId(e){await this.indexDb.setDBValue(a.dbKeyContactFieldId,"number"==typeof e?e.toString():void 0)}async setMeClientServiceApiBaseUrl(e){await this.indexDb.setDBValue(a.dbKeyMeClientServiceApiBaseUrl,e)}async setMeDeviceEventServiceApiBaseUrl(e){await this.indexDb.setDBValue(a.dbKeyMeDeviceEventServiceApiBaseUrl,e)}async setPushToken(e){await this.indexDb.setDBValue(a.dbKeyPushToken,e)}async setServiceWorkerVersion(e){await this.indexDb.setDBValue(a.dbKeyServiceWorkerVersion,e)}async setSdkVersion(e){await this.indexDb.setDBValue(a.dbKeySdkVersion,e)}async setLastPermissionStatus(e){await this.indexDb.setDBValue(a.dbKeyLastPermissionStatus,e)}async setAppCode(e){await this.indexDb.setDBValue(a.dbKeyApplicationCode,e),this.appCode=e}async setClientState(e){await this.indexDb.setDBValue(a.dbKeyXClientState,e)}async setContactToken(e){await this.indexDb.setDBValue(a.dbKeyContactToken,e)}async setRefreshToken(e){await this.indexDb.setDBValue(a.dbKeyRefreshToken,e)}async setClientId(e){await this.indexDb.setDBValue(a.dbKeyBrowserId,e)}async setClientIdForAppCode(e,t){const i=await this.getBrowserIdsFromDb();void 0!==e?i[t.toUpperCase()]=e:delete i[t.toUpperCase()],await this.indexDb.setDBValue(a.dbKeyBrowserIds,JSON.stringify(i))}async setClientIds(e){await this.indexDb.setDBValue(a.dbKeyBrowserIds,JSON.stringify(e))}async setDefaultNotificationIcon(e){await this.indexDb.setDBValue(a.dbKeyDefaultNotificationIcon,e)}async setDefaultNotificationTitle(e){await this.indexDb.setDBValue(a.dbKeyDefaultNotificationTitle,e)}async setServiceWorkerUrl(e){await this.indexDb.setDBValue(a.dbKeyServiceWorkerUrl,e)}async setServiceWorkerScope(e){await this.indexDb.setDBValue(a.dbKeyServiceWorkerScope,e)}async setApplicationServerPublicKey(e){await this.indexDb.setDBValue(a.dbKeyApplicationServerPublicKey,e)}async setInitParams(e){await this.indexDb.setDBValue(a.dbKeyInitParams,JSON.stringify(e))}async setWebsitePushId(e){await this.indexDb.setDBValue(a.dbKeyWebsitePushId,e)}async setLoggingEnabled(e){await this.indexDb.setDBValue(a.dbKeyLoggingEnabled,""+e)}async setLastUsedAt(){const e=(new Date).toISOString();await this.indexDb.setDBValue(a.dbKeyLastUsedAt,e)}async deleteLastUsedAt(){await this.indexDb.deleteDBKey(a.dbKeyLastUsedAt)}async clearAll(){await Promise.all([this.setAppCode(void 0),this.setClientState(void 0),this.setContactToken(void 0),this.setRefreshToken(void 0),this.setDefaultNotificationIcon(void 0),this.setDefaultNotificationTitle(void 0),this.setServiceWorkerUrl(void 0),this.setServiceWorkerScope(void 0),this.setApplicationServerPublicKey(void 0),this.setSdkVersion(void 0),this.setServiceWorkerVersion(void 0),this.setInitParams(void 0),this.setWebsitePushId(void 0),this.setPushPackageServiceUrl(void 0),this.setLastPermissionStatus(void 0),this.setPushToken(void 0),this.setContactFieldId(void 0),this.setContactFieldValue(void 0),this.setPlatform(void 0),this.setApplicationVersion(void 0),this.setDeviceModel(void 0),this.setTimezone(void 0),this.setLanguage(void 0),this.setOsVersion(void 0),this.setMeClientServiceApiBaseUrl(void 0),this.setMeDeviceEventServiceApiBaseUrl(void 0),this.deleteLastUsedAt()])}static create(e){return new o(e)}}t.MEWebPushDb=o},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IndexDb=void 0;const s=i(1),r="not_found";class n{constructor(){this.name="keyValue"}setDBValue(e,t){return this.openIndexDB().then((i=>new Promise(((s,r)=>{const n=i.transaction([this.name],"readwrite").objectStore(this.name).put({key:e,value:t});n.onsuccess=()=>(this.indexedDBInstance=void 0,i.close(),s(e)),n.onerror=e=>(this.indexedDBInstance=void 0,i.close(),r(e))}))))}deleteDBKey(e){return this.openIndexDB().then((t=>new Promise(((i,s)=>{const r=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);r.onsuccess=()=>(this.indexedDBInstance=void 0,t.close(),i(!0)),r.onerror=e=>(this.indexedDBInstance=void 0,t.close(),s(e))}))))}async getDBValue(e){let t;try{t=await this.openIndexDB()}catch(e){throw e}return new Promise(((i,s)=>{const n=t.transaction(this.name).objectStore(this.name).get(e);n.onsuccess=()=>{const{result:e}=n;return e?(this.indexedDBInstance=void 0,t.close(),i(e.value)):(this.indexedDBInstance=void 0,t.close(),s(new Error(r)))},n.onerror=e=>(this.indexedDBInstance=void 0,t.close(),s(e))}))}async getDBValueOrDefault(e,t){try{return await this.getDBValue(e)}catch(e){if(e.message===r)return t;throw e}}openIndexDB(){return new Promise(((e,t)=>{if(this.indexedDBInstance)return e(this.indexedDBInstance);const i=indexedDB.open(s.indexedDbName,s.indexedDbVersion);i.onsuccess=t=>(this.indexedDBInstance=t.target.result,e(this.indexedDBInstance)),i.onerror=e=>t(e),i.onupgradeneeded=e=>{e.target.result.createObjectStore("keyValue",{keyPath:"key"})}}))}static create(){return new n}}t.IndexDb=n},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.removeRegistrationStatus=t.setRegistrationStatus=t.getRegistrationStatus=void 0;const a=n(i(1));t.getRegistrationStatus=function(){const e=localStorage.getItem(a.KEY_DEVICE_REGISTRATION_STATUS);return e||void 0},t.setRegistrationStatus=function(e){localStorage.setItem(a.KEY_DEVICE_REGISTRATION_STATUS,e)},t.removeRegistrationStatus=function(){localStorage.removeItem(a.KEY_DEVICE_REGISTRATION_STATUS)}},function(e,t,i){"use strict";i.r(t),i.d(t,"v1",(function(){return b})),i.d(t,"v3",(function(){return w})),i.d(t,"v4",(function(){return _})),i.d(t,"v5",(function(){return N})),i.d(t,"NIL",(function(){return C})),i.d(t,"version",(function(){return k})),i.d(t,"validate",(function(){return o})),i.d(t,"stringify",(function(){return h})),i.d(t,"parse",(function(){return p}));var s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),r=new Uint8Array(16);function n(){if(!s)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(r)}var a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var o=function(e){return"string"==typeof e&&a.test(e)},c=[],u=0;u<256;++u)c.push((u+256).toString(16).substr(1));var l,d,h=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]).toLowerCase();if(!o(i))throw TypeError("Stringified UUID is invalid");return i},g=0,f=0;var b=function(e,t,i){var s=t&&i||0,r=t||new Array(16),a=(e=e||{}).node||l,o=void 0!==e.clockseq?e.clockseq:d;if(null==a||null==o){var c=e.random||(e.rng||n)();null==a&&(a=l=[1|c[0],c[1],c[2],c[3],c[4],c[5]]),null==o&&(o=d=16383&(c[6]<<8|c[7]))}var u=void 0!==e.msecs?e.msecs:Date.now(),b=void 0!==e.nsecs?e.nsecs:f+1,p=u-g+(b-f)/1e4;if(p<0&&void 0===e.clockseq&&(o=o+1&16383),(p<0||u>g)&&void 0===e.nsecs&&(b=0),b>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");g=u,f=b,d=o;var v=(1e4*(268435455&(u+=122192928e5))+b)%4294967296;r[s++]=v>>>24&255,r[s++]=v>>>16&255,r[s++]=v>>>8&255,r[s++]=255&v;var S=u/4294967296*1e4&268435455;r[s++]=S>>>8&255,r[s++]=255&S,r[s++]=S>>>24&15|16,r[s++]=S>>>16&255,r[s++]=o>>>8|128,r[s++]=255&o;for(var y=0;y<6;++y)r[s+y]=a[y];return t||h(r)};var p=function(e){if(!o(e))throw TypeError("Invalid UUID");var t,i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i};var v=function(e,t,i){function s(e,s,r,n){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],i=0;i>>9<<4)+1}function y(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function D(e,t,i,s,r,n){return y((a=y(y(t,e),y(s,n)))<<(o=r)|a>>>32-o,i);var a,o}function E(e,t,i,s,r,n,a){return D(t&i|~t&s,e,t,r,n,a)}function P(e,t,i,s,r,n,a){return D(t&s|i&~s,e,t,r,n,a)}function m(e,t,i,s,r,n,a){return D(t^i^s,e,t,r,n,a)}function I(e,t,i,s,r,n,a){return D(i^(t|~s),e,t,r,n,a)}var w=v("v3",48,(function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var i=0;i>5]>>>r%32&255,a=parseInt(s.charAt(n>>>4&15)+s.charAt(15&n),16);t.push(a)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[s/8])<>>32-t}var N=v("v5",80,(function(e){var t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var s=unescape(encodeURIComponent(e));e=[];for(var r=0;r>>0;y=S,S=v,v=O(p,30)>>>0,p=b,b=P}i[0]=i[0]+b>>>0,i[1]=i[1]+p>>>0,i[2]=i[2]+v>>>0,i[3]=i[3]+S>>>0,i[4]=i[4]+y>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]})),C="00000000-0000-0000-0000-000000000000";var k=function(e){if(!o(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)}},,,function(e,t,i){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=s(i(15)),n=i(2);function a(){const e=n.getGlobal();let t,{WebEmarsysSdk:i}=e;i&&(t=i),i=r.default.create(window,navigator),Array.isArray(t)&&t.forEach((e=>i.push(e))),e.WebEmarsysSdk=i}"complete"===document.readyState?a():window.addEventListener("load",a)},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=n(i(1)),c=a(i(0)),u=i(6),l=i(5),d=i(16),h=i(17),g=i(8),f=i(9),b=i(7),p=i(19),v=i(11),S=a(i(22)),y=n(i(10)),D=n(i(4)),E=n(i(2)),P=i(3),{Logger:m,enableLogger:I}=c.default;class w{constructor(e,t){this.ready=!1,this.navigator=t,this.window=e,this.navigatorInfo=h.NavigatorInfo.create(t),this.pushNotificationSupportInfo=d.PushNotificationSupportInfo.create(this.navigatorInfo,e),this.meWebPushDb=g.MEWebPushDb.create(f.IndexDb.create()),this.storageWithLog=new P.StorageWithLog(this.meWebPushDb),this.eventEmitter=new S.default,this.permissionPromises={},this.pushNotificationSupportInfo.canUsePromises()&&(this.permissionPromises={[o.EVENT_ON_PERMISSION_DENIED]:new Promise((e=>this.eventEmitter.once(o.EVENT_ON_PERMISSION_DENIED,e))),[o.EVENT_ON_PERMISSION_PROMPT]:new Promise((e=>this.eventEmitter.once(o.EVENT_ON_PERMISSION_PROMPT,e))),[o.EVENT_ON_PERMISSION_GRANTED]:new Promise((e=>this.eventEmitter.once(o.EVENT_ON_PERMISSION_GRANTED,e)))})}push(e){if("function"!=typeof e){if(!Array.isArray(e))throw new Error("Invalid command!");switch(e[0]){case"init":this.init(e[1]).then((()=>m.debug("Initialized"))).catch((e=>m.error(e,"Init failed!")));break;case o.EVENT_ON_READY:this.registerOrHandleOnReadyCallback(e[1]);break;case o.EVENT_ON_SUBSCRIBE:case o.EVENT_ON_UNSUBSCRIBE:case o.EVENT_ON_SW_INIT_ERROR:this.registerEventCallback(e[0],e[1]);break;case o.EVENT_ON_PERMISSION_DENIED:case o.EVENT_ON_PERMISSION_PROMPT:case o.EVENT_ON_PERMISSION_GRANTED:this.registerChangePermissionCallback(e[0],e[1]);break;default:m.warn(`WARN: Command "${JSON.stringify(e)}" not yet implemented!`)}}else this.registerOrHandleOnReadyCallback(e)}async customEvent(e,t){try{const i={dnd:!0,events:[{type:"custom",name:e,timestamp:(new Date).toISOString(),attributes:{...t,"me:origin":"webpush"}}],clicks:[],viewedMessages:[]};let s=await this.meDeviceEventService.postEvents(i);return s.success||401!==s.statusCode||(m.log("Contact token seems outdated, try to refresh and send again..."),s=await this.retrySendAfterContactTokenRefresh(i)),m.debug("Sent custom event",e,JSON.stringify(t),JSON.stringify(s)),s.success}catch(e){return m.error("Error sending custom event",e.message,e),!1}}async subscribe(){const e=this.getPushService();let t;e.isPermissionDefault()?(t=await e.askPermission().catch((e=>(m.error("Safari ask permission error",e),o.PERMISSION_DENIED))),this.eventEmitter.emit(o.EVENT_ON_PERMISSION_PROMPT)):t=e.getPermission();const i=await this.isFullyRegistered(!1);if(t===o.PERMISSION_GRANTED){const t=await this.getLoggedInContact();return m.debug("User granted permission for push notifications"),this.eventEmitter.emit(o.EVENT_ON_PERMISSION_GRANTED),i?m.debug("Triggering subscribe for token update"):(m.debug("Triggering push service unsubscribe"),await e.unsubscribe(),m.debug("Triggering push service subscribe")),await e.subscribe(t),await this.meWebPushDb.setLastUsedAt(),void this.eventEmitter.emit(o.EVENT_ON_SUBSCRIBE)}if(t===o.PERMISSION_DENIED)return m.log("User has declined push permission"),i&&await e.unsubscribe(),void this.eventEmitter.emit(o.EVENT_ON_PERMISSION_DENIED)}async unsubscribe(){try{m.debug("Unsubscribing..."),await this.getPushService().unsubscribe(),y.setRegistrationStatus(o.DEVICE_REGISTRATION_STATUS_UNREGISTERED),this.eventEmitter.emit(o.EVENT_ON_UNSUBSCRIBE)}catch(e){m.error(e,"Error occurred during unsubscribe")}}async getParams(){const e=await this.meWebPushDb.getAppCode(),t=await this.meWebPushDb.getClientIdForAppCode(e),i=await this.meWebPushDb.getInitParams();return{applicationCode:e,clientId:t,pushToken:await this.meWebPushDb.getPushToken(),serviceWorkerScope:await this.meWebPushDb.getServiceWorkerScope(),serviceWorkerVersion:await this.meWebPushDb.getServiceWorkerVersion(),sdkVersion:await this.meWebPushDb.getSdkVersion(),meClientServiceApiBaseUrl:await this.meWebPushDb.getMeClientServiceApiBaseUrl(),meDeviceEventServiceApiBaseUrl:await this.meWebPushDb.getMeDeviceEventServiceApiBaseUrl(),clientState:await this.meWebPushDb.getClientState(),contactToken:await this.meWebPushDb.getContactToken(),refreshToken:await this.meWebPushDb.getRefreshToken(),...i}}async getLoggedInContact(){const e=await this.storageWithLog.getClientState({level:"info"});if(!e)return;const t=D.decode(e);if(!t)return void m.error("Decoding failed",JSON.stringify(e));const i=t.contactField;return void 0!==i?null===i||0===Object.keys(i).length?{}:void 0!==i.contactFieldId&&i.contactFieldValue?{fieldId:i.contactFieldId,fieldValue:i.contactFieldValue,encrypted:"boolean"==typeof i.contactFieldEncryped&&i.contactFieldEncryped}:void m.error("contactField information incomplete",JSON.stringify(i)):void 0}async isLoggedIn(){const e=await this.getLoggedInContact();return!(E.isEmptyObject(e)||void 0===e)}setOpenIdAuthenticatedContact(e){return this.assertOpenIdContactInfo(e),this.meClientService.linkClientToContact(e)}login(e){this.assertContactInfo(e);const t=void 0!==e?{...e,encrypted:!1}:e;return this.meClientService.linkClientToContact(t)}async logout(){return this.meClientService.linkClientToContact()}async removeAllDeviceData(){await this.cleanupClientOnBackend(this.meClientService),await this.meWebPushDb.clearAll()}async isSubscribed(){return this.isFullyRegistered()}async registerClient(e){this.assertContactInfo(e);const t=e?{...e,encrypted:!1}:void 0;return await this.meClientService.storeClientDetails()&&await this.meClientService.linkClientToContact(t)}assertContactInfo(e){if(e&&(void 0===e.fieldId||!e.fieldValue))throw new Error("Incomplete contact info: "+JSON.stringify(e))}assertOpenIdContactInfo(e){if(void 0===e.fieldId||!e.openIdToken)throw new Error("Incomplete contact info: "+JSON.stringify(e))}async init(e){if(!this.pushNotificationSupportInfo.pushNotificationsSupported())return Promise.reject(new Error("Web push not supported"));this.enableLogging(e.enableLogging),await this.setupMeClientService(e.clientServiceApiBaseUrl),await this.setupMeDeviceEventService(e.deviceEventServiceApiBaseUrl);const t=await this.checkApplicationCode(this.meClientService,e.applicationCode);await this.checkClientId(t),await this.persistPlatformInfo(e),await this.persistConfig(e),await this.initPushNotifications(e),this.eventEmitter.emit(o.EVENT_ON_READY),this.ready=!0}enableLogging(e){I(!0===e)}async setupMeClientService(e){const t=e||o.defaultClientServiceApiBaseUrl;this.meClientService=u.MEClientService.create(t,b.MEV3ApiRequest.create(),this.meWebPushDb),await this.meWebPushDb.setMeClientServiceApiBaseUrl(t)}async setupMeDeviceEventService(e){const t=e||o.defaultDeviceEventServiceApiBaseUrl;this.meDeviceEventService=l.MEDeviceEventService.create(t,b.MEV3ApiRequest.create(),this.meWebPushDb),await this.meWebPushDb.setMeDeviceEventServiceApiBaseUrl(t)}async checkApplicationCode(e,t){const i=await this.meWebPushDb.getAppCode();if(!t)return Promise.reject(new Error("Can't find application code!"));return(!i||i&&i!==t)&&(await this.cleanupClientOnBackend(e),await this.meWebPushDb.clearAll(),await this.meWebPushDb.setAppCode(t)),t}async checkClientId(e){const t=await this.meWebPushDb.getClientIdForAppCode(e);if(t)m.log("ClientId exists:",t);else{m.log("No ClientId stored. Creating one...");const t=e+"_"+v.v4();await this.meWebPushDb.setClientIdForAppCode(t,e)}}async persistPlatformInfo(e){const t=this.navigatorInfo.getAll();await Promise.all([this.meWebPushDb.setPlatform(t.browser),this.meWebPushDb.setApplicationVersion(e.applicationVersion||o.defaultApplicationVersion),this.meWebPushDb.setDeviceModel(t.userAgent),this.meWebPushDb.setOsVersion(t.browserVersion),this.meWebPushDb.setLanguage(t.language),this.meWebPushDb.setTimezone(t.timezone),this.meWebPushDb.setSdkVersion("3.6.0")])}async persistConfig(e){const t=e.serviceWorker?e.serviceWorker.url:void 0,i=E.determineServiceWorkerScope(e.serviceWorker),s=e.serviceWorker?e.serviceWorker.applicationServerPublicKey:void 0;await Promise.all([this.meWebPushDb.setServiceWorkerUrl(t),this.meWebPushDb.setServiceWorkerScope(i),this.meWebPushDb.setApplicationServerPublicKey(s),this.meWebPushDb.setDefaultNotificationIcon(e.defaultNotificationIcon),this.meWebPushDb.setDefaultNotificationTitle(e.defaultNotificationTitle),this.meWebPushDb.setWebsitePushId(e.safariWebsitePushID),this.meWebPushDb.setPushPackageServiceUrl(e.safariPushPackageServiceUrl),this.meWebPushDb.setLoggingEnabled(Boolean(e.enableLogging).valueOf()),this.meWebPushDb.setMeClientServiceApiBaseUrl(e.clientServiceApiBaseUrl||o.defaultClientServiceApiBaseUrl),this.meWebPushDb.setMeDeviceEventServiceApiBaseUrl(e.deviceEventServiceApiBaseUrl||o.defaultDeviceEventServiceApiBaseUrl),this.meWebPushDb.setLastUsedAt()])}async initPushNotifications(e){const t={...e,enableLogging:Boolean(e.enableLogging).valueOf()};await this.meWebPushDb.setInitParams(t),await this.setupPushService();try{await this.initialPushServiceProcessing(t)}catch(e){m.error(e,"Internal error")}}async setupPushService(){if(!this.meClientService)throw new Error("Me client service connection is not set up!");if(this.pushNotificationSupportInfo.canUseSafariPush()){const e=await this.buildApnsApiRegistrationConfig();this.pushService=new p.SafariPushService(this.meWebPushDb,e,this.meClientService)}else if(this.pushNotificationSupportInfo.canUseServiceWorkers()){const e=new p.VapidPushService(this.meWebPushDb,this.meClientService);return await e.updateServiceWorker(),void(this.pushService=e)}}async initialPushServiceProcessing(e){const t=this.getPushService(),i=t.getPermission();i===o.PERMISSION_GRANTED&&await this.meWebPushDb.setLastPermissionStatus(i);await t.isResubscribeNeeded()&&(m.log("Re-subscribe is needed."),await this.unsubscribe());const s=await this.isFullyRegistered(!1);switch(i){case o.PERMISSION_PROMPT:s&&(m.debug("Unsubscribing in PROMPT state"),this.eventEmitter.emit(o.EVENT_ON_PERMISSION_PROMPT),await this.unsubscribe());break;case o.PERMISSION_DENIED:s&&await this.unsubscribe(),this.eventEmitter.emit(o.EVENT_ON_PERMISSION_DENIED);break;case o.PERMISSION_GRANTED:await this.subscribe(),this.eventEmitter.emit(o.EVENT_ON_PERMISSION_GRANTED)}}async cleanupClientOnBackend(e){m.debug("Cleanup of client information on backend side");const{exists:t,pushTokenExists:i,identified:s}=await E.checkDevice(this.meWebPushDb);if(t){if(i){const t=await e.removePushToken();m.log("Removed registered push token:",t)}if(s){const t=await e.linkClientToContact();m.log("Assigned anonymous contact:",t)}}else m.debug("The browser is not registered at all.")}getPushService(){if(this.pushService)return this.pushService;throw new Error("Push service is not set up!")}async buildApnsApiRegistrationConfig(){const e=await this.meWebPushDb.getWebsitePushId(),t=await this.meWebPushDb.getAppCode(),i=await this.meWebPushDb.getClientIdForAppCode(t);if(e&&t&&i){return{clientId:i,applicationCode:t,safariWebsitePushID:e,safariPushPackageServiceUrl:await this.meWebPushDb.getPushPackageServiceUrl()||o.defaultSafariPushPackageServiceUrl}}throw new Error("safariWebsitePushID must be specified for Safari support!")}onReadyHandler(e){this.ready?e(void 0):this.eventEmitter.on(o.EVENT_ON_READY,(t=>e(void 0,t)))}registerOrHandleOnReadyCallback(e){this.onReadyHandler(e)}registerEventCallback(e,t){this.eventEmitter.on(e,(e=>t(void 0,e)))}registerChangePermissionCallback(e,t){const i=this.permissionPromises[e];if(!i)return;const s=this.registerEventCallback.bind(this);i.then((()=>(s(e,t),t(void 0)))).catch((e=>m.error(e,"Error while handling permission change callback.")))}async isFullyRegistered(e=!0){const t=y.getRegistrationStatus();return m.debug("Local status is",t),void 0!==t&&e?Promise.resolve(t===o.DEVICE_REGISTRATION_STATUS_REGISTERED):this.updateRegistrationStatus()}async updateRegistrationStatus(){m.debug("Checking device...");const e=await this.pushService.isRegistered();m.debug("Device exists & has token",e);const t=e?o.DEVICE_REGISTRATION_STATUS_REGISTERED:o.DEVICE_REGISTRATION_STATUS_UNREGISTERED;return y.setRegistrationStatus(t),t===o.DEVICE_REGISTRATION_STATUS_REGISTERED}async retrySendAfterContactTokenRefresh(e){return await this.meClientService.generateAccessToken()?this.meDeviceEventService.postEvents(e):(m.error("Refresh of access token failed!"),{success:!1})}static create(e,t){return new w(e,t)}}t.default=w},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushNotificationSupportInfo=void 0;class s{constructor(e,t){this.navigatorInfo=e,this.window=t}pushNotificationsSupported(){return this.canUseSafariPush()||this.canUseServiceWorkers()}canUseServiceWorkers(){return this.navigatorInfo.hasServiceWorker()&&"PushManager"in this.window}canUseSafariPush(){return"safari"in this.window&&"pushNotification"in this.window.safari}canUsePromises(){return"Promise"in this.window}static create(e,t){return new s(e,t)}}t.PushNotificationSupportInfo=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NavigatorInfo=void 0;const s=i(18),r=[["edge",/Edge\/([0-9\._]+)/],["edge",/EdgiOS\/([0-9\._]+)/],["edge",/EdgA?\/([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["opera",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["safari",/Version\/([0-9\._]+).*Safari/]],n={samsung:"chrome",opera:"chrome"};class a{constructor(e){this.navigator=e}getAll(){return{userAgent:this.getUserAgent(),browser:this.getBrowserName(),browserVersion:this.getVersion(),timezone:this.getTimezone(),language:this.getLanguage()}}hasServiceWorker(){return"serviceWorker"in this.navigator}getUserAgent(){return this.navigator.userAgent}getBrowserName(){let e="chrome";const t=this.navigator.userAgent;for(const i of r){const[s,r]=i;if(r.exec(t)){e=s;break}}return this.getMappedBrowserName(e)}getMappedBrowserName(e){const t=n[e];return t||e}getVersion(){return s.BrowserVersionParser.parseBrowserVersion(this.navigator)}getTimezone(){const e=(new Date).getTimezoneOffset();return(e<0?"+":"-")+this.pad(Math.abs(e/60),2)+this.pad(Math.abs(e%60),2)}getLanguage(){return this.navigator.language}pad(e,t){let i=""+e;for(;i.length=0?i+e.length+1:-1}static trimVersion(e){const t=/^(([0-9]|\.)*)[ );]/;return t.test(e)?t.exec(e)[1]:e}}t.BrowserVersionParser=s},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=i(20);Object.defineProperty(t,"VapidPushService",{enumerable:!0,get:function(){return s.VapidPushService}});var r=i(21);Object.defineProperty(t,"SafariPushService",{enumerable:!0,get:function(){return r.SafariPushService}})},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VapidPushService=void 0;const o=i(11),c=n(i(1)),u=a(i(0)),l=n(i(10)),d=n(i(2));t.VapidPushService=class{constructor(e,t){this.webPushDb=e,this.meClientService=t}getPermission(){return Notification.permission}isPermissionGranted(){return this.getPermission()===c.PERMISSION_GRANTED}isPermissionDefault(){return this.getPermission()===c.PERMISSION_PROMPT}async askPermission(){return Notification.requestPermission()}async getPushToken(){return this.webPushDb.getPushToken()}async subscribe(e){if(!this.isPermissionGranted())return void u.default.Logger.error("Permission must be granted before subscription!");const t=await this.getPushSubscription();if(null!==t){const i=JSON.stringify(t);u.default.Logger.debug("Got valid subscription:",i);await this.getPushToken()!==i&&(u.default.Logger.debug("Registering device, linking and registering push token"),await this.meClientService.storeClientDetails()&&await this.meClientService.linkClientToContact(d.toContactInfo(e))&&await this.meClientService.registerPushToken(i)&&(await this.webPushDb.setPushToken(i),l.setRegistrationStatus(c.DEVICE_REGISTRATION_STATUS_REGISTERED)))}else u.default.Logger.warn("Issue fetching the actual push token (subscription).")}async unsubscribe(){u.default.Logger.log("VAPID: unsubscribe");const e=await this.getServiceWorkerRegistration();u.default.Logger.log("VAPID: registration",e);const t=await e.pushManager.getSubscription();u.default.Logger.log("VAPID: subscription",t),await this.meClientService.removePushToken(),await this.webPushDb.setPushToken(void 0),t&&(await t.unsubscribe(),l.setRegistrationStatus(c.DEVICE_REGISTRATION_STATUS_UNREGISTERED))}async isRegistered(){return d.isDeviceRegistered(this.webPushDb)}async isResubscribeNeeded(){const e=await this.webPushDb.getLastPermissionStatus(),t=this.getPermission();return e!==t&&await this.webPushDb.setLastPermissionStatus(t),e!==t}updateServiceWorker(){return this.registerServiceWorker()}async getServiceWorkerRegistration(){if(!this.registration){if(u.default.Logger.debug("No service worker found. Registering service worker..."),this.registration=await this.registerServiceWorker(),!this.registration)throw new Error("Internal Error: Can't register service worker!");u.default.Logger.log("Service worker is registered"),await this.registration.update()}return this.registration}async registerServiceWorker(){const e=await this.webPushDb.getServiceWorkerUrl(),t=await this.webPushDb.getServiceWorkerScope(),i=await this.webPushDb.getSdkVersion()!==await this.webPushDb.getServiceWorkerVersion()?"?cache_clean="+o.v4():"",s=t?{scope:t}:void 0;return navigator.serviceWorker.register(`/${e}${i}`,s)}async getPushSubscription(e=!1){const t=await this.getServiceWorkerRegistration(),i=await this.getApplicationServerKey(),s=await t.pushManager.getSubscription(),r=null!==s?s:await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:i});return r.endpoint.length>0?r:e?(u.default.Logger.warn("Retry to get subscription without empty endpoint failed. Giving up."),null):this.handleSubscriptionWithEmptyEndpoint(r)}async handleSubscriptionWithEmptyEndpoint(e){u.default.Logger.warn("Got subscription with empty endpoint",e);return await e.unsubscribe()?(u.default.Logger.debug("Retrying to get a subscription without an empty endpoint"),this.getPushSubscription(!0)):(u.default.Logger.warn("Unable to unsubscribe from subscription with empty endpoint"),null)}async getApplicationServerKey(){return this.webPushDb.getApplicationServerPublicKey()}}},function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.hasOwnProperty.call(e,i)&&s(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SafariPushService=void 0;const o=n(i(1)),c=a(i(0)),u=n(i(10)),l=n(i(2));t.SafariPushService=class{constructor(e,t,i){this.webPushDb=e,this.config=t,this.meClientService=i}getPermission(){const{permission:e}=this.getPermissionInfo();return e}isPermissionGranted(){return this.getPermission()===o.PERMISSION_GRANTED}isPermissionDefault(){return this.getPermission()===o.PERMISSION_PROMPT}async askPermission(){const e={application:this.config.applicationCode,clientId:this.config.clientId};return new Promise((t=>{safari.pushNotification.requestPermission(this.config.safariPushPackageServiceUrl,this.config.safariWebsitePushID,e,(e=>t(e.permission)))}))}async getPushToken(){return this.webPushDb.getPushToken()}async subscribe(e){if(!this.isPermissionGranted())return void c.default.Logger.error("Permission must be granted before subscribing!");const{deviceToken:t}=this.getPermissionInfo();if(t){c.default.Logger.debug("Got device token:",t);await this.getPushToken()!==t&&(c.default.Logger.debug("Registering device, linking and registering push token"),await this.meClientService.storeClientDetails()&&await this.meClientService.linkClientToContact(l.toContactInfo(e))&&await this.meClientService.registerPushToken(t)&&(await this.webPushDb.setPushToken(t),u.setRegistrationStatus(o.DEVICE_REGISTRATION_STATUS_REGISTERED)))}else await this.webPushDb.setPushToken(t),u.setRegistrationStatus(o.DEVICE_REGISTRATION_STATUS_UNREGISTERED)}async unsubscribe(){await this.meClientService.removePushToken(),await this.webPushDb.setPushToken(void 0),u.setRegistrationStatus(o.DEVICE_REGISTRATION_STATUS_UNREGISTERED)}async isRegistered(){return l.isDeviceRegistered(this.webPushDb)}async isResubscribeNeeded(){const e=await this.webPushDb.getWebsitePushId(),t=void 0!==e,i=t&&this.config.safariWebsitePushID!==e;await this.webPushDb.setWebsitePushId(this.config.safariWebsitePushID);const s=await this.webPushDb.getLastPermissionStatus(),r=this.getPermission();return s!==r?(await this.webPushDb.setLastPermissionStatus(r),!0):i||!t}getPermissionInfo(){return safari.pushNotification.permission(this.config.safariWebsitePushID)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{constructor(){this._events={}}emit(e,t){const i=this._events[e]&&this._events[e].slice();if(i&&i.length)for(let e=0;e{if(!i)return i=!0,this.removeListener(e,s),t(r)};return this.on(e,s)}removeListener(e,t){const i=this._events[e];if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1),i.length<1&&delete this._events[e]}}totalListenerCount(){let e=0;return Object.keys(this._events).forEach((t=>{e+=this._events[t].length})),e}listenerCountFor(e){const t=this._events[e];return t?t.length:0}}}]); //# sourceMappingURL=web-emarsys-sdk.js.map