web-push-notifications 3.50.5 → 3.50.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/npm.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var a in s)("object"==typeof exports?exports:e)[a]=s[a]}}(this,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var a in s)e.o(s,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:s[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Pushwoosh:()=>ge});const s="/pushwoosh-service-worker.js",a="deviceRegistrationStatus",i="registered",r="unregistered",n="denied",o="granted",c="default",h="onReady",u="onSubscribe",d="onUnsubscribe",g="onRegister",l="onPermissionPrompt",p="onPermissionDenied",m="onPermissionGranted",w="onSWInitError",b="onPushDelivery",v="onNotificationClick",y="onNotificationClose",f="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",k="onShowNotificationPermissionDialog",P="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",I="onHideSubscriptionWidget",E="PW_SiteOpened",x={autoSubscribe:!0,serviceWorkerUrl:s};function T(){return globalThis}function M(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const _=e=>"function"==typeof e,W={[g]:{name:"register"},[u]:{name:"subscribe"},[d]:{name:"unsubscribe"},[w]:{name:"initialize-service-worker-error",prop:"error"},[b]:{name:"receive-push",prop:"notification"},[v]:{name:"open-notification",prop:"notification"},[y]:{name:"hide-notification",prop:"notification"},[f]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[k]:{name:"show-notification-permission-dialog"},[P]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[I]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[l]:{name:"permission-default"},[m]:{name:"permission-granted"}},N="keyValue",A="messages",R="log",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const U=[q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];const B=[q(N,function(e){e.createObjectStore(N,{keyPath:"key"})}),q(R,function(e){const t=e.createObjectStore(R,{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(A,function(e){e.createObjectStore(A,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class L{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class V{constructor(e=new L){this.migrations={initial:B,"2018/11/26":U},this.dateModule=e}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(e=>"initial"!==e).sort((e,t)=>{const s=new L(new Date(e)),a=new L(new Date(t));return s.getTimestamp()-a.getTimestamp()}).map(e=>this.migrations[e])}}class j{constructor(e,t=new V){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(e=>{this.applyMigrationsPack(e)})}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let $;function F(e){return($||($=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=H.bind(null,a,t),e(a)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t),new j(s).applyMigrations()}})),$).then(t=>new Promise((s,a)=>e(t,s,a)))}class K{_add(e){return F((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);i.onsuccess=()=>{s(e)},i.onerror=()=>{a(i.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return F((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return F((e,t,s)=>{const a=[],i=e.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=e=>{const s=e.target.result;s?(s.value&&a.push(s.value),s.continue()):t(a)},i.onerror=()=>{s(i.error)}})}}const z=(G=N,{get:(e,t)=>F((s,a,i)=>{const r=s.transaction(G).objectStore(G).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(r.result?.value||t):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>F((e,t,s)=>{const a={},i=e.transaction(G).objectStore(G).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=e=>{const t=e.target.result;t?(a[t.key]=t.value.value,t.continue()):n=!0},i.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...a}=t;await this.set(e,{...s,...a})},set:(e,t)=>F((s,a,i)=>{const r=s.transaction([G],"readwrite").objectStore(G).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(e):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var G;const J=new class extends K{constructor(){super(...arguments),this.name=R,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const a={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(a.stack=t.stack),s&&(a.additional=s),this._add(a)}},Y=new class extends K{constructor(){super(...arguments),this.name=A,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Q={error:1,info:2,debug:3};let X=3;const Z={setLevel(e){Q[e]||(e="error"),X=Q[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),J.add(e,t,s)}};Object.keys(Q).forEach(e=>{const t=Q[e];Z[e]=(...s)=>{t<=X&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class ee{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||M(),a=this.handlers[e];return a?(a.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}class te{constructor(e,t,s,a=new L){this.data=e,this.api=t,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const a=[],i=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,a.push(t),i.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=s||await this.data.getDefaultNotificationImage(),h=a||await this.data.getDefaultNotificationTitle(),u=JSON.parse(t);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,u),link:u?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=JSON.parse(t.action_params),a=this.messageTypeFactory(t.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class se{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{a(e.error)}})}readRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target;s(a.result||t)},e.onerror=()=>{a(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target.result;a?(t.push(a.value),a.continue()):s(t)},e.onerror=()=>{a(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class ae{dbVersionChangeHandler(e,t){console.info("onversionchange",t),e.close()}dbRequestSuccessHandler(e,t){const s=t.target.result;s.onversionchange=e=>{this.dbVersionChangeHandler(s,e)},e(s)}dbRequestUpgradeNeededHandler(e){const t=e.target.result;t.onversionchange=e=>{this.dbVersionChangeHandler(t,e)};new j(t).applyMigrations()}getDB(){return new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=t=>{this.dbRequestSuccessHandler(e,t)},s.onupgradeneeded=e=>{this.dbRequestUpgradeNeededHandler(e)},s.onerror=()=>t(s.error)})}async put(e,t,s){const a=await this.getDB(),i=new se(a,e),r=await i.put(t,s);return a.close(),r}async delete(e,t){const s=await this.getDB(),a=new se(s,e),i=await a.delete(t);return s.close(),i}async get(e,t,s){const a=await this.getDB(),i=new se(a,e),r=await i.get(t,s);return a.close(),r}async getAll(e){const t=await this.getDB(),s=new se(t,e),a=await s.getAll();return t.close(),a||[]}async count(e,t){const s=await this.getDB(),a=new se(s,e),i=await a.count(t);return s.close(),i}async countByIndex(e,t,s){const a=await this.getDB(),i=new se(a,e);i.index=t;const r=await i.countByIndex(s);return a.close(),r}}class ie{constructor(e,t,s,a=new ae,i=new L){this.eventBus=e,this.data=t,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new te(this.data,this.api,this)})}}const re=e=>`params.${e}`;class ne{constructor(e=z){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime"];for(const t of e)await this.store.set(re(t),void 0)}async setApplicationCode(e){await this.store.set(re("applicationCode"),e)}async getApplicationCode(){return this.store.get(re("applicationCode"))}async setApiToken(e){return await this.store.set(re("apiToken"),e)}async getApiToken(){return this.store.get(re("apiToken"))}async setHwid(e){await this.store.set(re("hwid"),e)}async getHwid(){return this.store.get(re("hwid"))}async setDeviceType(e){await this.store.set(re("deviceType"),e)}async getDeviceType(){return this.store.get(re("deviceType"))}async setDeviceModel(e){await this.store.set(re("deviceModel"),e)}async getDeviceModel(){return this.store.get(re("deviceModel"))}async setLanguage(e){await this.store.set(re("language"),e)}async getLanguage(){return this.store.get(re("language"),"en")}async setApiEntrypoint(e){await this.store.set(re("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(re("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(re("tokens"),e)}getTokens(){return this.store.get(re("tokens"))}async setApplicationServerKey(e){await this.store.set(re("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(re("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(re("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(re("isVapidChanged"),!1)}async setWebSitePushId(e){await this.store.set(re("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(re("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(re("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(re("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(re("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(re("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(re("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(re("userId"))}async setStatusUserIdWasChanged(e){await this.store.set(re("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(re("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(re("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(re("email"))}async setStatusEmailWasChanged(e){await this.store.set(re("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(re("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(re("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(re("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(re("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(re("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(re("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(re("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(re("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(re("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(re("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(re("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(re("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(re("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(re("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(re("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(re("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(re("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(re("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(re("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(re("sdkVersion"),e)}async getSdkVersion(){return this.store.get(re("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(re("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(re("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(re("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(re("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(re("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(re("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(re("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(re("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(re("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(re("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(re("features"),e)}async getFeatures(){return this.store.get(re("features"))}async setInitParams(e){await this.store.set(re("init"),e)}async getInitParams(){return this.store.get(re("init"))}async setInboxLastRequestCode(e){await this.store.set(re("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(re("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(re("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(re("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(re("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(re("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(re("delayedEvent"),e)}getDelayedEvent(){return this.store.get(re("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(re("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(re("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(re("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(re("promptLastSeenTime"),0)}}class oe{constructor(e=new ne,t=Z){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e){return this.createRequest("postEvent",e)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}pageVisit(e,t){return this.createRequest("pageVisit",e,t)}setPurchase(e){return this.createRequest("setPurchase",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}async createRequest(e,t,s){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=s||a+e,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:T().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t=`status: ${e.status}. statusText: ${e.statusText}.`;try{const s=await e.json();s&&s.status_message&&(t+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(e){}throw new Error(t)}const t=await e.json();if(200!==t.status_code)throw new Error(`Error code: ${t.status_code}. Error text: ${t.status_message}`);return t}}class ce{constructor(e,t=new ne,s=new oe,a=()=>!1){this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=a}async checkDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(void 0===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?i:r),t=localStorage.getItem(a)}return t===i}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(e)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=await this.apiClient.registerDevice({...e,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,i),this.eventBus.dispatchEvent("register",{}),s}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:e,metaData:s})}async pushStat(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:e}),this.apiClient.setTags({...a,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.apiClient.registerUser({...i,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),t&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...i,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),r}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async postEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams(),a=new Date,i=a.getTime(),r=Math.floor(i/1e3),n=r-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:e,timestampUTC:r,timestampCurrent:n,attributes:t});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:a})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async pageVisit(e){const t=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...t,...e},a)}async setPurchase(e){const t=await this.getRequestParams();return this.apiClient.setPurchase({...t,...e})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),r=await this.data.getDeviceType(),n=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid(),u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?await this.data.setLanguage(u.language):u.language=n,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,i),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:e,hwid:t,userId:s||t,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class he{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const a=e.match(/\bEdg\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;let i=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=i;i=i[2]?[r,i[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&i.splice(1,1,n[1]),i.join(" ")}}class ue{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),a=t.getKey("p256dh"),i=t.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t)return await this.data.setLastPermissionStatus(t),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),r=a===(i&&i.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${M()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),a=new Uint8Array(s.length);for(let e=0;e<s.length;++e)a[e]=s.charCodeAt(e);return a}}class de{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),a=this.getPermission();return s!==a?(await this.data.setLastPermissionStatus(a),!0):t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class ge{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await J.getAll();console.log(e)},async showKeyValues(){const e=await z.getAll();console.log(e)},async showMessages(){(await Y.getAll()).forEach(e=>console.log(e))}},this.eventBus=new ee,this.data=new ne,this.apiClient=new oe(this.data),this.api=new ce(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled),this.platformChecker=new he(T()),this.inboxModel=new ie(this.eventBus,this.data,this.api),this.pwinbox=new te(this.data,this.api,this.inboxModel)}push(e){if(_(e))this.subscribeToLegacyEvents(h,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const e=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e})}const t=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(t===o){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!s||e)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(t===n)return this.eventBus.dispatchEvent("permission-denied",{}),void(a&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(e){throw Z.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===i}isDeviceUnregistered(){return localStorage.getItem(a)===r}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();this.driver.checkIsPermissionGranted()&&(await this.api.registerDevice(),await this.sendData())}else await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),await this.data.setStatusDropAllData(!0)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}async sendStatisticsVisitedPage(){const{document:{title:e},location:{origin:t,pathname:s,href:a}}=window;await this.api.pageVisit({title:e,url_path:`${t}${s}`,url:a})}async initialize(e){this.initParams={...x,...e};const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Z.setLevel(t||e.logLevel||"error"),!this.isAvailableNotifications())return;if(!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,a=await this.data.getCommunicationEnabled(),i=await this.data.getStatusCommunicationDisabled();(s&&!0!==a||!1===a||i)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();if((!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail()),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.50.5"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{await this.finishInit();try{await this.inboxModel.updateMessages()}catch(e){Z.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.platformChecker.isSafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){await this.ensureHwid(),await this.loadConfig(),await this.open(),await this.sendData();await this.data.getApplicationServerKey()?await this.initPushNotifications(this.initParams):Z.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}async ensureHwid(e=!1){await this.data.getHwid()&&!e||await this.data.setHwid(this.initParams.applicationCode+"_"+M())}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.driver.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const t=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),a=await this.driver.checkIsNeedResubscribe();if(t||s)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const i=await this.data.getStatusManualUnsubscribed(),r=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case c:this.eventBus.dispatchEvent("permission-default",{}),r&&await this.unsubscribe();break;case n:this.eventBus.dispatchEvent("permission-denied",{}),r&&await this.unsubscribe();break;case o:this.eventBus.dispatchEvent("permission-granted",{}),i&&r&&await this.unsubscribe(),(!r&&!i||a)&&await this.subscribe(!0)}}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:a={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,a)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}async sendData(){const e=this.initParams,t=await this.data.getUserId();e.userId&&"user_id"!==e.userId&&e.userId!==t&&await this.api.registerUser(e.userId,!1);const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags,task:async()=>{await this.api.setTags(e.tags)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){const e=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(t.page_visit&&t.page_visit.enabled&&(await z.set("PAGE_VISITED_URL",t.page_visit.entrypoint),this.sendStatisticsVisitedPage()),t.events&&t.events.length){t.events.some(e=>e===E)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async initPushNotifications(e){await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.data.setInitParams(e),await this.initDriver();try{await this.defaultProcess()}catch(e){Z.error(e,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new de(this.api,this.data,{webSitePushId:e})):void Z.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}Z.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new ue(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window;this.api.postEvent(E,{url:t,title:e,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===h:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in W:this.eventBus.addEventHandler(W[e].name,s=>{const{prop:a}=W[e];t(this.api,a?s[a]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case b:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case v:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case y:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var a in s)("object"==typeof exports?exports:e)[a]=s[a]}}(this,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var a in s)e.o(s,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:s[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Pushwoosh:()=>ge});const s="/pushwoosh-service-worker.js",a="deviceRegistrationStatus",i="registered",r="unregistered",n="denied",o="granted",c="default",h="onReady",u="onSubscribe",d="onUnsubscribe",g="onRegister",l="onPermissionPrompt",p="onPermissionDenied",m="onPermissionGranted",w="onSWInitError",b="onPushDelivery",v="onNotificationClick",y="onNotificationClose",f="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",k="onShowNotificationPermissionDialog",P="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",I="onHideSubscriptionWidget",E="PW_SiteOpened",x={autoSubscribe:!0,serviceWorkerUrl:s};function T(){return globalThis}function M(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const _=e=>"function"==typeof e,W={[g]:{name:"register"},[u]:{name:"subscribe"},[d]:{name:"unsubscribe"},[w]:{name:"initialize-service-worker-error",prop:"error"},[b]:{name:"receive-push",prop:"notification"},[v]:{name:"open-notification",prop:"notification"},[y]:{name:"hide-notification",prop:"notification"},[f]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[k]:{name:"show-notification-permission-dialog"},[P]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[I]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[l]:{name:"permission-default"},[m]:{name:"permission-granted"}},N="keyValue",A="messages",R="log",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const U=[q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];const B=[q(N,function(e){e.createObjectStore(N,{keyPath:"key"})}),q(R,function(e){const t=e.createObjectStore(R,{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(A,function(e){e.createObjectStore(A,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class L{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class V{constructor(e=new L){this.migrations={initial:B,"2018/11/26":U},this.dateModule=e}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(e=>"initial"!==e).sort((e,t)=>{const s=new L(new Date(e)),a=new L(new Date(t));return s.getTimestamp()-a.getTimestamp()}).map(e=>this.migrations[e])}}class j{constructor(e,t=new V){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(e=>{this.applyMigrationsPack(e)})}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let $;function F(e){return($||($=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=H.bind(null,a,t),e(a)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t),new j(s).applyMigrations()}})),$).then(t=>new Promise((s,a)=>e(t,s,a)))}class K{_add(e){return F((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);i.onsuccess=()=>{s(e)},i.onerror=()=>{a(i.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return F((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return F((e,t,s)=>{const a=[],i=e.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=e=>{const s=e.target.result;s?(s.value&&a.push(s.value),s.continue()):t(a)},i.onerror=()=>{s(i.error)}})}}const z=(G=N,{get:(e,t)=>F((s,a,i)=>{const r=s.transaction(G).objectStore(G).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(r.result?.value||t):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>F((e,t,s)=>{const a={},i=e.transaction(G).objectStore(G).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=e=>{const t=e.target.result;t?(a[t.key]=t.value.value,t.continue()):n=!0},i.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...a}=t;await this.set(e,{...s,...a})},set:(e,t)=>F((s,a,i)=>{const r=s.transaction([G],"readwrite").objectStore(G).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(e):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var G;const J=new class extends K{constructor(){super(...arguments),this.name=R,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const a={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(a.stack=t.stack),s&&(a.additional=s),this._add(a)}},Y=new class extends K{constructor(){super(...arguments),this.name=A,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Q={error:1,info:2,debug:3};let X=3;const Z={setLevel(e){Q[e]||(e="error"),X=Q[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),J.add(e,t,s)}};Object.keys(Q).forEach(e=>{const t=Q[e];Z[e]=(...s)=>{t<=X&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class ee{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||M(),a=this.handlers[e];return a?(a.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}class te{constructor(e,t,s,a=new L){this.data=e,this.api=t,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const a=[],i=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,a.push(t),i.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=s||await this.data.getDefaultNotificationImage(),h=a||await this.data.getDefaultNotificationTitle(),u=JSON.parse(t);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,u),link:u?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=JSON.parse(t.action_params),a=this.messageTypeFactory(t.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class se{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{a(e.error)}})}readRequestPromise(e,t){return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target;s(a.result||t)},e.onerror=()=>{a(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,a)=>{e.onsuccess=e=>{const a=e.target.result;a?(t.push(a.value),a.continue()):s(t)},e.onerror=()=>{a(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class ae{dbVersionChangeHandler(e,t){console.info("onversionchange",t),e.close()}dbRequestSuccessHandler(e,t){const s=t.target.result;s.onversionchange=e=>{this.dbVersionChangeHandler(s,e)},e(s)}dbRequestUpgradeNeededHandler(e){const t=e.target.result;t.onversionchange=e=>{this.dbVersionChangeHandler(t,e)};new j(t).applyMigrations()}getDB(){return new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=t=>{this.dbRequestSuccessHandler(e,t)},s.onupgradeneeded=e=>{this.dbRequestUpgradeNeededHandler(e)},s.onerror=()=>t(s.error)})}async put(e,t,s){const a=await this.getDB(),i=new se(a,e),r=await i.put(t,s);return a.close(),r}async delete(e,t){const s=await this.getDB(),a=new se(s,e),i=await a.delete(t);return s.close(),i}async get(e,t,s){const a=await this.getDB(),i=new se(a,e),r=await i.get(t,s);return a.close(),r}async getAll(e){const t=await this.getDB(),s=new se(t,e),a=await s.getAll();return t.close(),a||[]}async count(e,t){const s=await this.getDB(),a=new se(s,e),i=await a.count(t);return s.close(),i}async countByIndex(e,t,s){const a=await this.getDB(),i=new se(a,e);i.index=t;const r=await i.countByIndex(s);return a.close(),r}}class ie{constructor(e,t,s,a=new ae,i=new L){this.eventBus=e,this.data=t,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new te(this.data,this.api,this)})}}const re=e=>`params.${e}`;class ne{constructor(e=z){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime"];for(const t of e)await this.store.set(re(t),void 0)}async setApplicationCode(e){await this.store.set(re("applicationCode"),e)}async getApplicationCode(){return this.store.get(re("applicationCode"))}async setApiToken(e){return await this.store.set(re("apiToken"),e)}async getApiToken(){return this.store.get(re("apiToken"))}async setHwid(e){await this.store.set(re("hwid"),e)}async getHwid(){return this.store.get(re("hwid"))}async setDeviceType(e){await this.store.set(re("deviceType"),e)}async getDeviceType(){return this.store.get(re("deviceType"))}async setDeviceModel(e){await this.store.set(re("deviceModel"),e)}async getDeviceModel(){return this.store.get(re("deviceModel"))}async setLanguage(e){await this.store.set(re("language"),e)}async getLanguage(){return this.store.get(re("language"),"en")}async setApiEntrypoint(e){await this.store.set(re("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(re("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(re("tokens"),e)}getTokens(){return this.store.get(re("tokens"))}async setApplicationServerKey(e){await this.store.set(re("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(re("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(re("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(re("isVapidChanged"),!1)}async setWebSitePushId(e){await this.store.set(re("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(re("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(re("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(re("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(re("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(re("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(re("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(re("userId"))}async setStatusUserIdWasChanged(e){await this.store.set(re("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(re("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(re("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(re("email"))}async setStatusEmailWasChanged(e){await this.store.set(re("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(re("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(re("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(re("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(re("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(re("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(re("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(re("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(re("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(re("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(re("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(re("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(re("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(re("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(re("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(re("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(re("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(re("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(re("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(re("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(re("sdkVersion"),e)}async getSdkVersion(){return this.store.get(re("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(re("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(re("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(re("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(re("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(re("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(re("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(re("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(re("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(re("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(re("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(re("features"),e)}async getFeatures(){return this.store.get(re("features"))}async setInitParams(e){await this.store.set(re("init"),e)}async getInitParams(){return this.store.get(re("init"))}async setInboxLastRequestCode(e){await this.store.set(re("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(re("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(re("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(re("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(re("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(re("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(re("delayedEvent"),e)}getDelayedEvent(){return this.store.get(re("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(re("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(re("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(re("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(re("promptLastSeenTime"),0)}}class oe{constructor(e=new ne,t=Z){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e){return this.createRequest("postEvent",e)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}pageVisit(e,t){return this.createRequest("pageVisit",e,t)}setPurchase(e){return this.createRequest("setPurchase",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}async createRequest(e,t,s){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),r=s||a+e,n=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:T().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t=`status: ${e.status}. statusText: ${e.statusText}.`;try{const s=await e.json();s&&s.status_message&&(t+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(e){}throw new Error(t)}const t=await e.json();if(200!==t.status_code)throw new Error(`Error code: ${t.status_code}. Error text: ${t.status_message}`);return t}}class ce{constructor(e,t=new ne,s=new oe,a=()=>!1){this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=a}async checkDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(void 0===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?i:r),t=localStorage.getItem(a)}return t===i}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(e)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=await this.apiClient.registerDevice({...e,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,i),this.eventBus.dispatchEvent("register",{}),s}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:e,metaData:s})}async pushStat(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:e}),this.apiClient.setTags({...a,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.apiClient.registerUser({...i,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),t&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...i,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),r}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async postEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams(),a=new Date,i=a.getTime(),r=Math.floor(i/1e3),n=r-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:e,timestampUTC:r,timestampCurrent:n,attributes:t});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:a})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async pageVisit(e){const t=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...t,...e},a)}async setPurchase(e){const t=await this.getRequestParams();return this.apiClient.setPurchase({...t,...e})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),r=await this.data.getDeviceType(),n=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid(),u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?await this.data.setLanguage(u.language):u.language=n,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:r,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,i),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:e,hwid:t,userId:s||t,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class he{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const a=e.match(/\bEdg\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;let i=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=i;i=i[2]?[r,i[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&i.splice(1,1,n[1]),i.join(" ")}}class ue{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),a=t.getKey("p256dh"),i=t.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t)return await this.data.setLastPermissionStatus(t),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),r=a===(i&&i.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${M()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),a=new Uint8Array(s.length);for(let e=0;e<s.length;++e)a[e]=s.charCodeAt(e);return a}}class de{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void Z.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),a=this.getPermission();return s!==a?(await this.data.setLastPermissionStatus(a),!0):t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class ge{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await J.getAll();console.log(e)},async showKeyValues(){const e=await z.getAll();console.log(e)},async showMessages(){(await Y.getAll()).forEach(e=>console.log(e))}},this.eventBus=new ee,this.data=new ne,this.apiClient=new oe(this.data),this.api=new ce(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled),this.platformChecker=new he(T()),this.inboxModel=new ie(this.eventBus,this.data,this.api),this.pwinbox=new te(this.data,this.api,this.inboxModel)}push(e){if(_(e))this.subscribeToLegacyEvents(h,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const e=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e})}const t=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(t===o){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!s||e)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(t===n)return this.eventBus.dispatchEvent("permission-denied",{}),void(a&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(e){throw Z.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===i}isDeviceUnregistered(){return localStorage.getItem(a)===r}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();this.driver.checkIsPermissionGranted()&&(await this.api.registerDevice(),await this.sendData())}else await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),await this.data.setStatusDropAllData(!0)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}async sendStatisticsVisitedPage(){const{document:{title:e},location:{origin:t,pathname:s,href:a}}=window;await this.api.pageVisit({title:e,url_path:`${t}${s}`,url:a})}async initialize(e){this.initParams={...x,...e};const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Z.setLevel(t||e.logLevel||"error"),!this.isAvailableNotifications())return;if(!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,a=await this.data.getCommunicationEnabled(),i=await this.data.getStatusCommunicationDisabled();(s&&!0!==a||!1===a||i)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();if((!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail()),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.50.6"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{await this.finishInit();try{await this.inboxModel.updateMessages()}catch(e){Z.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.platformChecker.isSafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){await this.ensureHwid(),await this.loadConfig(),await this.open(),await this.sendData();await this.data.getApplicationServerKey()?await this.initPushNotifications(this.initParams):Z.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}async ensureHwid(e=!1){await this.data.getHwid()&&!e||await this.data.setHwid(this.initParams.applicationCode+"_"+M())}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.driver.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const t=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),a=await this.driver.checkIsNeedResubscribe();if(t||s)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const i=await this.data.getStatusManualUnsubscribed(),r=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case c:this.eventBus.dispatchEvent("permission-default",{}),r&&await this.unsubscribe();break;case n:this.eventBus.dispatchEvent("permission-denied",{}),r&&await this.unsubscribe();break;case o:this.eventBus.dispatchEvent("permission-granted",{}),i&&r&&await this.unsubscribe(),(!r&&!i||a)&&await this.subscribe(!0)}}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:a={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,a)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}async sendData(){const e=this.initParams,t=await this.data.getUserId();e.userId&&"user_id"!==e.userId&&e.userId!==t&&await this.api.registerUser(e.userId,!1);const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags,task:async()=>{await this.api.setTags(e.tags)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){const e=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(t.page_visit&&t.page_visit.enabled&&(await z.set("PAGE_VISITED_URL",t.page_visit.entrypoint),this.sendStatisticsVisitedPage()),t.events&&t.events.length){t.events.some(e=>e===E)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async initPushNotifications(e){await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.data.setInitParams(e),await this.initDriver();try{await this.defaultProcess()}catch(e){Z.error(e,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new de(this.api,this.data,{webSitePushId:e})):void Z.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}Z.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new ue(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window;this.api.postEvent(E,{url:t,title:e,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===h:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in W:this.eventBus.addEventHandler(W[e].name,s=>{const{prop:a}=W[e];t(this.api,a?s[a]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case b:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case v:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case y:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
2
2
  //# sourceMappingURL=npm.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-push-notifications",
3
- "version": "3.50.5",
3
+ "version": "3.50.6",
4
4
  "description": "Pushwoosh web push notifications",
5
5
  "main": "npm.js",
6
6
  "types": "npm.d.ts",
package/service-worker.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var a in s)("object"==typeof exports?exports:t)[a]=s[a]}}(this,()=>(()=>{"use strict";const t="deviceRegistrationStatus",e="registered",s="unregistered";function a(t,e){if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.log(t)}return void 0===t&&void 0!==e?e:t}function i(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const n=t=>"function"==typeof t,r="keyValue",o="messages",c="log",u="inboxMessages";function h(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const d=[h(u,function(t){const e="status",s=t.createObjectStore(u,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];const l=[h(r,function(t){t.createObjectStore(r,{keyPath:"key"})}),h(c,function(t){const e=t.createObjectStore(c,{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),h(o,function(t){t.createObjectStore(o,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class g{constructor(t=new Date){this._date=t}set date(t){this._date=t}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const t=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(t)}addDays(t){const e=this._date.getTime()+24*t*60*60*1e3;this._date=new Date(e)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class p{constructor(t=new g){this.migrations={initial:l,"2018/11/26":d},this.dateModule=t}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(t=>"initial"!==t).sort((t,e)=>{const s=new g(new Date(t)),a=new g(new Date(e));return s.getTimestamp()-a.getTimestamp()}).map(t=>this.migrations[t])}}class m{constructor(t,e=new p){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(t=>{this.applyMigrationsPack(t)})}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function w(t,e){console.info("onversionchange",e),t.close()}let y;function b(t){return(y||(y=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=w.bind(null,a,e),t(a)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=w.bind(null,s,e),new m(s).applyMigrations()}})),y).then(e=>new Promise((s,a)=>t(e,s,a)))}class f{_add(t){return b((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).add(t);i.onsuccess=()=>{s(t)},i.onerror=()=>{a(i.error)}}).then(t=>this.getAll().then(e=>{if(Array.isArray(e)){const s=e.map(t=>t.id).sort((t,e)=>t==e?0:t<e?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(t=>this.delete(t))).then(()=>t)}return t}))}delete(t){return b((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).delete(t);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return b((t,e,s)=>{const a=[],i=t.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=t=>{const s=t.target.result;s?(s.value&&a.push(s.value),s.continue()):e(a)},i.onerror=()=>{s(i.error)}})}}const v=(S=r,{get:(t,e)=>b((s,a,i)=>{const n=s.transaction(S).objectStore(S).get(t);let r,o=!1,c=!1;const u=()=>{clearTimeout(r),o?a(n.result?.value||e):c?i(n.error):r=setTimeout(u,0)};n.onsuccess=()=>o=!0,n.onerror=()=>c=!0,u()}),getAll:()=>b((t,e,s)=>{const a={},i=t.transaction(S).objectStore(S).openCursor();let n,r=!1,o=!1;const c=()=>{clearTimeout(n),r?e(a):o?s(i.error):n=setTimeout(c,0)};i.onsuccess=t=>{const e=t.target.result;e?(a[e.key]=e.value.value,e.continue()):r=!0},i.onerror=()=>o=!0,c()}),async extend(t,e){const s=await this.get(t),{...a}=e;await this.set(t,{...s,...a})},set:(t,e)=>b((s,a,i)=>{const n=s.transaction([S],"readwrite").objectStore(S).put({key:t,value:e});let r,o=!1,c=!1;const u=()=>{clearTimeout(r),o?a(t):c?i(n.error):r=setTimeout(u,0)};n.onsuccess=()=>o=!0,n.onerror=()=>c=!0,u()})});var S;const x=new class extends f{constructor(){super(...arguments),this.name=c,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(t,e,s){const a={type:t,environment:this.environment,message:`${e}`,date:new Date};return e instanceof Error&&(a.stack=e.stack),s&&(a.additional=s),this._add(a)}},C=new class extends f{constructor(){super(...arguments),this.name=o,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},D={error:1,info:2,debug:3};let T=3;const k={setLevel(t){D[t]||(t="error"),T=D[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),x.add(t,e,s)}};Object.keys(D).forEach(t=>{const e=D[t];k[t]=(...s)=>{e<=T&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});const I="silent",M="fatal",P="error",E="warn",_="info",A="debug",R={[I]:0,[M]:10,[P]:20,[E]:30,[_]:40,[A]:50};function W(t){const{code:e,text:s,type:a}=t,i=function(t){switch(t){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(e?`${e}: ${s}`:s),console.groupEnd()}const N=new class{constructor(t){this.relations=R,this.level=t&&void 0!==t.level?t.level:P,this.applicationType=t&&void 0!==t.applicationType?t.applicationType:"sdk",this.subscribers=t&&void 0!==t.subscribers?t.subscribers:[]}updateLogLevel(t){this.level=t}updateApplicationType(t){this.applicationType=t}updateApplicationCode(t){this.applicationCode=t}updateDomain(t){this.domain=t}updateDeviceInfo(t){this.deviceInfo=t}subscribe(t,e){this.subscribers.push({handler:e,level:t})}async log(t){const e=[],{options:s,...a}=t;let i=a;if(s){const{handler:t,...e}=s;i={...a,...e}}const n=this.getMessage(i);this.subscribers.forEach(s=>{s.level===t.type&&this.relations[s.level]<=this.relations[this.level]&&e.push(s.handler.call(null,n))}),s&&s.handler&&this.level!==I&&s.handler.call(null,n),await Promise.all(e)}async debug(t,e){return this.log({type:A,text:t,options:e})}async info(t,e){return this.log({type:_,text:t,options:e})}async warn(t,e,s){return this.log({type:E,text:t,code:e,options:s})}async error(t,e,s){return this.log({type:P,text:t,code:e,options:s})}async fatal(t,e,s){return this.log({type:M,text:t,code:e,options:s})}async errorAndThrow(t,e,s){return this.logAndThrow({type:P,text:t,code:e,options:s})}async errorAndReject(t,e,s,a){return this.logAndReject(t,{type:P,text:e,code:s,options:a})}async fatalAndThrow(t,e,s){return this.logAndThrow({type:M,text:t,code:e,options:s})}async fatalAndReject(t,e,s,a){return this.logAndReject(t,{type:M,text:e,code:s,options:a})}async logAndThrow(t){await this.log(t);const e=new Error(t.text);throw t.code&&(e.code=t.code),e}async logAndReject(t,e){await this.log(e);const s=new Error(e.text);e.code&&(s.code=e.code),t(s)}getMessage(t){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...t}}}({level:"error",subscribers:[{level:"fatal",handler:W},{level:"error",handler:W}]});async function q(t){const e=O(t);return N.fatal(e.text,e.code,e.options)}function O(t){const{message:e,code:s,error:a,...i}=t,n=function(t){let e=new Error("unknown error");"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||(e.message=t.toString());t instanceof Error&&(e=t);return e}(a);return{text:e,code:s,options:{...i,errorText:n.message,errorStack:n.stack}}}class U{constructor(t,e,s,a=new g){this.data=t,this.api=e,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(t,e){let s=0;return 2===t?s=1:"l"in e&&null!=e.l&&(s=e.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(t,e,s){const a=[],i=[];e.forEach(async e=>{-1!==t.indexOf(e.inbox_id)&&(e.status=s,a.push(e),i.push(this.api.inboxStatus(e.order,e.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:t,action_params:e,image:s,title:a,send_date:i,inbox_id:n,text:r,status:o}){const c=s||await this.data.getDefaultNotificationImage(),u=a||await this.data.getDefaultNotificationTitle(),h=JSON.parse(e);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:u,imageUrl:c,code:n,message:r,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,h),link:h?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const t=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((t,e)=>parseInt(e.send_date,10)-parseInt(t.send_date,10)).sort((t,e)=>parseInt(e.order||"0",10)-parseInt(t.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(t)}async readMessagesWithCodes(t){const e=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,e,2)}async performActionForMessageWithCode(t){const e=await this.inboxModel.getMessage(t),s=JSON.parse(e.action_params),a=this.messageTypeFactory(e.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async deleteMessagesWithCodes(t){const e=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,[...e,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class L{constructor(t,e){this.name=e,this.store=t.transaction(this.name,"readwrite").objectStore(this.name)}set index(t){this.store.indexNames.contains(t)?this._index=this.store.index(t):console.warn(`Index "${t}" in `)}writeRequestPromise(t,e){return new Promise((s,a)=>{t.onsuccess=()=>{s(e)},t.onerror=()=>{a(t.error)}})}readRequestPromise(t,e){return new Promise((s,a)=>{t.onsuccess=t=>{const a=t.target;s(a.result||e)},t.onerror=()=>{a(t.error)}})}put(t,e){const s=this.store.put(t,e);return this.writeRequestPromise(s,e)}add(t,e){return this.put(t,e)}delete(t){const e=this.store.delete(t);return this.writeRequestPromise(e)}get(t,e){const s=this.store.get(t);return this.readRequestPromise(s,e)}getAll(){const t=this.store.openCursor(),e=[];return new Promise((s,a)=>{t.onsuccess=t=>{const a=t.target.result;a?(e.push(a.value),a.continue()):s(e)},t.onerror=()=>{a(t.error)}})}count(t){const e=this.store.count(t);return this.readRequestPromise(e,0)}countByIndex(t){const e=this._index.count(t);return this.readRequestPromise(e,0)}}class V{dbVersionChangeHandler(t,e){console.info("onversionchange",e),t.close()}dbRequestSuccessHandler(t,e){const s=e.target.result;s.onversionchange=t=>{this.dbVersionChangeHandler(s,t)},t(s)}dbRequestUpgradeNeededHandler(t){const e=t.target.result;e.onversionchange=t=>{this.dbVersionChangeHandler(e,t)};new m(e).applyMigrations()}getDB(){return new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=e=>{this.dbRequestSuccessHandler(t,e)},s.onupgradeneeded=t=>{this.dbRequestUpgradeNeededHandler(t)},s.onerror=()=>e(s.error)})}async put(t,e,s){const a=await this.getDB(),i=new L(a,t),n=await i.put(e,s);return a.close(),n}async delete(t,e){const s=await this.getDB(),a=new L(s,t),i=await a.delete(e);return s.close(),i}async get(t,e,s){const a=await this.getDB(),i=new L(a,t),n=await i.get(e,s);return a.close(),n}async getAll(t){const e=await this.getDB(),s=new L(e,t),a=await s.getAll();return e.close(),a||[]}async count(t,e){const s=await this.getDB(),a=new L(s,t),i=await a.count(e);return s.close(),i}async countByIndex(t,e,s){const a=await this.getDB(),i=new L(a,t);i.index=e;const n=await i.countByIndex(s);return a.close(),n}}class j{constructor(t,e,s,a=new V,i=new g){this.eventBus=t,this.data=e,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const t=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(t.next,t.new_inbox),t}async storeGetInboxMessagesRequestParams(t,e){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(t),await this.data.setInboxNewMessagesCount(e)}async putServerMessages(t){const e=t.map(async t=>{const e=await this.storage.get(this.storeName,t.inbox_id,{});return"status"in e&&(t.status=e.status),this.putMessage(t)});return Promise.all(e)}putMessage(t){return this.storage.put(this.storeName,t)}putBulkMessages(t){const e=t.map(t=>this.putMessage(t));return Promise.all(e)}deleteMessages(t){const e=t.map(t=>this.storage.delete(this.storeName,t));return Promise.all(e)}async deleteExpiredMessages(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString(),e=(await this.storage.getAll(this.storeName)).filter(e=>e.rt<t).map(t=>t.inbox_id);return this.deleteMessages(e)}getMessage(t){return this.storage.get(this.storeName,t)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>2===t.status||3===t.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>1===t.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[t,e]=[2,3],s=IDBKeyRange.bound(t,e);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const t=await this.getInboxMessages();await this.deleteExpiredMessages(),t.deleted&&await this.deleteMessages(t.deleted),await this.putServerMessages(t.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new U(this.data,this.api,this)})}}const B={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},H=/&(?:amp|lt|gt|quot|#39);/g,$=RegExp(H.source);const F=t=>`params.${t}`;class K{constructor(t=v){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime"];for(const e of t)await this.store.set(F(e),void 0)}async setApplicationCode(t){await this.store.set(F("applicationCode"),t)}async getApplicationCode(){return this.store.get(F("applicationCode"))}async setApiToken(t){return await this.store.set(F("apiToken"),t)}async getApiToken(){return this.store.get(F("apiToken"))}async setHwid(t){await this.store.set(F("hwid"),t)}async getHwid(){return this.store.get(F("hwid"))}async setDeviceType(t){await this.store.set(F("deviceType"),t)}async getDeviceType(){return this.store.get(F("deviceType"))}async setDeviceModel(t){await this.store.set(F("deviceModel"),t)}async getDeviceModel(){return this.store.get(F("deviceModel"))}async setLanguage(t){await this.store.set(F("language"),t)}async getLanguage(){return this.store.get(F("language"),"en")}async setApiEntrypoint(t){await this.store.set(F("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(F("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set(F("tokens"),t)}getTokens(){return this.store.get(F("tokens"))}async setApplicationServerKey(t){await this.store.set(F("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(F("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(F("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(F("isVapidChanged"),!1)}async setWebSitePushId(t){await this.store.set(F("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(F("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(F("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(F("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(F("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(F("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(F("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(F("userId"))}async setStatusUserIdWasChanged(t){await this.store.set(F("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(F("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(F("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(F("email"))}async setStatusEmailWasChanged(t){await this.store.set(F("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(F("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(F("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(F("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(F("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(F("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(F("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(F("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(F("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(F("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(F("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(F("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(F("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(F("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(F("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(F("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(F("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(F("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(F("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(F("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(F("sdkVersion"),t)}async getSdkVersion(){return this.store.get(F("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(F("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(F("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(F("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(F("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(t){t&&await this.store.set(F("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(F("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(F("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(F("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(F("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(F("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(F("features"),t)}async getFeatures(){return this.store.get(F("features"))}async setInitParams(t){await this.store.set(F("init"),t)}async getInitParams(){return this.store.get(F("init"))}async setInboxLastRequestCode(t){await this.store.set(F("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(F("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(F("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(F("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(F("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(F("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(F("delayedEvent"),t)}getDelayedEvent(){return this.store.get(F("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(F("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(F("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(F("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(F("promptLastSeenTime"),0)}}class z{constructor(t,e=new K,s=new g){if("data"in t){const e=t;this.payload=e.data}else this.payload=t;this.data=e,this.code=`notificationCode-${Date.now()}-${Math.random().toString(16).slice(2,10)}`,this.dateModule=s}async getIcon(){return this.payload.i||await this.data.getDefaultNotificationImage()}async getTitle(){return this.payload.header||await this.data.getDefaultNotificationTitle()}get silent(){return Boolean(this.payload.silent)}get body(){return this.payload.body}get messageHash(){return this.payload.p||""}get metaData(){return this.payload.md?a(this.payload.md):{}}get image(){return this.payload.image||""}get buttons(){return this.payload.buttons?a(this.payload.buttons):[]}get customData(){return this.payload.u?a(this.payload.u):{}}get campaignCode(){return this.payload.pwcid||""}get link(){return this.payload.l?(t=this.payload.l)&&$.test(t)?t.replace(H,t=>B[t]):t:"/";var t}get inboxId(){return this.payload.pw_inbox||""}get inboxParams(){return this.payload.inbox_params?a(this.payload.inbox_params):{}}get inboxRemovalTime(){return this.inboxParams&&this.inboxParams.rt?this.inboxParams.rt:(this.dateModule.date=new Date,this.dateModule.addDays(1),this.dateModule.getUtcTimestamp().toString())}async getInboxImage(){return this.inboxParams&&this.inboxParams.image?this.inboxParams.image:""}get rootParams(){const{body:t,p:e,header:s,i:a,u:i,l:n,pwcid:r,image:o,buttons:c,pw_inbox:u,inbox_params:h,...d}=this.payload;return d}async getNotificationOptionsPayload(){const t=await this.getTitle(),e=await this.getIcon();return{...this.rootParams,body:this.body,title:t,icon:e,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const t=await this.getIcon(),e=this.buttons.map((t,e)=>(t.action=`action-${e}`,t));return{renotify:!0,...this.rootParams,body:this.body,icon:t,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:e,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:e,image:this.image,buttons:e}}async getInboxMessage(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString();return{title:this.payload.header||"",image:await this.getInboxImage(),status:1,order:this.dateModule.getInboxFakeOrder(),inbox_id:this.inboxId,send_date:t,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}class J{constructor(t=new K,e=k){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}applicationOpen(t){return this.createRequest("applicationOpen",t)}registerDevice(t){return this.createRequest("registerDevice",t)}unregisterDevice(t){return this.createRequest("unregisterDevice",t)}deleteDevice(t){return this.createRequest("deleteDevice",t)}messageDeliveryEvent(t){return this.createRequest("messageDeliveryEvent",t)}pushStat(t){return this.createRequest("pushStat",t)}setTags(t){return this.createRequest("setTags",t)}getTags(t){return this.createRequest("getTags",t)}registerUser(t){return this.createRequest("registerUser",t)}registerEmail(t){return this.createRequest("registerEmail",t)}registerEmailUser(t){return this.createRequest("registerEmailUser",t)}setEmailTags(t){return this.createRequest("setEmailTags",t)}postEvent(t){return this.createRequest("postEvent",t)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t){return this.createRequest("inboxStatus",t)}pageVisit(t,e){return this.createRequest("pageVisit",t,e)}setPurchase(t){return this.createRequest("setPurchase",t)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}async createRequest(t,e,s){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),n=s||a+t,r=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=await fetch(n,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...r}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(t){if(200!==t.status){let e=`status: ${t.status}. statusText: ${t.statusText}.`;try{const s=await t.json();s&&s.status_message&&(e+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(t){}throw new Error(e)}const e=await t.json();if(200!==e.status_code)throw new Error(`Error code: ${e.status_code}. Error text: ${e.status_message}`);return e}}class G{constructor(t,e,s){this.api=t,this.data=e,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return"granted"===this.getPermission()}checkIsPermissionDefault(){return"default"===this.getPermission()}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(t){const e=t||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void k.error("You must have permission granted before subscribe!");const s=this.getPushToken(e),a=e.getKey("p256dh"),i=e.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const n=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),r=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:n,pushToken:s,authToken:r,endpoint:e.endpoint}),await this.api.registerDevice()}async unsubscribe(){const t=await this.getServiceWorkerRegistration(),e=await t.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),e&&await e.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const t=await this.data.getLastPermissionStatus(),e=this.getPermission();if(t!==e)return await this.data.setLastPermissionStatus(e),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),n=a===(i&&i.pushToken||""),r=await this.data.getIsVapidChanged();return!n||r}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const t=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(t),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const t=await this.data.getServiceWorkerUrl(),e=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${i()}`),await navigator.serviceWorker.register(`${t}${s}`,{scope:e})}async trySubscribe(){try{return await this.subscribePushManager()}catch(t){return console.error(t),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const t=await this.getServiceWorkerRegistration(),e=await this.getApplicationServerKey();return t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e?this.urlBase64ToUint8Array(e):null})}async getCredentials(){const t=await this.getServiceWorkerRegistration();return await t.pushManager.getSubscription()}getPushToken(t){return t?t.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(e),a=new Uint8Array(s.length);for(let t=0;t<s.length;++t)a[t]=s.charCodeAt(t);return a}}class Y{constructor(t,e,s){this._canceled=!1,this.showNotificationOptions=t,this.body=e,this.title=s}async show(){if(this._canceled)return;const t=this.showNotificationOptions;t.silent||await self.registration.showNotification(this.title,t)}cancel(){this._canceled=!0}}const Q=new class{constructor(){this.addEventHandler=(t,e)=>{let s=this.handlers[t];s||(s=[]),s.push(e),this.handlers[t]=s},this.removeEventHandler=(t,e)=>{const s=this.handlers[t];s&&(this.handlers[t]=s.filter(t=>t!==e))},this.dispatchEvent=(t,e)=>{const s=e.eventId||i(),a=this.handlers[t];return a?(a.forEach(t=>{n(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}},X=new K,Z=new class{constructor(t,e=new K,s=new J,a=()=>!1){this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=a}async checkDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(a=!0){let i=localStorage.getItem(t);if(void 0===i||!a){const{exist:a,push_token_exist:n}=await this.checkDevice();localStorage.setItem(t,a&&n?e:s),i=localStorage.getItem(t)}return i===e}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(t)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const s=await this.getRequestParams(),a=await this.data.getTokens();if(!a.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=await this.apiClient.registerDevice({...s,push_token:a.pushToken,auth_token:a.authToken,public_key:a.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,e),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),a=await this.apiClient.unregisterDevice(e);return localStorage.setItem(t,s),this.eventBus.dispatchEvent("unsubscribe",{}),a}async deleteDevice(){const e=await this.getRequestParams(),a=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(t,s),this.eventBus.dispatchEvent("unsubscribe",{}),a}async messageDeliveryEvent(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:t,metaData:s})}async pushStat(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:t,metaData:s})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:e,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:t}),this.apiClient.setTags({...a,hwid:e,device_type:s,tags:t})}async getTags(){const t=await this.getRequestParams();return this.apiClient.getTags(t)}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),n=await this.data.getDeviceType(),r=`${t}`,o=await this.apiClient.registerUser({...i,hwid:s,userId:r,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:n});return await this.data.setUserId(r),e&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),n=await this.apiClient.registerEmail({...i,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),n}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async postEvent(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams(),a=new Date,i=a.getTime(),n=Math.floor(i/1e3),r=n-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:t,timestampUTC:n,timestampCurrent:r,attributes:e});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(t=0){const e=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...e,count:t,last_code:s,last_request_time:a})}async inboxStatus(t,e){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:t,status:e,time:(new Date).getTime()})}async pageVisit(t){const e=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...e,...t},a)}async setPurchase(t){const e=await this.getRequestParams();return this.apiClient.setPurchase({...e,...t})}async multiRegisterDevice(s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.data.getApplicationCode(),i=await this.data.getDeviceModel(),n=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),u=await this.data.getHwid(),h={application:a,...s};if(s.user_id){h.user_id=String(s.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(s.email){if(!/^\S+@\S+\.\S+$/.test(s.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==s.email&&(await this.data.setEmail(s.email),await this.data.setStatusEmailWasChanged(!0))}if(s.sms_phone_number){if(!/^\+?[0-9]+$/.test(s.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==s.sms_phone_number&&(await this.data.setSmsNumber(s.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(s.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(s.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==s.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(s.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(h.language?await this.data.setLanguage(h.language):h.language=r,!h.timezone){const t=60*-(new Date).getTimezoneOffset();h.timezone=String(t)}if(!h.push_devices&&c.pushToken){const t={hwid:u,platform:n,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),i&&(e.browser=i),t.platformData=e}h.push_devices=[t]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,e),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const t=await this.data.getApplicationCode(),e=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),n=await this.data.getLanguage(),r=await this.data.getSdkVersion();return{application:t,hwid:e,userId:s||e,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:n,v:r}}}(Q,X),tt=self.Pushwoosh=new class{constructor(t,e,s){this._listeners={},this.eventBus=t,this.data=e,this.api=s}push(t){Array.isArray(t)&&"onPush"===t[0]&&n(t[1])&&(this._listeners[t[0]]||(this._listeners[t[0]]=[]),this._listeners[t[0]].push(t[1]))}getListeners(t){return this._listeners[t]||[]}async initApi(){return Promise.resolve()}}(Q,X,Z),et=[];async function st(t){(await self.clients.matchAll()).forEach(e=>e.postMessage(t))}async function at(t){const{notification:e={}}=t,{data:s}=e,i=a(e.tag,{});let n="";if(t.action&&Array.isArray(s.buttons)){n=(s.buttons.find(e=>e.action===t.action)||{}).url}else n=i.url;return{title:e.title,body:e.body,icon:e.icon,buttons:s.buttons,image:s.image,code:s.code,campaignCode:s.campaignCode,inboxId:s.inboxId,messageHash:i.messageHash,customData:i.customData,metaData:i.metaData,openUrl:i.url,tag:e.tag,url:n}}async function it(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:t,applicationCode:e,workerVersion:s})}async function nt(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:t,applicationCode:e,workerVersion:s})}async function rt(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:t,applicationCode:e,workerVersion:s})}async function ot(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:t,applicationCode:e,workerVersion:s})}async function ct(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:t,applicationCode:e,workerVersion:s})}return self.addEventListener("install",function(t){return t.waitUntil(async function(){await Promise.all([tt.data.setServiceWorkerVersion("3.50.5"),k.write("info","install")]),await self.skipWaiting()}().catch(it))}),self.addEventListener("activate",function(t){t.waitUntil(async function(){await Promise.all([k.write("info","activate")]),await self.clients.claim()}().catch(nt))}),self.addEventListener("push",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await t.data.json(),s=new z(e),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),n=s.messageHash;await k.write("info",JSON.stringify(a),"onPush");const r=new Y(i,s.body,await s.getTitle()),o=tt.getListeners("onPush");await o.reduce((t,e)=>t.then(()=>e(r)),Promise.resolve());const c=[r.show(),C.add({payload:e,parsedPayload:a,showOptions:i}),st({type:"onPushDelivery",payload:a})];if(n&&c.push(tt.initApi().then(()=>tt.api.messageDeliveryEvent(n,!0,a.metaData))),""!==s.inboxId){const t=new j(tt.eventBus,tt.data,tt.api),e=new U(tt.data,tt.api,t),a=await s.getInboxMessage(),i=await e.publicMessageBuilder(a);c.push(t.putMessage(a),st({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(t).catch(e=>async function(t,e){const s=await tt.data.getApplicationCode(),a=await tt.data.getServiceWorkerVersion();await q({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:t,applicationCode:s,workerVersion:a}),t instanceof Error||(t=new Error(t));return C.add({error:`${t}`,stack:t.stack,payload:e.data&&e.data.text()})}(e,t)))}),self.addEventListener("notificationclick",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await at(t),{messageHash:s,metaData:a,url:i,code:n,inboxId:r}=e;if(n&&et.push(n),""!==r){const t=new j(tt.eventBus,tt.data,tt.api),e=await t.getMessage(r);e.status=3,await t.putMessage(e)}t.notification.close();const o={type:"onNotificationClick",payload:e};return i&&t.waitUntil(self.clients.matchAll({type:"window"}).then(t=>async function(t,e){const{hostname:s,pathname:a}=new URL(e,self.location.origin),i=t.find(t=>{const{hostname:e,pathname:i}=new URL(t.url);return e===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(e).then(t=>{t&&t.focus()}),!0)}(t,i)).then(t=>{t&&tt.data.setDelayedEvent(o)})),Promise.all([tt.initApi().then(()=>tt.api.pushStat(s,!0,a)),tt.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),st(o)])}(t).catch(rt))}),self.addEventListener("notificationclose",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await at(t),{code:s}=e;if(t.notification.close(),!s)return;const a=et.indexOf(s);if(!(a>=0))return st({type:"onNotificationClose",payload:e});et.splice(a,1)}(t).catch(ot))}),self.addEventListener("pushsubscriptionchange",async function(t){t.waitUntil(async function(t){let e=t.newSubscription;if(!e&&(e=await self.registration.pushManager.getSubscription(),!e))return;const s=new G(Z,X,{});await s.subscribe(e)}(t).catch(ct))}),{}})());
1
+ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var a in s)("object"==typeof exports?exports:t)[a]=s[a]}}(this,()=>(()=>{"use strict";const t="deviceRegistrationStatus",e="registered",s="unregistered";function a(t,e){if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.log(t)}return void 0===t&&void 0!==e?e:t}function i(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const n=t=>"function"==typeof t,r="keyValue",o="messages",c="log",u="inboxMessages";function h(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const d=[h(u,function(t){const e="status",s=t.createObjectStore(u,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];const l=[h(r,function(t){t.createObjectStore(r,{keyPath:"key"})}),h(c,function(t){const e=t.createObjectStore(c,{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),h(o,function(t){t.createObjectStore(o,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class g{constructor(t=new Date){this._date=t}set date(t){this._date=t}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const t=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(t)}addDays(t){const e=this._date.getTime()+24*t*60*60*1e3;this._date=new Date(e)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class p{constructor(t=new g){this.migrations={initial:l,"2018/11/26":d},this.dateModule=t}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(t=>"initial"!==t).sort((t,e)=>{const s=new g(new Date(t)),a=new g(new Date(e));return s.getTimestamp()-a.getTimestamp()}).map(t=>this.migrations[t])}}class m{constructor(t,e=new p){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(t=>{this.applyMigrationsPack(t)})}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function w(t,e){console.info("onversionchange",e),t.close()}let y;function b(t){return(y||(y=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=w.bind(null,a,e),t(a)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=w.bind(null,s,e),new m(s).applyMigrations()}})),y).then(e=>new Promise((s,a)=>t(e,s,a)))}class f{_add(t){return b((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).add(t);i.onsuccess=()=>{s(t)},i.onerror=()=>{a(i.error)}}).then(t=>this.getAll().then(e=>{if(Array.isArray(e)){const s=e.map(t=>t.id).sort((t,e)=>t==e?0:t<e?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(t=>this.delete(t))).then(()=>t)}return t}))}delete(t){return b((e,s,a)=>{const i=e.transaction([this.name],"readwrite").objectStore(this.name).delete(t);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}})}getAll(){return b((t,e,s)=>{const a=[],i=t.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=t=>{const s=t.target.result;s?(s.value&&a.push(s.value),s.continue()):e(a)},i.onerror=()=>{s(i.error)}})}}const v=(S=r,{get:(t,e)=>b((s,a,i)=>{const n=s.transaction(S).objectStore(S).get(t);let r,o=!1,c=!1;const u=()=>{clearTimeout(r),o?a(n.result?.value||e):c?i(n.error):r=setTimeout(u,0)};n.onsuccess=()=>o=!0,n.onerror=()=>c=!0,u()}),getAll:()=>b((t,e,s)=>{const a={},i=t.transaction(S).objectStore(S).openCursor();let n,r=!1,o=!1;const c=()=>{clearTimeout(n),r?e(a):o?s(i.error):n=setTimeout(c,0)};i.onsuccess=t=>{const e=t.target.result;e?(a[e.key]=e.value.value,e.continue()):r=!0},i.onerror=()=>o=!0,c()}),async extend(t,e){const s=await this.get(t),{...a}=e;await this.set(t,{...s,...a})},set:(t,e)=>b((s,a,i)=>{const n=s.transaction([S],"readwrite").objectStore(S).put({key:t,value:e});let r,o=!1,c=!1;const u=()=>{clearTimeout(r),o?a(t):c?i(n.error):r=setTimeout(u,0)};n.onsuccess=()=>o=!0,n.onerror=()=>c=!0,u()})});var S;const x=new class extends f{constructor(){super(...arguments),this.name=c,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(t,e,s){const a={type:t,environment:this.environment,message:`${e}`,date:new Date};return e instanceof Error&&(a.stack=e.stack),s&&(a.additional=s),this._add(a)}},C=new class extends f{constructor(){super(...arguments),this.name=o,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},D={error:1,info:2,debug:3};let T=3;const k={setLevel(t){D[t]||(t="error"),T=D[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),x.add(t,e,s)}};Object.keys(D).forEach(t=>{const e=D[t];k[t]=(...s)=>{e<=T&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});const I="silent",M="fatal",P="error",E="warn",_="info",A="debug",R={[I]:0,[M]:10,[P]:20,[E]:30,[_]:40,[A]:50};function W(t){const{code:e,text:s,type:a}=t,i=function(t){switch(t){case"fatal":case"error":return console.error;case"warn":case"info":case"debug":return console.log}}(a);console.groupCollapsed(a),i(e?`${e}: ${s}`:s),console.groupEnd()}const N=new class{constructor(t){this.relations=R,this.level=t&&void 0!==t.level?t.level:P,this.applicationType=t&&void 0!==t.applicationType?t.applicationType:"sdk",this.subscribers=t&&void 0!==t.subscribers?t.subscribers:[]}updateLogLevel(t){this.level=t}updateApplicationType(t){this.applicationType=t}updateApplicationCode(t){this.applicationCode=t}updateDomain(t){this.domain=t}updateDeviceInfo(t){this.deviceInfo=t}subscribe(t,e){this.subscribers.push({handler:e,level:t})}async log(t){const e=[],{options:s,...a}=t;let i=a;if(s){const{handler:t,...e}=s;i={...a,...e}}const n=this.getMessage(i);this.subscribers.forEach(s=>{s.level===t.type&&this.relations[s.level]<=this.relations[this.level]&&e.push(s.handler.call(null,n))}),s&&s.handler&&this.level!==I&&s.handler.call(null,n),await Promise.all(e)}async debug(t,e){return this.log({type:A,text:t,options:e})}async info(t,e){return this.log({type:_,text:t,options:e})}async warn(t,e,s){return this.log({type:E,text:t,code:e,options:s})}async error(t,e,s){return this.log({type:P,text:t,code:e,options:s})}async fatal(t,e,s){return this.log({type:M,text:t,code:e,options:s})}async errorAndThrow(t,e,s){return this.logAndThrow({type:P,text:t,code:e,options:s})}async errorAndReject(t,e,s,a){return this.logAndReject(t,{type:P,text:e,code:s,options:a})}async fatalAndThrow(t,e,s){return this.logAndThrow({type:M,text:t,code:e,options:s})}async fatalAndReject(t,e,s,a){return this.logAndReject(t,{type:M,text:e,code:s,options:a})}async logAndThrow(t){await this.log(t);const e=new Error(t.text);throw t.code&&(e.code=t.code),e}async logAndReject(t,e){await this.log(e);const s=new Error(e.text);e.code&&(s.code=e.code),t(s)}getMessage(t){return{applicationCode:this.applicationCode,domain:this.domain,applicationType:this.applicationType,deviceInfo:this.deviceInfo,...t}}}({level:"error",subscribers:[{level:"fatal",handler:W},{level:"error",handler:W}]});async function q(t){const e=O(t);return N.fatal(e.text,e.code,e.options)}function O(t){const{message:e,code:s,error:a,...i}=t,n=function(t){let e=new Error("unknown error");"string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||(e.message=t.toString());t instanceof Error&&(e=t);return e}(a);return{text:e,code:s,options:{...i,errorText:n.message,errorStack:n.stack}}}class U{constructor(t,e,s,a=new g){this.data=t,this.api=e,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(t,e){let s=0;return 2===t?s=1:"l"in e&&null!=e.l&&(s=e.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(t,e,s){const a=[],i=[];e.forEach(async e=>{-1!==t.indexOf(e.inbox_id)&&(e.status=s,a.push(e),i.push(this.api.inboxStatus(e.order,e.status)))}),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:t,action_params:e,image:s,title:a,send_date:i,inbox_id:n,text:r,status:o}){const c=s||await this.data.getDefaultNotificationImage(),u=a||await this.data.getDefaultNotificationTitle(),h=JSON.parse(e);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:u,imageUrl:c,code:n,message:r,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,h),link:h?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const t=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((t,e)=>parseInt(e.send_date,10)-parseInt(t.send_date,10)).sort((t,e)=>parseInt(e.order||"0",10)-parseInt(t.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(t)}async readMessagesWithCodes(t){const e=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,e,2)}async performActionForMessageWithCode(t){const e=await this.inboxModel.getMessage(t),s=JSON.parse(e.action_params),a=this.messageTypeFactory(e.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async deleteMessagesWithCodes(t){const e=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,[...e,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class L{constructor(t,e){this.name=e,this.store=t.transaction(this.name,"readwrite").objectStore(this.name)}set index(t){this.store.indexNames.contains(t)?this._index=this.store.index(t):console.warn(`Index "${t}" in `)}writeRequestPromise(t,e){return new Promise((s,a)=>{t.onsuccess=()=>{s(e)},t.onerror=()=>{a(t.error)}})}readRequestPromise(t,e){return new Promise((s,a)=>{t.onsuccess=t=>{const a=t.target;s(a.result||e)},t.onerror=()=>{a(t.error)}})}put(t,e){const s=this.store.put(t,e);return this.writeRequestPromise(s,e)}add(t,e){return this.put(t,e)}delete(t){const e=this.store.delete(t);return this.writeRequestPromise(e)}get(t,e){const s=this.store.get(t);return this.readRequestPromise(s,e)}getAll(){const t=this.store.openCursor(),e=[];return new Promise((s,a)=>{t.onsuccess=t=>{const a=t.target.result;a?(e.push(a.value),a.continue()):s(e)},t.onerror=()=>{a(t.error)}})}count(t){const e=this.store.count(t);return this.readRequestPromise(e,0)}countByIndex(t){const e=this._index.count(t);return this.readRequestPromise(e,0)}}class V{dbVersionChangeHandler(t,e){console.info("onversionchange",e),t.close()}dbRequestSuccessHandler(t,e){const s=e.target.result;s.onversionchange=t=>{this.dbVersionChangeHandler(s,t)},t(s)}dbRequestUpgradeNeededHandler(t){const e=t.target.result;e.onversionchange=t=>{this.dbVersionChangeHandler(e,t)};new m(e).applyMigrations()}getDB(){return new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=e=>{this.dbRequestSuccessHandler(t,e)},s.onupgradeneeded=t=>{this.dbRequestUpgradeNeededHandler(t)},s.onerror=()=>e(s.error)})}async put(t,e,s){const a=await this.getDB(),i=new L(a,t),n=await i.put(e,s);return a.close(),n}async delete(t,e){const s=await this.getDB(),a=new L(s,t),i=await a.delete(e);return s.close(),i}async get(t,e,s){const a=await this.getDB(),i=new L(a,t),n=await i.get(e,s);return a.close(),n}async getAll(t){const e=await this.getDB(),s=new L(e,t),a=await s.getAll();return e.close(),a||[]}async count(t,e){const s=await this.getDB(),a=new L(s,t),i=await a.count(e);return s.close(),i}async countByIndex(t,e,s){const a=await this.getDB(),i=new L(a,t);i.index=e;const n=await i.countByIndex(s);return a.close(),n}}class j{constructor(t,e,s,a=new V,i=new g){this.eventBus=t,this.data=e,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const t=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(t.next,t.new_inbox),t}async storeGetInboxMessagesRequestParams(t,e){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(t),await this.data.setInboxNewMessagesCount(e)}async putServerMessages(t){const e=t.map(async t=>{const e=await this.storage.get(this.storeName,t.inbox_id,{});return"status"in e&&(t.status=e.status),this.putMessage(t)});return Promise.all(e)}putMessage(t){return this.storage.put(this.storeName,t)}putBulkMessages(t){const e=t.map(t=>this.putMessage(t));return Promise.all(e)}deleteMessages(t){const e=t.map(t=>this.storage.delete(this.storeName,t));return Promise.all(e)}async deleteExpiredMessages(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString(),e=(await this.storage.getAll(this.storeName)).filter(e=>e.rt<t).map(t=>t.inbox_id);return this.deleteMessages(e)}getMessage(t){return this.storage.get(this.storeName,t)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>2===t.status||3===t.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>1===t.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[t,e]=[2,3],s=IDBKeyRange.bound(t,e);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const t=await this.getInboxMessages();await this.deleteExpiredMessages(),t.deleted&&await this.deleteMessages(t.deleted),await this.putServerMessages(t.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new U(this.data,this.api,this)})}}const B={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},H=/&(?:amp|lt|gt|quot|#39);/g,$=RegExp(H.source);const F=t=>`params.${t}`;class K{constructor(t=v){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime"];for(const e of t)await this.store.set(F(e),void 0)}async setApplicationCode(t){await this.store.set(F("applicationCode"),t)}async getApplicationCode(){return this.store.get(F("applicationCode"))}async setApiToken(t){return await this.store.set(F("apiToken"),t)}async getApiToken(){return this.store.get(F("apiToken"))}async setHwid(t){await this.store.set(F("hwid"),t)}async getHwid(){return this.store.get(F("hwid"))}async setDeviceType(t){await this.store.set(F("deviceType"),t)}async getDeviceType(){return this.store.get(F("deviceType"))}async setDeviceModel(t){await this.store.set(F("deviceModel"),t)}async getDeviceModel(){return this.store.get(F("deviceModel"))}async setLanguage(t){await this.store.set(F("language"),t)}async getLanguage(){return this.store.get(F("language"),"en")}async setApiEntrypoint(t){await this.store.set(F("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(F("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set(F("tokens"),t)}getTokens(){return this.store.get(F("tokens"))}async setApplicationServerKey(t){await this.store.set(F("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(F("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(F("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(F("isVapidChanged"),!1)}async setWebSitePushId(t){await this.store.set(F("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(F("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(F("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(F("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(F("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(F("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(F("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(F("userId"))}async setStatusUserIdWasChanged(t){await this.store.set(F("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(F("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(F("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(F("email"))}async setStatusEmailWasChanged(t){await this.store.set(F("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(F("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(F("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(F("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(F("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(F("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(F("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(F("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(F("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(F("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(F("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(F("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(F("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(F("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(F("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(F("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(F("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(F("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(F("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(F("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(F("sdkVersion"),t)}async getSdkVersion(){return this.store.get(F("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(F("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(F("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(F("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(F("serviceWorkerUrl"),"/pushwoosh-service-worker.js")}async setServiceWorkerScope(t){t&&await this.store.set(F("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(F("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(F("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(F("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(F("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(F("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(F("features"),t)}async getFeatures(){return this.store.get(F("features"))}async setInitParams(t){await this.store.set(F("init"),t)}async getInitParams(){return this.store.get(F("init"))}async setInboxLastRequestCode(t){await this.store.set(F("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(F("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(F("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(F("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(F("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(F("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(F("delayedEvent"),t)}getDelayedEvent(){return this.store.get(F("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(F("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(F("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(F("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(F("promptLastSeenTime"),0)}}class z{constructor(t,e=new K,s=new g){if("data"in t){const e=t;this.payload=e.data}else this.payload=t;this.data=e,this.code=`notificationCode-${Date.now()}-${Math.random().toString(16).slice(2,10)}`,this.dateModule=s}async getIcon(){return this.payload.i||await this.data.getDefaultNotificationImage()}async getTitle(){return this.payload.header||await this.data.getDefaultNotificationTitle()}get silent(){return Boolean(this.payload.silent)}get body(){return this.payload.body}get messageHash(){return this.payload.p||""}get metaData(){return this.payload.md?a(this.payload.md):{}}get image(){return this.payload.image||""}get buttons(){return this.payload.buttons?a(this.payload.buttons):[]}get customData(){return this.payload.u?a(this.payload.u):{}}get campaignCode(){return this.payload.pwcid||""}get link(){return this.payload.l?(t=this.payload.l)&&$.test(t)?t.replace(H,t=>B[t]):t:"/";var t}get inboxId(){return this.payload.pw_inbox||""}get inboxParams(){return this.payload.inbox_params?a(this.payload.inbox_params):{}}get inboxRemovalTime(){return this.inboxParams&&this.inboxParams.rt?this.inboxParams.rt:(this.dateModule.date=new Date,this.dateModule.addDays(1),this.dateModule.getUtcTimestamp().toString())}async getInboxImage(){return this.inboxParams&&this.inboxParams.image?this.inboxParams.image:""}get rootParams(){const{body:t,p:e,header:s,i:a,u:i,l:n,pwcid:r,image:o,buttons:c,pw_inbox:u,inbox_params:h,...d}=this.payload;return d}async getNotificationOptionsPayload(){const t=await this.getTitle(),e=await this.getIcon();return{...this.rootParams,body:this.body,title:t,icon:e,image:this.image,buttons:this.buttons,customData:this.customData,metaData:this.metaData,campaignCode:this.campaignCode,openUrl:this.link,messageHash:this.messageHash}}async getShowNotificationOptions(){const t=await this.getIcon(),e=this.buttons.map((t,e)=>(t.action=`action-${e}`,t));return{renotify:!0,...this.rootParams,body:this.body,icon:t,tag:JSON.stringify({url:this.link,messageHash:this.messageHash,customData:this.customData,metaData:this.metaData}),data:{code:this.code,buttons:e,image:this.image,campaignCode:this.campaignCode,inboxId:this.inboxId},silent:this.silent,actions:e,image:this.image,buttons:e}}async getInboxMessage(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString();return{title:this.payload.header||"",image:await this.getInboxImage(),status:1,order:this.dateModule.getInboxFakeOrder(),inbox_id:this.inboxId,send_date:t,rt:this.inboxRemovalTime,text:this.body,action_type:1,action_params:JSON.stringify({l:this.link})}}}class J{constructor(t=new K,e=k){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}applicationOpen(t){return this.createRequest("applicationOpen",t)}registerDevice(t){return this.createRequest("registerDevice",t)}unregisterDevice(t){return this.createRequest("unregisterDevice",t)}deleteDevice(t){return this.createRequest("deleteDevice",t)}messageDeliveryEvent(t){return this.createRequest("messageDeliveryEvent",t)}pushStat(t){return this.createRequest("pushStat",t)}setTags(t){return this.createRequest("setTags",t)}getTags(t){return this.createRequest("getTags",t)}registerUser(t){return this.createRequest("registerUser",t)}registerEmail(t){return this.createRequest("registerEmail",t)}registerEmailUser(t){return this.createRequest("registerEmailUser",t)}setEmailTags(t){return this.createRequest("setEmailTags",t)}postEvent(t){return this.createRequest("postEvent",t)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t){return this.createRequest("inboxStatus",t)}pageVisit(t,e){return this.createRequest("pageVisit",t,e)}setPurchase(t){return this.createRequest("setPurchase",t)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}async createRequest(t,e,s){const a=await this.data.getApiEntrypoint(),i=await this.data.getApiToken(),n=s||a+t,r=i?{headers:{Authorization:`Token ${i}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},o=await fetch(n,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...r}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(t){if(200!==t.status){let e=`status: ${t.status}. statusText: ${t.statusText}.`;try{const s=await t.json();s&&s.status_message&&(e+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(t){}throw new Error(e)}const e=await t.json();if(200!==e.status_code)throw new Error(`Error code: ${e.status_code}. Error text: ${e.status_message}`);return e}}class G{constructor(t,e,s){this.api=t,this.data=e,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return"granted"===this.getPermission()}checkIsPermissionDefault(){return"default"===this.getPermission()}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(t){const e=t||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void k.error("You must have permission granted before subscribe!");const s=this.getPushToken(e),a=e.getKey("p256dh"),i=e.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const n=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),r=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:n,pushToken:s,authToken:r,endpoint:e.endpoint}),await this.api.registerDevice()}async unsubscribe(){const t=await this.getServiceWorkerRegistration(),e=await t.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),e&&await e.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const t=await this.data.getLastPermissionStatus(),e=this.getPermission();if(t!==e)return await this.data.setLastPermissionStatus(e),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),n=a===(i&&i.pushToken||""),r=await this.data.getIsVapidChanged();return!n||r}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const t=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(t),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const t=await this.data.getServiceWorkerUrl(),e=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${i()}`),await navigator.serviceWorker.register(`${t}${s}`,{scope:e})}async trySubscribe(){try{return await this.subscribePushManager()}catch(t){return console.error(t),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const t=await this.getServiceWorkerRegistration(),e=await this.getApplicationServerKey();return t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e?this.urlBase64ToUint8Array(e):null})}async getCredentials(){const t=await this.getServiceWorkerRegistration();return await t.pushManager.getSubscription()}getPushToken(t){return t?t.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(e),a=new Uint8Array(s.length);for(let t=0;t<s.length;++t)a[t]=s.charCodeAt(t);return a}}class Y{constructor(t,e,s){this._canceled=!1,this.showNotificationOptions=t,this.body=e,this.title=s}async show(){if(this._canceled)return;const t=this.showNotificationOptions;t.silent||await self.registration.showNotification(this.title,t)}cancel(){this._canceled=!0}}const Q=new class{constructor(){this.addEventHandler=(t,e)=>{let s=this.handlers[t];s||(s=[]),s.push(e),this.handlers[t]=s},this.removeEventHandler=(t,e)=>{const s=this.handlers[t];s&&(this.handlers[t]=s.filter(t=>t!==e))},this.dispatchEvent=(t,e)=>{const s=e.eventId||i(),a=this.handlers[t];return a?(a.forEach(t=>{n(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}},X=new K,Z=new class{constructor(t,e=new K,s=new J,a=()=>!1){this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=a}async checkDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(a=!0){let i=localStorage.getItem(t);if(void 0===i||!a){const{exist:a,push_token_exist:n}=await this.checkDevice();localStorage.setItem(t,a&&n?e:s),i=localStorage.getItem(t)}return i===e}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(t)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const s=await this.getRequestParams(),a=await this.data.getTokens();if(!a.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=await this.apiClient.registerDevice({...s,push_token:a.pushToken,auth_token:a.authToken,public_key:a.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,e),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),a=await this.apiClient.unregisterDevice(e);return localStorage.setItem(t,s),this.eventBus.dispatchEvent("unsubscribe",{}),a}async deleteDevice(){const e=await this.getRequestParams(),a=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(t,s),this.eventBus.dispatchEvent("unsubscribe",{}),a}async messageDeliveryEvent(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:t,metaData:s})}async pushStat(t,e,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:t,metaData:s})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:e,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:t}),this.apiClient.setTags({...a,hwid:e,device_type:s,tags:t})}async getTags(){const t=await this.getRequestParams();return this.apiClient.getTags(t)}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),n=await this.data.getDeviceType(),r=`${t}`,o=await this.apiClient.registerUser({...i,hwid:s,userId:r,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:n});return await this.data.setUserId(r),e&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const{hwid:s,device_type:a,...i}=await this.getRequestParams(),n=await this.apiClient.registerEmail({...i,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),n}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),i}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:a}=await this.getRequestParams(),i=await this.apiClient.registerDevice({application:s,userId:a,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),i}async postEvent(t,e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams(),a=new Date,i=a.getTime(),n=Math.floor(i/1e3),r=n-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:t,timestampUTC:n,timestampCurrent:r,attributes:e});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(t=0){const e=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...e,count:t,last_code:s,last_request_time:a})}async inboxStatus(t,e){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:t,status:e,time:(new Date).getTime()})}async pageVisit(t){const e=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...e,...t},a)}async setPurchase(t){const e=await this.getRequestParams();return this.apiClient.setPurchase({...e,...t})}async multiRegisterDevice(s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const a=await this.data.getApplicationCode(),i=await this.data.getDeviceModel(),n=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),u=await this.data.getHwid(),h={application:a,...s};if(s.user_id){h.user_id=String(s.user_id);await this.data.getUserId()!==h.user_id&&(await this.data.setUserId(h.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(s.email){if(!/^\S+@\S+\.\S+$/.test(s.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==s.email&&(await this.data.setEmail(s.email),await this.data.setStatusEmailWasChanged(!0))}if(s.sms_phone_number){if(!/^\+?[0-9]+$/.test(s.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==s.sms_phone_number&&(await this.data.setSmsNumber(s.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(s.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(s.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==s.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(s.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(h.language?await this.data.setLanguage(h.language):h.language=r,!h.timezone){const t=60*-(new Date).getTimezoneOffset();h.timezone=String(t)}if(!h.push_devices&&c.pushToken){const t={hwid:u,platform:n,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||i){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),i&&(e.browser=i),t.platformData=e}h.push_devices=[t]}const d=await this.apiClient.multiRegisterDevice(h);return h.push_devices?.length&&(await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(t,e),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const t=await this.data.getApplicationCode(),e=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),n=await this.data.getLanguage(),r=await this.data.getSdkVersion();return{application:t,hwid:e,userId:s||e,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:n,v:r}}}(Q,X),tt=self.Pushwoosh=new class{constructor(t,e,s){this._listeners={},this.eventBus=t,this.data=e,this.api=s}push(t){Array.isArray(t)&&"onPush"===t[0]&&n(t[1])&&(this._listeners[t[0]]||(this._listeners[t[0]]=[]),this._listeners[t[0]].push(t[1]))}getListeners(t){return this._listeners[t]||[]}async initApi(){return Promise.resolve()}}(Q,X,Z),et=[];async function st(t){(await self.clients.matchAll()).forEach(e=>e.postMessage(t))}async function at(t){const{notification:e={}}=t,{data:s}=e,i=a(e.tag,{});let n="";if(t.action&&Array.isArray(s.buttons)){n=(s.buttons.find(e=>e.action===t.action)||{}).url}else n=i.url;return{title:e.title,body:e.body,icon:e.icon,buttons:s.buttons,image:s.image,code:s.code,campaignCode:s.campaignCode,inboxId:s.inboxId,messageHash:i.messageHash,customData:i.customData,metaData:i.metaData,openUrl:i.url,tag:e.tag,url:n}}async function it(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:t,applicationCode:e,workerVersion:s})}async function nt(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:t,applicationCode:e,workerVersion:s})}async function rt(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:t,applicationCode:e,workerVersion:s})}async function ot(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:t,applicationCode:e,workerVersion:s})}async function ct(t){const e=await tt.data.getApplicationCode(),s=await tt.data.getServiceWorkerVersion();await q({message:"Error in onPushSubscriptionChange",code:"FATAL-SW-006",error:t,applicationCode:e,workerVersion:s})}return self.addEventListener("install",function(t){return t.waitUntil(async function(){await Promise.all([tt.data.setServiceWorkerVersion("3.50.6"),k.write("info","install")]),await self.skipWaiting()}().catch(it))}),self.addEventListener("activate",function(t){t.waitUntil(async function(){await Promise.all([k.write("info","activate")]),await self.clients.claim()}().catch(nt))}),self.addEventListener("push",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await t.data.json(),s=new z(e),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),n=s.messageHash;await k.write("info",JSON.stringify(a),"onPush");const r=new Y(i,s.body,await s.getTitle()),o=tt.getListeners("onPush");await o.reduce((t,e)=>t.then(()=>e(r)),Promise.resolve());const c=[r.show(),C.add({payload:e,parsedPayload:a,showOptions:i}),st({type:"onPushDelivery",payload:a})];if(n&&c.push(tt.initApi().then(()=>tt.api.messageDeliveryEvent(n,!0,a.metaData))),""!==s.inboxId){const t=new j(tt.eventBus,tt.data,tt.api),e=new U(tt.data,tt.api,t),a=await s.getInboxMessage(),i=await e.publicMessageBuilder(a);c.push(t.putMessage(a),st({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(t).catch(e=>async function(t,e){const s=await tt.data.getApplicationCode(),a=await tt.data.getServiceWorkerVersion();await q({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:t,applicationCode:s,workerVersion:a}),t instanceof Error||(t=new Error(t));return C.add({error:`${t}`,stack:t.stack,payload:e.data&&e.data.text()})}(e,t)))}),self.addEventListener("notificationclick",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await at(t),{messageHash:s,metaData:a,url:i,code:n,inboxId:r}=e;if(n&&et.push(n),""!==r){const t=new j(tt.eventBus,tt.data,tt.api),e=await t.getMessage(r);e.status=3,await t.putMessage(e)}t.notification.close();const o={type:"onNotificationClick",payload:e};return i&&t.waitUntil(self.clients.matchAll({type:"window"}).then(t=>async function(t,e){const{hostname:s,pathname:a}=new URL(e,self.location.origin),i=t.find(t=>{const{hostname:e,pathname:i}=new URL(t.url);return e===s&&i===a});return i?(await i.focus(),!1):(await self.clients.openWindow(e).then(t=>{t&&t.focus()}),!0)}(t,i)).then(t=>{t&&tt.data.setDelayedEvent(o)})),Promise.all([tt.initApi().then(()=>tt.api.pushStat(s,!0,a)),tt.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),st(o)])}(t).catch(rt))}),self.addEventListener("notificationclose",function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await at(t),{code:s}=e;if(t.notification.close(),!s)return;const a=et.indexOf(s);if(!(a>=0))return st({type:"onNotificationClose",payload:e});et.splice(a,1)}(t).catch(ot))}),self.addEventListener("pushsubscriptionchange",async function(t){t.waitUntil(async function(t){let e=t.newSubscription;if(!e&&(e=await self.registration.pushManager.getSubscription(),!e))return;const s=new G(Z,X,{});await s.subscribe(e)}(t).catch(ct))}),{}})());
2
2
  //# sourceMappingURL=service-worker.js.map
@@ -1,2 +1,2 @@
1
- !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n=e();for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}(this,()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{PWSubscriptionPromptWidget:()=>i});const n={headerText:"Subscribe to our news",headerTextColor:"#000000",subheaderText:"Don't miss out on the latest news and updates!",subheaderTextColor:"#000000",buttonAcceptText:"Agree",buttonAcceptTextColor:"#1A72E8",buttonAcceptRound:"4px",buttonAcceptBackgroundColor:"#FFFFFF",buttonAcceptBorderColor:"#E3E4E8",buttonCancelText:"Deny",buttonCancelTextColor:"#1A72E8",buttonCancelRound:"4px",buttonCancelBackgroundColor:"#FFFFFF",buttonCancelBorderColor:"#E3E4E8",cappingCount:3,cappingDelay:144e5,backgroundColor:"#FFFFFF"},o="pushwoosh-subscription-widget";class i{constructor(t){this.pw=t}async run(){const{pw:t}=this,e=await t.data.getFeatures(),o=(t=>{const e=t.subscription_prompt_widget&&t.subscription_prompt_widget.params,o={cappingCount:n.cappingCount,cappingDelay:n.cappingDelay,...e};return e?o:n})(e),i=await(async(t,e)=>{const n=(new Date).getTime(),o=await e.data.getPromptDisplayCount(),i=await e.data.getPromptLastSeenTime(),r=t.cappingCount>o,s=n-i>t.cappingDelay;return r&&s})(o,t);if(!i)return;const r=e.subscription_prompt?.use_case,s="default"===r,c="not-set"===r&&t.initParams.autoSubscribe;(s||c)&&(this.init(o),this.show(),t.moduleRegistry.subscriptionPrompt=this),await(async t=>{const e=await t.data.getPromptDisplayCount(),n=(new Date).getTime();await t.data.setPromptDisplayCount(e+1),await t.data.setPromptLastSeenTime(n)})(t)}init(t){if(!this.getRootElement()){const e=(t=>`\n <div id="${o}-root" class="${o}">\n <div class="${o}__body">\n <div class="${o}__header">\n ${t.headerText}\n </div>\n <div class="${o}__description">\n ${t.subheaderText}\n </div>\n <div class="${o}__controls">\n <button type="button" id="${o}-decline" class="${o}__control ${o}__control_decline">\n ${t.buttonCancelText}\n </button>\n <button type="button" id="${o}-accept" class="${o}__control ${o}__control_accept">\n ${t.buttonAcceptText}\n </button>\n </div>\n </div>\n </div>\n `)(t),n=(t=>{const e=document.createElement("style");return e.innerHTML=`\n .${o} * {\n box-sizing: border-box!important;\n }\n \n .${o} {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n margin: 0 auto;\n width: 320px;\n display: none;\n z-index: 2147483648;\n opacity: 0.99;\n }\n \n .${o}_show {\n display: block;\n }\n \n .${o}__body {\n width: 320px;\n background-color: ${t.backgroundColor?t.backgroundColor:"#FFFFFF"};\n box-shadow: 0 9px 15px rgba(0, 0, 0, 0.1), 0 0 6px rgba(0, 0, 0, 0.06);\n border-radius: 4px;\n padding: 20px 20px 12px;\n }\n \n .${o}__header {\n color: ${t.headerTextColor};\n font-size: 18px;\n font-weight: bold; \n }\n \n .${o}__description {\n color: ${t.subheaderTextColor};\n font-size: 14px;\n line-height: 1.5;\n margin-top: 14px;\n }\n \n .${o}__description:empty {\n display: none;\n }\n \n .${o}__controls {\n display: flex;\n flex-wrap: nowrap;\n justify-content: flex-end;\n margin: 20px 0 0;\n }\n \n .${o}__control {\n -webkit-appearance: none;\n border: 1px solid transparent;\n font-size: 12px;\n font-weight: bold;\n padding: 0 20px;\n height: 32px;\n cursor: pointer;\n }\n \n .${o}__control_decline {\n color: ${t.buttonCancelTextColor};\n background-color: ${t.buttonCancelBackgroundColor};\n border-radius: ${t.buttonCancelRound};\n border-color: ${t.buttonCancelBorderColor};\n }\n \n .${o}__control_accept {\n color: ${t.buttonAcceptTextColor};\n background-color: ${t.buttonAcceptBackgroundColor};\n border-radius: ${t.buttonAcceptRound};\n border-color: ${t.buttonAcceptBorderColor};\n margin: 0 0 0 12px;\n }\n `,e})(t);document.body.insertAdjacentHTML("beforeend",e),document.head.appendChild(n)}this.addEventListeners()}show(){const t=this.getRootElementWithCheckExist();this.pw.dispatchEvent("show-subscription-widget",{}),t.classList.add(`${o}_show`)}hide(){const t=this.getRootElementWithCheckExist();t.classList.contains(`${o}_show`)&&(this.pw.dispatchEvent("hide-subscription-widget",{}),t.classList.remove(`${o}_show`))}getRootElement(){return document.getElementById(`${o}-root`)}getRootElementWithCheckExist(){const t=this.getRootElement();if(!t)throw new Error(`Can't find element by id "${o}-root", please use method init first.`);return t}getDeclineButtonWithCheckExist(){const t=document.getElementById(`${o}-decline`);if(!t)throw new Error(`Can't find element by id "${o}-decline", please use method init first.`);return t}getAcceptButtonWithCheckExist(){const t=document.getElementById(`${o}-accept`);if(!t)throw new Error(`Can't find element by id "${o}-accept", please use method init first.`);return t}addEventListeners(){const t=this.getRootElementWithCheckExist(),e=this.getDeclineButtonWithCheckExist(),n=this.getAcceptButtonWithCheckExist();document.addEventListener("click",e=>{t.contains(e.target)||this.hide()}),e.addEventListener("click",()=>{this.hide()}),n.addEventListener("click",()=>{this.hide(),this.pw.subscribe()})}}return e})());
1
+ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n=e();for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}(this,()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{PWSubscriptionPromptWidget:()=>i});const n={headerText:"Subscribe to our news",headerTextColor:"#000000",subheaderText:"Don't miss out on the latest news and updates!",subheaderTextColor:"#000000",buttonAcceptText:"Agree",buttonAcceptTextColor:"#1A72E8",buttonAcceptRound:"4px",buttonAcceptBackgroundColor:"#FFFFFF",buttonAcceptBorderColor:"#E3E4E8",buttonCancelText:"Deny",buttonCancelTextColor:"#1A72E8",buttonCancelRound:"4px",buttonCancelBackgroundColor:"#FFFFFF",buttonCancelBorderColor:"#E3E4E8",cappingCount:3,cappingDelay:144e5,backgroundColor:"#FFFFFF"},o="pushwoosh-subscription-widget";class i{constructor(t){this.pw=t}async run(){const{pw:t}=this,e=await t.data.getFeatures(),o=(t=>{const e=t.subscription_prompt_widget&&t.subscription_prompt_widget.params,o={cappingCount:n.cappingCount,cappingDelay:n.cappingDelay,...e};return e?o:n})(e),i=await(async(t,e)=>{const n=(new Date).getTime(),o=await e.data.getPromptDisplayCount(),i=await e.data.getPromptLastSeenTime(),r=t.cappingCount>o,s=n-i>t.cappingDelay;return r&&s})(o,t);if(!i)return;const r=e.subscription_prompt?.use_case,s="default"===r,c="not-set"===r&&t.initParams.autoSubscribe;(s||c)&&(this.init(o),this.show(),t.moduleRegistry.subscriptionPrompt=this,await(async t=>{const e=await t.data.getPromptDisplayCount(),n=(new Date).getTime();await t.data.setPromptDisplayCount(e+1),await t.data.setPromptLastSeenTime(n)})(t))}init(t){if(!this.getRootElement()){const e=(t=>`\n <div id="${o}-root" class="${o}">\n <div class="${o}__body">\n <div class="${o}__header">\n ${t.headerText}\n </div>\n <div class="${o}__description">\n ${t.subheaderText}\n </div>\n <div class="${o}__controls">\n <button type="button" id="${o}-decline" class="${o}__control ${o}__control_decline">\n ${t.buttonCancelText}\n </button>\n <button type="button" id="${o}-accept" class="${o}__control ${o}__control_accept">\n ${t.buttonAcceptText}\n </button>\n </div>\n </div>\n </div>\n `)(t),n=(t=>{const e=document.createElement("style");return e.innerHTML=`\n .${o} * {\n box-sizing: border-box!important;\n }\n \n .${o} {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n margin: 0 auto;\n width: 320px;\n display: none;\n z-index: 2147483648;\n opacity: 0.99;\n }\n \n .${o}_show {\n display: block;\n }\n \n .${o}__body {\n width: 320px;\n background-color: ${t.backgroundColor?t.backgroundColor:"#FFFFFF"};\n box-shadow: 0 9px 15px rgba(0, 0, 0, 0.1), 0 0 6px rgba(0, 0, 0, 0.06);\n border-radius: 4px;\n padding: 20px 20px 12px;\n }\n \n .${o}__header {\n color: ${t.headerTextColor};\n font-size: 18px;\n font-weight: bold; \n }\n \n .${o}__description {\n color: ${t.subheaderTextColor};\n font-size: 14px;\n line-height: 1.5;\n margin-top: 14px;\n }\n \n .${o}__description:empty {\n display: none;\n }\n \n .${o}__controls {\n display: flex;\n flex-wrap: nowrap;\n justify-content: flex-end;\n margin: 20px 0 0;\n }\n \n .${o}__control {\n -webkit-appearance: none;\n border: 1px solid transparent;\n font-size: 12px;\n font-weight: bold;\n padding: 0 20px;\n height: 32px;\n cursor: pointer;\n }\n \n .${o}__control_decline {\n color: ${t.buttonCancelTextColor};\n background-color: ${t.buttonCancelBackgroundColor};\n border-radius: ${t.buttonCancelRound};\n border-color: ${t.buttonCancelBorderColor};\n }\n \n .${o}__control_accept {\n color: ${t.buttonAcceptTextColor};\n background-color: ${t.buttonAcceptBackgroundColor};\n border-radius: ${t.buttonAcceptRound};\n border-color: ${t.buttonAcceptBorderColor};\n margin: 0 0 0 12px;\n }\n `,e})(t);document.body.insertAdjacentHTML("beforeend",e),document.head.appendChild(n)}this.addEventListeners()}show(){const t=this.getRootElementWithCheckExist();this.pw.dispatchEvent("show-subscription-widget",{}),t.classList.add(`${o}_show`)}hide(){const t=this.getRootElementWithCheckExist();t.classList.contains(`${o}_show`)&&(this.pw.dispatchEvent("hide-subscription-widget",{}),t.classList.remove(`${o}_show`))}getRootElement(){return document.getElementById(`${o}-root`)}getRootElementWithCheckExist(){const t=this.getRootElement();if(!t)throw new Error(`Can't find element by id "${o}-root", please use method init first.`);return t}getDeclineButtonWithCheckExist(){const t=document.getElementById(`${o}-decline`);if(!t)throw new Error(`Can't find element by id "${o}-decline", please use method init first.`);return t}getAcceptButtonWithCheckExist(){const t=document.getElementById(`${o}-accept`);if(!t)throw new Error(`Can't find element by id "${o}-accept", please use method init first.`);return t}addEventListeners(){const t=this.getRootElementWithCheckExist(),e=this.getDeclineButtonWithCheckExist(),n=this.getAcceptButtonWithCheckExist();document.addEventListener("click",e=>{t.contains(e.target)||this.hide()}),e.addEventListener("click",()=>{this.hide()}),n.addEventListener("click",()=>{this.hide(),this.pw.subscribe()})}}return e})());
2
2
  //# sourceMappingURL=widget-subscription-prompt.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"widget-subscription-prompt.js","mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,SACb,GAAqB,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,OACP,CACJ,IAAIK,EAAIL,IACR,IAAI,IAAIM,KAAKD,GAAuB,iBAAZJ,QAAuBA,QAAUF,GAAMO,GAAKD,EAAEC,EACvE,CACA,CATD,CASGC,KAAM,I,mBCRT,IAAIC,EAAsB,CCA1BA,EAAwB,CAACP,EAASQ,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAEV,EAASS,IAC5EE,OAAOC,eAAeZ,EAASS,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBP,IACH,oBAAXoB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeZ,EAASoB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeZ,EAAS,aAAc,CAAEsB,OAAO,M,sDCLhD,MAGMC,EAA4C,CACvDC,WAAY,wBACZC,gBAAiB,UACjBC,cAAe,iDACfC,mBAAoB,UACpBC,iBAAkB,QAClBC,sBAAuB,UACvBC,kBAAmB,MACnBC,4BAA6B,UAC7BC,wBAAyB,UACzBC,iBAAkB,OAClBC,sBAAuB,UACvBC,kBAAmB,MACnBC,4BAA6B,UAC7BC,wBAAyB,UACzBC,aAAc,EACdC,aAAc,MACdC,gBAAiB,WCpBNC,EAAuC,gCCO7C,MAAMC,EAGX,WAAAC,CAAYC,GACVtC,KAAKsC,GAAKA,CACZ,CAEO,SAAMC,GACX,MAAM,GAAED,GAAOtC,KAETwC,QAAiBF,EAAGG,KAAKC,cACzBC,ECdqB,CAACH,IAE9B,MAAMI,EAAgBJ,EAAqC,4BAAKA,EAAqC,2BAAEK,OAGjGC,EAA4D,CAChEd,aAAcf,EAA0Ce,aACxDC,aAAchB,EAA0CgB,gBACrDW,GAIL,OAAOA,EACHE,EACA7B,GDAmB8B,CAAgBP,GAC/BQ,OCE2BC,OAAON,EAA+CL,KACzF,MAAMY,GAAc,IAAIC,MAAOC,UACzBC,QAAqBf,EAAGG,KAAKa,wBAC7BC,QAAqBjB,EAAGG,KAAKe,wBAG7BR,EAAmBL,EAAaX,aAAeqB,EAG/CI,EAAoBP,EAAcK,EAAeZ,EAAaV,aAEpE,OAAOe,GAAoBS,GDbMC,CAAsBf,EAAcL,GACnE,IAAKU,EACH,OAGF,MAAMW,EAAuBnB,EAA8B,qBAAc,SAGnEoB,EF1B0C,YE0BvBD,EACnBE,EF5B0C,YE4BxBF,GAAiErB,EAAGwB,WAAWC,eAGnGH,GAAoBC,KACtB7D,KAAKgE,KAAKrB,GACV3C,KAAKiE,OACL3B,EAAG4B,eAAeC,mBAAqBnE,WCCViD,OAAOX,IACxC,MAAMe,QAAqBf,EAAGG,KAAKa,wBAC7BJ,GAAc,IAAIC,MAAOC,gBAEzBd,EAAGG,KAAK2B,sBAAsBf,EAAe,SAC7Cf,EAAGG,KAAK4B,sBAAsBnB,IDH5BoB,CAAoBhC,EAC5B,CAEO,IAAA0B,CAAKnB,GAKV,IAJoB7C,KAAKuE,iBAIP,CAChB,MAAMC,EE3CW,CAAC3B,GACf,gBACIV,kBAAqDA,wBAChDA,gCACEA,wBACVU,EAAO3B,+CAEGiB,6BACVU,EAAOzB,kDAEGe,oDACgBA,qBAAwDA,cAAiDA,mCACjIU,EAAOlB,0EAEiBQ,oBAAuDA,cAAiDA,kCAChIU,EAAOvB,8EF4BAmD,CAAQ5B,GACf6B,EErBa,CAAC7B,IACxB,MAAM6B,EAASC,SAASC,cAAc,SAiFtC,OA/EAF,EAAOG,UAAY,UACd1C,mEAIAA,sNAYAA,sDAIAA,2DAEmBU,EAAOX,gBAAkBW,EAAOX,gBAAkB,2KAMrEC,6BACQU,EAAO1B,0FAKfgB,kCACQU,EAAOxB,oHAMfc,mEAIAA,+IAOAA,iOAUAA,sCACQU,EAAOjB,mDACIiB,EAAOf,sDACVe,EAAOhB,2CACRgB,EAAOd,+CAGtBI,qCACQU,EAAOtB,mDACIsB,EAAOpB,sDACVoB,EAAOrB,2CACRqB,EAAOnB,iEAKpBgD,GF7DYI,CAAUjC,GAGzB8B,SAASI,KAAKC,mBAAmB,YAAaR,GAG9CG,SAASM,KAAKC,YAAYR,EAC5B,CAEA1E,KAAKmF,mBACP,CAEO,IAAAlB,GACL,MAAMmB,EAAcpF,KAAKqF,+BACzBrF,KAAKsC,GAAGgD,cAAc,2BAA4B,CAAC,GAEnDF,EAAYG,UAAUC,IAAI,GAAGrD,SAC/B,CAEO,IAAAsD,GACL,MAAML,EAAcpF,KAAKqF,+BAErBD,EAAYG,UAAUG,SAAS,GAAGvD,YACpCnC,KAAKsC,GAAGgD,cAAc,2BAA4B,CAAC,GACnDF,EAAYG,UAAUI,OAAO,GAAGxD,UAEpC,CAEQ,cAAAoC,GACN,OAAOI,SAASiB,eAAe,GAAGzD,SACpC,CAEQ,4BAAAkD,GACN,MAAMQ,EAAU7F,KAAKuE,iBAErB,IAAKsB,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,0CAG/C,OAAO0D,CACT,CAEQ,8BAAAE,GACN,MAAMF,EAAUlB,SAASiB,eAAe,GAAGzD,aAE3C,IAAK0D,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,6CAG/C,OAAO0D,CACT,CAEQ,6BAAAG,GACN,MAAMH,EAAUlB,SAASiB,eAAe,GAAGzD,YAE3C,IAAK0D,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,4CAG/C,OAAO0D,CACT,CAEQ,iBAAAV,GACN,MAAMC,EAAcpF,KAAKqF,+BACnBY,EAAiBjG,KAAK+F,iCACtBG,EAAgBlG,KAAKgG,gCAE3BrB,SAASwB,iBAAiB,QAAUC,IAC7BhB,EAAYM,SAAUU,EAAMC,SAC/BrG,KAAKyF,SAITQ,EAAeE,iBAAiB,QAAS,KACvCnG,KAAKyF,SAGPS,EAAcC,iBAAiB,QAAS,KACtCnG,KAAKyF,OACLzF,KAAKsC,GAAGgE,aAEZ,E","sources":["webpack://web-push-notifications/webpack/universalModuleDefinition","webpack://web-push-notifications/webpack/bootstrap","webpack://web-push-notifications/webpack/runtime/define property getters","webpack://web-push-notifications/webpack/runtime/hasOwnProperty shorthand","webpack://web-push-notifications/webpack/runtime/make namespace object","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/helpers.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.helpers.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export const SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET = 'not-set';\nexport const SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT = 'default';\n\nexport const SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG = {\n headerText: 'Subscribe to our news',\n headerTextColor: '#000000',\n subheaderText: 'Don\\'t miss out on the latest news and updates!',\n subheaderTextColor: '#000000',\n buttonAcceptText: 'Agree',\n buttonAcceptTextColor: '#1A72E8',\n buttonAcceptRound: '4px',\n buttonAcceptBackgroundColor: '#FFFFFF',\n buttonAcceptBorderColor: '#E3E4E8',\n buttonCancelText: 'Deny',\n buttonCancelTextColor: '#1A72E8',\n buttonCancelRound: '4px',\n buttonCancelBackgroundColor: '#FFFFFF',\n buttonCancelBorderColor: '#E3E4E8',\n cappingCount: 3,\n cappingDelay: 1000 * 60 * 60 * 4, // time in ms\n backgroundColor: '#FFFFFF',\n};\n","export const SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE = 'pushwoosh-subscription-widget';\n","import { SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT, SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET } from './constants';\nimport { checkCanShowByCapping, getWidgetConfig, updateCappingParams } from './helpers';\nimport { SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE } from './SubscriptionPromptWidget.constants';\nimport { getHTML, getStyles } from './SubscriptionPromptWidget.helpers';\nimport { type ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\nimport { type Pushwoosh } from '../../core/Pushwoosh';\n\nexport class PWSubscriptionPromptWidget {\n private readonly pw: Pushwoosh;\n\n constructor(pw: Pushwoosh) {\n this.pw = pw;\n };\n\n public async run(): Promise<void> {\n const { pw } = this;\n\n const features = await pw.data.getFeatures();\n const widgetConfig = getWidgetConfig(features);\n const canShowByCapping = await checkCanShowByCapping(widgetConfig, pw);\n if (!canShowByCapping) {\n return;\n }\n\n const currentPromptUseCase = features['subscription_prompt']?.['use_case'];\n\n // show subscription prompt widget\n const isDefaultUseCase = currentPromptUseCase === SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT;\n const isNotSetUseCase = currentPromptUseCase === SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET && pw.initParams.autoSubscribe;\n\n // show subscription prompt widget\n if (isDefaultUseCase || isNotSetUseCase) {\n this.init(widgetConfig);\n this.show();\n pw.moduleRegistry.subscriptionPrompt = this;\n }\n\n await updateCappingParams(pw);\n }\n\n public init(params: ISubscriptionPromptWidgetParams): void {\n const rootElement = this.getRootElement();\n\n // if root element not exist\n // create widget\n if (!rootElement) {\n const html = getHTML(params);\n const styles = getStyles(params);\n\n // append popup to body\n document.body.insertAdjacentHTML('beforeend', html);\n\n // append styles to head\n document.head.appendChild(styles);\n }\n\n this.addEventListeners();\n }\n\n public show(): void {\n const rootElement = this.getRootElementWithCheckExist();\n this.pw.dispatchEvent('show-subscription-widget', {});\n\n rootElement.classList.add(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`);\n }\n\n public hide(): void {\n const rootElement = this.getRootElementWithCheckExist();\n\n if (rootElement.classList.contains(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`)) {\n this.pw.dispatchEvent('hide-subscription-widget', {});\n rootElement.classList.remove(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`);\n }\n }\n\n private getRootElement(): HTMLElement | null {\n return document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root`);\n }\n\n private getRootElementWithCheckExist(): HTMLElement {\n const element = this.getRootElement();\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root\", please use method init first.`);\n }\n\n return element;\n }\n\n private getDeclineButtonWithCheckExist(): HTMLButtonElement {\n const element = document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline`) as HTMLButtonElement;\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline\", please use method init first.`);\n }\n\n return element;\n }\n\n private getAcceptButtonWithCheckExist(): HTMLButtonElement {\n const element = document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept`) as HTMLButtonElement;\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept\", please use method init first.`);\n }\n\n return element;\n }\n\n private addEventListeners(): void {\n const rootElement = this.getRootElementWithCheckExist();\n const declineElement = this.getDeclineButtonWithCheckExist();\n const acceptElement = this.getAcceptButtonWithCheckExist();\n\n document.addEventListener('click', (event) => {\n if (!rootElement.contains((event.target as HTMLElement))) {\n this.hide();\n }\n });\n\n declineElement.addEventListener('click', () => {\n this.hide();\n });\n\n acceptElement.addEventListener('click', () => {\n this.hide();\n this.pw.subscribe();\n });\n }\n}\n","import { SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG } from './constants';\nimport type { ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\nimport type { Pushwoosh } from '../../core/Pushwoosh';\n\nexport const getWidgetConfig = (features: any): ISubscriptionPromptWidgetParams => {\n // get config by features from get config method\n const currentConfig = features['subscription_prompt_widget'] && features['subscription_prompt_widget'].params;\n\n // merge current config with capping defaults\n const configWithDefaultCapping: ISubscriptionPromptWidgetParams = {\n cappingCount: SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingCount,\n cappingDelay: SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingDelay,\n ...currentConfig,\n };\n\n // if current config is not exist show with default values\n return currentConfig\n ? configWithDefaultCapping\n : SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG;\n};\n\nexport const checkCanShowByCapping = async (widgetConfig: ISubscriptionPromptWidgetParams, pw: Pushwoosh): Promise<boolean> => {\n const currentTime = new Date().getTime();\n const displayCount = await pw.data.getPromptDisplayCount();\n const lastSeenTime = await pw.data.getPromptLastSeenTime();\n\n // can show by max display count\n const canShowByCapping = widgetConfig.cappingCount > displayCount;\n\n // can show last seen time\n const canShowByLastTime = currentTime - lastSeenTime > widgetConfig.cappingDelay;\n\n return canShowByCapping && canShowByLastTime;\n};\n\nexport const updateCappingParams = async (pw: Pushwoosh): Promise<void> => {\n const displayCount = await pw.data.getPromptDisplayCount();\n const currentTime = new Date().getTime();\n\n await pw.data.setPromptDisplayCount(displayCount + 1);\n await pw.data.setPromptLastSeenTime(currentTime);\n};\n","import { SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE } from './SubscriptionPromptWidget.constants';\nimport { type ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\n\nexport const getHTML = (params: ISubscriptionPromptWidgetParams): string => {\n return `\n <div id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}\">\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__body\">\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__header\">\n ${params.headerText}\n </div>\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description\">\n ${params.subheaderText}\n </div>\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__controls\">\n <button type=\"button\" id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control ${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_decline\">\n ${params.buttonCancelText}\n </button>\n <button type=\"button\" id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control ${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_accept\">\n ${params.buttonAcceptText}\n </button>\n </div>\n </div>\n </div>\n `;\n};\n\nexport const getStyles = (params: ISubscriptionPromptWidgetParams) => {\n const styles = document.createElement('style');\n\n styles.innerHTML = `\n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE} * {\n box-sizing: border-box!important;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE} {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n margin: 0 auto;\n width: 320px;\n display: none;\n z-index: 2147483648;\n opacity: 0.99;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show {\n display: block;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__body {\n width: 320px;\n background-color: ${params.backgroundColor ? params.backgroundColor : '#FFFFFF'};\n box-shadow: 0 9px 15px rgba(0, 0, 0, 0.1), 0 0 6px rgba(0, 0, 0, 0.06);\n border-radius: 4px;\n padding: 20px 20px 12px;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__header {\n color: ${params.headerTextColor};\n font-size: 18px;\n font-weight: bold; \n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description {\n color: ${params.subheaderTextColor};\n font-size: 14px;\n line-height: 1.5;\n margin-top: 14px;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description:empty {\n display: none;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__controls {\n display: flex;\n flex-wrap: nowrap;\n justify-content: flex-end;\n margin: 20px 0 0;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control {\n -webkit-appearance: none;\n border: 1px solid transparent;\n font-size: 12px;\n font-weight: bold;\n padding: 0 20px;\n height: 32px;\n cursor: pointer;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_decline {\n color: ${params.buttonCancelTextColor};\n background-color: ${params.buttonCancelBackgroundColor};\n border-radius: ${params.buttonCancelRound};\n border-color: ${params.buttonCancelBorderColor};\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_accept {\n color: ${params.buttonAcceptTextColor};\n background-color: ${params.buttonAcceptBackgroundColor};\n border-radius: ${params.buttonAcceptRound};\n border-color: ${params.buttonAcceptBorderColor};\n margin: 0 0 0 12px;\n }\n `;\n\n return styles;\n};\n"],"names":["root","factory","exports","module","define","amd","a","i","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG","headerText","headerTextColor","subheaderText","subheaderTextColor","buttonAcceptText","buttonAcceptTextColor","buttonAcceptRound","buttonAcceptBackgroundColor","buttonAcceptBorderColor","buttonCancelText","buttonCancelTextColor","buttonCancelRound","buttonCancelBackgroundColor","buttonCancelBorderColor","cappingCount","cappingDelay","backgroundColor","SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE","PWSubscriptionPromptWidget","constructor","pw","run","features","data","getFeatures","widgetConfig","currentConfig","params","configWithDefaultCapping","getWidgetConfig","canShowByCapping","async","currentTime","Date","getTime","displayCount","getPromptDisplayCount","lastSeenTime","getPromptLastSeenTime","canShowByLastTime","checkCanShowByCapping","currentPromptUseCase","isDefaultUseCase","isNotSetUseCase","initParams","autoSubscribe","init","show","moduleRegistry","subscriptionPrompt","setPromptDisplayCount","setPromptLastSeenTime","updateCappingParams","getRootElement","html","getHTML","styles","document","createElement","innerHTML","getStyles","body","insertAdjacentHTML","head","appendChild","addEventListeners","rootElement","getRootElementWithCheckExist","dispatchEvent","classList","add","hide","contains","remove","getElementById","element","Error","getDeclineButtonWithCheckExist","getAcceptButtonWithCheckExist","declineElement","acceptElement","addEventListener","event","target","subscribe"],"sourceRoot":""}
1
+ {"version":3,"file":"widget-subscription-prompt.js","mappings":"CAAA,SAA2CA,EAAMC,GAChD,GAAsB,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,SACb,GAAqB,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,OACP,CACJ,IAAIK,EAAIL,IACR,IAAI,IAAIM,KAAKD,GAAuB,iBAAZJ,QAAuBA,QAAUF,GAAMO,GAAKD,EAAEC,EACvE,CACA,CATD,CASGC,KAAM,I,mBCRT,IAAIC,EAAsB,CCA1BA,EAAwB,CAACP,EAASQ,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAEV,EAASS,IAC5EE,OAAOC,eAAeZ,EAASS,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBP,IACH,oBAAXoB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeZ,EAASoB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeZ,EAAS,aAAc,CAAEsB,OAAO,M,sDCLhD,MAGMC,EAA4C,CACvDC,WAAY,wBACZC,gBAAiB,UACjBC,cAAe,iDACfC,mBAAoB,UACpBC,iBAAkB,QAClBC,sBAAuB,UACvBC,kBAAmB,MACnBC,4BAA6B,UAC7BC,wBAAyB,UACzBC,iBAAkB,OAClBC,sBAAuB,UACvBC,kBAAmB,MACnBC,4BAA6B,UAC7BC,wBAAyB,UACzBC,aAAc,EACdC,aAAc,MACdC,gBAAiB,WCpBNC,EAAuC,gCCO7C,MAAMC,EAGX,WAAAC,CAAYC,GACVtC,KAAKsC,GAAKA,CACZ,CAEO,SAAMC,GACX,MAAM,GAAED,GAAOtC,KAETwC,QAAiBF,EAAGG,KAAKC,cACzBC,ECdqB,CAACH,IAE9B,MAAMI,EAAgBJ,EAAqC,4BAAKA,EAAqC,2BAAEK,OAGjGC,EAA4D,CAChEd,aAAcf,EAA0Ce,aACxDC,aAAchB,EAA0CgB,gBACrDW,GAIL,OAAOA,EACHE,EACA7B,GDAmB8B,CAAgBP,GAC/BQ,OCE2BC,OAAON,EAA+CL,KACzF,MAAMY,GAAc,IAAIC,MAAOC,UACzBC,QAAqBf,EAAGG,KAAKa,wBAC7BC,QAAqBjB,EAAGG,KAAKe,wBAG7BR,EAAmBL,EAAaX,aAAeqB,EAG/CI,EAAoBP,EAAcK,EAAeZ,EAAaV,aAEpE,OAAOe,GAAoBS,GDbMC,CAAsBf,EAAcL,GACnE,IAAKU,EACH,OAGF,MAAMW,EAAuBnB,EAA8B,qBAAc,SAGnEoB,EF1B0C,YE0BvBD,EACnBE,EF5B0C,YE4BxBF,GAAiErB,EAAGwB,WAAWC,eAGnGH,GAAoBC,KACtB7D,KAAKgE,KAAKrB,GACV3C,KAAKiE,OACL3B,EAAG4B,eAAeC,mBAAqBnE,UCCViD,OAAOX,IACxC,MAAMe,QAAqBf,EAAGG,KAAKa,wBAC7BJ,GAAc,IAAIC,MAAOC,gBAEzBd,EAAGG,KAAK2B,sBAAsBf,EAAe,SAC7Cf,EAAGG,KAAK4B,sBAAsBnB,IDL1BoB,CAAoBhC,GAE9B,CAEO,IAAA0B,CAAKnB,GAKV,IAJoB7C,KAAKuE,iBAIP,CAChB,MAAMC,EE1CW,CAAC3B,GACf,gBACIV,kBAAqDA,wBAChDA,gCACEA,wBACVU,EAAO3B,+CAEGiB,6BACVU,EAAOzB,kDAEGe,oDACgBA,qBAAwDA,cAAiDA,mCACjIU,EAAOlB,0EAEiBQ,oBAAuDA,cAAiDA,kCAChIU,EAAOvB,8EF2BAmD,CAAQ5B,GACf6B,EEpBa,CAAC7B,IACxB,MAAM6B,EAASC,SAASC,cAAc,SAiFtC,OA/EAF,EAAOG,UAAY,UACd1C,mEAIAA,sNAYAA,sDAIAA,2DAEmBU,EAAOX,gBAAkBW,EAAOX,gBAAkB,2KAMrEC,6BACQU,EAAO1B,0FAKfgB,kCACQU,EAAOxB,oHAMfc,mEAIAA,+IAOAA,iOAUAA,sCACQU,EAAOjB,mDACIiB,EAAOf,sDACVe,EAAOhB,2CACRgB,EAAOd,+CAGtBI,qCACQU,EAAOtB,mDACIsB,EAAOpB,sDACVoB,EAAOrB,2CACRqB,EAAOnB,iEAKpBgD,GF9DYI,CAAUjC,GAGzB8B,SAASI,KAAKC,mBAAmB,YAAaR,GAG9CG,SAASM,KAAKC,YAAYR,EAC5B,CAEA1E,KAAKmF,mBACP,CAEO,IAAAlB,GACL,MAAMmB,EAAcpF,KAAKqF,+BACzBrF,KAAKsC,GAAGgD,cAAc,2BAA4B,CAAC,GAEnDF,EAAYG,UAAUC,IAAI,GAAGrD,SAC/B,CAEO,IAAAsD,GACL,MAAML,EAAcpF,KAAKqF,+BAErBD,EAAYG,UAAUG,SAAS,GAAGvD,YACpCnC,KAAKsC,GAAGgD,cAAc,2BAA4B,CAAC,GACnDF,EAAYG,UAAUI,OAAO,GAAGxD,UAEpC,CAEQ,cAAAoC,GACN,OAAOI,SAASiB,eAAe,GAAGzD,SACpC,CAEQ,4BAAAkD,GACN,MAAMQ,EAAU7F,KAAKuE,iBAErB,IAAKsB,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,0CAG/C,OAAO0D,CACT,CAEQ,8BAAAE,GACN,MAAMF,EAAUlB,SAASiB,eAAe,GAAGzD,aAE3C,IAAK0D,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,6CAG/C,OAAO0D,CACT,CAEQ,6BAAAG,GACN,MAAMH,EAAUlB,SAASiB,eAAe,GAAGzD,YAE3C,IAAK0D,EACH,MAAM,IAAIC,MAAM,6BAA6B3D,4CAG/C,OAAO0D,CACT,CAEQ,iBAAAV,GACN,MAAMC,EAAcpF,KAAKqF,+BACnBY,EAAiBjG,KAAK+F,iCACtBG,EAAgBlG,KAAKgG,gCAE3BrB,SAASwB,iBAAiB,QAAUC,IAC7BhB,EAAYM,SAAUU,EAAMC,SAC/BrG,KAAKyF,SAITQ,EAAeE,iBAAiB,QAAS,KACvCnG,KAAKyF,SAGPS,EAAcC,iBAAiB,QAAS,KACtCnG,KAAKyF,OACLzF,KAAKsC,GAAGgE,aAEZ,E","sources":["webpack://web-push-notifications/webpack/universalModuleDefinition","webpack://web-push-notifications/webpack/bootstrap","webpack://web-push-notifications/webpack/runtime/define property getters","webpack://web-push-notifications/webpack/runtime/hasOwnProperty shorthand","webpack://web-push-notifications/webpack/runtime/make namespace object","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.constants.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/helpers.ts","webpack://web-push-notifications/./src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.helpers.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export const SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET = 'not-set';\nexport const SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT = 'default';\n\nexport const SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG = {\n headerText: 'Subscribe to our news',\n headerTextColor: '#000000',\n subheaderText: 'Don\\'t miss out on the latest news and updates!',\n subheaderTextColor: '#000000',\n buttonAcceptText: 'Agree',\n buttonAcceptTextColor: '#1A72E8',\n buttonAcceptRound: '4px',\n buttonAcceptBackgroundColor: '#FFFFFF',\n buttonAcceptBorderColor: '#E3E4E8',\n buttonCancelText: 'Deny',\n buttonCancelTextColor: '#1A72E8',\n buttonCancelRound: '4px',\n buttonCancelBackgroundColor: '#FFFFFF',\n buttonCancelBorderColor: '#E3E4E8',\n cappingCount: 3,\n cappingDelay: 1000 * 60 * 60 * 4, // time in ms\n backgroundColor: '#FFFFFF',\n};\n","export const SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE = 'pushwoosh-subscription-widget';\n","import { SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT, SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET } from './constants';\nimport { checkCanShowByCapping, getWidgetConfig, updateCappingParams } from './helpers';\nimport { SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE } from './SubscriptionPromptWidget.constants';\nimport { getHTML, getStyles } from './SubscriptionPromptWidget.helpers';\nimport { type ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\nimport { type Pushwoosh } from '../../core/Pushwoosh';\n\nexport class PWSubscriptionPromptWidget {\n private readonly pw: Pushwoosh;\n\n constructor(pw: Pushwoosh) {\n this.pw = pw;\n };\n\n public async run(): Promise<void> {\n const { pw } = this;\n\n const features = await pw.data.getFeatures();\n const widgetConfig = getWidgetConfig(features);\n const canShowByCapping = await checkCanShowByCapping(widgetConfig, pw);\n if (!canShowByCapping) {\n return;\n }\n\n const currentPromptUseCase = features['subscription_prompt']?.['use_case'];\n\n // show subscription prompt widget\n const isDefaultUseCase = currentPromptUseCase === SUBSCRIPTION_WIDGET_USE_CASE_DEFAULT;\n const isNotSetUseCase = currentPromptUseCase === SUBSCRIPTION_WIDGET_USE_CASE_NOT_SET && pw.initParams.autoSubscribe;\n\n // show subscription prompt widget\n if (isDefaultUseCase || isNotSetUseCase) {\n this.init(widgetConfig);\n this.show();\n pw.moduleRegistry.subscriptionPrompt = this;\n await updateCappingParams(pw);\n }\n }\n\n public init(params: ISubscriptionPromptWidgetParams): void {\n const rootElement = this.getRootElement();\n\n // if root element not exist\n // create widget\n if (!rootElement) {\n const html = getHTML(params);\n const styles = getStyles(params);\n\n // append popup to body\n document.body.insertAdjacentHTML('beforeend', html);\n\n // append styles to head\n document.head.appendChild(styles);\n }\n\n this.addEventListeners();\n }\n\n public show(): void {\n const rootElement = this.getRootElementWithCheckExist();\n this.pw.dispatchEvent('show-subscription-widget', {});\n\n rootElement.classList.add(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`);\n }\n\n public hide(): void {\n const rootElement = this.getRootElementWithCheckExist();\n\n if (rootElement.classList.contains(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`)) {\n this.pw.dispatchEvent('hide-subscription-widget', {});\n rootElement.classList.remove(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show`);\n }\n }\n\n private getRootElement(): HTMLElement | null {\n return document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root`);\n }\n\n private getRootElementWithCheckExist(): HTMLElement {\n const element = this.getRootElement();\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root\", please use method init first.`);\n }\n\n return element;\n }\n\n private getDeclineButtonWithCheckExist(): HTMLButtonElement {\n const element = document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline`) as HTMLButtonElement;\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline\", please use method init first.`);\n }\n\n return element;\n }\n\n private getAcceptButtonWithCheckExist(): HTMLButtonElement {\n const element = document.getElementById(`${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept`) as HTMLButtonElement;\n\n if (!element) {\n throw new Error(`Can't find element by id \"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept\", please use method init first.`);\n }\n\n return element;\n }\n\n private addEventListeners(): void {\n const rootElement = this.getRootElementWithCheckExist();\n const declineElement = this.getDeclineButtonWithCheckExist();\n const acceptElement = this.getAcceptButtonWithCheckExist();\n\n document.addEventListener('click', (event) => {\n if (!rootElement.contains((event.target as HTMLElement))) {\n this.hide();\n }\n });\n\n declineElement.addEventListener('click', () => {\n this.hide();\n });\n\n acceptElement.addEventListener('click', () => {\n this.hide();\n this.pw.subscribe();\n });\n }\n}\n","import { SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG } from './constants';\nimport type { ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\nimport type { Pushwoosh } from '../../core/Pushwoosh';\n\nexport const getWidgetConfig = (features: any): ISubscriptionPromptWidgetParams => {\n // get config by features from get config method\n const currentConfig = features['subscription_prompt_widget'] && features['subscription_prompt_widget'].params;\n\n // merge current config with capping defaults\n const configWithDefaultCapping: ISubscriptionPromptWidgetParams = {\n cappingCount: SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingCount,\n cappingDelay: SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG.cappingDelay,\n ...currentConfig,\n };\n\n // if current config is not exist show with default values\n return currentConfig\n ? configWithDefaultCapping\n : SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG;\n};\n\nexport const checkCanShowByCapping = async (widgetConfig: ISubscriptionPromptWidgetParams, pw: Pushwoosh): Promise<boolean> => {\n const currentTime = new Date().getTime();\n const displayCount = await pw.data.getPromptDisplayCount();\n const lastSeenTime = await pw.data.getPromptLastSeenTime();\n\n // can show by max display count\n const canShowByCapping = widgetConfig.cappingCount > displayCount;\n\n // can show last seen time\n const canShowByLastTime = currentTime - lastSeenTime > widgetConfig.cappingDelay;\n\n return canShowByCapping && canShowByLastTime;\n};\n\nexport const updateCappingParams = async (pw: Pushwoosh): Promise<void> => {\n const displayCount = await pw.data.getPromptDisplayCount();\n const currentTime = new Date().getTime();\n\n await pw.data.setPromptDisplayCount(displayCount + 1);\n await pw.data.setPromptLastSeenTime(currentTime);\n};\n","import { SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE } from './SubscriptionPromptWidget.constants';\nimport { type ISubscriptionPromptWidgetParams } from './SubscriptionPromptWidget.types';\n\nexport const getHTML = (params: ISubscriptionPromptWidgetParams): string => {\n return `\n <div id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-root\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}\">\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__body\">\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__header\">\n ${params.headerText}\n </div>\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description\">\n ${params.subheaderText}\n </div>\n <div class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__controls\">\n <button type=\"button\" id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-decline\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control ${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_decline\">\n ${params.buttonCancelText}\n </button>\n <button type=\"button\" id=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}-accept\" class=\"${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control ${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_accept\">\n ${params.buttonAcceptText}\n </button>\n </div>\n </div>\n </div>\n `;\n};\n\nexport const getStyles = (params: ISubscriptionPromptWidgetParams) => {\n const styles = document.createElement('style');\n\n styles.innerHTML = `\n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE} * {\n box-sizing: border-box!important;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE} {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n margin: 0 auto;\n width: 320px;\n display: none;\n z-index: 2147483648;\n opacity: 0.99;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}_show {\n display: block;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__body {\n width: 320px;\n background-color: ${params.backgroundColor ? params.backgroundColor : '#FFFFFF'};\n box-shadow: 0 9px 15px rgba(0, 0, 0, 0.1), 0 0 6px rgba(0, 0, 0, 0.06);\n border-radius: 4px;\n padding: 20px 20px 12px;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__header {\n color: ${params.headerTextColor};\n font-size: 18px;\n font-weight: bold; \n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description {\n color: ${params.subheaderTextColor};\n font-size: 14px;\n line-height: 1.5;\n margin-top: 14px;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__description:empty {\n display: none;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__controls {\n display: flex;\n flex-wrap: nowrap;\n justify-content: flex-end;\n margin: 20px 0 0;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control {\n -webkit-appearance: none;\n border: 1px solid transparent;\n font-size: 12px;\n font-weight: bold;\n padding: 0 20px;\n height: 32px;\n cursor: pointer;\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_decline {\n color: ${params.buttonCancelTextColor};\n background-color: ${params.buttonCancelBackgroundColor};\n border-radius: ${params.buttonCancelRound};\n border-color: ${params.buttonCancelBorderColor};\n }\n \n .${SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE}__control_accept {\n color: ${params.buttonAcceptTextColor};\n background-color: ${params.buttonAcceptBackgroundColor};\n border-radius: ${params.buttonAcceptRound};\n border-color: ${params.buttonAcceptBorderColor};\n margin: 0 0 0 12px;\n }\n `;\n\n return styles;\n};\n"],"names":["root","factory","exports","module","define","amd","a","i","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","SUBSCRIPTION_PROMPT_WIDGET_DEFAULT_CONFIG","headerText","headerTextColor","subheaderText","subheaderTextColor","buttonAcceptText","buttonAcceptTextColor","buttonAcceptRound","buttonAcceptBackgroundColor","buttonAcceptBorderColor","buttonCancelText","buttonCancelTextColor","buttonCancelRound","buttonCancelBackgroundColor","buttonCancelBorderColor","cappingCount","cappingDelay","backgroundColor","SUBSCRIPTION_PROMPT_WIDGET_NAMESPACE","PWSubscriptionPromptWidget","constructor","pw","run","features","data","getFeatures","widgetConfig","currentConfig","params","configWithDefaultCapping","getWidgetConfig","canShowByCapping","async","currentTime","Date","getTime","displayCount","getPromptDisplayCount","lastSeenTime","getPromptLastSeenTime","canShowByLastTime","checkCanShowByCapping","currentPromptUseCase","isDefaultUseCase","isNotSetUseCase","initParams","autoSubscribe","init","show","moduleRegistry","subscriptionPrompt","setPromptDisplayCount","setPromptLastSeenTime","updateCappingParams","getRootElement","html","getHTML","styles","document","createElement","innerHTML","getStyles","body","insertAdjacentHTML","head","appendChild","addEventListeners","rootElement","getRootElementWithCheckExist","dispatchEvent","classList","add","hide","contains","remove","getElementById","element","Error","getDeclineButtonWithCheckExist","getAcceptButtonWithCheckExist","declineElement","acceptElement","addEventListener","event","target","subscribe"],"sourceRoot":""}
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};