UNPKG

web-push-notifications

Version:
2 lines 40.2 kB
!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 r=t=>"function"==typeof t,n="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(n,(function(t){t.createObjectStore(n,{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=(x=n,{get:(t,e)=>b(((s,a,i)=>{const r=s.transaction(x).objectStore(x).get(t);let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(r.result?.value||e):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()})),getAll:()=>b(((t,e,s)=>{const a={},i=t.transaction(x).objectStore(x).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?e(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=t=>{const e=t.target.result;e?(a[e.key]=e.value.value,e.continue()):n=!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 r=s.transaction([x],"readwrite").objectStore(x).put({key:t,value:e});let n,o=!1,c=!1;const u=()=>{clearTimeout(n),o?a(t):c?i(r.error):n=setTimeout(u,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,u()}))});var x;const S=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)}},M=new class extends f{constructor(){super(...arguments),this.name=o,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},C={error:1,info:2,debug:3};let T=3;const k={setLevel(t){C[t]||(t="error"),T=C[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),S.add(t,e,s)}};Object.keys(C).forEach((t=>{const e=C[t];k[t]=(...s)=>{e<=T&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}}));const D="silent",I="fatal",P="error",E="warn",R="info",A="debug",q={[D]:0,[I]:10,[P]:20,[E]:30,[R]:40,[A]:50};function _(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 W=new class{constructor(t){this.relations=q,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 r=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,r))})),s&&s.handler&&this.level!==D&&s.handler.call(null,r),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:R,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:I,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:I,text:t,code:e,options:s})}async fatalAndReject(t,e,s,a){return this.logAndReject(t,{type:I,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:_},{level:"error",handler:_}]});async function O(t){const e=N(t);return W.fatal(e.text,e.code,e.options)}function N(t){const{message:e,code:s,error:a,...i}=t,r=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:r.message,errorStack:r.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:r,text:n,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:r,message:n,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),r=await i.put(e,s);return a.close(),r}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),r=await i.get(e,s);return a.close(),r}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 r=await i.countByIndex(s);return a.close(),r}}class B{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 H={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},j=/&(?:amp|lt|gt|quot|#39);/g,$=RegExp(j.source);class F{constructor(t=v){this.store=t}async clearAll(){await this.store.set("params.applicationCode",void 0),await this.store.set("params.hwid",void 0),await this.store.set("params.deviceType",void 0),await this.store.set("params.deviceModel",void 0),await this.store.set("params.language",void 0),await this.store.set("params.apiEntrypoint",void 0),await this.store.set("params.tokens",void 0),await this.store.set("params.applicationServerKey",void 0),await this.store.set("params.senderId",void 0),await this.store.set("params.webSitePushId",void 0),await this.store.set("params.defaultNotificationImage",void 0),await this.store.set("params.defaultNotificationTitle",void 0),await this.store.set("params.userId",void 0),await this.store.set("params.email",void 0),await this.store.set("params.userIdWasChanged",void 0),await this.store.set("params.isLastPermissionStatus",void 0),await this.store.set("params.isManualUnsubscribed",void 0),await this.store.set("params.isCommunicationDisabled",void 0),await this.store.set("params.isDropAllData",void 0),await this.store.set("params.sdkVersion",void 0),await this.store.set("params.serviceWorkerVersion",void 0),await this.store.set("params.serviceWorkerUrl",void 0),await this.store.set("params.serviceWorkerScope",void 0),await this.store.set("params.lastOpenMessage",void 0),await this.store.set("params.lastOpenApplicationTime",void 0),await this.store.set("params.features",void 0),await this.store.set("params.init",void 0)}async setApplicationCode(t){await this.store.set("params.applicationCode",t)}async getApplicationCode(){return await this.store.get("params.applicationCode")}async setApiToken(t){return await this.store.set("params.apiToken",t)}async getApiToken(){return await this.store.get("params.apiToken")}async setHwid(t){await this.store.set("params.hwid",t)}async getHwid(){return await this.store.get("params.hwid")}async setDeviceType(t){await this.store.set("params.deviceType",t)}async getDeviceType(){return await this.store.get("params.deviceType")}async setDeviceModel(t){await this.store.set("params.deviceModel",t)}async getDeviceModel(){return await this.store.get("params.deviceModel")}async setLanguage(t){await this.store.set("params.language",t)}async getLanguage(){return await this.store.get("params.language","en")}async setApiEntrypoint(t){await this.store.set("params.apiEntrypoint",t)}async getApiEntrypoint(){return await this.store.get("params.apiEntrypoint","https://cp.pushwoosh.com/json/1.3/")}async setTokens(t){await this.store.set("params.tokens",t)}getTokens(){return this.store.get("params.tokens")}async setApplicationServerKey(t){await this.store.set("params.applicationServerKey",t)}async getApplicationServerKey(){return await this.store.get("params.applicationServerKey")}async setIsVapidChanged(t){await this.store.set("params.isVapidChanged",t)}async getIsVapidChanged(){return await this.store.get("params.isVapidChanged",!1)}async setWebSitePushId(t){await this.store.set("params.webSitePushId",t)}async getWebSitePushId(){return await this.store.get("params.webSitePushId")}async setDefaultNotificationImage(t){await this.store.set("params.defaultNotificationImage",t)}async getDefaultNotificationImage(){return await this.store.get("params.defaultNotificationImage","https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set("params.defaultNotificationTitle",t)}async getDefaultNotificationTitle(){return await this.store.get("params.defaultNotificationTitle","Pushwoosh notification")}async setUserId(t){t?await this.store.set("params.userId",t.toString()):await this.store.set("params.userId",void 0)}async getUserId(){return await this.store.get("params.userId")}async setStatusUserIdWasChanged(t){await this.store.set("params.userIdWasChanged",t)}async getStatusUserIdWasChanged(){return await this.store.get("params.userIdWasChanged",!1)}async setEmail(t){t?await this.store.set("params.email",t.toString()):await this.store.set("params.email",void 0)}async getEmail(){return await this.store.get("params.email")}async setStatusEmailWasChanged(t){await this.store.set("params.emailWasChanged",t)}async getStatusEmailWasChanged(){return await this.store.get("params.emailWasChanged",!1)}async setLastPermissionStatus(t){await this.store.set("params.isLastPermissionStatus",t)}async getLastPermissionStatus(){return await this.store.get("params.isLastPermissionStatus")}async setStatusManualUnsubscribed(t){await this.store.set("params.isManualUnsubscribed",t)}getStatusManualUnsubscribed(){return this.store.get("params.isManualUnsubscribed",!1)}async setStatusCommunicationDisabled(t){await this.store.set("params.isCommunicationDisabled",t)}getStatusCommunicationDisabled(){return this.store.get("params.isCommunicationDisabled",!1)}async setStatusDropAllData(t){await this.store.set("params.isDropAllData",t)}getStatusDropAllData(){return this.store.get("params.isDropAllData",!1)}async setSdkVersion(t){await this.store.set("params.sdkVersion",t)}async getSdkVersion(){return await this.store.get("params.sdkVersion")}async setServiceWorkerVersion(t){await this.store.set("params.serviceWorkerVersion",t)}getServiceWorkerVersion(){return this.store.get("params.serviceWorkerVersion")}async setServiceWorkerUrl(t){t&&await this.store.set("params.serviceWorkerUrl",t)}async getServiceWorkerUrl(){return await this.store.get("params.serviceWorkerUrl","/pushwoosh-service-worker.js")}async setServiceWorkerScope(t){t&&await this.store.set("params.serviceWorkerScope",t)}async getServiceWorkerScope(){return await this.store.get("params.serviceWorkerScope")}async setLastOpenMessage(t){await this.store.set("params.lastOpenMessage",t)}getLastOpenMessage(){return this.store.get("params.lastOpenMessage")}async setLastOpenApplicationTime(t){await this.store.set("params.lastOpenApplicationTime",t)}async getLastOpenApplicationTime(){return await this.store.get("params.lastOpenApplicationTime")}async setFeatures(t){await this.store.set("params.features",t)}async getFeatures(){return await this.store.get("params.features")}async setInitParams(t){await this.store.set("params.init",t)}async getInitParams(){return await this.store.get("params.init")}async setInboxLastRequestCode(t){await this.store.set("params.inbox.lastRequestCode",t)}async getInboxLastRequestCode(){return await this.store.get("params.inbox.lastRequestCode","")}async setInboxLastRequestTime(t){await this.store.set("params.inbox.lastRequestTime",t)}async getInboxLastRequestTime(){return this.store.get("params.inbox.lastRequestTime",0)}async setInboxNewMessagesCount(t){await this.store.set("params.inbox.newMessagesCount",t)}async getInboxNewMessagesCount(){return this.store.get("params.inbox.newMessagesCount",0)}async setDelayedEvent(t){await this.store.set("params.delayedEvent",t)}getDelayedEvent(){return this.store.get("params.delayedEvent")}async setPromptDisplayCount(t){await this.store.set("params.promptDisplayCount",t)}async getPromptDisplayCount(){return this.store.get("params.promptDisplayCount",0)}async setPromptLastSeenTime(t){await this.store.set("params.promptLastSeenTime",t)}async getPromptLastSeenTime(){return this.store.get("params.promptLastSeenTime",0)}}class K{constructor(t,e=new F,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(j,(t=>H[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:r,pwcid:n,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 z{constructor(t=new F,e=k){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t,"",!0)}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)}async createRequest(t,e,s,a){const i=await this.data.getApiEntrypoint(),r=a?"":await this.data.getApiToken(),n=s||i+t,o=r?{headers:{Authorization:`Token ${r}`,"Content-Type":"text/plain;charset=UTF-8",Origin:globalThis.location.origin},credentials:"include"}:{},c=await fetch(n,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...o}),u=await this.checkResponse(c);return u.base_url&&await this.data.setApiEntrypoint(u.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(u.response)}`),u.response}async checkResponse(t){if(200!==t.status)throw new Error(`Error code: ${t.status}. Error text: ${t.statusText}`);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 J{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 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: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(),r=a===(i&&i.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}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 G{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 Y=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=>{r(t)&&setTimeout((()=>{t({...e,eventId:s})}),0)})),s):s},this.handlers={}}},Q=new F,X=new class{constructor(t,e=new F,s=new z){this.eventBus=t,this.data=e,this.apiClient=s}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:r}=await this.checkDevice();localStorage.setItem(t,a&&r?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){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){const{hwid:e,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getDeviceType(),r=`${t}`,n=await this.data.getEmail(),o=await this.apiClient.registerUser({...a,hwid:e,userId:r,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:i});return n&&await this.apiClient.registerEmailUser({...a,email:n,userId:r,ts_offset:60*-(new Date).getTimezoneOffset()}),await this.data.setUserId(`${t}`),await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(t,e){const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...i,...e,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(`${t}`),await this.data.setStatusEmailWasChanged(!0),r}async postEvent(t,e){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(e.msgHash)return Promise.reject("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:r,timestampCurrent:n,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 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(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:t,hwid:e,userId:s||e,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}(Y,Q),Z=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]&&r(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()}}(Y,Q,X),tt=[];async function et(t){(await self.clients.matchAll()).forEach((e=>e.postMessage(t)))}async function st(t){const{notification:e={}}=t,{data:s}=e,i=a(e.tag,{});let r="";if(t.action&&Array.isArray(s.buttons)){r=(s.buttons.find((e=>e.action===t.action))||{}).url}else r=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:r}}async function at(t){const e=await Z.data.getApplicationCode(),s=await Z.data.getServiceWorkerVersion();await O({message:"Error in onInstallEventHandler",code:"FATAL-SW-001",error:t,applicationCode:e,workerVersion:s})}async function it(t){const e=await Z.data.getApplicationCode(),s=await Z.data.getServiceWorkerVersion();await O({message:"Error in onActivateEventHandler",code:"FATAL-SW-002",error:t,applicationCode:e,workerVersion:s})}async function rt(t){const e=await Z.data.getApplicationCode(),s=await Z.data.getServiceWorkerVersion();await O({message:"Error in onNotificationClickEventHandler",code:"FATAL-SW-004",error:t,applicationCode:e,workerVersion:s})}async function nt(t){const e=await Z.data.getApplicationCode(),s=await Z.data.getServiceWorkerVersion();await O({message:"Error in onNotificationCloseEventHandler",code:"FATAL-SW-005",error:t,applicationCode:e,workerVersion:s})}async function ot(t){const e=await Z.data.getApplicationCode(),s=await Z.data.getServiceWorkerVersion();await O({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([Z.data.setServiceWorkerVersion("3.45.2"),k.write("info","install")]),await self.skipWaiting()}().catch(at))})),self.addEventListener("activate",(function(t){t.waitUntil(async function(){await Promise.all([k.write("info","activate")]),await self.clients.claim()}().catch(it))})),self.addEventListener("push",(function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await t.data.json(),s=new K(e),a=await s.getNotificationOptionsPayload(),i=await s.getShowNotificationOptions(),r=s.messageHash;await k.write("info",JSON.stringify(a),"onPush");const n=new G(i,s.body,await s.getTitle()),o=Z.getListeners("onPush");await o.reduce(((t,e)=>t.then((()=>e(n)))),Promise.resolve());const c=[n.show(),M.add({payload:e,parsedPayload:a,showOptions:i}),et({type:"onPushDelivery",payload:a})];if(r&&c.push(Z.initApi().then((()=>Z.api.messageDeliveryEvent(r,!0,a.metaData)))),""!==s.inboxId){const t=new B(Z.eventBus,Z.data,Z.api),e=new U(Z.data,Z.api,t),a=await s.getInboxMessage(),i=await e.publicMessageBuilder(a);c.push(t.putMessage(a),et({type:"onPutNewMessageToInboxStore",payload:i}))}await Promise.all(c)}(t).catch((e=>async function(t,e){const s=await Z.data.getApplicationCode(),a=await Z.data.getServiceWorkerVersion();await O({message:"Error in onPushEventHandler",code:"FATAL-SW-003",error:t,applicationCode:s,workerVersion:a}),t instanceof Error||(t=new Error(t));return M.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 st(t),{messageHash:s,metaData:a,url:i,code:r,inboxId:n}=e;if(r&&tt.push(r),""!==n){const t=new B(Z.eventBus,Z.data,Z.api),e=await t.getMessage(n);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&&Z.data.setDelayedEvent(o)}))),Promise.all([Z.initApi().then((()=>Z.api.pushStat(s,!0,a))),Z.data.setLastOpenMessage({url:i,messageHash:s,expiry:Date.now()+864e5}),et(o)])}(t).catch(rt))})),self.addEventListener("notificationclose",(function(t){t.waitUntil(async function(t){await self.clients.claim();const e=await st(t),{code:s}=e;if(t.notification.close(),!s)return;const a=tt.indexOf(s);if(!(a>=0))return et({type:"onNotificationClose",payload:e});tt.splice(a,1)}(t).catch(nt))})),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 J(X,Q,{});await s.subscribe(e)}(t).catch(ot))})),{}})())); //# sourceMappingURL=service-worker.js.map