web-push-notifications 3.98.0 → 3.99.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 +12 -0
- package/modules/Api/Api.d.ts +2 -0
- package/modules/ApiClient/ApiClient.d.ts +1 -0
- package/modules/ApiClient/ApiClient.types.d.ts +13 -1
- package/npm.js +1 -1
- package/npm.js.map +1 -1
- package/package.json +2 -2
- package/service-worker.js +1 -1
- package/service-worker.js.map +1 -1
- package/widget-subscription.js.map +1 -1
- package/widget-web-popups.js +1 -1
- package/widget-web-popups.js.map +1 -1
- package/widgets/WebPopups/EmbeddedWebPopups.d.ts +1 -1
- package/widgets/WebPopups/WebPopupsWidget.d.ts +1 -0
- package/widgets/WebPopups/__tests__/deviceSubmitApi.test.d.ts +1 -0
- package/widgets/WebPopups/__tests__/formValuesRender.test.d.ts +1 -0
- package/widgets/WebPopups/deviceSubmitApi.d.ts +2 -1
- package/widgets/WebPopups/renderer.d.ts +5 -2
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,18 @@ 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
|
+
## feat(web-popups): submit web content forms to submitPopupForm
|
|
13
|
+
|
|
14
|
+
- A FORM web content (email input, tag inputs, consent, submit) sends its values in one request to
|
|
15
|
+
`/json/1.3/submitPopupForm`, under the code of the campaign that shows it and with the visitor's hwid.
|
|
16
|
+
The same content in a popup and in an inline block submits under each campaign's own code.
|
|
17
|
+
- `OK` opens the Success page, `INVALID_EMAIL` shows the email input's invalid message. Any other answer
|
|
18
|
+
or a network error shows the Submit error, and the visitor can submit again.
|
|
19
|
+
- Nothing is sent while communication is disabled.
|
|
20
|
+
- A content with form fields opened without a campaign (inbox `wp`, `show(<content code>)`) is not shown:
|
|
21
|
+
`show()` logs and resolves `false`, and the inbox follows the message link as before.
|
|
22
|
+
- `@pushwoosh/websdk-common` 6.22.1.
|
|
23
|
+
|
|
12
24
|
## feat(widgets): load widgets from the bundle's own host, version widget URLs
|
|
13
25
|
|
|
14
26
|
- The CDN bundle loads widgets from the folder it was itself loaded from, or from `cdn.pushwoosh.com/webpush/v3/` when that folder is unknown.
|
package/modules/Api/Api.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type WebPopupFormValues } from '@pushwoosh/websdk-common/web-popups';
|
|
1
2
|
import { type MultiRegisterDeviceRequest } from './Api.types';
|
|
2
3
|
import { type EventBus } from '../../core/modules/EventBus';
|
|
3
4
|
import { type TPushPermissionStatus } from '../../services/PushService/pushPermissionStatus';
|
|
@@ -50,6 +51,7 @@ export declare class Api {
|
|
|
50
51
|
getPopupForms(): Promise<Array<WebPopup>>;
|
|
51
52
|
getPopupFormContent(code: string): Promise<IMapResponse['getPopupFormContent']>;
|
|
52
53
|
recordPopupFormEvent(code: string, event: 1 | 2): Promise<IMapResponse['recordPopupFormEvent']>;
|
|
54
|
+
submitPopupForm(code: string, values: WebPopupFormValues): Promise<IMapResponse['submitPopupForm']>;
|
|
53
55
|
postEvent(event: string, attributes: {
|
|
54
56
|
[key: string]: any;
|
|
55
57
|
}, init?: IRequestInit): Promise<IMapResponse['postEvent']>;
|
|
@@ -13,6 +13,7 @@ export declare class ApiClient {
|
|
|
13
13
|
getPopupForms(options: IMapRequest['getPopupForms']): Promise<IMapResponse['getPopupForms']>;
|
|
14
14
|
getPopupFormContent(options: IMapRequest['getPopupFormContent']): Promise<IMapResponse['getPopupFormContent']>;
|
|
15
15
|
recordPopupFormEvent(options: IMapRequest['recordPopupFormEvent']): Promise<IMapResponse['recordPopupFormEvent']>;
|
|
16
|
+
submitPopupForm(options: IMapRequest['submitPopupForm']): Promise<IMapResponse['submitPopupForm']>;
|
|
16
17
|
applicationOpen(options: IMapRequest['applicationOpen']): Promise<IMapResponse['applicationOpen']>;
|
|
17
18
|
registerDevice(options: IMapRequest['registerDevice']): Promise<IMapResponse['registerDevice']>;
|
|
18
19
|
unregisterDevice(options: IMapRequest['unregisterDevice']): Promise<IMapResponse['unregisterDevice']>;
|
|
@@ -21,6 +21,7 @@ type TMethodRegisterWhatsappNumber = 'registerWhatsappNumber';
|
|
|
21
21
|
type TMethodGetPopupForms = 'getPopupForms';
|
|
22
22
|
type TMethodGetPopupFormContent = 'getPopupFormContent';
|
|
23
23
|
type TMethodRecordPopupFormEvent = 'recordPopupFormEvent';
|
|
24
|
+
type TMethodSubmitPopupForm = 'submitPopupForm';
|
|
24
25
|
type TMethodSetEmailTags = 'setEmailTags';
|
|
25
26
|
type TMethodPostEvent = 'postEvent';
|
|
26
27
|
type TMethodGetInboxMessages = 'getInboxMessages';
|
|
@@ -55,6 +56,12 @@ interface IRequestRecordPopupFormEvent extends IRequest {
|
|
|
55
56
|
code: string;
|
|
56
57
|
event: 1 | 2;
|
|
57
58
|
}
|
|
59
|
+
interface IRequestSubmitPopupForm extends IRequest {
|
|
60
|
+
code: string;
|
|
61
|
+
email?: string;
|
|
62
|
+
tags: Record<string, unknown>;
|
|
63
|
+
policy_accepted: boolean;
|
|
64
|
+
}
|
|
58
65
|
interface IRequestApplicationOpen extends IRequest {
|
|
59
66
|
push_permission_status?: TPushPermissionStatus;
|
|
60
67
|
}
|
|
@@ -150,6 +157,9 @@ interface IResponseGetPopupFormContent {
|
|
|
150
157
|
json: string;
|
|
151
158
|
html: string | null;
|
|
152
159
|
}
|
|
160
|
+
interface IResponseSubmitPopupForm {
|
|
161
|
+
result: 'OK' | 'INVALID_EMAIL';
|
|
162
|
+
}
|
|
153
163
|
interface IResponseGetTags {
|
|
154
164
|
result: {
|
|
155
165
|
[key: string]: any;
|
|
@@ -164,7 +174,7 @@ interface IResponseGetInboxMessages {
|
|
|
164
174
|
deleted: Array<string>;
|
|
165
175
|
new_inbox: number;
|
|
166
176
|
}
|
|
167
|
-
export type TMethod = TMethodCheckDevice | TMethodGetConfig | TMethodApplicationOpen | TMethodRegisterDevice | TMethodUnregisterDevice | TMethodDeleteDevice | TMethodMessageDeliveryEvent | TMethodPushStat | TMethodSetTags | TMethodGetTags | TMethodRegisterUser | TMethodRegisterEmail | TMethodRegisterEmailUser | TMethodRegisterSmsNumber | TMethodRegisterWhatsappNumber | TMethodGetPopupForms | TMethodGetPopupFormContent | TMethodRecordPopupFormEvent | TMethodSetEmailTags | TMethodPostEvent | TMethodGetInboxMessages | TMethodInboxStatus | TMethodMultiRegisterDevice;
|
|
177
|
+
export type TMethod = TMethodCheckDevice | TMethodGetConfig | TMethodApplicationOpen | TMethodRegisterDevice | TMethodUnregisterDevice | TMethodDeleteDevice | TMethodMessageDeliveryEvent | TMethodPushStat | TMethodSetTags | TMethodGetTags | TMethodRegisterUser | TMethodRegisterEmail | TMethodRegisterEmailUser | TMethodRegisterSmsNumber | TMethodRegisterWhatsappNumber | TMethodGetPopupForms | TMethodGetPopupFormContent | TMethodRecordPopupFormEvent | TMethodSubmitPopupForm | TMethodSetEmailTags | TMethodPostEvent | TMethodGetInboxMessages | TMethodInboxStatus | TMethodMultiRegisterDevice;
|
|
168
178
|
export interface IMapRequest {
|
|
169
179
|
checkDevice: IRequest;
|
|
170
180
|
getConfig: IRequestGetConfig;
|
|
@@ -184,6 +194,7 @@ export interface IMapRequest {
|
|
|
184
194
|
getPopupForms: IRequest;
|
|
185
195
|
getPopupFormContent: IRequestGetPopupFormContent;
|
|
186
196
|
recordPopupFormEvent: IRequestRecordPopupFormEvent;
|
|
197
|
+
submitPopupForm: IRequestSubmitPopupForm;
|
|
187
198
|
setEmailTags: IRequestSetEmailTags;
|
|
188
199
|
postEvent: IRequestPostEvent;
|
|
189
200
|
getInboxMessages: IRequestGetInboxMessages;
|
|
@@ -209,6 +220,7 @@ export interface IMapResponse {
|
|
|
209
220
|
getPopupForms: IResponseGetPopupForms;
|
|
210
221
|
getPopupFormContent: IResponseGetPopupFormContent;
|
|
211
222
|
recordPopupFormEvent: IResponse;
|
|
223
|
+
submitPopupForm: IResponseSubmitPopupForm;
|
|
212
224
|
setEmailTags: IResponse;
|
|
213
225
|
postEvent: IResponsePostEvent;
|
|
214
226
|
getInboxMessages: IResponseGetInboxMessages;
|
package/npm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var i in s)("object"==typeof exports?exports:t)[i]=s[i]}}(this,()=>(()=>{"use strict";const t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}};let e={};t.r(e),t.d(e,{Pushwoosh:()=>Lt});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",C="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",x="PW_SiteOpened",W="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.",_=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function M(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const R=t=>"function"==typeof t;function N(t){const e=new WeakSet;return async s=>{if(e.has(s))return!1;const i=await function(t,e){let s;const i=new Promise(t=>{s=setTimeout(()=>t(!1),e)}),a=t.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,t);return i||e.add(s),i}}const F={[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"},[C]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[k]:{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"}},U="keyValue",O="messages",q="inboxMessages";function L(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const B=[L(U,function(t){t.createObjectStore(U,{keyPath:"key"})}),L("log",function(t){const e=t.createObjectStore("log",{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),L(O,function(t){t.createObjectStore(O,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),L(q,function(t){const e="status",s=t.createObjectStore(q,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class ${constructor(t,e=new j){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function V(t,e){console.info("onversionchange",e),t.close()}let H;function K(){return H||(H=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=V.bind(null,i,e),t(i)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=V.bind(null,s,e);new $(s).applyMigrations()}})),H}function z(t){return K().then(e=>new Promise((s,i)=>t(e,s,i)))}class G{_add(t){return z((e,s,i)=>{const a=e.transaction([this.name],"readwrite").objectStore(this.name).add(t);a.onsuccess=()=>{s(t)},a.onerror=()=>{i(a.error)}}).then(t=>this.getAll().then(e=>{if(Array.isArray(e)){const s=e.map(t=>t.id).sort((t,e)=>t==e?0:t<e?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(t=>this.delete(t))).then(()=>t)}return t}))}delete(t){return z((e,s,i)=>{const a=e.transaction([this.name],"readwrite").objectStore(this.name).delete(t);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((t,e,s)=>{const i=[],a=t.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=t=>{const s=t.target.result;s?(s.value&&i.push(s.value),s.continue()):e(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=U,{get:(t,e)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(t);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((t,e,s)=>{const i={},a=t.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?e(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=t=>{const e=t.target.result;e?(i[e.key]=e.value.value,e.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(t,e){const s=await this.get(t),{...i}=e;await this.set(t,{...s,...i})},set:(t,e)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:t,value:e});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(t):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(t,e,s){const i={type:t,environment:this.environment,message:`${e}`,date:new Date};return e instanceof Error&&(i.stack=e.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=O,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},Z={error:1,info:2,debug:3};let tt=3;const et={setLevel(t){Z[t]||(t="error"),tt=Z[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),X.add(t,e,s)}};Object.keys(Z).forEach(t=>{const e=Z[t];et[t]=(...s)=>{e<=tt&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});class st{constructor(){this.addEventHandler=(t,e)=>{let s=this.handlers[t];s||(s=[]),s.push(e),this.handlers[t]=s},this.removeEventHandler=(t,e)=>{const s=this.handlers[t];s&&(this.handlers[t]=s.filter(t=>t!==e))},this.dispatchEvent=(t,e)=>{const s=e.eventId||M(),i=this.handlers[t];return i?(i.forEach(t=>{R(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}}const it=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function at(t,e){if(e)return{...t,...e}}class rt{constructor(t=new Date){this._date=t}set date(t){this._date=t}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const t=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(t)}addDays(t){const e=this._date.getTime()+24*t*60*60*1e3;this._date=new Date(e)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const nt=["classic","captioned","banner","carousel"];function ot(t){return(Array.isArray(t)?t:[]).filter(t=>!!t&&!!t.imageUrl).slice(0,5)}const ct=/^(?:javascript|vbscript|data|blob|file):/i,ht=/^[a-z][a-z\d+\-.]*:/i;function ut(t){return t.split("").filter(t=>t.charCodeAt(0)>32&&127!==t.charCodeAt(0)).join("")}function dt(t){const e=ut(t);return ht.test(e)&&!ct.test(e)}function lt(t,e){return e||t.image||""}function gt(t){const e=["displayType","carousel","image"];return Object.keys(t).filter(t=>-1===e.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}class pt{constructor(t,e,s,i={},a=()=>Promise.resolve(void 0),r=new rt){this.data=t,this.api=e,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(t){try{return JSON.parse(t)||{}}catch(e){return et.write("error",`Pushwoosh: cannot parse inbox action_params: ${t}`,e),{}}}messageTypeFactory(t,e){let s=0;return 2===t?s=1:"l"in e&&null!=e.l&&(s=e.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(t,e,s){const i=[],a=[];e.forEach(async e=>{-1!==t.indexOf(e.inbox_id)&&(e.status=s,i.push(e),a.push(this.api.inboxStatus(e.order,e.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:t,action_params:e,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(e),h=function(t){const e=t?.u;if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)||{}}catch{return{}}return"object"==typeof e?e:{}}(c),u=function(t){return(Array.isArray(t.carousel)?t.carousel:[]).filter(t=>!!t&&!!t.image).slice(0,5).map(t=>({imageUrl:t.image,caption:t.title||"",link:t.url&&dt(t.url)?t.url:""}))}(h),d=function(t,e,s){return t?.b||s||e.image||""}(c,h,s),l=function(t){const e=!!t.title,s=!!t.body,i=function(t){return t.bannerUrl||t.iconUrl||""}(t);let a=t.layoutType;switch(nt.includes(a)||(a=t.bannerUrl&&!e?"banner":t.bannerUrl&&e&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&e&&s?"captioned":"classic";case"carousel":return e&&s&&ot(t.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:lt(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=lt(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:gt(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,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 t=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((t,e)=>parseInt(e.send_date,10)-parseInt(t.send_date,10)).sort((t,e)=>parseInt(e.order||"0",10)-parseInt(t.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(t)}async readMessagesWithCodes(t){const e=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,e,2)}async performActionForMessageWithCode(t){const e=await this.inboxModel.getMessage(t),s=this.parseActionParams(e.action_params),i=this.messageTypeFactory(e.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ct.test(ut(r)))&&(document.location.href=s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async showWebPopup(t){if(!t)return!1;try{const e=this.moduleRegistry.webPopups??await this.loadWebPopups();return e?await e.show(t):(et.write("error",`Pushwoosh: inbox message opens web popup "${t}", but the web popups widget could not be loaded`),!1)}catch(e){return et.write("error",`Pushwoosh: failed to open web popup "${t}" from inbox`,e),!1}}async deleteMessagesWithCodes(t){const e=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,[...e,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class mt{constructor(t,e){this.name=e,this.store=t.transaction(this.name,"readwrite").objectStore(this.name)}set index(t){this.store.indexNames.contains(t)?this._index=this.store.index(t):console.warn(`Index "${t}" in `)}writeRequestPromise(t,e){return new Promise((s,i)=>{t.onsuccess=()=>{s(e)},t.onerror=()=>{i(t.error)}})}readRequestPromise(t,e){return new Promise((s,i)=>{t.onsuccess=t=>{const i=t.target;s(i.result||e)},t.onerror=()=>{i(t.error)}})}put(t,e){const s=this.store.put(t,e);return this.writeRequestPromise(s,e)}add(t,e){return this.put(t,e)}delete(t){const e=this.store.delete(t);return this.writeRequestPromise(e)}get(t,e){const s=this.store.get(t);return this.readRequestPromise(s,e)}getAll(){const t=this.store.openCursor(),e=[];return new Promise((s,i)=>{t.onsuccess=t=>{const i=t.target.result;i?(e.push(i.value),i.continue()):s(e)},t.onerror=()=>{i(t.error)}})}count(t){const e=this.store.count(t);return this.readRequestPromise(e,0)}countByIndex(t){const e=this._index.count(t);return this.readRequestPromise(e,0)}}class wt{getDB(){return K()}async put(t,e,s){const i=await this.getDB();return new mt(i,t).put(e,s)}async delete(t,e){const s=await this.getDB();return new mt(s,t).delete(e)}async get(t,e,s){const i=await this.getDB();return new mt(i,t).get(e,s)}async getAll(t){const e=await this.getDB(),s=new mt(e,t);return await s.getAll()||[]}async count(t,e){const s=await this.getDB();return new mt(s,t).count(e)}async countByIndex(t,e,s){const i=await this.getDB(),a=new mt(i,t);return a.index=e,a.countByIndex(s)}}class bt{constructor(t,e,s,i=new wt,a=new rt){this.eventBus=t,this.data=e,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const t=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(t.next,t.new_inbox),t}async storeGetInboxMessagesRequestParams(t,e){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(t),await this.data.setInboxNewMessagesCount(e)}async putServerMessages(t){const e=t.map(async t=>{const e=await this.storage.get(this.storeName,t.inbox_id,{});return"status"in e&&(t.status=e.status),this.putMessage(t)});return Promise.all(e)}putMessage(t){return this.storage.put(this.storeName,t)}putBulkMessages(t){const e=t.map(t=>this.putMessage(t));return Promise.all(e)}deleteMessages(t){const e=t.map(t=>this.storage.delete(this.storeName,t));return Promise.all(e)}async deleteExpiredMessages(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString(),e=(await this.storage.getAll(this.storeName)).filter(e=>e.rt<t).map(t=>t.inbox_id);return this.deleteMessages(e)}getMessage(t){return this.storage.get(this.storeName,t)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>2===t.status||3===t.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>1===t.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[t,e]=[2,3],s=IDBKeyRange.bound(t,e);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const t=await this.getInboxMessages();await this.deleteExpiredMessages(),t.deleted&&await this.deleteMessages(t.deleted),await this.putServerMessages(t.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new pt(this.data,this.api,this)})}}class ft extends Error{constructor(t,e){super(t),this.name="ApiRequestError",this.statusCode=e}}const yt=t=>`params.${t}`;class vt{constructor(t=J){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const e of t)await this.store.set(yt(e),void 0)}async setApplicationCode(t){await this.store.set(yt("applicationCode"),t)}async getApplicationCode(){return this.store.get(yt("applicationCode"))}async setApiToken(t){return await this.store.set(yt("apiToken"),t)}async getApiToken(){return this.store.get(yt("apiToken"))}async setHwid(t){await this.store.set(yt("hwid"),t)}async getHwid(){return this.store.get(yt("hwid"))}async setDeviceType(t){await this.store.set(yt("deviceType"),t)}async getDeviceType(){return this.store.get(yt("deviceType"))}async setFormFactor(t){await this.store.set(yt("formFactor"),t)}async getFormFactor(){return this.store.get(yt("formFactor"))}async setDeviceModel(t){await this.store.set(yt("deviceModel"),t)}async getDeviceModel(){return this.store.get(yt("deviceModel"))}async setLanguage(t){await this.store.set(yt("language"),t)}async getLanguage(){return this.store.get(yt("language"),"en")}async setStatusLanguageWasChanged(t){await this.store.set(yt("languageWasChanged"),t)}async getStatusLanguageWasChanged(){return this.store.get(yt("languageWasChanged"),!1)}async setApiEntrypoint(t){await this.store.set(yt("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(yt("apiEntrypoint"),i)}async setTokens(t){await this.store.set(yt("tokens"),t)}getTokens(){return this.store.get(yt("tokens"))}async setApplicationServerKey(t){await this.store.set(yt("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(yt("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(yt("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(yt("isVapidChanged"),!1)}async setWebSitePushId(t){await this.store.set(yt("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(yt("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(yt("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(yt("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(yt("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(yt("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(yt("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(yt("userId"))}async getFeatureFlags(){return this.store.get(yt("featureFlags"))}async setFeatureFlags(t){await this.store.set(yt("featureFlags"),t)}async getFeatureFlagImpressions(){return this.store.get(yt("featureFlagImpressions"),{})}async setFeatureFlagImpressions(t){await this.store.set(yt("featureFlagImpressions"),t)}async setStatusUserIdWasChanged(t){await this.store.set(yt("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(yt("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(yt("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(yt("email"))}async setStatusEmailWasChanged(t){await this.store.set(yt("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(yt("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(yt("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(yt("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(yt("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(yt("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(yt("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(yt("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(yt("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(yt("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(yt("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(yt("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(yt("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(yt("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(yt("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(yt("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(yt("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(yt("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(yt("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(yt("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(yt("sdkVersion"),t)}async getSdkVersion(){return this.store.get(yt("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(yt("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(yt("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(yt("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(yt("serviceWorkerUrl"),s)}async setServiceWorkerScope(t){t&&await this.store.set(yt("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(yt("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(yt("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(yt("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(yt("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(yt("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(yt("features"),t)}async getFeatures(){return this.store.get(yt("features"))}async setInitParams(t){await this.store.set(yt("init"),t)}async getInitParams(){return this.store.get(yt("init"))}async setInboxLastRequestCode(t){await this.store.set(yt("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(yt("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(yt("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(yt("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(yt("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(yt("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(yt("delayedEvent"),t)}getDelayedEvent(){return this.store.get(yt("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(yt("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(yt("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(yt("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(yt("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(t){await this.store.set(yt("subscriptionWidgetHistory"),t)}async getSubscriptionWidgetHistory(){return this.store.get(yt("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(t){await this.store.set(yt("logLevel"),t)}async getLogLevel(){return this.store.get(yt("logLevel"),"error")}async getShownWebPopups(){return this.store.get(yt("shownWebPopups"),[])}async addShownWebPopup(t){const e=await this.getShownWebPopups();e.includes(t)||(e.push(t),await this.store.set(yt("shownWebPopups"),e))}async setIsRecurringVisitor(t){await this.store.set(yt("isRecurringVisitor"),t)}async getIsRecurringVisitor(){return this.store.get(yt("isRecurringVisitor"),!1)}}class Pt{constructor(t=new vt,e=et){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}getPopupForms(t){return this.createRequest("getPopupForms",t)}getPopupFormContent(t){return this.createRequest("getPopupFormContent",t)}recordPopupFormEvent(t){return this.createRequest("recordPopupFormEvent",t)}applicationOpen(t){return this.createRequest("applicationOpen",t)}registerDevice(t){return this.createRequest("registerDevice",t)}unregisterDevice(t){return this.createRequest("unregisterDevice",t)}deleteDevice(t){return this.createRequest("deleteDevice",t)}messageDeliveryEvent(t){return this.createRequest("messageDeliveryEvent",t)}pushStat(t){return this.createRequest("pushStat",t)}setTags(t){return this.createRequest("setTags",t)}getTags(t){return this.createRequest("getTags",t)}registerUser(t){return this.createRequest("registerUser",t)}registerEmail(t){return this.createRequest("registerEmail",t)}registerEmailUser(t){return this.createRequest("registerEmailUser",t)}setEmailTags(t){return this.createRequest("setEmailTags",t)}postEvent(t,e){return this.createRequest("postEvent",t,e)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t){return this.createRequest("inboxStatus",t)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}async createRequest(t,e,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+t,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(t){if(200!==t.status){let e,s=`status: ${t.status}. statusText: ${t.statusText}.`;try{const i=await t.json();i&&"number"==typeof i.status_code&&(e=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(t){}throw new ft(s,e)}const e=await t.json();if(200!==e.status_code)throw new ft(`Error code: ${e.status_code}. Error text: ${e.status_message}`,"number"==typeof e.status_code?e.status_code:void 0);return e}}class St{constructor(t,e=new vt,s=new Pt,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(t=>{throw this.checkDevicePromise=null,t})),this.checkDevicePromise}async requestCheckDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(t=!0){let e=localStorage.getItem(a);if(null===e||!t){const{exist:t,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,t&&s?n:o),e=localStorage.getItem(a)}return e===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(t=>{throw this.ensureDeviceRegisteredPromise=null,t})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:t}=await this.checkDevice();if(t)return!1;const e=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e),!0}async reportPushPermissionStatus(t=!1){const e=this.getPushPermissionStatus();if(e&&e!==this.reportingPushPermissionStatus&&e!==localStorage.getItem(r)){this.reportingPushPermissionStatus=e;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!t&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e)}finally{this.reportingPushPermissionStatus===e&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(t){t&&localStorage.setItem(r,t)}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const e=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...t,push_permission_status:e});return this.rememberReportedPushPermissionStatus(e),s}async registerDevice(){const t=this.requestRegisterDevice();this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=await this.getRequestParams(),e=await this.data.getTokens();if(!e.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...t,push_permission_status:s,push_token:e.pushToken,auth_token:e.authToken,public_key:e.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const t=await this.getRequestParams(),e=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),e}async deleteDevice(){const t=await this.getRequestParams(),e=await this.apiClient.deleteDevice(t);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),e}async messageDeliveryEvent(t,e,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:t,metaData:s})}async pushStat(t,e,s={}){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:t,metaData:s})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:e,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:t}),this.apiClient.setTags({...i,hwid:e,device_type:s,tags:t})}async getTags(){const t=await this.getRequestParams();return this.apiClient.getTags(t)}async setLanguage(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:t}))}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${t}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),e&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:t})}async recordPopupFormEvent(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.recordPopupFormEvent({...await this.getRequestParams(),code:t,event:e})}async postEvent(t,e,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(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:t,timestampUTC:n,timestampCurrent:o,attributes:e},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h}async getInboxMessages(t=0){const e=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...e,count:t,last_code:s,last_request_time:i})}async inboxStatus(t,e){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:t,status:e,time:(new Date).getTime()})}async multiRegisterDevice(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const e=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();!t.push_devices&&c.pushToken&&await this.requireHwid();const u={application:e,...t};if(t.user_id){u.user_id=String(t.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(t.email){if(!/^\S+@\S+\.\S+$/.test(t.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==t.email&&(await this.data.setEmail(t.email),await this.data.setStatusEmailWasChanged(!0))}if(t.sms_phone_number){if(!/^\+?[0-9]+$/.test(t.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==t.sms_phone_number&&(await this.data.setSmsNumber(t.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(t.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(t.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==t.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(t.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 t=60*-(new Date).getTimezoneOffset();u.timezone=String(t)}if(!u.push_devices&&c.pushToken){const t={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),s&&(e.browser=s),t.platformData=e}u.push_devices=[t]}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 t=await this.requireHwid(),e=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:t,device_type:e}}async getIdentityRequestParams(){const t=await this.data.getApplicationCode(),e=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&&!e)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:t,userId:s||e,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const t=await this.data.getHwid();if(!t)throw new Error(W);return t}}class Ct{constructor(t,e,s,i){this.key=t,this.enabled=e,this.ruleId=s,this.properties=i}getString(t,e){const s=this.properties[t];return"string"==typeof s?s:e}getNumber(t,e){const s=this.properties[t];return"number"==typeof s&&Number.isFinite(s)?s:e}getBool(t,e){const s=this.properties[t];return"boolean"==typeof s?s:e}getJson(t,e){const s=this.properties[t];return s??e}getProperties(){return{...this.properties}}}class It extends Error{constructor(t,e){super(t),this.name="FeatureFlagsError",this.httpStatus=e}}const kt=/json\/1\.3\/?$/,Dt="api/v2/device-api/getFeatureFlags";const Et=18e5;class xt{constructor(t){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:(t,e)=>fetch(t,e),now:()=>Date.now(),...t},this.deps.eventBus.addEventHandler("change-user-id",({userId:t})=>this.onUserChanged(t)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const t=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=t);const e=await this.deps.data.getFeatureFlags();e&&e.applicationCode===this.applicationCode&&(this.cache=e),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(t){if(this.activate(),!this.cache||!this.hasValidCache())return null;const e=this.cache.flags[t];return e?new Ct(t,e.enabled,e.rule_id,e.properties):null}isEnabled(t,e){const s=this.get(t);return s?s.enabled:e}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(t){this.activate(),this.listeners.add(t)}removeUpdateListener(t){this.listeners.delete(t)}async logImpression(t){const e=this.get(t);if(!e||this.deps.isCommunicationDisabled())return;const s=`${t}|${e.ruleId}|${e.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(e,s)}catch(t){this.pageImpressions.delete(s),et.error(t,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(t,e){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[e]&&s-i[e]<Et)){await this.deps.data.setFeatureFlagImpressions({...Tt(i,s),[e]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:t.key,rule_id:t.ruleId,enabled:t.enabled})}catch(t){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[e],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),t}}}onUserChanged(t){if(!this.isLoaded)return this.userId=t,void(this.userChangedWhileLoading=!0);t!==this.userId&&(this.userId=t,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const t=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||t)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const t=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,e=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||t>9e5||e?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(t=>et.error(t,"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 It("Communication is disabled",0);const t=this.generation,e=await this.deps.data.getHwid();if(!e||!this.applicationCode)throw new It("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:e};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(t){const e=t||i;if(kt.test(e))return e.replace(kt,Dt);try{return`${new URL(e).origin}/${Dt}`}catch(t){return i.replace(kt,Dt)}}(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(t){throw new It(`getFeatureFlags request failed: ${t instanceof Error?t.message:String(t)}`,0)}if(200!==o.status)throw new It(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(t){throw new It("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Wt(c.response))throw new It(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);t===this.generation&&await this.apply(c.response)}async apply(t){const e=this.visibleSnapshot(),s=this.deps.now();if(!0===t.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===t.partial){if(this.hasValidCache())return;this.cache=this.newCache(t,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(t,"string"==typeof t.etag?t.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==e&&this.notify()}newCache(t,e,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:_t(t.flags),etag:e,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(t=>{try{t()}catch(t){et.error(t,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const t=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),e=Math.max(0,t+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),e)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const t=this.deps.now()-this.cache.fetchedAt;return t>=0&&t<=864e5}isCacheOfCurrentUser(t){return t.applicationCode===this.applicationCode&&t.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?At(this.cache.flags):""}}function Wt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function _t(t){const e={};return Wt(t)?(Object.keys(t).forEach(s=>{const i=t[s];Wt(i)&&"boolean"==typeof i.enabled&&(e[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Wt(i.properties)?i.properties:{}})}),e):e}function Tt(t,e){const s={};return Object.keys(t).forEach(i=>{e-t[i]<Et&&(s[i]=t[i])}),s}function At(t){return Array.isArray(t)?`[${t.map(At).join(",")}]`:Wt(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${At(t[e])}`).join(",")}}`:JSON.stringify(t)}class Mt{constructor(t){this.global=t,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let t=11;switch(!0){case this._isSafari:t=10;break;case this._isOpera||this._isChrome:t=11;break;case this._isFirefox:t=12;break;case this._isEdge:t=150}return t}getFormFactor(){const t=navigator.userAgentData;if(t&&"boolean"==typeof t.mobile)return t.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:t}=navigator,e=t.match(/\bOPR\/(\d+)/);if(null!==e)return`Opera ${e[1]}`;const s=t.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=t.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=t.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=t.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const Rt="pushwoosh-recommendations-views";function Nt(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const t=new Map;return{getItem:e=>t.get(e)??null,setItem:(e,s)=>{t.set(e,s)}}}class Ft{constructor(t){this.deps={fetch:(...t)=>fetch(...t),now:Date.now,storage:Nt(),...t}}async trackProductView(t){!t?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(t.id))||await this.deps.postEvent("PW_ProductView",{productId:String(t.id),name:t.name,price:t.price,currency:t.currency,category:t.category,productUrl:t.url,imageUrl:t.imageUrl})}async fetch(t){const e=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:t.strategy});t.fallback&&e.set("fallback",t.fallback),t.limit&&e.set("limit",String(t.limit)),t.productId&&e.set("product_id",t.productId),t.exclude?.length&&e.set("exclude",t.exclude.join(",")),t.block&&e.set("block",t.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?${e}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(t){t?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:t.block,strategy:t.strategy,recoProductId:String(t.productId),position:t.position},{keepalive:!0})}seenRecently(t){const e=this.deps.now(),s=function(t){try{const e=JSON.parse(t||"{}");return null===e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>"number"==typeof t))}catch{return{}}}(this.deps.storage.getItem(Rt));if(e-(s[t]??-1/0)<3e4)return!0;const i={[t]:e};Object.keys(s).forEach(t=>{e-s[t]<3e4&&(i[t]=s[t])});try{this.deps.storage.setItem(Rt,JSON.stringify(i))}catch{}return!1}}function Ut(t){switch(t){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}class Ot{constructor(t,e,s){this.api=t,this.data=e,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(t){const e=t||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void et.error("You must have permission granted before subscribe!");const s=this.getPushToken(e),i=e.getKey("p256dh"),a=e.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:e.endpoint}),await this.api.registerDevice()}async unsubscribe(){const t=await this.getServiceWorkerRegistration(),e=await t.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),e&&await e.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const t=await this.data.getLastPermissionStatus(),e=this.getPermission();if(t!==e&&(await this.data.setLastPermissionStatus(e),void 0!==t))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 t=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(t),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const t=await this.data.getServiceWorkerUrl(),e=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${M()}`),await navigator.serviceWorker.register(`${t}${s}`,{scope:e})}async trySubscribe(){try{return await this.subscribePushManager()}catch(t){return console.error(t),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const t=await this.getServiceWorkerRegistration(),e=await this.getApplicationServerKey();return t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e?this.urlBase64ToUint8Array(e):null})}async getCredentials(){const t=await this.getServiceWorkerRegistration();return await t.pushManager.getSubscription()}getPushToken(t){return t?t.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(e),i=new Uint8Array(s.length);for(let t=0;t<s.length;++t)i[t]=s.charCodeAt(t);return i}}class qt{constructor(t,e,s){this.api=t,this.config=s,this.data=e}getPermission(){const{permission:t}=this.getPermissionInfo();return t}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const t={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(e=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,t,()=>e())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void et.error("You must have permission granted before subscribe!");const{deviceToken:t}=this.getPermissionInfo();await this.data.setTokens({pushToken:t}),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 t=await this.data.getWebSitePushId(),e=void 0!==t&&this.config.webSitePushId!==t;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)||e}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Lt{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.addEventHandler=(t,e)=>this.eventBus.addEventHandler(t,e),this.removeEventHandler=(t,e)=>this.eventBus.removeEventHandler(t,e),this.dispatchEvent=(t,e)=>this.eventBus.dispatchEvent(t,e),this.debug={async showLog(){const t=await X.getAll();console.log(t)},async showKeyValues(){const t=await J.getAll();console.log(t)},async showMessages(){(await Q.getAll()).forEach(t=>console.log(t))}},this.eventBus=new st,this.data=new vt,this.apiClient=new Pt(this.data),this.api=new St(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new xt({eventBus:this.eventBus,data:this.data,postEvent:(t,e)=>this.api.postEvent(t,e),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Ft({postEvent:(t,e,s)=>this.api.postEvent(t,e,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Mt(A()),this.inboxModel=new bt(this.eventBus,this.data,this.api),this.pwinbox=new pt(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget())}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let t;const e=new Promise(e=>{t=setTimeout(()=>e(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),e]),clearTimeout(t),this.moduleRegistry.webPopups}push(t){if(R(t))this.subscribeToLegacyEvents(u,t);else{if(!Array.isArray(t))throw new Error("Invalid command!");if("init"===t[0])this.initialize(t[1]).catch(t=>{console.error("Pushwoosh: Error during initialization",t)});else if(!this.subscribeToLegacyEvents(t[0],t[1]))throw console.log("Pushwoosh: Unknown command",t),new Error("Unknown command!")}}async subscribe(t=!0){const e=this.runSubscribe(t);this.subscriptionInFlight=e;try{await e}finally{this.subscriptionInFlight===e&&(this.subscriptionInFlight=null)}}async runSubscribe(t){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 e=this.requireDriver();if(e.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await e.askPermission();const t=e.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:t})}const s=e.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||t)&&await e.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await e.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(t){throw et.error(t,"Error occurred during the unsubscribe"),t}}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(t=!0){if(await this.data.setCommunicationEnabled(t),t){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const t=this.driver?.checkIsPermissionGranted();t&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:t});const e=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:t,device_type:e})}async removeAllDeviceData(){const t=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:t}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(t){return this.recommendations.trackProductView(t)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:t}=await this.data.getTokens();return t}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}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(t){this.rawInitParams={...t},this.initParams={...T,...t},this.isInitAborted=!1;const e=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(et.setLevel(e||t.logLevel||"error"),t.logLevel&&await this.data.setLogLevel(t.logLevel),this.isPushDisabled=!1===t.pushNotifications,this.isAvailableNotifications()||et.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!t.applicationCode)throw new Error("Can't find application code!");const s=!1===t.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!==t.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(t.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(t.tags?.Language||navigator.language),await this.data.setApiEntrypoint(t.pushwooshUrl||""),await this.data.setApiToken(t.apiToken||""),await this.data.setSdkVersion("3.98.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(t){et.write("error",t)}const t=await this.data.getDelayedEvent();if(t){const{type:e,payload:s}=t;this.emitLegacyEventsFromServiceWorker(e,s),await this.data.setDelayedEvent(null)}if(this.platformChecker.isSafari&&!this.initParams.unifiedPlatform){const t=/#P(.*)/,e=decodeURIComponent(document.location.hash);t.test(e)&&this.api.pushStat(t.exec(e)[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.data.setDeviceType(this.resolvePlatformType()),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)):et.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(t=>et.error(t,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=t=>this.onServiceWorkerMessage(t)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(t,e){if(!this.isInitAborted)try{await e()}catch(e){const s=function(t){const e=t?.statusCode;return"number"==typeof e?e:void 0}(e);if(void 0!==s&&-1!==_.indexOf(s))return void this.abortInit(s);et.error(e,`Pushwoosh: init step "${t}" failed`)}}abortInit(t){this.isInitAborted=!0,et.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${t}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){return this.initParams.unifiedPlatform?11:this.platformChecker.getPlatformType()}async ensureHwid(t=!1){if(await this.readHwid()&&!t)return;const e=this.initParams.applicationCode+"_"+M();try{await this.data.setHwid(e),await this.data.getHwid()!==e&&et.info(W)}catch(t){et.info(t,W)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:t}=this.initParams||{};return t&&"user_id"!==t?t:void 0}async isUserIdChanged(){const{userId:t}=this.initParams,e=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!t&&"user_id"!==t&&t!==e&&!s}async defaultProcess(){const t=this.requireDriver(),e=t.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await t.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(t){const{data:e={}}=t||{},{type:s="",payload:i={}}=e||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(t){let e=await this.data.getLastOpenApplicationTime();const s=Date.now();e||(e=0);(t||!(s-e<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){if(this.driver)return Ut(this.driver.getPermission());const t=this.platformChecker.isSafari&&!this.initParams?.unifiedPlatform;return function(t,e){const s="safari"in t?t.safari?.pushNotification:void 0;if(s&&e)try{return Ut(s.permission(e).permission)}catch{return"unsupported"}return"PushManager"in t&&"Notification"in t?Ut(t.Notification.permission):s?"not_determined":"unsupported"}(A(),t?this.initParams?.safariWebsitePushID:void 0)}async reportPushPermissionChange(){const t=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const e=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(e===c)s||t||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(t=>et.error(t,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const t=this.dropRevokedSubscription(e).catch(t=>et.error(t,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(t)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(t){await this.data.setLastPermissionStatus(t),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(t=>et.error(t,"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",()=>this.reportPushPermissionChangeInBackground()),this.isPushPermissionWatched=!0}catch(t){et.info(t,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const t=this.initParams,e=await this.data.getUserId();if(t.userId&&"user_id"!==t.userId&&t.userId!==e)try{await this.api.registerUser(t.userId,!1)}catch(t){et.error(t,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const e=await this.data.getEmail();return!!t.email&&t.email!==e},task:async()=>{await this.api.registerEmail(t.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const e=await this.data.getSmsNumber();return!!t.smsNumber&&t.smsNumber!==e},task:async()=>{await this.api.registerSmsNumber(t.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const e=await this.data.getWhatsAppNumber();return!!t.whatsAppNumber&&t.whatsAppNumber!==e},task:async()=>{await this.api.registerWhatsappNumber(t.whatsAppNumber,!1)}},{test:async()=>!!t.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const e=await this.data.getLanguage(),s={...t.tags||{},Language:e};await this.api.setTags(s)}}];await Promise.all(s.map(async t=>{try{await t.test()&&await t.task()}catch(t){console.error("Pushwoosh: Error during data registration",t)}}))}async loadConfig(){const t=await this.api.getConfig(["vapid_key","events","subscription_prompt","popup_forms","web_sdk","web_sdk_modules"]),e=t&&t.features;if(await this.data.setFeatures(e),e){if(await this.applyServerInitParams(function(t){if(void 0!==t?.web_sdk)return t.web_sdk;const e=t?.web_sdk_modules;return void 0!==e?{inboxWidget:e.inboxWidget,webPopups:e.webPopups}:void 0}(e)),e.events&&e.events.length){e.events.some(t=>t===x)&&this.sendPostEventVisitedPage()}if(e.vapid_key){const t=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(e.vapid_key),void 0!==t&&t!==e.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async applyServerInitParams(t){const e=function(t,e){if(!e)return{};const s={};if(it.forEach(t=>{void 0!==e[t]&&(s[t]=e[t])}),void 0!==e.inboxWidget&&(s.inboxWidget={...t.inboxWidget,...e.inboxWidget}),void 0!==e.webPopups&&(s.webPopups={...t.webPopups,...e.webPopups}),void 0!==e.subscriptionWidget){const i=at(t.subscribeWidget,e.subscribeWidget)??t.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...t.subscribePopup,enable:!1},s}const i=at(t.subscribeWidget,e.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,t);0!==Object.keys(e).length&&(this.initParams={...this.initParams,...e},await this.data.setInitParams(this.initParams))}async initPushNotifications(t){if(await this.data.setDefaultNotificationImage(t.defaultNotificationImage),await this.data.setDefaultNotificationTitle(t.defaultNotificationTitle),await this.data.setServiceWorkerUrl(t.serviceWorkerUrl),await this.data.setServiceWorkerScope(t.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return et.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(t){et.error(t,"Internal error: defaultProcess fail")}}else et.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:t}=await this.data.getTokens();t&&et.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.platformChecker.isSafari&&!this.initParams.unifiedPlatform){const{safariWebsitePushID:t}=await this.data.getInitParams();return t?void(this.driver=new qt(this.api,this.data,{webSitePushId:t})):void et.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}et.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new Ot(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:t},location:{href:e}}=window,s=await this.data.getDeviceType();this.api.postEvent(x,{url:e,title:t,device_type:s})}subscribeToLegacyEvents(t,e){let s=!0;switch(!0){case"onLoad"===t:e();break;case t===u:if(this.ready){e(this.api);break}this.eventBus.addEventHandler("ready",()=>e(this.api));break;case t in F:this.eventBus.addEventHandler(F[t].name,s=>{const{prop:i}=F[t];e(this.api,i?s[i]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(t,e){switch(t){case f:this.eventBus.dispatchEvent("receive-push",{notification:e});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:e});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:e});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:e})}}}return e})());
|
|
1
|
+
!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var s=e();for(var i in s)("object"==typeof exports?exports:t)[i]=s[i]}}(this,()=>(()=>{"use strict";const t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}};let e={};t.r(e),t.d(e,{Pushwoosh:()=>Lt});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",C="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",x="PW_SiteOpened",W="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.",_=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function R(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const M=t=>"function"==typeof t;function N(t){const e=new WeakSet;return async s=>{if(e.has(s))return!1;const i=await function(t,e){let s;const i=new Promise(t=>{s=setTimeout(()=>t(!1),e)}),a=t.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,t);return i||e.add(s),i}}const F={[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"},[C]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[k]:{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"}},U="keyValue",O="messages",q="inboxMessages";function L(t,e){return function(s){s.objectStoreNames.contains(t)||e(s)}}const B=[L(U,function(t){t.createObjectStore(U,{keyPath:"key"})}),L("log",function(t){const e=t.createObjectStore("log",{keyPath:"id",autoIncrement:!0});e.createIndex("environment","environment",{unique:!1}),e.createIndex("date","date",{unique:!1}),e.createIndex("type","type",{unique:!1})}),L(O,function(t){t.createObjectStore(O,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),L(q,function(t){const e="status",s=t.createObjectStore(q,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(e,e,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class ${constructor(t,e=new j){this.db=t,this.migrationsBuilder=e}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(t){t.forEach(t=>{t(this.db)})}}function V(t,e){console.info("onversionchange",e),t.close()}let H;function K(){return H||(H=new Promise((t,e)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=V.bind(null,i,e),t(i)},s.onerror=()=>e(s.error),s.onupgradeneeded=t=>{const s=t.target.result;s.onversionchange=V.bind(null,s,e);new $(s).applyMigrations()}})),H}function z(t){return K().then(e=>new Promise((s,i)=>t(e,s,i)))}class G{_add(t){return z((e,s,i)=>{const a=e.transaction([this.name],"readwrite").objectStore(this.name).add(t);a.onsuccess=()=>{s(t)},a.onerror=()=>{i(a.error)}}).then(t=>this.getAll().then(e=>{if(Array.isArray(e)){const s=e.map(t=>t.id).sort((t,e)=>t==e?0:t<e?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(t=>this.delete(t))).then(()=>t)}return t}))}delete(t){return z((e,s,i)=>{const a=e.transaction([this.name],"readwrite").objectStore(this.name).delete(t);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((t,e,s)=>{const i=[],a=t.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=t=>{const s=t.target.result;s?(s.value&&i.push(s.value),s.continue()):e(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=U,{get:(t,e)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(t);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((t,e,s)=>{const i={},a=t.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?e(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=t=>{const e=t.target.result;e?(i[e.key]=e.value.value,e.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(t,e){const s=await this.get(t),{...i}=e;await this.set(t,{...s,...i})},set:(t,e)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:t,value:e});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(t):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(t,e,s){const i={type:t,environment:this.environment,message:`${e}`,date:new Date};return e instanceof Error&&(i.stack=e.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=O,this.maxItems=25}add(t){return this._add({...t,date:new Date})}},Z={error:1,info:2,debug:3};let tt=3;const et={setLevel(t){Z[t]||(t="error"),tt=Z[t]},write(t,e,s){return"error"===t?this.error(e):this.info(e),X.add(t,e,s)}};Object.keys(Z).forEach(t=>{const e=Z[t];et[t]=(...s)=>{e<=tt&&(console.groupCollapsed(t),console.info("",...s),console.trace("trace"),console.groupEnd())}});class st{constructor(){this.addEventHandler=(t,e)=>{let s=this.handlers[t];s||(s=[]),s.push(e),this.handlers[t]=s},this.removeEventHandler=(t,e)=>{const s=this.handlers[t];s&&(this.handlers[t]=s.filter(t=>t!==e))},this.dispatchEvent=(t,e)=>{const s=e.eventId||R(),i=this.handlers[t];return i?(i.forEach(t=>{M(t)&&setTimeout(()=>{t({...e,eventId:s})},0)}),s):s},this.handlers={}}}const it=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function at(t,e){if(e)return{...t,...e}}class rt{constructor(t=new Date){this._date=t}set date(t){this._date=t}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const t=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(t)}addDays(t){const e=this._date.getTime()+24*t*60*60*1e3;this._date=new Date(e)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const nt=["classic","captioned","banner","carousel"];function ot(t){return(Array.isArray(t)?t:[]).filter(t=>!!t&&!!t.imageUrl).slice(0,5)}const ct=/^(?:javascript|vbscript|data|blob|file):/i,ht=/^[a-z][a-z\d+\-.]*:/i;function ut(t){return t.split("").filter(t=>t.charCodeAt(0)>32&&127!==t.charCodeAt(0)).join("")}function dt(t){const e=ut(t);return ht.test(e)&&!ct.test(e)}function lt(t,e){return e||t.image||""}function gt(t){const e=["displayType","carousel","image"];return Object.keys(t).filter(t=>-1===e.indexOf(t)).reduce((e,s)=>(e[s]=t[s],e),{})}class pt{constructor(t,e,s,i={},a=()=>Promise.resolve(void 0),r=new rt){this.data=t,this.api=e,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(t){try{return JSON.parse(t)||{}}catch(e){return et.write("error",`Pushwoosh: cannot parse inbox action_params: ${t}`,e),{}}}messageTypeFactory(t,e){let s=0;return 2===t?s=1:"l"in e&&null!=e.l&&(s=e.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(t,e,s){const i=[],a=[];e.forEach(async e=>{-1!==t.indexOf(e.inbox_id)&&(e.status=s,i.push(e),a.push(this.api.inboxStatus(e.order,e.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:t,action_params:e,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(e),h=function(t){const e=t?.u;if(!e)return{};if("string"==typeof e)try{return JSON.parse(e)||{}}catch{return{}}return"object"==typeof e?e:{}}(c),u=function(t){return(Array.isArray(t.carousel)?t.carousel:[]).filter(t=>!!t&&!!t.image).slice(0,5).map(t=>({imageUrl:t.image,caption:t.title||"",link:t.url&&dt(t.url)?t.url:""}))}(h),d=function(t,e,s){return t?.b||s||e.image||""}(c,h,s),l=function(t){const e=!!t.title,s=!!t.body,i=function(t){return t.bannerUrl||t.iconUrl||""}(t);let a=t.layoutType;switch(nt.includes(a)||(a=t.bannerUrl&&!e?"banner":t.bannerUrl&&e&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&e&&s?"captioned":"classic";case"carousel":return e&&s&&ot(t.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:lt(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=lt(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:gt(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(t,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 t=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((t,e)=>parseInt(e.send_date,10)-parseInt(t.send_date,10)).sort((t,e)=>parseInt(e.order||"0",10)-parseInt(t.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(t)}async readMessagesWithCodes(t){const e=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,e,2)}async performActionForMessageWithCode(t){const e=await this.inboxModel.getMessage(t),s=this.parseActionParams(e.action_params),i=this.messageTypeFactory(e.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ct.test(ut(r)))&&(document.location.href=s.l),e.status=3,await this.inboxModel.putMessage(e),await this.api.inboxStatus(e.order,e.status)}async showWebPopup(t){if(!t)return!1;try{const e=this.moduleRegistry.webPopups??await this.loadWebPopups();return e?await e.show(t):(et.write("error",`Pushwoosh: inbox message opens web popup "${t}", but the web popups widget could not be loaded`),!1)}catch(e){return et.write("error",`Pushwoosh: failed to open web popup "${t}" from inbox`,e),!1}}async deleteMessagesWithCodes(t){const e=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(t,[...e,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class mt{constructor(t,e){this.name=e,this.store=t.transaction(this.name,"readwrite").objectStore(this.name)}set index(t){this.store.indexNames.contains(t)?this._index=this.store.index(t):console.warn(`Index "${t}" in `)}writeRequestPromise(t,e){return new Promise((s,i)=>{t.onsuccess=()=>{s(e)},t.onerror=()=>{i(t.error)}})}readRequestPromise(t,e){return new Promise((s,i)=>{t.onsuccess=t=>{const i=t.target;s(i.result||e)},t.onerror=()=>{i(t.error)}})}put(t,e){const s=this.store.put(t,e);return this.writeRequestPromise(s,e)}add(t,e){return this.put(t,e)}delete(t){const e=this.store.delete(t);return this.writeRequestPromise(e)}get(t,e){const s=this.store.get(t);return this.readRequestPromise(s,e)}getAll(){const t=this.store.openCursor(),e=[];return new Promise((s,i)=>{t.onsuccess=t=>{const i=t.target.result;i?(e.push(i.value),i.continue()):s(e)},t.onerror=()=>{i(t.error)}})}count(t){const e=this.store.count(t);return this.readRequestPromise(e,0)}countByIndex(t){const e=this._index.count(t);return this.readRequestPromise(e,0)}}class wt{getDB(){return K()}async put(t,e,s){const i=await this.getDB();return new mt(i,t).put(e,s)}async delete(t,e){const s=await this.getDB();return new mt(s,t).delete(e)}async get(t,e,s){const i=await this.getDB();return new mt(i,t).get(e,s)}async getAll(t){const e=await this.getDB(),s=new mt(e,t);return await s.getAll()||[]}async count(t,e){const s=await this.getDB();return new mt(s,t).count(e)}async countByIndex(t,e,s){const i=await this.getDB(),a=new mt(i,t);return a.index=e,a.countByIndex(s)}}class bt{constructor(t,e,s,i=new wt,a=new rt){this.eventBus=t,this.data=e,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const t=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(t.next,t.new_inbox),t}async storeGetInboxMessagesRequestParams(t,e){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(t),await this.data.setInboxNewMessagesCount(e)}async putServerMessages(t){const e=t.map(async t=>{const e=await this.storage.get(this.storeName,t.inbox_id,{});return"status"in e&&(t.status=e.status),this.putMessage(t)});return Promise.all(e)}putMessage(t){return this.storage.put(this.storeName,t)}putBulkMessages(t){const e=t.map(t=>this.putMessage(t));return Promise.all(e)}deleteMessages(t){const e=t.map(t=>this.storage.delete(this.storeName,t));return Promise.all(e)}async deleteExpiredMessages(){this.dateModule.date=new Date;const t=this.dateModule.getTimestamp().toString(),e=(await this.storage.getAll(this.storeName)).filter(e=>e.rt<t).map(t=>t.inbox_id);return this.deleteMessages(e)}getMessage(t){return this.storage.get(this.storeName,t)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>2===t.status||3===t.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(t=>1===t.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[t,e]=[2,3],s=IDBKeyRange.bound(t,e);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const t=await this.getInboxMessages();await this.deleteExpiredMessages(),t.deleted&&await this.deleteMessages(t.deleted),await this.putServerMessages(t.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new pt(this.data,this.api,this)})}}class ft extends Error{constructor(t,e){super(t),this.name="ApiRequestError",this.statusCode=e}}const yt=t=>`params.${t}`;class vt{constructor(t=J){this.store=t}async clearAll(){const t=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const e of t)await this.store.set(yt(e),void 0)}async setApplicationCode(t){await this.store.set(yt("applicationCode"),t)}async getApplicationCode(){return this.store.get(yt("applicationCode"))}async setApiToken(t){return await this.store.set(yt("apiToken"),t)}async getApiToken(){return this.store.get(yt("apiToken"))}async setHwid(t){await this.store.set(yt("hwid"),t)}async getHwid(){return this.store.get(yt("hwid"))}async setDeviceType(t){await this.store.set(yt("deviceType"),t)}async getDeviceType(){return this.store.get(yt("deviceType"))}async setFormFactor(t){await this.store.set(yt("formFactor"),t)}async getFormFactor(){return this.store.get(yt("formFactor"))}async setDeviceModel(t){await this.store.set(yt("deviceModel"),t)}async getDeviceModel(){return this.store.get(yt("deviceModel"))}async setLanguage(t){await this.store.set(yt("language"),t)}async getLanguage(){return this.store.get(yt("language"),"en")}async setStatusLanguageWasChanged(t){await this.store.set(yt("languageWasChanged"),t)}async getStatusLanguageWasChanged(){return this.store.get(yt("languageWasChanged"),!1)}async setApiEntrypoint(t){await this.store.set(yt("apiEntrypoint"),t)}async getApiEntrypoint(){return this.store.get(yt("apiEntrypoint"),i)}async setTokens(t){await this.store.set(yt("tokens"),t)}getTokens(){return this.store.get(yt("tokens"))}async setApplicationServerKey(t){await this.store.set(yt("applicationServerKey"),t)}async getApplicationServerKey(){return this.store.get(yt("applicationServerKey"))}async setIsVapidChanged(t){await this.store.set(yt("isVapidChanged"),t)}async getIsVapidChanged(){return this.store.get(yt("isVapidChanged"),!1)}async setWebSitePushId(t){await this.store.set(yt("webSitePushId"),t)}async getWebSitePushId(){return this.store.get(yt("webSitePushId"))}async setDefaultNotificationImage(t){await this.store.set(yt("defaultNotificationImage"),t)}async getDefaultNotificationImage(){return this.store.get(yt("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(t){await this.store.set(yt("defaultNotificationTitle"),t)}async getDefaultNotificationTitle(){return this.store.get(yt("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(t){await this.store.set(yt("userId"),t?`${t}`:void 0)}async getUserId(){return this.store.get(yt("userId"))}async getFeatureFlags(){return this.store.get(yt("featureFlags"))}async setFeatureFlags(t){await this.store.set(yt("featureFlags"),t)}async getFeatureFlagImpressions(){return this.store.get(yt("featureFlagImpressions"),{})}async setFeatureFlagImpressions(t){await this.store.set(yt("featureFlagImpressions"),t)}async setStatusUserIdWasChanged(t){await this.store.set(yt("userIdWasChanged"),t)}async getStatusUserIdWasChanged(){return this.store.get(yt("userIdWasChanged"),!1)}async setEmail(t){await this.store.set(yt("email"),t?`${t}`:void 0)}async getEmail(){return this.store.get(yt("email"))}async setStatusEmailWasChanged(t){await this.store.set(yt("emailWasChanged"),t)}async getStatusEmailWasChanged(){return this.store.get(yt("emailWasChanged"),!1)}async setSmsNumber(t){await this.store.set(yt("smsNumber"),t?`${t}`:void 0)}async getSmsNumber(){return this.store.get(yt("smsNumber"))}async setStatusSmsNumberWasChanged(t){await this.store.set(yt("smsNumberWasChanged"),t)}async getStatusSmsNumberWasChanged(){return this.store.get(yt("smsNumberWasChanged"),!1)}async setWhatsAppNumber(t){await this.store.set(yt("whatsAppNumber"),t?`${t}`:void 0)}async getWhatsAppNumber(){return this.store.get(yt("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(t){await this.store.set(yt("whatsAppNumberWasChanged"),t)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(yt("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(t){await this.store.set(yt("isLastPermissionStatus"),t)}async getLastPermissionStatus(){return this.store.get(yt("isLastPermissionStatus"))}async setStatusManualUnsubscribed(t){await this.store.set(yt("isManualUnsubscribed"),t)}getStatusManualUnsubscribed(){return this.store.get(yt("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(t){await this.store.set(yt("isCommunicationDisabled"),t)}getStatusCommunicationDisabled(){return this.store.get(yt("isCommunicationDisabled"),!1)}async setCommunicationEnabled(t){await this.store.set(yt("communicationEnabled"),t)}getCommunicationEnabled(){return this.store.get(yt("communicationEnabled"))}async setStatusDropAllData(t){await this.store.set(yt("isDropAllData"),t)}getStatusDropAllData(){return this.store.get(yt("isDropAllData"),!1)}async setSdkVersion(t){await this.store.set(yt("sdkVersion"),t)}async getSdkVersion(){return this.store.get(yt("sdkVersion"))}async setServiceWorkerVersion(t){await this.store.set(yt("serviceWorkerVersion"),t)}getServiceWorkerVersion(){return this.store.get(yt("serviceWorkerVersion"))}async setServiceWorkerUrl(t){t&&await this.store.set(yt("serviceWorkerUrl"),t)}async getServiceWorkerUrl(){return this.store.get(yt("serviceWorkerUrl"),s)}async setServiceWorkerScope(t){t&&await this.store.set(yt("serviceWorkerScope"),t)}async getServiceWorkerScope(){return this.store.get(yt("serviceWorkerScope"))}async setLastOpenMessage(t){await this.store.set(yt("lastOpenMessage"),t)}getLastOpenMessage(){return this.store.get(yt("lastOpenMessage"))}async setLastOpenApplicationTime(t){await this.store.set(yt("lastOpenApplicationTime"),t)}async getLastOpenApplicationTime(){return this.store.get(yt("lastOpenApplicationTime"))}async setFeatures(t){await this.store.set(yt("features"),t)}async getFeatures(){return this.store.get(yt("features"))}async setInitParams(t){await this.store.set(yt("init"),t)}async getInitParams(){return this.store.get(yt("init"))}async setInboxLastRequestCode(t){await this.store.set(yt("inbox.lastRequestCode"),t)}async getInboxLastRequestCode(){return this.store.get(yt("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(t){await this.store.set(yt("inbox.lastRequestTime"),t)}async getInboxLastRequestTime(){return this.store.get(yt("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(t){await this.store.set(yt("inbox.newMessagesCount"),t)}async getInboxNewMessagesCount(){return this.store.get(yt("inbox.newMessagesCount"),0)}async setDelayedEvent(t){await this.store.set(yt("delayedEvent"),t)}getDelayedEvent(){return this.store.get(yt("delayedEvent"))}async setPromptDisplayCount(t){await this.store.set(yt("promptDisplayCount"),t)}async getPromptDisplayCount(){return this.store.get(yt("promptDisplayCount"),0)}async setPromptLastSeenTime(t){await this.store.set(yt("promptLastSeenTime"),t)}async getPromptLastSeenTime(){return this.store.get(yt("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(t){await this.store.set(yt("subscriptionWidgetHistory"),t)}async getSubscriptionWidgetHistory(){return this.store.get(yt("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(t){await this.store.set(yt("logLevel"),t)}async getLogLevel(){return this.store.get(yt("logLevel"),"error")}async getShownWebPopups(){return this.store.get(yt("shownWebPopups"),[])}async addShownWebPopup(t){const e=await this.getShownWebPopups();e.includes(t)||(e.push(t),await this.store.set(yt("shownWebPopups"),e))}async setIsRecurringVisitor(t){await this.store.set(yt("isRecurringVisitor"),t)}async getIsRecurringVisitor(){return this.store.get(yt("isRecurringVisitor"),!1)}}class Pt{constructor(t=new vt,e=et){this.data=t,this.logger=e}checkDevice(t){return this.createRequest("checkDevice",t)}getConfig(t){return this.createRequest("getConfig",t)}getPopupForms(t){return this.createRequest("getPopupForms",t)}getPopupFormContent(t){return this.createRequest("getPopupFormContent",t)}recordPopupFormEvent(t){return this.createRequest("recordPopupFormEvent",t)}submitPopupForm(t){return this.createRequest("submitPopupForm",t)}applicationOpen(t){return this.createRequest("applicationOpen",t)}registerDevice(t){return this.createRequest("registerDevice",t)}unregisterDevice(t){return this.createRequest("unregisterDevice",t)}deleteDevice(t){return this.createRequest("deleteDevice",t)}messageDeliveryEvent(t){return this.createRequest("messageDeliveryEvent",t)}pushStat(t){return this.createRequest("pushStat",t)}setTags(t){return this.createRequest("setTags",t)}getTags(t){return this.createRequest("getTags",t)}registerUser(t){return this.createRequest("registerUser",t)}registerEmail(t){return this.createRequest("registerEmail",t)}registerEmailUser(t){return this.createRequest("registerEmailUser",t)}setEmailTags(t){return this.createRequest("setEmailTags",t)}postEvent(t,e){return this.createRequest("postEvent",t,e)}getInboxMessages(t){return this.createRequest("getInboxMessages",t)}inboxStatus(t){return this.createRequest("inboxStatus",t)}multiRegisterDevice(t){return this.createRequest("multiRegisterDevice",t)}async createRequest(t,e,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+t,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:e}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${t} call with arguments: ${JSON.stringify(e)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(t){if(200!==t.status){let e,s=`status: ${t.status}. statusText: ${t.statusText}.`;try{const i=await t.json();i&&"number"==typeof i.status_code&&(e=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(t){}throw new ft(s,e)}const e=await t.json();if(200!==e.status_code)throw new ft(`Error code: ${e.status_code}. Error text: ${e.status_message}`,"number"==typeof e.status_code?e.status_code:void 0);return e}}class St{constructor(t,e=new vt,s=new Pt,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=t,this.data=e,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(t=>{throw this.checkDevicePromise=null,t})),this.checkDevicePromise}async requestCheckDevice(){const t=await this.getRequestParams();return await this.apiClient.checkDevice(t)}async checkDeviceSubscribeForPushNotifications(t=!0){let e=localStorage.getItem(a);if(null===e||!t){const{exist:t,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,t&&s?n:o),e=localStorage.getItem(a)}return e===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(t=>{throw this.ensureDeviceRegisteredPromise=null,t})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:t}=await this.checkDevice();if(t)return!1;const e=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e),!0}async reportPushPermissionStatus(t=!1){const e=this.getPushPermissionStatus();if(e&&e!==this.reportingPushPermissionStatus&&e!==localStorage.getItem(r)){this.reportingPushPermissionStatus=e;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!t&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:e}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(e)}finally{this.reportingPushPermissionStatus===e&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(t){t&&localStorage.setItem(r,t)}async getConfig(t){const e=await this.getRequestParams();return this.apiClient.getConfig({...e,features:t})}async applicationOpen(){const t=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const e=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...t,push_permission_status:e});return this.rememberReportedPushPermissionStatus(e),s}async registerDevice(){const t=this.requestRegisterDevice();this.registerDevicePromise=t;try{return await t}finally{this.registerDevicePromise===t&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const t=await this.getRequestParams(),e=await this.data.getTokens();if(!e.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...t,push_permission_status:s,push_token:e.pushToken,auth_token:e.authToken,public_key:e.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const t=await this.getRequestParams(),e=await this.apiClient.unregisterDevice(t);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),e}async deleteDevice(){const t=await this.getRequestParams(),e=await this.apiClient.deleteDevice(t);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),e}async messageDeliveryEvent(t,e,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:t,metaData:s})}async pushStat(t,e,s={}){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:t,metaData:s})}async setTags(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:e,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:t}),this.apiClient.setTags({...i,hwid:e,device_type:s,tags:t})}async getTags(){const t=await this.getRequestParams();return this.apiClient.getTags(t)}async setLanguage(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:t}))}async registerUser(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${t}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),e&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(t))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:t,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(t),e&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:t,device_type:18});return await this.data.setSmsNumber(t),e&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(t,e=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(t))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:t,device_type:21});return await this.data.setWhatsAppNumber(t),e&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:t})}async recordPopupFormEvent(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.recordPopupFormEvent({...await this.getRequestParams(),code:t,event:e})}async submitPopupForm(t,e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:t,email:e.email,tags:e.tags,policy_accepted:e.policyAccepted})}async postEvent(t,e,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(e.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));e={...e,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:t,timestampUTC:n,timestampCurrent:o,attributes:e},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h}async getInboxMessages(t=0){const e=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...e,count:t,last_code:s,last_request_time:i})}async inboxStatus(t,e){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:t,status:e,time:(new Date).getTime()})}async multiRegisterDevice(t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const e=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();!t.push_devices&&c.pushToken&&await this.requireHwid();const u={application:e,...t};if(t.user_id){u.user_id=String(t.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(t.email){if(!/^\S+@\S+\.\S+$/.test(t.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==t.email&&(await this.data.setEmail(t.email),await this.data.setStatusEmailWasChanged(!0))}if(t.sms_phone_number){if(!/^\+?[0-9]+$/.test(t.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==t.sms_phone_number&&(await this.data.setSmsNumber(t.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(t.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(t.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==t.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(t.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 t=60*-(new Date).getTimezoneOffset();u.timezone=String(t)}if(!u.push_devices&&c.pushToken){const t={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const e={};c.publicKey&&(e.public_key=c.publicKey),c.authToken&&(e.auth_token=c.authToken),s&&(e.browser=s),t.platformData=e}u.push_devices=[t]}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 t=await this.requireHwid(),e=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:t,device_type:e}}async getIdentityRequestParams(){const t=await this.data.getApplicationCode(),e=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&&!e)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:t,userId:s||e,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const t=await this.data.getHwid();if(!t)throw new Error(W);return t}}class Ct{constructor(t,e,s,i){this.key=t,this.enabled=e,this.ruleId=s,this.properties=i}getString(t,e){const s=this.properties[t];return"string"==typeof s?s:e}getNumber(t,e){const s=this.properties[t];return"number"==typeof s&&Number.isFinite(s)?s:e}getBool(t,e){const s=this.properties[t];return"boolean"==typeof s?s:e}getJson(t,e){const s=this.properties[t];return s??e}getProperties(){return{...this.properties}}}class It extends Error{constructor(t,e){super(t),this.name="FeatureFlagsError",this.httpStatus=e}}const kt=/json\/1\.3\/?$/,Dt="api/v2/device-api/getFeatureFlags";const Et=18e5;class xt{constructor(t){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:(t,e)=>fetch(t,e),now:()=>Date.now(),...t},this.deps.eventBus.addEventHandler("change-user-id",({userId:t})=>this.onUserChanged(t)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const t=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=t);const e=await this.deps.data.getFeatureFlags();e&&e.applicationCode===this.applicationCode&&(this.cache=e),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(t){if(this.activate(),!this.cache||!this.hasValidCache())return null;const e=this.cache.flags[t];return e?new Ct(t,e.enabled,e.rule_id,e.properties):null}isEnabled(t,e){const s=this.get(t);return s?s.enabled:e}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(t){this.activate(),this.listeners.add(t)}removeUpdateListener(t){this.listeners.delete(t)}async logImpression(t){const e=this.get(t);if(!e||this.deps.isCommunicationDisabled())return;const s=`${t}|${e.ruleId}|${e.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(e,s)}catch(t){this.pageImpressions.delete(s),et.error(t,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(t,e){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[e]&&s-i[e]<Et)){await this.deps.data.setFeatureFlagImpressions({...Tt(i,s),[e]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:t.key,rule_id:t.ruleId,enabled:t.enabled})}catch(t){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[e],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),t}}}onUserChanged(t){if(!this.isLoaded)return this.userId=t,void(this.userChangedWhileLoading=!0);t!==this.userId&&(this.userId=t,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const t=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||t)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const t=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,e=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||t>9e5||e?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(t=>et.error(t,"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 It("Communication is disabled",0);const t=this.generation,e=await this.deps.data.getHwid();if(!e||!this.applicationCode)throw new It("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:e};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(t){const e=t||i;if(kt.test(e))return e.replace(kt,Dt);try{return`${new URL(e).origin}/${Dt}`}catch(t){return i.replace(kt,Dt)}}(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(t){throw new It(`getFeatureFlags request failed: ${t instanceof Error?t.message:String(t)}`,0)}if(200!==o.status)throw new It(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(t){throw new It("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Wt(c.response))throw new It(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);t===this.generation&&await this.apply(c.response)}async apply(t){const e=this.visibleSnapshot(),s=this.deps.now();if(!0===t.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===t.partial){if(this.hasValidCache())return;this.cache=this.newCache(t,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(t,"string"==typeof t.etag?t.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==e&&this.notify()}newCache(t,e,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:_t(t.flags),etag:e,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(t=>{try{t()}catch(t){et.error(t,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const t=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),e=Math.max(0,t+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),e)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const t=this.deps.now()-this.cache.fetchedAt;return t>=0&&t<=864e5}isCacheOfCurrentUser(t){return t.applicationCode===this.applicationCode&&t.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?At(this.cache.flags):""}}function Wt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function _t(t){const e={};return Wt(t)?(Object.keys(t).forEach(s=>{const i=t[s];Wt(i)&&"boolean"==typeof i.enabled&&(e[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Wt(i.properties)?i.properties:{}})}),e):e}function Tt(t,e){const s={};return Object.keys(t).forEach(i=>{e-t[i]<Et&&(s[i]=t[i])}),s}function At(t){return Array.isArray(t)?`[${t.map(At).join(",")}]`:Wt(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${At(t[e])}`).join(",")}}`:JSON.stringify(t)}class Rt{constructor(t){this.global=t,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let t=11;switch(!0){case this._isSafari:t=10;break;case this._isOpera||this._isChrome:t=11;break;case this._isFirefox:t=12;break;case this._isEdge:t=150}return t}getFormFactor(){const t=navigator.userAgentData;if(t&&"boolean"==typeof t.mobile)return t.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:t}=navigator,e=t.match(/\bOPR\/(\d+)/);if(null!==e)return`Opera ${e[1]}`;const s=t.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=t.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=t.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=t.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const Mt="pushwoosh-recommendations-views";function Nt(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const t=new Map;return{getItem:e=>t.get(e)??null,setItem:(e,s)=>{t.set(e,s)}}}class Ft{constructor(t){this.deps={fetch:(...t)=>fetch(...t),now:Date.now,storage:Nt(),...t}}async trackProductView(t){!t?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(t.id))||await this.deps.postEvent("PW_ProductView",{productId:String(t.id),name:t.name,price:t.price,currency:t.currency,category:t.category,productUrl:t.url,imageUrl:t.imageUrl})}async fetch(t){const e=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:t.strategy});t.fallback&&e.set("fallback",t.fallback),t.limit&&e.set("limit",String(t.limit)),t.productId&&e.set("product_id",t.productId),t.exclude?.length&&e.set("exclude",t.exclude.join(",")),t.block&&e.set("block",t.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?${e}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(t){t?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:t.block,strategy:t.strategy,recoProductId:String(t.productId),position:t.position},{keepalive:!0})}seenRecently(t){const e=this.deps.now(),s=function(t){try{const e=JSON.parse(t||"{}");return null===e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>"number"==typeof t))}catch{return{}}}(this.deps.storage.getItem(Mt));if(e-(s[t]??-1/0)<3e4)return!0;const i={[t]:e};Object.keys(s).forEach(t=>{e-s[t]<3e4&&(i[t]=s[t])});try{this.deps.storage.setItem(Mt,JSON.stringify(i))}catch{}return!1}}function Ut(t){switch(t){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}class Ot{constructor(t,e,s){this.api=t,this.data=e,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(t){const e=t||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void et.error("You must have permission granted before subscribe!");const s=this.getPushToken(e),i=e.getKey("p256dh"),a=e.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:e.endpoint}),await this.api.registerDevice()}async unsubscribe(){const t=await this.getServiceWorkerRegistration(),e=await t.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),e&&await e.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const t=await this.data.getLastPermissionStatus(),e=this.getPermission();if(t!==e&&(await this.data.setLastPermissionStatus(e),void 0!==t))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 t=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(t),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const t=await this.data.getServiceWorkerUrl(),e=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${R()}`),await navigator.serviceWorker.register(`${t}${s}`,{scope:e})}async trySubscribe(){try{return await this.subscribePushManager()}catch(t){return console.error(t),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const t=await this.getServiceWorkerRegistration(),e=await this.getApplicationServerKey();return t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e?this.urlBase64ToUint8Array(e):null})}async getCredentials(){const t=await this.getServiceWorkerRegistration();return await t.pushManager.getSubscription()}getPushToken(t){return t?t.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(e),i=new Uint8Array(s.length);for(let t=0;t<s.length;++t)i[t]=s.charCodeAt(t);return i}}class qt{constructor(t,e,s){this.api=t,this.config=s,this.data=e}getPermission(){const{permission:t}=this.getPermissionInfo();return t}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const t={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(e=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,t,()=>e())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void et.error("You must have permission granted before subscribe!");const{deviceToken:t}=this.getPermissionInfo();await this.data.setTokens({pushToken:t}),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 t=await this.data.getWebSitePushId(),e=void 0!==t&&this.config.webSitePushId!==t;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)||e}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class Lt{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.addEventHandler=(t,e)=>this.eventBus.addEventHandler(t,e),this.removeEventHandler=(t,e)=>this.eventBus.removeEventHandler(t,e),this.dispatchEvent=(t,e)=>this.eventBus.dispatchEvent(t,e),this.debug={async showLog(){const t=await X.getAll();console.log(t)},async showKeyValues(){const t=await J.getAll();console.log(t)},async showMessages(){(await Q.getAll()).forEach(t=>console.log(t))}},this.eventBus=new st,this.data=new vt,this.apiClient=new Pt(this.data),this.api=new St(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new xt({eventBus:this.eventBus,data:this.data,postEvent:(t,e)=>this.api.postEvent(t,e),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Ft({postEvent:(t,e,s)=>this.api.postEvent(t,e,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Rt(A()),this.inboxModel=new bt(this.eventBus,this.data,this.api),this.pwinbox=new pt(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget())}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let t;const e=new Promise(e=>{t=setTimeout(()=>e(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),e]),clearTimeout(t),this.moduleRegistry.webPopups}push(t){if(M(t))this.subscribeToLegacyEvents(u,t);else{if(!Array.isArray(t))throw new Error("Invalid command!");if("init"===t[0])this.initialize(t[1]).catch(t=>{console.error("Pushwoosh: Error during initialization",t)});else if(!this.subscribeToLegacyEvents(t[0],t[1]))throw console.log("Pushwoosh: Unknown command",t),new Error("Unknown command!")}}async subscribe(t=!0){const e=this.runSubscribe(t);this.subscriptionInFlight=e;try{await e}finally{this.subscriptionInFlight===e&&(this.subscriptionInFlight=null)}}async runSubscribe(t){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 e=this.requireDriver();if(e.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await e.askPermission();const t=e.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:t})}const s=e.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||t)&&await e.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await e.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(t){throw et.error(t,"Error occurred during the unsubscribe"),t}}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(t=!0){if(await this.data.setCommunicationEnabled(t),t){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const t=this.driver?.checkIsPermissionGranted();t&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:t});const e=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:t,device_type:e})}async removeAllDeviceData(){const t=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:t}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(t){return this.recommendations.trackProductView(t)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:t}=await this.data.getTokens();return t}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}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(t){this.rawInitParams={...t},this.initParams={...T,...t},this.isInitAborted=!1;const e=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(et.setLevel(e||t.logLevel||"error"),t.logLevel&&await this.data.setLogLevel(t.logLevel),this.isPushDisabled=!1===t.pushNotifications,this.isAvailableNotifications()||et.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!t.applicationCode)throw new Error("Can't find application code!");const s=!1===t.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!==t.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(t.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(t.tags?.Language||navigator.language),await this.data.setApiEntrypoint(t.pushwooshUrl||""),await this.data.setApiToken(t.apiToken||""),await this.data.setSdkVersion("3.99.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(t){et.write("error",t)}const t=await this.data.getDelayedEvent();if(t){const{type:e,payload:s}=t;this.emitLegacyEventsFromServiceWorker(e,s),await this.data.setDelayedEvent(null)}if(this.platformChecker.isSafari&&!this.initParams.unifiedPlatform){const t=/#P(.*)/,e=decodeURIComponent(document.location.hash);t.test(e)&&this.api.pushStat(t.exec(e)[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.data.setDeviceType(this.resolvePlatformType()),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)):et.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(t=>et.error(t,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=t=>this.onServiceWorkerMessage(t)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(t,e){if(!this.isInitAborted)try{await e()}catch(e){const s=function(t){const e=t?.statusCode;return"number"==typeof e?e:void 0}(e);if(void 0!==s&&-1!==_.indexOf(s))return void this.abortInit(s);et.error(e,`Pushwoosh: init step "${t}" failed`)}}abortInit(t){this.isInitAborted=!0,et.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${t}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){return this.initParams.unifiedPlatform?11:this.platformChecker.getPlatformType()}async ensureHwid(t=!1){if(await this.readHwid()&&!t)return;const e=this.initParams.applicationCode+"_"+R();try{await this.data.setHwid(e),await this.data.getHwid()!==e&&et.info(W)}catch(t){et.info(t,W)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:t}=this.initParams||{};return t&&"user_id"!==t?t:void 0}async isUserIdChanged(){const{userId:t}=this.initParams,e=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!t&&"user_id"!==t&&t!==e&&!s}async defaultProcess(){const t=this.requireDriver(),e=t.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await t.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(t){const{data:e={}}=t||{},{type:s="",payload:i={}}=e||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(t){let e=await this.data.getLastOpenApplicationTime();const s=Date.now();e||(e=0);(t||!(s-e<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){if(this.driver)return Ut(this.driver.getPermission());const t=this.platformChecker.isSafari&&!this.initParams?.unifiedPlatform;return function(t,e){const s="safari"in t?t.safari?.pushNotification:void 0;if(s&&e)try{return Ut(s.permission(e).permission)}catch{return"unsupported"}return"PushManager"in t&&"Notification"in t?Ut(t.Notification.permission):s?"not_determined":"unsupported"}(A(),t?this.initParams?.safariWebsitePushID:void 0)}async reportPushPermissionChange(){const t=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const e=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(e===c)s||t||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(t=>et.error(t,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const t=this.dropRevokedSubscription(e).catch(t=>et.error(t,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(t)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(t){await this.data.setLastPermissionStatus(t),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(t=>et.error(t,"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",()=>this.reportPushPermissionChangeInBackground()),this.isPushPermissionWatched=!0}catch(t){et.info(t,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const t=this.initParams,e=await this.data.getUserId();if(t.userId&&"user_id"!==t.userId&&t.userId!==e)try{await this.api.registerUser(t.userId,!1)}catch(t){et.error(t,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const e=await this.data.getEmail();return!!t.email&&t.email!==e},task:async()=>{await this.api.registerEmail(t.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const e=await this.data.getSmsNumber();return!!t.smsNumber&&t.smsNumber!==e},task:async()=>{await this.api.registerSmsNumber(t.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const e=await this.data.getWhatsAppNumber();return!!t.whatsAppNumber&&t.whatsAppNumber!==e},task:async()=>{await this.api.registerWhatsappNumber(t.whatsAppNumber,!1)}},{test:async()=>!!t.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const e=await this.data.getLanguage(),s={...t.tags||{},Language:e};await this.api.setTags(s)}}];await Promise.all(s.map(async t=>{try{await t.test()&&await t.task()}catch(t){console.error("Pushwoosh: Error during data registration",t)}}))}async loadConfig(){const t=await this.api.getConfig(["vapid_key","events","subscription_prompt","popup_forms","web_sdk","web_sdk_modules"]),e=t&&t.features;if(await this.data.setFeatures(e),e){if(await this.applyServerInitParams(function(t){if(void 0!==t?.web_sdk)return t.web_sdk;const e=t?.web_sdk_modules;return void 0!==e?{inboxWidget:e.inboxWidget,webPopups:e.webPopups}:void 0}(e)),e.events&&e.events.length){e.events.some(t=>t===x)&&this.sendPostEventVisitedPage()}if(e.vapid_key){const t=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(e.vapid_key),void 0!==t&&t!==e.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async applyServerInitParams(t){const e=function(t,e){if(!e)return{};const s={};if(it.forEach(t=>{void 0!==e[t]&&(s[t]=e[t])}),void 0!==e.inboxWidget&&(s.inboxWidget={...t.inboxWidget,...e.inboxWidget}),void 0!==e.webPopups&&(s.webPopups={...t.webPopups,...e.webPopups}),void 0!==e.subscriptionWidget){const i=at(t.subscribeWidget,e.subscribeWidget)??t.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...t.subscribePopup,enable:!1},s}const i=at(t.subscribeWidget,e.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,t);0!==Object.keys(e).length&&(this.initParams={...this.initParams,...e},await this.data.setInitParams(this.initParams))}async initPushNotifications(t){if(await this.data.setDefaultNotificationImage(t.defaultNotificationImage),await this.data.setDefaultNotificationTitle(t.defaultNotificationTitle),await this.data.setServiceWorkerUrl(t.serviceWorkerUrl),await this.data.setServiceWorkerScope(t.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return et.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(t){et.error(t,"Internal error: defaultProcess fail")}}else et.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:t}=await this.data.getTokens();t&&et.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.platformChecker.isSafari&&!this.initParams.unifiedPlatform){const{safariWebsitePushID:t}=await this.data.getInitParams();return t?void(this.driver=new qt(this.api,this.data,{webSitePushId:t})):void et.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}et.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new Ot(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:t},location:{href:e}}=window,s=await this.data.getDeviceType();this.api.postEvent(x,{url:e,title:t,device_type:s})}subscribeToLegacyEvents(t,e){let s=!0;switch(!0){case"onLoad"===t:e();break;case t===u:if(this.ready){e(this.api);break}this.eventBus.addEventHandler("ready",()=>e(this.api));break;case t in F:this.eventBus.addEventHandler(F[t].name,s=>{const{prop:i}=F[t];e(this.api,i?s[i]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(t,e){switch(t){case f:this.eventBus.dispatchEvent("receive-push",{notification:e});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:e});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:e});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:e})}}}return e})());
|
|
2
2
|
//# sourceMappingURL=npm.js.map
|