web-push-notifications 3.125.1 → 3.126.0

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/CHANGELOG.md CHANGED
@@ -9,6 +9,15 @@ the same mapping is in the
9
9
  Entries for 3.71.0 through 3.78.0 are grouped under version headings, which is how this file was
10
10
  kept before the version moved to the tag; earlier versions live only in the git history.
11
11
 
12
+
13
+ ## feat(inbox): border, web link and data with open/copy on card buttons (contract v9)
14
+
15
+ - A card button may carry `border_color` (`#RRGGBB`/`#RRGGBBAA`): the widget draws a border of that color; with no
16
+ `bg_color` it is the outline style. An `open` button opens `urls.web` when the payload has a safe one, else `url`.
17
+ - `data` sent with an `open` or `copy` button reaches the site too: the widget fires `click-inbox-button` with it
18
+ before running the action. A button without data fires nothing, as before.
19
+ - Needs `@pushwoosh/websdk-common` 6.37.0 (border drawing); the backend sends these fields from channels/api/messaging!344.
20
+
12
21
  ## chore(inbox): stack card buttons at full width (websdk-common 6.36.0)
13
22
 
14
23
  - The inbox widget draws the card buttons one under another at full width instead of sharing one row, as in the DESIGN-970
@@ -16,7 +16,9 @@ export interface IInboxButtonRaw {
16
16
  title?: unknown;
17
17
  text_color?: unknown;
18
18
  bg_color?: unknown;
19
+ border_color?: unknown;
19
20
  action?: unknown;
21
+ urls?: unknown;
20
22
  url?: unknown;
21
23
  copy_text?: unknown;
22
24
  data?: unknown;
@@ -49,11 +51,13 @@ export interface IInboxMessageButton {
49
51
  textColor: string;
50
52
  /** `#RRGGBB` or `#RRGGBBAA`; empty draws the button as a link. */
51
53
  bgColor: string;
54
+ /** `#RRGGBB` or `#RRGGBBAA` border; with no `bgColor` the button is an outline. Empty: no border. */
55
+ borderColor: string;
52
56
  action: TInboxButtonAction;
53
- /** Target of an `open` button; empty when none was sent or its scheme is unsafe. */
57
+ /** Target of an `open` button (`urls.web` when sent, else `url`); empty when none was sent or its scheme is unsafe. */
54
58
  url: string;
55
59
  /** Text a `copy` button puts on the clipboard. */
56
60
  copyText: string;
57
- /** Payload of a `custom` button, passed to the `click-inbox-button` event. */
61
+ /** Data passed to the `click-inbox-button` event: of a `custom` button, or sent with `open` / `copy`. */
58
62
  data: Record<string, unknown>;
59
63
  }
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 i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperties(e,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>Pt});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",l="onUnsubscribe",g="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",k="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",C="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",T="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],M={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function U(){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;function R(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const O={[g]:{name:"register"},[d]:{name:"subscribe"},[l]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[k]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[C]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},L="keyValue",N="messages",F="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(L,function(e){e.createObjectStore(L,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(N,function(e){e.createObjectStore(N,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(F,function(e){const t="status",s=e.createObjectStore(F,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class ${get all(){return B}}class j{constructor(e,t=new $){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let V;function K(){return V||(V=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=H.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t);new j(s).applyMigrations()}})),V}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.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 z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=L,{get(e,t){return this.getStored(e).then(e=>e||t)},getStored:e=>z((t,s,i)=>{const a=t.transaction(Y).objectStore(Y).get(e);let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?s(a.result?.value):o?i(a.error):r=setTimeout(c,0)};a.onsuccess=()=>n=!0,a.onerror=()=>o=!0,c()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=N,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{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||U(),i=this.handlers[e];return i?(i.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups,sharedDevice:t.sharedDevice}:void 0}function re(e,t){if(t)return{...e,...t}}const ne=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],oe=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],ce=e=>{const t=e.toLowerCase();let s,i=3;return ne.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function he(e){const t=[];return Object.entries(e).forEach(([e,s])=>{ne.includes(e)?oe.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:ce(e)})}),t}function ue(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class de{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()}}const le=["classic","captioned","banner","carousel"];function ge(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const pe=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;const me=/^(?:javascript|vbscript|data|blob|file):/i,we=/^[a-z][a-z\d+\-.]*:/i;function be(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function fe(e){const t=be(e);return we.test(t)&&!me.test(t)}const ye=/^intent:/i;const ve=["id","title","text_color","bg_color"];function Pe(e){return"string"==typeof e?e:""}function Se(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ke(e){const t=Pe(e);return t&&fe(t)&&!function(e){return ye.test(be(e))}(t)?t:""}function Ie(e,t){return t?"":(s=e,("string"==typeof s&&pe.test(s)?s:void 0)||"").toUpperCase();var s}function Ce(e){return Object.keys(e).filter(e=>-1===ve.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}const De=/^[0-2]$/;function Ee(e){return Se(e)&&"string"==typeof e.title&&""!==e.title.trim()}function We(e){return(Array.isArray(e.buttons)?e.buttons:[]).filter(Ee).slice(0,3).map((e,t)=>{const s="string"==typeof e.id&&De.test(e.id);return function(e,t,s){const i=ke(e.url),a={id:t,title:Pe(e.title),textColor:Ie(e.text_color,s),bgColor:Ie(e.bg_color,s),action:"custom",url:i,copyText:Pe(e.copy_text),data:Se(e.data)?e.data:{}};if(s){const t="dismiss"===e.action||"markRead"===e.action||"markread"===e.action;i&&!t?a.action="open":a.data=Ce(e)}else"open"===e.action||"copy"===e.action||"custom"===e.action?a.action=e.action:a.data=Ce(e);return a}(e,s?e.id:String(t),!s)})}function Te(e,t){return t||e.image||""}function xe(e){const t=["displayType","carousel","buttons","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class Me{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new de){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}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 i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&fe(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(le.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&ge(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:Te(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=Te(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:u,customData:xe(h),webPopupCode:c.wp||"",buttons:We(h),code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.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=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!me.test(be(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async reportButtonClick(e,t){const s=await this.inboxModel.getMessage(e),i=3!==s.status;i&&await this.sendStatus(s.order,3),await this.sendStatus(s.order,6,t),i&&(s.status=3,await this.inboxModel.putMessage(s))}sendStatus(e,t,s){return new Promise(i=>{this.api.inboxStatus(e,t,s,{keepalive:!0,onSent:i}).catch(s=>te.write("error",`Pushwoosh: inbox status ${t} for "${e}" failed`,s)).finally(i)})}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}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.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class Ae{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,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(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,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(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 Ue{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new Ae(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new Ae(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new Ae(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new Ae(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new Ae(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new Ae(i,e);return a.index=t,a.countByIndex(s)}}class _e{constructor(e,t,s,i=new Ue,a=new de){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}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 Me(this.data,this.api,this)})}}class Re extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const Oe=e=>`params.${e}`;class Le{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","sharedDeviceHwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","ownUserId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isOwnManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(Oe(t),void 0)}async setApplicationCode(e){await this.store.set(Oe("applicationCode"),e)}async getApplicationCode(){return this.store.get(Oe("applicationCode"))}async setApiToken(e){return await this.store.set(Oe("apiToken"),e)}async getApiToken(){return this.store.get(Oe("apiToken"))}async setHwid(e){await this.store.set(Oe("hwid"),e)}async getHwid(){return this.store.get(Oe("hwid"))}async setSharedDeviceHwid(e){await this.store.set(Oe("sharedDeviceHwid"),e)}async getSharedDeviceHwid(){return this.store.get(Oe("sharedDeviceHwid"))}async setDeviceType(e){await this.store.set(Oe("deviceType"),e)}async getDeviceType(){return this.store.get(Oe("deviceType"))}async setFormFactor(e){await this.store.set(Oe("formFactor"),e)}async getFormFactor(){return this.store.get(Oe("formFactor"))}async setDeviceModel(e){await this.store.set(Oe("deviceModel"),e)}async getDeviceModel(){return this.store.get(Oe("deviceModel"))}async setLanguage(e){await this.store.set(Oe("language"),e)}async getLanguage(){return this.store.get(Oe("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(Oe("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(Oe("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(Oe("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(Oe("apiEntrypoint"),i)}async setTokens(e){await this.store.set(Oe("tokens"),e)}getTokens(){return this.store.get(Oe("tokens"))}async setApplicationServerKey(e){await this.store.set(Oe("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(Oe("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(Oe("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(Oe("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(Oe("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(Oe("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(Oe("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(Oe("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(Oe("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(Oe("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(Oe("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(Oe("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){const t=e?`${e}`:void 0;await this.store.set(Oe("userId"),t),await this.store.set(Oe("ownUserId"),t)}async getUserId(){return this.store.get(Oe("userId"))}async setUserIdFromSharedDevice(e){await this.store.set(Oe("userId"),e)}async getOwnUserId(){return this.store.get(Oe("ownUserId"))}async keepOwnUserId(){void 0===await this.store.getStored(Oe("ownUserId"))&&await this.store.set(Oe("ownUserId"),await this.getUserId()??"")}async getFeatureFlags(){return this.store.get(Oe("featureFlags"))}async setFeatureFlags(e){await this.store.set(Oe("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(Oe("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(Oe("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(Oe("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(Oe("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(Oe("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(Oe("email"))}async setStatusEmailWasChanged(e){await this.store.set(Oe("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(Oe("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(Oe("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(Oe("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(Oe("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(Oe("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(Oe("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(Oe("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(Oe("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(Oe("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(Oe("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(Oe("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(Oe("isManualUnsubscribed"),e),await this.store.set(Oe("isOwnManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(Oe("isManualUnsubscribed"),!1)}async setStatusManualUnsubscribedFromSharedDevice(e){await this.store.set(Oe("isManualUnsubscribed"),e)}getOwnStatusManualUnsubscribed(){return this.store.get(Oe("isOwnManualUnsubscribed"),!1)}async keepOwnStatusManualUnsubscribed(){void 0===await this.store.getStored(Oe("isOwnManualUnsubscribed"))&&await this.store.set(Oe("isOwnManualUnsubscribed"),await this.getStatusManualUnsubscribed())}async setStatusCommunicationDisabled(e){await this.store.set(Oe("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(Oe("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(Oe("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.getStored(Oe("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(Oe("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(Oe("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(Oe("sdkVersion"),e)}async getSdkVersion(){return this.store.get(Oe("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(Oe("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(Oe("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(Oe("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(Oe("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(Oe("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(Oe("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(Oe("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(Oe("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(Oe("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(Oe("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(Oe("features"),e)}async getFeatures(){return this.store.get(Oe("features"))}async setInitParams(e){await this.store.set(Oe("init"),e)}async getInitParams(){return this.store.get(Oe("init"))}async setInboxLastRequestCode(e){await this.store.set(Oe("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(Oe("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(Oe("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(Oe("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(Oe("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(Oe("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(Oe("delayedEvent"),e)}getDelayedEvent(){return this.store.get(Oe("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(Oe("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(Oe("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(Oe("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(Oe("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(Oe("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(Oe("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(Oe("logLevel"),e)}async getLogLevel(){return this.store.get(Oe("logLevel"),"error")}async getShownWebPopups(){return this.store.get(Oe("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(Oe("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(Oe("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(Oe("isRecurringVisitor"),!1)}}class Ne{constructor(e=new Le,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",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,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e,t){return this.createRequest("inboxStatus",e,t)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive});s.onSent?.();const c=await o,h=await this.checkResponse(c);return h.base_url&&await this.data.setApiEntrypoint(h.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(h.response)}`),h.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Re(s,t)}const t=await e.json();if(200!==t.status_code)throw new Re(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Fe{constructor(e,t=new Le,s=new Ne,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=R(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}forgetDeviceStatus(){this.checkDevicePromise=null,localStorage.removeItem(a)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async isDeviceSubscribed(e){const{exist:t,push_token_exist:s}=await this.apiClient.checkDevice({...await this.getRequestParams(),hwid:e});return t&&s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice({keepUserId:e=!1}={}){const t=this.requestRegisterDevice(e);this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(e){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=await this.getRequestParams(),s=await this.data.getTokens();if(!s.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=this.getPushPermissionStatus(),r=await this.apiClient.registerDevice({...t,push_permission_status:i,locale:await this.getLocale(),page:ue(),push_token:s.pushToken,auth_token:s.authToken,public_key:s.publicKey,...e?{keep_user_id:!0}:{}});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(i),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice({silent:e=!1}={}){const t=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,e||(localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{})),s}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={},i){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s,...i?{button_id:i}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=qe(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return qe(await this.data.getLanguage())||void 0}async registerUser(e,t=!0,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:i,device_type:a,...r}=await this.getRequestParams(),n=s??i,o=await this.data.getDeviceType(),c=`${e}`,h=await this.data.getUserId(),u=await this.apiClient.registerUser({...r,hwid:n,userId:c,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:o});return await this.data.setUserId(c),c&&c!==h&&this.eventBus.dispatchEvent("change-user-id",{userId:c}),t&&await this.data.setStatusUserIdWasChanged(!0),u}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 s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}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:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}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:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:U()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t,s,i){const a=await this.getRequestParams();return this.apiClient.inboxStatus({...a,inbox_code:e,status:t,time:(new Date).getTime(),...void 0===s?{}:{button_id:s}},i)}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(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const 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),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,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&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),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.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(T);return e}}function qe(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class Be{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class $e extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const je=/json\/1\.3\/?$/,He="api/v2/device-api/getFeatureFlags";const Ve=18e5;class Ke{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new Be(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Ve)){await this.deps.data.setFeatureFlagImpressions({...Je(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new $e("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new $e("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(je.test(t))return t.replace(je,He);try{return`${new URL(t).origin}/${He}`}catch(e){return i.replace(je,He)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new $e(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new $e(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new $e("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!ze(c.response))throw new $e(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Ge(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Ye(this.cache.flags):""}}function ze(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ge(e){const t={};return ze(e)?(Object.keys(e).forEach(s=>{const i=e[s];ze(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:ze(i.properties)?i.properties:{}})}),t):t}function Je(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Ve&&(s[i]=e[i])}),s}function Ye(e){return Array.isArray(e)?`[${e.map(Ye).join(",")}]`:ze(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ye(e[t])}`).join(",")}}`:JSON.stringify(e)}const Xe=[["opera",/\bOPR\/|Opera/],["edge",/\bEdge?\//],["firefox",/firefox/i],["chrome",/\bChrome\/|\bCriOS\//],["safari",/\bSafari\//]];function Qe(e){const t=Xe.find(([,t])=>t.test(e));return t?t[0]:"unknown"}function Ze({userAgent:e,appName:t,appVersion:s}){const i=e.match(/\bOPR\/(\d+)/);if(null!==i)return`Opera ${i[1]}`;const a=e.match(/\bEdge?\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;const[,r="",n]=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[],o=n?[r,n]:[t,s,"-?"],c=e.match(/version\/([.\d]+)/i);return null!==c&&o.splice(1,1,c[1]),o.join(" ")}function et(e){return{name:Qe(e.userAgent),model:Ze(e)}}function tt(e){const t=e.userAgentData?.mobile;return"boolean"==typeof t?t?"MOBILE":"DESKTOP":/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e.userAgent)?"MOBILE":"DESKTOP"}function st(e){const t=e.navigator?.userAgent??"";return{webPush:!!e.navigator?.serviceWorker&&"PushManager"in e&&"Notification"in e,safariLegacy:"safari"in e&&t.includes("Safari")}}function it(e){return e.webPush||e.safariLegacy}function at({legacySafari:e,unifiedPlatform:t,browser:s}){return e?10:t?11:"firefox"===s?12:11}class rt{constructor(e){this.browser=e.browser,this.capabilities=e.capabilities,this.formFactor=e.formFactor}get isAvailableNotifications(){return it(this.capabilities)}get isAvailableServiceWorker(){return this.capabilities.webPush}get isSafari(){return this.capabilities.safariLegacy}get isOpera(){return"opera"===this.browser.name}get isEdge(){return"edge"===this.browser.name}get browserVersion(){return this.browser.model}get isMobile(){return"MOBILE"===this.formFactor}get isDesktop(){return"DESKTOP"===this.formFactor}get platform(){return this.getPlatformType()}getPlatformType(){return at({legacySafari:this.capabilities.safariLegacy,unifiedPlatform:!1,browser:this.browser.name})}getBrowserVersion(){return this.browser.model}getFormFactor(){return this.formFactor}}const nt="pushwoosh-recommendations-views";function ot(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class ct{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:ot(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(nt));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(nt,JSON.stringify(i))}catch{}return!1}}const ht="sdkUsageReportedOn";class ut{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.deprecatedApis=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}recordDeprecatedApi(e){this.deprecatedApis.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(ht)===t)return;localStorage.setItem(ht,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents],deprecated_apis:[...this.deprecatedApis]},{keepalive:!0}).catch(()=>{})}}const dt=/^www\./;const lt="pw_root_domain_probe";class gt{constructor(e,t){this.name=`pw_shared_device_${e}`,this.domain=t}static forApplication(e){const t=function(e){const t=e.split(".");if(t.length<2||/^[\d.]+$/.test(e)||e.includes(":"))return null;for(let e=t.length-2;e>=0;e--){const s=t.slice(e).join("."),i=U();if(document.cookie=`${lt}=${i}; domain=${s}; path=/; SameSite=Lax`,document.cookie.split("; ").includes(`${lt}=${i}`))return document.cookie=`${lt}=; domain=${s}; path=/; max-age=0; SameSite=Lax`,s}return null}(location.hostname);return t?new gt(e,t):null}read(){const e=`${this.name}=`,t=document.cookie.split("; ").find(t=>t.startsWith(e));if(!t)return null;try{const s=JSON.parse(decodeURIComponent(t.slice(e.length)));return"string"==typeof s?.hwid&&s.hwid?{hwid:s.hwid,subscribed:!0===s.subscribed,manualUnsubscribed:!0===s.manualUnsubscribed,askToSubscribe:!0===s.askToSubscribe,userId:"string"==typeof s.userId&&s.userId?s.userId:void 0,tokenOrigin:"string"==typeof s.tokenOrigin&&s.tokenOrigin?s.tokenOrigin:void 0}:null}catch{return null}}write(e){const t="https:"===location.protocol?"; Secure":"",s=encodeURIComponent(JSON.stringify(e));document.cookie=`${this.name}=${s}; domain=${this.domain}; path=/; max-age=34560000; SameSite=Lax${t}`}}class pt{constructor(e,t,s,i){this.record=null,this.origin=location.origin,this.data=t,this.api=s,this.isPermissionGranted=i,e.addEventHandler("register",()=>this.update({subscribed:!0,manualUnsubscribed:!1,askToSubscribe:!1,tokenOrigin:this.origin})),e.addEventHandler("change-user-id",({userId:e})=>this.update({userId:e}))}async choose(e,t,s,i=!1){if(this.record=t?gt.forApplication(e):null,!this.record)return void await this.leave(e,i);const a=await this.data.getHwid(),r=await this.readShared(a);if(r&&(r.hwid===a||r.subscribed))return void await this.join(r,s);const n=await this.isOwnDeviceSubscribed(),o=await this.readShared(a);!o||!o.subscribed&&n?await this.join({hwid:a,subscribed:n,manualUnsubscribed:!n&&await this.data.getStatusManualUnsubscribed(),userId:o?.userId,tokenOrigin:n?this.origin:void 0},s):await this.join(o,s)}isSubscribed(){return!!this.record?.read()?.subscribed}mayDropSubscription(){return!this.record||this.record.read()?.tokenOrigin===this.origin}async isOwnDeviceSubscribed(){return await this.hasPushToken()&&await this.api.checkDeviceSubscribeForPushNotifications(!1)}async hasPushToken(){return!!(await this.data.getTokens())?.pushToken}async holdsOwnSubscription(e){return!!e.subscribed&&e.tokenOrigin!==this.origin&&await this.hasPushToken()}async readShared(e){const t=this.record.read();return t&&t.hwid!==e&&await this.holdsOwnSubscription(t)&&!await this.api.isDeviceSubscribed(t.hwid)?{...t,subscribed:!1,askToSubscribe:!0}:t}async dropOwnSubscription(){const e=await(navigator.serviceWorker?.getRegistration(await this.data.getServiceWorkerUrl()));await((await(e?.pushManager.getSubscription()))?.unsubscribe()),await this.data.setTokens({})}async join(e,t){await this.data.keepOwnUserId(),await this.data.keepOwnStatusManualUnsubscribed();const s=await this.holdsOwnSubscription(e),i=s&&e.hwid!==await this.data.getHwid(),a=i?t??await this.data.getOwnUserId():void 0;let r=e;if(a&&(await this.api.registerUser(a,!1,e.hwid),r={...r,userId:a}),this.record.write(r),i&&await this.api.unregisterDevice({silent:!0}),s&&await this.dropOwnSubscription(),await this.switchTo(e.hwid),await this.data.setSharedDeviceHwid(e.hwid),a||t||(e.userId?await this.data.setUserIdFromSharedDevice(e.userId):await this.data.setUserId(await this.data.getOwnUserId())),e.subscribed&&!await this.api.checkDeviceSubscribeForPushNotifications(!1)){const e={subscribed:!1,askToSubscribe:!0};await this.update(e),r={...r,...e}}await this.holdManualUnsubscribe(r)}mustAskToSubscribe(){return!!this.record?.read()?.askToSubscribe}async holdManualUnsubscribe(e){e.askToSubscribe?await this.data.setStatusManualUnsubscribedFromSharedDevice(this.isPermissionGranted()):(e.subscribed||e.manualUnsubscribed)&&await this.data.setStatusManualUnsubscribedFromSharedDevice(!!e.manualUnsubscribed)}async retire(e){const t=await this.data.getHwid();this.record?.read()?.hwid===t&&this.record.write({hwid:`${e}_${U()}`,askToSubscribe:!0}),this.record=null}async leave(e,t){const s=await this.data.getSharedDeviceHwid();if(!s)return;const i=s===await this.data.getHwid(),a=i&&await this.hasPushToken();a&&t&&await this.dropSharedSubscription(e,s),!i||a&&!t||(await this.switchTo(`${e}_${U()}`),await this.data.setUserId(await this.data.getOwnUserId()),await this.data.setStatusManualUnsubscribed(await this.data.getOwnStatusManualUnsubscribed())),await this.data.setSharedDeviceHwid(void 0)}async dropSharedSubscription(e,t){await this.api.unregisterDevice({silent:!0});const s=gt.forApplication(e),i=s?.read();i?.hwid===t&&s.write({...i,subscribed:!1,askToSubscribe:!0,tokenOrigin:void 0})}async update(e){const t=await this.data.getHwid(),s=this.record?.read();s&&s.hwid===t&&this.record.write({...s,...e})}async switchTo(e){await this.data.getHwid()!==e&&(await this.data.setHwid(e),this.api.forgetDeviceStatus())}}function mt(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function wt(e){return"safari"in e?e.safari?.pushNotification:void 0}function bt(e,t){try{return wt(e)?.permission(t)}catch{return}}function ft(e,t){const s=t?bt(e,t):void 0;return s?.permission===c&&!!s.deviceToken}class yt{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}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 te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice({keepUserId:this.config.keepUserId})}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&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.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=${U()}`),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),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class vt{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()===c}checkIsPermissionDefault(){return this.getPermission()===h}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 te.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(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Pt{constructor(){var e;this.ready=!1,this.rawInitParams={},this.isSharedDeviceEnabled=!1,this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isSiteOpenedEventOn=!1,this.isLegacySafari=!1,this.waitForPermissionWork=R(1e4),this.moduleRegistry={},this.sdkUsage=new ut,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(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 X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new Le,this.apiClient=new Ne(this.data),this.api=new Fe(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getReportedPushPermissionStatus()),this.sharedDevice=new pt(this.eventBus,this.data,this.api,()=>this.readPermission()===c),this.featureFlags=new Ke({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new ct({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.environment={browser:et((e=A()).navigator),capabilities:st(e),formFactor:tt(e.navigator)},this.legacyPlatformChecker=new rt(this.environment),this.inboxModel=new _e(this.eventBus,this.data,this.api),this.pwinbox=new Me(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}get platformChecker(){return this.sdkUsage.recordDeprecatedApi("platformChecker"),this.legacyPlatformChecker}push(e){if(_(e))this.subscribeToLegacyEvents(u,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){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await this.dropSubscription(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}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();const e=!!(await this.data.getTokens())?.pushToken,t=this.driver?.checkIsPermissionGranted();t&&e&&(await this.api.registerDevice(),await this.sendData())}else{this.featureFlags.reset(),await this.api.unregisterDevice();const e=await this.data.getOwnStatusManualUnsubscribed();await this.data.setStatusManualUnsubscribed(e||await this.data.getStatusManualUnsubscribed()),await this.sharedDevice.retire(this.initParams.applicationCode)}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.sharedDevice.retire(this.initParams.applicationCode),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}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 it(this.environment.capabilities)}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){he(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...M,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.environment.formFactor),await this.data.setDeviceModel(this.environment.browser.model);if(await this.data.getStatusLanguageWasChanged()||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.125.1"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.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.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.initStep("chooseDevice",async()=>{const{enable:e,excludedSites:t}=ae(await this.data.getFeatures())?.sharedDevice??{},s=!0===e&&function(e,t){if(!Array.isArray(t))return!1;const s=e.toLowerCase().replace(dt,"");return t.some(e=>"string"==typeof e&&e.toLowerCase().replace(dt,"")===s)}(location.hostname,t);this.isSharedDeviceEnabled=!0===e&&!s;const i=this.isSharedDeviceEnabled&&!await this.data.getStatusDropAllData();await this.sharedDevice.choose(this.initParams.applicationCode,i,this.getInitUserId(),s)}),await this.data.setDeviceType(this.resolvePlatformType()),this.isSiteOpenedEventOn&&this.sendPostEventVisitedPage(),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"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 initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){const{safariWebsitePushID:e,unifiedPlatform:t=!1}=this.initParams??{},{capabilities:s,browser:i}=this.environment;return this.isLegacySafari=function({capabilities:e,hasLegacySubscription:t,webVapidConfigured:s,unifiedPlatform:i}){return!(!e.safariLegacy||e.webPush&&!t&&(i||s))}({capabilities:s,hasLegacySubscription:s.safariLegacy&&ft(A(),e),webVapidConfigured:this.isWebVapidConfigured,unifiedPlatform:t}),at({legacySafari:this.isLegacySafari,unifiedPlatform:t,browser:i.name})}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+U();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(T)}catch(e){te.info(e,T)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}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.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void(i&&this.isSharedDeviceEnabled||await this.unsubscribe());a&&(await this.dropSubscription(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.dropSubscription();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.dropSubscription();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}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())}getPushPermissionStatus(){return this.driver?mt(this.driver.getPermission()):function(e,t){const s=wt(e);if(s&&t){const s=bt(e,t);return s?mt(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?mt(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}getReportedPushPermissionStatus(){const e=this.getPushPermissionStatus();return"granted_explicit"!==e&&this.sharedDevice.isSubscribed()?void 0:e}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c){const t=!await this.data.getStatusManualUnsubscribed()&&!this.sharedDevice.mustAskToSubscribe();s||e||this.isPushDisabled||!t||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight))}else if(s){const e=this.dropSubscription(()=>this.dropRevokedSubscription(t)).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropSubscription(e=()=>this.unsubscribe()){this.sharedDevice.mayDropSubscription()&&await e()}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}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||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];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(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(ae(t)),this.isSiteOpenedEventOn=!!t.events?.some(e=>e===W),t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=re(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=re(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(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.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new vt(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}const{webPush:e}=this.environment.capabilities;te.info({isAvailableServiceWorker:e}),e&&(this.driver=new yt(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=ue(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in O:this.eventBus.addEventHandler(O[e].name,s=>{const{prop:i}=O[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v: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 i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperties(e,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>Pt});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",l="onUnsubscribe",g="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",k="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",C="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",T="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],M={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function U(){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;function R(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const O={[g]:{name:"register"},[d]:{name:"subscribe"},[l]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[k]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[C]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},L="keyValue",N="messages",F="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(L,function(e){e.createObjectStore(L,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(N,function(e){e.createObjectStore(N,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(F,function(e){const t="status",s=e.createObjectStore(F,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class ${get all(){return B}}class j{constructor(e,t=new $){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let V;function K(){return V||(V=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=H.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t);new j(s).applyMigrations()}})),V}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.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 z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=L,{get(e,t){return this.getStored(e).then(e=>e||t)},getStored:e=>z((t,s,i)=>{const a=t.transaction(Y).objectStore(Y).get(e);let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?s(a.result?.value):o?i(a.error):r=setTimeout(c,0)};a.onsuccess=()=>n=!0,a.onerror=()=>o=!0,c()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=N,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{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||U(),i=this.handlers[e];return i?(i.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups,sharedDevice:t.sharedDevice}:void 0}function re(e,t){if(t)return{...e,...t}}const ne=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],oe=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],ce=e=>{const t=e.toLowerCase();let s,i=3;return ne.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function he(e){const t=[];return Object.entries(e).forEach(([e,s])=>{ne.includes(e)?oe.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:ce(e)})}),t}function ue(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class de{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()}}const le=["classic","captioned","banner","carousel"];function ge(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const pe=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;const me=/^(?:javascript|vbscript|data|blob|file):/i,we=/^[a-z][a-z\d+\-.]*:/i;function be(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function fe(e){const t=be(e);return we.test(t)&&!me.test(t)}const ye=/^intent:/i;const ve=["id","title","text_color","bg_color","border_color"];function Pe(e){return"string"==typeof e?e:""}function Se(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ke(e){const t=Pe(e);return t&&fe(t)&&!function(e){return ye.test(be(e))}(t)?t:""}function Ie(e,t){return t?"":(s=e,("string"==typeof s&&pe.test(s)?s:void 0)||"").toUpperCase();var s}function Ce(e){return Object.keys(e).filter(e=>-1===ve.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}const De=/^[0-2]$/;function Ee(e){return Se(e)&&"string"==typeof e.title&&""!==e.title.trim()}function We(e){return(Array.isArray(e.buttons)?e.buttons:[]).filter(Ee).slice(0,3).map((e,t)=>{const s="string"==typeof e.id&&De.test(e.id);return function(e,t,s){const i=(!s&&Se(e.urls)?ke(e.urls.web):"")||ke(e.url),a={id:t,title:Pe(e.title),textColor:Ie(e.text_color,s),bgColor:Ie(e.bg_color,s),borderColor:Ie(e.border_color,s),action:"custom",url:i,copyText:Pe(e.copy_text),data:Se(e.data)?e.data:{}};if(s){const t="dismiss"===e.action||"markRead"===e.action||"markread"===e.action;i&&!t?a.action="open":a.data=Ce(e)}else"open"===e.action||"copy"===e.action||"custom"===e.action?a.action=e.action:a.data=Ce(e);return a}(e,s?e.id:String(t),!s)})}function Te(e,t){return t||e.image||""}function xe(e){const t=["displayType","carousel","buttons","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class Me{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new de){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}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 i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&fe(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(le.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&ge(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:Te(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=Te(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:u,customData:xe(h),webPopupCode:c.wp||"",buttons:We(h),code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.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=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!me.test(be(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async reportButtonClick(e,t){const s=await this.inboxModel.getMessage(e),i=3!==s.status;i&&await this.sendStatus(s.order,3),await this.sendStatus(s.order,6,t),i&&(s.status=3,await this.inboxModel.putMessage(s))}sendStatus(e,t,s){return new Promise(i=>{this.api.inboxStatus(e,t,s,{keepalive:!0,onSent:i}).catch(s=>te.write("error",`Pushwoosh: inbox status ${t} for "${e}" failed`,s)).finally(i)})}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}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.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class Ae{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,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(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,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(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 Ue{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new Ae(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new Ae(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new Ae(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new Ae(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new Ae(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new Ae(i,e);return a.index=t,a.countByIndex(s)}}class _e{constructor(e,t,s,i=new Ue,a=new de){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}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 Me(this.data,this.api,this)})}}class Re extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const Oe=e=>`params.${e}`;class Le{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","sharedDeviceHwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","ownUserId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isOwnManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(Oe(t),void 0)}async setApplicationCode(e){await this.store.set(Oe("applicationCode"),e)}async getApplicationCode(){return this.store.get(Oe("applicationCode"))}async setApiToken(e){return await this.store.set(Oe("apiToken"),e)}async getApiToken(){return this.store.get(Oe("apiToken"))}async setHwid(e){await this.store.set(Oe("hwid"),e)}async getHwid(){return this.store.get(Oe("hwid"))}async setSharedDeviceHwid(e){await this.store.set(Oe("sharedDeviceHwid"),e)}async getSharedDeviceHwid(){return this.store.get(Oe("sharedDeviceHwid"))}async setDeviceType(e){await this.store.set(Oe("deviceType"),e)}async getDeviceType(){return this.store.get(Oe("deviceType"))}async setFormFactor(e){await this.store.set(Oe("formFactor"),e)}async getFormFactor(){return this.store.get(Oe("formFactor"))}async setDeviceModel(e){await this.store.set(Oe("deviceModel"),e)}async getDeviceModel(){return this.store.get(Oe("deviceModel"))}async setLanguage(e){await this.store.set(Oe("language"),e)}async getLanguage(){return this.store.get(Oe("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(Oe("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(Oe("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(Oe("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(Oe("apiEntrypoint"),i)}async setTokens(e){await this.store.set(Oe("tokens"),e)}getTokens(){return this.store.get(Oe("tokens"))}async setApplicationServerKey(e){await this.store.set(Oe("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(Oe("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(Oe("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(Oe("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(Oe("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(Oe("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(Oe("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(Oe("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(Oe("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(Oe("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(Oe("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(Oe("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){const t=e?`${e}`:void 0;await this.store.set(Oe("userId"),t),await this.store.set(Oe("ownUserId"),t)}async getUserId(){return this.store.get(Oe("userId"))}async setUserIdFromSharedDevice(e){await this.store.set(Oe("userId"),e)}async getOwnUserId(){return this.store.get(Oe("ownUserId"))}async keepOwnUserId(){void 0===await this.store.getStored(Oe("ownUserId"))&&await this.store.set(Oe("ownUserId"),await this.getUserId()??"")}async getFeatureFlags(){return this.store.get(Oe("featureFlags"))}async setFeatureFlags(e){await this.store.set(Oe("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(Oe("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(Oe("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(Oe("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(Oe("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(Oe("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(Oe("email"))}async setStatusEmailWasChanged(e){await this.store.set(Oe("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(Oe("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(Oe("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(Oe("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(Oe("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(Oe("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(Oe("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(Oe("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(Oe("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(Oe("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(Oe("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(Oe("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(Oe("isManualUnsubscribed"),e),await this.store.set(Oe("isOwnManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(Oe("isManualUnsubscribed"),!1)}async setStatusManualUnsubscribedFromSharedDevice(e){await this.store.set(Oe("isManualUnsubscribed"),e)}getOwnStatusManualUnsubscribed(){return this.store.get(Oe("isOwnManualUnsubscribed"),!1)}async keepOwnStatusManualUnsubscribed(){void 0===await this.store.getStored(Oe("isOwnManualUnsubscribed"))&&await this.store.set(Oe("isOwnManualUnsubscribed"),await this.getStatusManualUnsubscribed())}async setStatusCommunicationDisabled(e){await this.store.set(Oe("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(Oe("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(Oe("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.getStored(Oe("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(Oe("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(Oe("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(Oe("sdkVersion"),e)}async getSdkVersion(){return this.store.get(Oe("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(Oe("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(Oe("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(Oe("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(Oe("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(Oe("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(Oe("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(Oe("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(Oe("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(Oe("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(Oe("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(Oe("features"),e)}async getFeatures(){return this.store.get(Oe("features"))}async setInitParams(e){await this.store.set(Oe("init"),e)}async getInitParams(){return this.store.get(Oe("init"))}async setInboxLastRequestCode(e){await this.store.set(Oe("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(Oe("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(Oe("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(Oe("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(Oe("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(Oe("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(Oe("delayedEvent"),e)}getDelayedEvent(){return this.store.get(Oe("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(Oe("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(Oe("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(Oe("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(Oe("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(Oe("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(Oe("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(Oe("logLevel"),e)}async getLogLevel(){return this.store.get(Oe("logLevel"),"error")}async getShownWebPopups(){return this.store.get(Oe("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(Oe("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(Oe("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(Oe("isRecurringVisitor"),!1)}}class Ne{constructor(e=new Le,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",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,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e,t){return this.createRequest("inboxStatus",e,t)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive});s.onSent?.();const c=await o,h=await this.checkResponse(c);return h.base_url&&await this.data.setApiEntrypoint(h.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(h.response)}`),h.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Re(s,t)}const t=await e.json();if(200!==t.status_code)throw new Re(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Fe{constructor(e,t=new Le,s=new Ne,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=R(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}forgetDeviceStatus(){this.checkDevicePromise=null,localStorage.removeItem(a)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async isDeviceSubscribed(e){const{exist:t,push_token_exist:s}=await this.apiClient.checkDevice({...await this.getRequestParams(),hwid:e});return t&&s}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice({keepUserId:e=!1}={}){const t=this.requestRegisterDevice(e);this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(e){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=await this.getRequestParams(),s=await this.data.getTokens();if(!s.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=this.getPushPermissionStatus(),r=await this.apiClient.registerDevice({...t,push_permission_status:i,locale:await this.getLocale(),page:ue(),push_token:s.pushToken,auth_token:s.authToken,public_key:s.publicKey,...e?{keep_user_id:!0}:{}});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(i),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),r}async unregisterDevice({silent:e=!1}={}){const t=await this.getRequestParams(),s=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,e||(localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{})),s}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={},i){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s,...i?{button_id:i}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=qe(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return qe(await this.data.getLanguage())||void 0}async registerUser(e,t=!0,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:i,device_type:a,...r}=await this.getRequestParams(),n=s??i,o=await this.data.getDeviceType(),c=`${e}`,h=await this.data.getUserId(),u=await this.apiClient.registerUser({...r,hwid:n,userId:c,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:o});return await this.data.setUserId(c),c&&c!==h&&this.eventBus.dispatchEvent("change-user-id",{userId:c}),t&&await this.data.setStatusUserIdWasChanged(!0),u}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 s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}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:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}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:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:U()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t,s,i){const a=await this.getRequestParams();return this.apiClient.inboxStatus({...a,inbox_code:e,status:t,time:(new Date).getTime(),...void 0===s?{}:{button_id:s}},i)}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(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const 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),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,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&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),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.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(T);return e}}function qe(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class Be{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class $e extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const je=/json\/1\.3\/?$/,He="api/v2/device-api/getFeatureFlags";const Ve=18e5;class Ke{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new Be(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Ve)){await this.deps.data.setFeatureFlagImpressions({...Je(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new $e("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new $e("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(je.test(t))return t.replace(je,He);try{return`${new URL(t).origin}/${He}`}catch(e){return i.replace(je,He)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new $e(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new $e(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new $e("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!ze(c.response))throw new $e(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Ge(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Ye(this.cache.flags):""}}function ze(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ge(e){const t={};return ze(e)?(Object.keys(e).forEach(s=>{const i=e[s];ze(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:ze(i.properties)?i.properties:{}})}),t):t}function Je(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Ve&&(s[i]=e[i])}),s}function Ye(e){return Array.isArray(e)?`[${e.map(Ye).join(",")}]`:ze(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ye(e[t])}`).join(",")}}`:JSON.stringify(e)}const Xe=[["opera",/\bOPR\/|Opera/],["edge",/\bEdge?\//],["firefox",/firefox/i],["chrome",/\bChrome\/|\bCriOS\//],["safari",/\bSafari\//]];function Qe(e){const t=Xe.find(([,t])=>t.test(e));return t?t[0]:"unknown"}function Ze({userAgent:e,appName:t,appVersion:s}){const i=e.match(/\bOPR\/(\d+)/);if(null!==i)return`Opera ${i[1]}`;const a=e.match(/\bEdge?\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;const[,r="",n]=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[],o=n?[r,n]:[t,s,"-?"],c=e.match(/version\/([.\d]+)/i);return null!==c&&o.splice(1,1,c[1]),o.join(" ")}function et(e){return{name:Qe(e.userAgent),model:Ze(e)}}function tt(e){const t=e.userAgentData?.mobile;return"boolean"==typeof t?t?"MOBILE":"DESKTOP":/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e.userAgent)?"MOBILE":"DESKTOP"}function st(e){const t=e.navigator?.userAgent??"";return{webPush:!!e.navigator?.serviceWorker&&"PushManager"in e&&"Notification"in e,safariLegacy:"safari"in e&&t.includes("Safari")}}function it(e){return e.webPush||e.safariLegacy}function at({legacySafari:e,unifiedPlatform:t,browser:s}){return e?10:t?11:"firefox"===s?12:11}class rt{constructor(e){this.browser=e.browser,this.capabilities=e.capabilities,this.formFactor=e.formFactor}get isAvailableNotifications(){return it(this.capabilities)}get isAvailableServiceWorker(){return this.capabilities.webPush}get isSafari(){return this.capabilities.safariLegacy}get isOpera(){return"opera"===this.browser.name}get isEdge(){return"edge"===this.browser.name}get browserVersion(){return this.browser.model}get isMobile(){return"MOBILE"===this.formFactor}get isDesktop(){return"DESKTOP"===this.formFactor}get platform(){return this.getPlatformType()}getPlatformType(){return at({legacySafari:this.capabilities.safariLegacy,unifiedPlatform:!1,browser:this.browser.name})}getBrowserVersion(){return this.browser.model}getFormFactor(){return this.formFactor}}const nt="pushwoosh-recommendations-views";function ot(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class ct{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:ot(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(nt));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(nt,JSON.stringify(i))}catch{}return!1}}const ht="sdkUsageReportedOn";class ut{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.deprecatedApis=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}recordDeprecatedApi(e){this.deprecatedApis.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(ht)===t)return;localStorage.setItem(ht,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents],deprecated_apis:[...this.deprecatedApis]},{keepalive:!0}).catch(()=>{})}}const dt=/^www\./;const lt="pw_root_domain_probe";class gt{constructor(e,t){this.name=`pw_shared_device_${e}`,this.domain=t}static forApplication(e){const t=function(e){const t=e.split(".");if(t.length<2||/^[\d.]+$/.test(e)||e.includes(":"))return null;for(let e=t.length-2;e>=0;e--){const s=t.slice(e).join("."),i=U();if(document.cookie=`${lt}=${i}; domain=${s}; path=/; SameSite=Lax`,document.cookie.split("; ").includes(`${lt}=${i}`))return document.cookie=`${lt}=; domain=${s}; path=/; max-age=0; SameSite=Lax`,s}return null}(location.hostname);return t?new gt(e,t):null}read(){const e=`${this.name}=`,t=document.cookie.split("; ").find(t=>t.startsWith(e));if(!t)return null;try{const s=JSON.parse(decodeURIComponent(t.slice(e.length)));return"string"==typeof s?.hwid&&s.hwid?{hwid:s.hwid,subscribed:!0===s.subscribed,manualUnsubscribed:!0===s.manualUnsubscribed,askToSubscribe:!0===s.askToSubscribe,userId:"string"==typeof s.userId&&s.userId?s.userId:void 0,tokenOrigin:"string"==typeof s.tokenOrigin&&s.tokenOrigin?s.tokenOrigin:void 0}:null}catch{return null}}write(e){const t="https:"===location.protocol?"; Secure":"",s=encodeURIComponent(JSON.stringify(e));document.cookie=`${this.name}=${s}; domain=${this.domain}; path=/; max-age=34560000; SameSite=Lax${t}`}}class pt{constructor(e,t,s,i){this.record=null,this.origin=location.origin,this.data=t,this.api=s,this.isPermissionGranted=i,e.addEventHandler("register",()=>this.update({subscribed:!0,manualUnsubscribed:!1,askToSubscribe:!1,tokenOrigin:this.origin})),e.addEventHandler("change-user-id",({userId:e})=>this.update({userId:e}))}async choose(e,t,s,i=!1){if(this.record=t?gt.forApplication(e):null,!this.record)return void await this.leave(e,i);const a=await this.data.getHwid(),r=await this.readShared(a);if(r&&(r.hwid===a||r.subscribed))return void await this.join(r,s);const n=await this.isOwnDeviceSubscribed(),o=await this.readShared(a);!o||!o.subscribed&&n?await this.join({hwid:a,subscribed:n,manualUnsubscribed:!n&&await this.data.getStatusManualUnsubscribed(),userId:o?.userId,tokenOrigin:n?this.origin:void 0},s):await this.join(o,s)}isSubscribed(){return!!this.record?.read()?.subscribed}mayDropSubscription(){return!this.record||this.record.read()?.tokenOrigin===this.origin}async isOwnDeviceSubscribed(){return await this.hasPushToken()&&await this.api.checkDeviceSubscribeForPushNotifications(!1)}async hasPushToken(){return!!(await this.data.getTokens())?.pushToken}async holdsOwnSubscription(e){return!!e.subscribed&&e.tokenOrigin!==this.origin&&await this.hasPushToken()}async readShared(e){const t=this.record.read();return t&&t.hwid!==e&&await this.holdsOwnSubscription(t)&&!await this.api.isDeviceSubscribed(t.hwid)?{...t,subscribed:!1,askToSubscribe:!0}:t}async dropOwnSubscription(){const e=await(navigator.serviceWorker?.getRegistration(await this.data.getServiceWorkerUrl()));await((await(e?.pushManager.getSubscription()))?.unsubscribe()),await this.data.setTokens({})}async join(e,t){await this.data.keepOwnUserId(),await this.data.keepOwnStatusManualUnsubscribed();const s=await this.holdsOwnSubscription(e),i=s&&e.hwid!==await this.data.getHwid(),a=i?t??await this.data.getOwnUserId():void 0;let r=e;if(a&&(await this.api.registerUser(a,!1,e.hwid),r={...r,userId:a}),this.record.write(r),i&&await this.api.unregisterDevice({silent:!0}),s&&await this.dropOwnSubscription(),await this.switchTo(e.hwid),await this.data.setSharedDeviceHwid(e.hwid),a||t||(e.userId?await this.data.setUserIdFromSharedDevice(e.userId):await this.data.setUserId(await this.data.getOwnUserId())),e.subscribed&&!await this.api.checkDeviceSubscribeForPushNotifications(!1)){const e={subscribed:!1,askToSubscribe:!0};await this.update(e),r={...r,...e}}await this.holdManualUnsubscribe(r)}mustAskToSubscribe(){return!!this.record?.read()?.askToSubscribe}async holdManualUnsubscribe(e){e.askToSubscribe?await this.data.setStatusManualUnsubscribedFromSharedDevice(this.isPermissionGranted()):(e.subscribed||e.manualUnsubscribed)&&await this.data.setStatusManualUnsubscribedFromSharedDevice(!!e.manualUnsubscribed)}async retire(e){const t=await this.data.getHwid();this.record?.read()?.hwid===t&&this.record.write({hwid:`${e}_${U()}`,askToSubscribe:!0}),this.record=null}async leave(e,t){const s=await this.data.getSharedDeviceHwid();if(!s)return;const i=s===await this.data.getHwid(),a=i&&await this.hasPushToken();a&&t&&await this.dropSharedSubscription(e,s),!i||a&&!t||(await this.switchTo(`${e}_${U()}`),await this.data.setUserId(await this.data.getOwnUserId()),await this.data.setStatusManualUnsubscribed(await this.data.getOwnStatusManualUnsubscribed())),await this.data.setSharedDeviceHwid(void 0)}async dropSharedSubscription(e,t){await this.api.unregisterDevice({silent:!0});const s=gt.forApplication(e),i=s?.read();i?.hwid===t&&s.write({...i,subscribed:!1,askToSubscribe:!0,tokenOrigin:void 0})}async update(e){const t=await this.data.getHwid(),s=this.record?.read();s&&s.hwid===t&&this.record.write({...s,...e})}async switchTo(e){await this.data.getHwid()!==e&&(await this.data.setHwid(e),this.api.forgetDeviceStatus())}}function mt(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function wt(e){return"safari"in e?e.safari?.pushNotification:void 0}function bt(e,t){try{return wt(e)?.permission(t)}catch{return}}function ft(e,t){const s=t?bt(e,t):void 0;return s?.permission===c&&!!s.deviceToken}class yt{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}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 te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice({keepUserId:this.config.keepUserId})}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&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.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=${U()}`),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),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class vt{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()===c}checkIsPermissionDefault(){return this.getPermission()===h}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 te.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(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Pt{constructor(){var e;this.ready=!1,this.rawInitParams={},this.isSharedDeviceEnabled=!1,this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isSiteOpenedEventOn=!1,this.isLegacySafari=!1,this.waitForPermissionWork=R(1e4),this.moduleRegistry={},this.sdkUsage=new ut,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(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 X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new Le,this.apiClient=new Ne(this.data),this.api=new Fe(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getReportedPushPermissionStatus()),this.sharedDevice=new pt(this.eventBus,this.data,this.api,()=>this.readPermission()===c),this.featureFlags=new Ke({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new ct({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.environment={browser:et((e=A()).navigator),capabilities:st(e),formFactor:tt(e.navigator)},this.legacyPlatformChecker=new rt(this.environment),this.inboxModel=new _e(this.eventBus,this.data,this.api),this.pwinbox=new Me(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}get platformChecker(){return this.sdkUsage.recordDeprecatedApi("platformChecker"),this.legacyPlatformChecker}push(e){if(_(e))this.subscribeToLegacyEvents(u,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){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await this.dropSubscription(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}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();const e=!!(await this.data.getTokens())?.pushToken,t=this.driver?.checkIsPermissionGranted();t&&e&&(await this.api.registerDevice(),await this.sendData())}else{this.featureFlags.reset(),await this.api.unregisterDevice();const e=await this.data.getOwnStatusManualUnsubscribed();await this.data.setStatusManualUnsubscribed(e||await this.data.getStatusManualUnsubscribed()),await this.sharedDevice.retire(this.initParams.applicationCode)}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.sharedDevice.retire(this.initParams.applicationCode),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}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 it(this.environment.capabilities)}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){he(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...M,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.environment.formFactor),await this.data.setDeviceModel(this.environment.browser.model);if(await this.data.getStatusLanguageWasChanged()||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.126.0"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.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.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.initStep("chooseDevice",async()=>{const{enable:e,excludedSites:t}=ae(await this.data.getFeatures())?.sharedDevice??{},s=!0===e&&function(e,t){if(!Array.isArray(t))return!1;const s=e.toLowerCase().replace(dt,"");return t.some(e=>"string"==typeof e&&e.toLowerCase().replace(dt,"")===s)}(location.hostname,t);this.isSharedDeviceEnabled=!0===e&&!s;const i=this.isSharedDeviceEnabled&&!await this.data.getStatusDropAllData();await this.sharedDevice.choose(this.initParams.applicationCode,i,this.getInitUserId(),s)}),await this.data.setDeviceType(this.resolvePlatformType()),this.isSiteOpenedEventOn&&this.sendPostEventVisitedPage(),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"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 initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){const{safariWebsitePushID:e,unifiedPlatform:t=!1}=this.initParams??{},{capabilities:s,browser:i}=this.environment;return this.isLegacySafari=function({capabilities:e,hasLegacySubscription:t,webVapidConfigured:s,unifiedPlatform:i}){return!(!e.safariLegacy||e.webPush&&!t&&(i||s))}({capabilities:s,hasLegacySubscription:s.safariLegacy&&ft(A(),e),webVapidConfigured:this.isWebVapidConfigured,unifiedPlatform:t}),at({legacySafari:this.isLegacySafari,unifiedPlatform:t,browser:i.name})}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+U();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(T)}catch(e){te.info(e,T)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}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.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void(i&&this.isSharedDeviceEnabled||await this.unsubscribe());a&&(await this.dropSubscription(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.dropSubscription();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.dropSubscription();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}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())}getPushPermissionStatus(){return this.driver?mt(this.driver.getPermission()):function(e,t){const s=wt(e);if(s&&t){const s=bt(e,t);return s?mt(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?mt(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}getReportedPushPermissionStatus(){const e=this.getPushPermissionStatus();return"granted_explicit"!==e&&this.sharedDevice.isSubscribed()?void 0:e}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c){const t=!await this.data.getStatusManualUnsubscribed()&&!this.sharedDevice.mustAskToSubscribe();s||e||this.isPushDisabled||!t||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight))}else if(s){const e=this.dropSubscription(()=>this.dropRevokedSubscription(t)).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropSubscription(e=()=>this.unsubscribe()){this.sharedDevice.mayDropSubscription()&&await e()}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}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||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];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(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(ae(t)),this.isSiteOpenedEventOn=!!t.events?.some(e=>e===W),t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=re(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=re(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(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.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new vt(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}const{webPush:e}=this.environment.capabilities;te.info({isAvailableServiceWorker:e}),e&&(this.driver=new yt(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=ue(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in O:this.eventBus.addEventHandler(O[e].name,s=>{const{prop:i}=O[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v: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