web-push-notifications 3.118.0 → 3.119.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 +25 -0
- package/core/events.types.d.ts +5 -0
- package/helpers/url.d.ts +2 -0
- package/models/InboxCell.d.ts +3 -1
- package/models/InboxCell.types.d.ts +32 -0
- package/models/InboxMessages.types.d.ts +7 -2
- package/modules/Api/Api.d.ts +1 -1
- package/modules/ApiClient/ApiClient.d.ts +2 -1
- package/modules/ApiClient/ApiClient.types.d.ts +1 -0
- package/modules/ApiClient/__tests__/ApiClient.test.d.ts +1 -0
- package/modules/InboxMessagesPublic.d.ts +3 -0
- 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-inbox.js +1 -1
- package/widget-inbox.js.map +1 -1
- package/widgets/Inbox/InboxWidget.d.ts +3 -0
- package/widgets/Inbox/constants.d.ts +2 -0
- package/widgets/Inbox/renderer.d.ts +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,31 @@ 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(inbox): card buttons in the inbox widget (DEV-1062)
|
|
13
|
+
|
|
14
|
+
- An inbox message may carry up to three buttons in `action_params.u.buttons` (unlabeled ones are dropped before counting;
|
|
15
|
+
the id is the payload's `"0"`..`"2"`, or the position among the kept buttons when there is none, as in the mobile SDKs); the widget draws them under the text
|
|
16
|
+
(a button without a background is drawn as a link; colours other than `#RRGGBB`/`#RRGGBBAA` are ignored, the rest are
|
|
17
|
+
upper-cased; a legacy item without a valid id keeps no colours and opens its url or arrives as `custom`).
|
|
18
|
+
- `open` goes to the button's url (script schemes, `intent:` and scheme-less urls are dropped), `copy` puts `copy_text` on the
|
|
19
|
+
clipboard and shows a short "Copied", `custom` fires the new `click-inbox-button` event with
|
|
20
|
+
`{messageCode, buttonId, data}`. A mobile-only action (`dismiss`, `markread`) or an unknown one arrives as `custom`,
|
|
21
|
+
with the rest of the item as `data`; a legacy `{title, url}` item opens its url.
|
|
22
|
+
- A tap reports the message opened (status 3, once per message, as a card tap does) and then `inboxStatus` with
|
|
23
|
+
status 6 and `button_id`, the order the Android SDK uses; both go with `keepalive`, 6 starting once 3 is sent, and `open`
|
|
24
|
+
navigates as soon as both are sent, not answered, so the reports outlive the page; it never runs the message's own action. Sites with their own inbox UI read `buttons` from
|
|
25
|
+
`pwinbox.loadMessages()` and report a tap with `pwinbox.reportButtonClick(code, buttonId)`.
|
|
26
|
+
- Needs `@pushwoosh/websdk-common` 6.33.0.
|
|
27
|
+
|
|
28
|
+
## fix(platform-checker): detect the legacy Safari path on window.safari alone again
|
|
29
|
+
|
|
30
|
+
- 3.117.0 took `window.safari.pushNotification` as the sign of the legacy Safari path. Apple exposes
|
|
31
|
+
`window.safari` without `pushNotification` on some devices, and those switched from `10` to `11`
|
|
32
|
+
on the next visit; an application without its own web VAPID keys then had every such device
|
|
33
|
+
re-created on registerDevice, tags lost (about 500 devices an hour on one application alone).
|
|
34
|
+
The test is `window.safari` plus "Safari" in the user agent again, as it was before 3.117.
|
|
35
|
+
- `platformChecker.isSafari` means the same as before 3.117 again.
|
|
36
|
+
|
|
12
37
|
## refactor(platform-checker): deprecate the PlatformChecker facade
|
|
13
38
|
|
|
14
39
|
- The SDK keeps what it detects about the browser in `Pushwoosh.environment` (`browser`, `capabilities`,
|
package/core/events.types.d.ts
CHANGED
|
@@ -48,6 +48,11 @@ export interface EventHandlerMap {
|
|
|
48
48
|
'update-inbox-messages': EventHandler<EventPayload<{
|
|
49
49
|
messages: unknown;
|
|
50
50
|
}>>;
|
|
51
|
+
'click-inbox-button': EventHandler<EventPayload<{
|
|
52
|
+
messageCode: string;
|
|
53
|
+
buttonId: string;
|
|
54
|
+
data: Record<string, unknown>;
|
|
55
|
+
}>>;
|
|
51
56
|
'receive-in-app-code': EventHandler<EventPayload<{
|
|
52
57
|
code: string;
|
|
53
58
|
}>>;
|
package/helpers/url.d.ts
CHANGED
|
@@ -2,3 +2,5 @@
|
|
|
2
2
|
export declare function isSafeUrl(url: string): boolean;
|
|
3
3
|
/** True when the url carries a scheme and that scheme is safe to navigate to. */
|
|
4
4
|
export declare function isSafeAbsoluteUrl(url: string): boolean;
|
|
5
|
+
/** True when the url opens an Android intent, whitespace and control characters ignored. */
|
|
6
|
+
export declare function isIntentUrl(url: string): boolean;
|
package/models/InboxCell.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { type IInboxMessageSlide, type IInboxUserData } from './InboxCell.types';
|
|
1
|
+
import { type IInboxMessageButton, type IInboxMessageSlide, type IInboxUserData } from './InboxCell.types';
|
|
2
2
|
import { type IInboxMessageActionParams } from './InboxMessages.types';
|
|
3
3
|
export declare function parseUserData(actionParams: IInboxMessageActionParams): IInboxUserData;
|
|
4
4
|
/** Slides we can draw: the ones with an image, at most {@link INBOX_MAX_CAROUSEL_SLIDES}. */
|
|
5
5
|
export declare function getValidSlides(userData: IInboxUserData): Array<IInboxMessageSlide>;
|
|
6
|
+
/** Labeled card buttons, at most {@link INBOX_MAX_BUTTONS}; id from the payload or the position, as in the mobile SDKs. */
|
|
7
|
+
export declare function getButtons(userData: IInboxUserData): Array<IInboxMessageButton>;
|
|
6
8
|
export declare function getHeroUrl(actionParams: IInboxMessageActionParams, userData: IInboxUserData, messageImage: string): string;
|
|
7
9
|
/** Small round avatar of a cell: the message image, or the one inside `u`. */
|
|
8
10
|
export declare function getIconUrl(userData: IInboxUserData, messageImage: string): string;
|
|
@@ -10,10 +10,23 @@ export interface IInboxSlideRaw {
|
|
|
10
10
|
title?: string;
|
|
11
11
|
url?: string;
|
|
12
12
|
}
|
|
13
|
+
/** One card button inside `action_params.u`; mobile-only legacy items may carry other actions and keys. */
|
|
14
|
+
export interface IInboxButtonRaw {
|
|
15
|
+
id?: unknown;
|
|
16
|
+
title?: unknown;
|
|
17
|
+
text_color?: unknown;
|
|
18
|
+
bg_color?: unknown;
|
|
19
|
+
action?: unknown;
|
|
20
|
+
url?: unknown;
|
|
21
|
+
copy_text?: unknown;
|
|
22
|
+
data?: unknown;
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
}
|
|
13
25
|
/** Cell contract plus the campaign's custom data, merged flat by the pipeline. */
|
|
14
26
|
export interface IInboxUserData {
|
|
15
27
|
displayType?: string;
|
|
16
28
|
carousel?: Array<IInboxSlideRaw>;
|
|
29
|
+
buttons?: unknown;
|
|
17
30
|
image?: string;
|
|
18
31
|
[key: string]: unknown;
|
|
19
32
|
}
|
|
@@ -25,3 +38,22 @@ export interface IInboxMessageSlide {
|
|
|
25
38
|
/** Where a tap on the slide goes; empty when the slide has none, and the message action applies. */
|
|
26
39
|
link: string;
|
|
27
40
|
}
|
|
41
|
+
/** What a tap on a card button does. */
|
|
42
|
+
export type TInboxButtonAction = 'open' | 'copy' | 'custom';
|
|
43
|
+
/** One card button of a public inbox message. */
|
|
44
|
+
export interface IInboxMessageButton {
|
|
45
|
+
/** Button id from the payload, `"0"`..`"2"`; the position among the labeled buttons when the payload has none. Reported with the click. */
|
|
46
|
+
id: string;
|
|
47
|
+
title: string;
|
|
48
|
+
/** `#RRGGBB` or `#RRGGBBAA`; empty for the default of the style. */
|
|
49
|
+
textColor: string;
|
|
50
|
+
/** `#RRGGBB` or `#RRGGBBAA`; empty draws the button as a link. */
|
|
51
|
+
bgColor: string;
|
|
52
|
+
action: TInboxButtonAction;
|
|
53
|
+
/** Target of an `open` button; empty when none was sent or its scheme is unsafe. */
|
|
54
|
+
url: string;
|
|
55
|
+
/** Text a `copy` button puts on the clipboard. */
|
|
56
|
+
copyText: string;
|
|
57
|
+
/** Payload of a `custom` button, passed to the `click-inbox-button` event. */
|
|
58
|
+
data: Record<string, unknown>;
|
|
59
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type IInboxMessageSlide, type TInboxLayout } from './InboxCell.types';
|
|
1
|
+
import { type IInboxMessageButton, type IInboxMessageSlide, type TInboxLayout } from './InboxCell.types';
|
|
2
2
|
export type TInboxActionLink = 1;
|
|
3
3
|
export type TInboxActionRichMedia = 2;
|
|
4
4
|
export type TInboxActionType = TInboxActionLink | TInboxActionRichMedia;
|
|
@@ -7,6 +7,7 @@ export type TInboxMessageStatusRead = 2;
|
|
|
7
7
|
export type TInboxMessageStatusOpen = 3;
|
|
8
8
|
export type TInboxMessageStatusDeleted = 4;
|
|
9
9
|
export type TInboxMessageStatus = TInboxMessageStatusDelivered | TInboxMessageStatusRead | TInboxMessageStatusOpen | TInboxMessageStatusDeleted;
|
|
10
|
+
export type TInboxMessageStatusButtonClick = 6;
|
|
10
11
|
export type TReadInboxMessagesStatusRange = [TInboxMessageStatusRead, TInboxMessageStatusOpen];
|
|
11
12
|
export interface IInboxMessageActionParams {
|
|
12
13
|
l?: string | null;
|
|
@@ -52,7 +53,8 @@ export interface IInboxStatusRequest {
|
|
|
52
53
|
application: string;
|
|
53
54
|
inbox_code: string;
|
|
54
55
|
time: number;
|
|
55
|
-
status: TInboxMessageStatus;
|
|
56
|
+
status: TInboxMessageStatus | TInboxMessageStatusButtonClick;
|
|
57
|
+
button_id?: string;
|
|
56
58
|
hash?: string;
|
|
57
59
|
device_type: number;
|
|
58
60
|
}
|
|
@@ -89,6 +91,8 @@ export interface IInboxMessagePublic {
|
|
|
89
91
|
customData: Record<string, unknown>;
|
|
90
92
|
/** Web popup a tap opens; empty when the message opens `link` instead. */
|
|
91
93
|
webPopupCode: string;
|
|
94
|
+
/** Card buttons by position, at most three; a label-less one is not drawn. */
|
|
95
|
+
buttons: Array<IInboxMessageButton>;
|
|
92
96
|
}
|
|
93
97
|
export interface IInboxMessages {
|
|
94
98
|
messagesWithNoActionPerformedCount(): Promise<number>;
|
|
@@ -97,6 +101,7 @@ export interface IInboxMessages {
|
|
|
97
101
|
loadMessages(): Promise<Array<IInboxMessagePublic>>;
|
|
98
102
|
readMessagesWithCodes(codes: Array<string>): Promise<void>;
|
|
99
103
|
performActionForMessageWithCode(code: string): Promise<void>;
|
|
104
|
+
reportButtonClick(code: string, buttonId: string): Promise<void>;
|
|
100
105
|
deleteMessagesWithCodes(codes: Array<string>): Promise<void>;
|
|
101
106
|
syncMessages(): Promise<void>;
|
|
102
107
|
publicMessageBuilder(message: IInboxMessage): Promise<IInboxMessagePublic>;
|
package/modules/Api/Api.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export declare class Api {
|
|
|
62
62
|
[key: string]: any;
|
|
63
63
|
}, init?: IRequestInit): Promise<IMapResponse['postEvent']>;
|
|
64
64
|
getInboxMessages(count?: number): Promise<IMapResponse['getInboxMessages']>;
|
|
65
|
-
inboxStatus(order: string, status: number): Promise<IMapResponse['inboxStatus']>;
|
|
65
|
+
inboxStatus(order: string, status: number, buttonId?: string, init?: IRequestInit): Promise<IMapResponse['inboxStatus']>;
|
|
66
66
|
multiRegisterDevice(request: Partial<MultiRegisterDeviceRequest>): Promise<IMapResponse['multiRegisterDevice']>;
|
|
67
67
|
getParams(): Promise<any>;
|
|
68
68
|
private getRequestParams;
|
|
@@ -3,6 +3,7 @@ import { Logger } from '../../core/logger';
|
|
|
3
3
|
import { Data } from '../Data/Data';
|
|
4
4
|
export type IRequestInit = {
|
|
5
5
|
keepalive?: boolean;
|
|
6
|
+
onSent?: () => void;
|
|
6
7
|
};
|
|
7
8
|
export declare class ApiClient {
|
|
8
9
|
private readonly data;
|
|
@@ -30,7 +31,7 @@ export declare class ApiClient {
|
|
|
30
31
|
setEmailTags(options: IMapRequest['setEmailTags']): Promise<IMapResponse['setEmailTags']>;
|
|
31
32
|
postEvent(options: IMapRequest['postEvent'], init?: IRequestInit): Promise<IMapResponse['postEvent']>;
|
|
32
33
|
getInboxMessages(options: IMapRequest['getInboxMessages']): Promise<IMapResponse['getInboxMessages']>;
|
|
33
|
-
inboxStatus(options: IMapRequest['inboxStatus']): Promise<IMapResponse['inboxStatus']>;
|
|
34
|
+
inboxStatus(options: IMapRequest['inboxStatus'], init?: IRequestInit): Promise<IMapResponse['inboxStatus']>;
|
|
34
35
|
multiRegisterDevice(options: IMapRequest['multiRegisterDevice']): Promise<IMapResponse['multiRegisterDevice']>;
|
|
35
36
|
sdkUsage(options: IMapRequest['sdkUsage'], init?: IRequestInit): Promise<IMapResponse['sdkUsage']>;
|
|
36
37
|
private createRequest;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -57,6 +57,9 @@ export default class InboxMessages implements IInboxMessages {
|
|
|
57
57
|
* @param code
|
|
58
58
|
*/
|
|
59
59
|
performActionForMessageWithCode(code: string): Promise<void>;
|
|
60
|
+
/** Report a card button tap: status 3 once per message, then 6 with `buttonId`; resolves once both are sent. */
|
|
61
|
+
reportButtonClick(code: string, buttonId: string): Promise<void>;
|
|
62
|
+
private sendStatus;
|
|
60
63
|
private showWebPopup;
|
|
61
64
|
/**
|
|
62
65
|
* Delete messages by codes
|
package/npm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperties(e,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>rt});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",W="PW_SiteOpened",x="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.",T=[210],R={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function M(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const _=e=>"function"==typeof e;function L(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const N={[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",F="messages",q="inboxMessages";function O(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[O(U,function(e){e.createObjectStore(U,{keyPath:"key"})}),O("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),O(F,function(e){e.createObjectStore(F,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),O(q,function(e){const t="status",s=e.createObjectStore(q,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=U,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=F,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||M(),i=this.handlers[e];return i?(i.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}const re=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],ne=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],oe=e=>{const t=e.toLowerCase();let s,i=3;return re.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function ce(e){const t=[];return Object.entries(e).forEach(([e,s])=>{re.includes(e)?ne.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:oe(e)})}),t}function he(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class ue{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const de=["classic","captioned","banner","carousel"];function le(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const ge=/^(?:javascript|vbscript|data|blob|file):/i,pe=/^[a-z][a-z\d+\-.]*:/i;function me(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function we(e){const t=me(e);return pe.test(t)&&!ge.test(t)}function be(e,t){return t||e.image||""}function fe(e){const t=["displayType","carousel","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class ye{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new ue){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&we(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(de.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&le(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:be(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=be(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:fe(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ge.test(me(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class ve{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class Pe{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new ve(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new ve(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new ve(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new ve(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new ve(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new ve(i,e);return a.index=t,a.countByIndex(s)}}class Se{constructor(e,t,s,i=new Pe,a=new ue){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new ye(this.data,this.api,this)})}}class Ce extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const Ie=e=>`params.${e}`;class ke{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","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 t of e)await this.store.set(Ie(t),void 0)}async setApplicationCode(e){await this.store.set(Ie("applicationCode"),e)}async getApplicationCode(){return this.store.get(Ie("applicationCode"))}async setApiToken(e){return await this.store.set(Ie("apiToken"),e)}async getApiToken(){return this.store.get(Ie("apiToken"))}async setHwid(e){await this.store.set(Ie("hwid"),e)}async getHwid(){return this.store.get(Ie("hwid"))}async setDeviceType(e){await this.store.set(Ie("deviceType"),e)}async getDeviceType(){return this.store.get(Ie("deviceType"))}async setFormFactor(e){await this.store.set(Ie("formFactor"),e)}async getFormFactor(){return this.store.get(Ie("formFactor"))}async setDeviceModel(e){await this.store.set(Ie("deviceModel"),e)}async getDeviceModel(){return this.store.get(Ie("deviceModel"))}async setLanguage(e){await this.store.set(Ie("language"),e)}async getLanguage(){return this.store.get(Ie("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(Ie("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(Ie("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(Ie("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(Ie("apiEntrypoint"),i)}async setTokens(e){await this.store.set(Ie("tokens"),e)}getTokens(){return this.store.get(Ie("tokens"))}async setApplicationServerKey(e){await this.store.set(Ie("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(Ie("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(Ie("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(Ie("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(Ie("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(Ie("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(Ie("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(Ie("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(Ie("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(Ie("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(Ie("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(Ie("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(Ie("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(Ie("userId"))}async getFeatureFlags(){return this.store.get(Ie("featureFlags"))}async setFeatureFlags(e){await this.store.set(Ie("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(Ie("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(Ie("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(Ie("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(Ie("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(Ie("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(Ie("email"))}async setStatusEmailWasChanged(e){await this.store.set(Ie("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(Ie("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(Ie("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(Ie("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(Ie("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(Ie("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(Ie("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(Ie("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(Ie("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(Ie("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(Ie("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(Ie("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(Ie("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(Ie("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(Ie("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(Ie("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(Ie("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(Ie("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(Ie("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(Ie("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(Ie("sdkVersion"),e)}async getSdkVersion(){return this.store.get(Ie("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(Ie("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(Ie("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(Ie("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(Ie("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(Ie("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(Ie("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(Ie("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(Ie("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(Ie("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(Ie("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(Ie("features"),e)}async getFeatures(){return this.store.get(Ie("features"))}async setInitParams(e){await this.store.set(Ie("init"),e)}async getInitParams(){return this.store.get(Ie("init"))}async setInboxLastRequestCode(e){await this.store.set(Ie("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(Ie("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(Ie("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(Ie("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(Ie("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(Ie("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(Ie("delayedEvent"),e)}getDelayedEvent(){return this.store.get(Ie("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(Ie("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(Ie("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(Ie("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(Ie("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(Ie("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(Ie("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(Ie("logLevel"),e)}async getLogLevel(){return this.store.get(Ie("logLevel"),"error")}async getShownWebPopups(){return this.store.get(Ie("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(Ie("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(Ie("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(Ie("isRecurringVisitor"),!1)}}class De{constructor(e=new ke,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...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",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Ce(s,t)}const t=await e.json();if(200!==t.status_code)throw new Ce(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Ee{constructor(e,t=new ke,s=new De,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=L(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,locale:await this.getLocale(),page:he(),push_token:t.pushToken,auth_token:t.authToken,public_key:t.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 e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={},i){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s,...i?{button_id:i}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=We(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return We(await this.data.getLanguage())||void 0}async registerUser(e,t=!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=`${e}`,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}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:M()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(x);return e}}function We(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class xe{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class Te extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const Re=/json\/1\.3\/?$/,Ae="api/v2/device-api/getFeatureFlags";const Me=18e5;class _e{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new xe(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Me)){await this.deps.data.setFeatureFlagImpressions({...Ue(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new Te("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new Te("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(Re.test(t))return t.replace(Re,Ae);try{return`${new URL(t).origin}/${Ae}`}catch(e){return i.replace(Re,Ae)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new Te(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new Te(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new Te("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Le(c.response))throw new Te(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Ne(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Fe(this.cache.flags):""}}function Le(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ne(e){const t={};return Le(e)?(Object.keys(e).forEach(s=>{const i=e[s];Le(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Le(i.properties)?i.properties:{}})}),t):t}function Ue(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Me&&(s[i]=e[i])}),s}function Fe(e){return Array.isArray(e)?`[${e.map(Fe).join(",")}]`:Le(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Fe(e[t])}`).join(",")}}`:JSON.stringify(e)}const qe=[["opera",/\bOPR\/|Opera/],["edge",/\bEdge?\//],["firefox",/firefox/i],["chrome",/\bChrome\/|\bCriOS\//],["safari",/\bSafari\//]];function Oe(e){const t=qe.find(([,t])=>t.test(e));return t?t[0]:"unknown"}function Be({userAgent:e,appName:t,appVersion:s}){const i=e.match(/\bOPR\/(\d+)/);if(null!==i)return`Opera ${i[1]}`;const a=e.match(/\bEdge?\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;const[,r="",n]=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[],o=n?[r,n]:[t,s,"-?"],c=e.match(/version\/([.\d]+)/i);return null!==c&&o.splice(1,1,c[1]),o.join(" ")}function je(e){return{name:Oe(e.userAgent),model:Be(e)}}function Ve(e){const t=e.userAgentData?.mobile;return"boolean"==typeof t?t?"MOBILE":"DESKTOP":/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e.userAgent)?"MOBILE":"DESKTOP"}function $e(e){const{safari:t}=e;return{webPush:!!e.navigator?.serviceWorker&&"PushManager"in e&&"Notification"in e,safariLegacy:!!t?.pushNotification}}function He(e){return e.webPush||e.safariLegacy}function Ke({legacySafari:e,unifiedPlatform:t,browser:s}){return e?10:t?11:"firefox"===s?12:11}class ze{constructor(e){this.browser=e.browser,this.capabilities=e.capabilities,this.formFactor=e.formFactor}get isAvailableNotifications(){return He(this.capabilities)}get isAvailableServiceWorker(){return this.capabilities.webPush}get isSafari(){return this.capabilities.safariLegacy}get isOpera(){return"opera"===this.browser.name}get isEdge(){return"edge"===this.browser.name}get browserVersion(){return this.browser.model}get isMobile(){return"MOBILE"===this.formFactor}get isDesktop(){return"DESKTOP"===this.formFactor}get platform(){return this.getPlatformType()}getPlatformType(){return Ke({legacySafari:this.capabilities.safariLegacy,unifiedPlatform:!1,browser:this.browser.name})}getBrowserVersion(){return this.browser.model}getFormFactor(){return this.formFactor}}const Ge="pushwoosh-recommendations-views";function Je(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class Ye{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:Je(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(Ge));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(Ge,JSON.stringify(i))}catch{}return!1}}const Xe="sdkUsageReportedOn";class Qe{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(Xe)===t)return;localStorage.setItem(Xe,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function Ze(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function et(e){return"safari"in e?e.safari?.pushNotification:void 0}function tt(e,t){try{return et(e)?.permission(t)}catch{return}}function st(e,t){const s=t?tt(e,t):void 0;return s?.permission===c&&!!s.deviceToken}class it{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${M()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class at{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class rt{constructor(){var e;this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=L(1e4),this.moduleRegistry={},this.sdkUsage=new Qe,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new ke,this.apiClient=new De(this.data),this.api=new Ee(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new _e({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Ye({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.environment={browser:je((e=A()).navigator),capabilities:$e(e),formFactor:Ve(e.navigator)},this.platformChecker=new ze(this.environment),this.inboxModel=new Se(this.eventBus,this.data,this.api),this.pwinbox=new ye(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(_(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return He(this.environment.capabilities)}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){ce(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...R,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.environment.formFactor),await this.data.setDeviceModel(this.environment.browser.model);if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.118.0"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.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)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==T.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){const{safariWebsitePushID:e,unifiedPlatform:t=!1}=this.initParams??{},{capabilities:s,browser:i}=this.environment;return this.isLegacySafari=function({capabilities:e,hasLegacySubscription:t,webVapidConfigured:s,unifiedPlatform:i}){return!(!e.safariLegacy||e.webPush&&!t&&(i||s))}({capabilities:s,hasLegacySubscription:s.safariLegacy&&st(A(),e),webVapidConfigured:this.isWebVapidConfigured,unifiedPlatform:t}),Ke({legacySafari:this.isLegacySafari,unifiedPlatform:t,browser:i.name})}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+M();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(x)}catch(e){te.info(e,x)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void 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(t){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(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?Ze(this.driver.getPermission()):function(e,t){const s=et(e);if(s&&t){const s=tt(e,t);return s?Ze(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?Ze(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new at(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}const{webPush:e}=this.environment.capabilities;te.info({isAvailableServiceWorker:e}),e&&(this.driver=new it(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=he(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in N:this.eventBus.addEventHandler(N[e].name,s=>{const{prop:i}=N[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperties(e,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>wt});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",W="PW_SiteOpened",x="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.",T=[210],A={autoSubscribe:!0,serviceWorkerUrl:s};function R(){return globalThis}function _(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const M=e=>"function"==typeof e;function L(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const N={[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",F="messages",q="inboxMessages";function O(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[O(U,function(e){e.createObjectStore(U,{keyPath:"key"})}),O("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),O(F,function(e){e.createObjectStore(F,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),O(q,function(e){const t="status",s=e.createObjectStore(q,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=U,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=F,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||_(),i=this.handlers[e];return i?(i.forEach(e=>{M(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}const re=[...Object.keys({applicationCode:!0,apiToken:!0,communicationEnabled:!0,serviceWorkerUrl:!0,safariWebsitePushID:!0,autoSubscribe:!0,pushNotifications:!0,pushwooshUrl:!0,defaultNotificationImage:!0,defaultNotificationTitle:!0,logLevel:!0,userId:!0,email:!0,smsNumber:!0,whatsAppNumber:!0,scope:!0,tags:!0,subscribeWidget:!0,inboxWidget:!0,subscribePopup:!0,subscriptionWidget:!0,webPopups:!0,webPlacements:!0,recommendations:!0,webSDKPath:!0,unifiedPlatform:!0}),"pushwooshApiUrl"],ne=["subscribeWidget","subscribePopup","inboxWidget","webPopups","webPlacements"],oe=e=>{const t=e.toLowerCase();let s,i=3;return re.forEach(e=>{const a=((e,t)=>{let s=Array.from({length:t.length+1},(e,t)=>t);for(let i=1;i<=e.length;i++){const a=[i];for(let r=1;r<=t.length;r++)a[r]=Math.min(s[r]+1,a[r-1]+1,s[r-1]+(e[i-1]===t[r-1]?0:1));s=a}return s[t.length]})(t,e.toLowerCase());a<i&&(s=e,i=a)}),s};function ce(e){const t=[];return Object.entries(e).forEach(([e,s])=>{re.includes(e)?ne.includes(e)&&(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(s)&&"enabled"in s&&!("enable"in s)&&t.push({key:`${e}.enabled`,suggestion:`${e}.enable`}):t.push({key:e,suggestion:oe(e)})}),t}function he(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}class ue{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const de=["classic","captioned","banner","carousel"];function le(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const ge=/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;const pe=/^(?:javascript|vbscript|data|blob|file):/i,me=/^[a-z][a-z\d+\-.]*:/i;function we(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function be(e){const t=we(e);return me.test(t)&&!pe.test(t)}const fe=/^intent:/i;const ye=["id","title","text_color","bg_color"];function ve(e){return"string"==typeof e?e:""}function Pe(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Se(e){const t=ve(e);return t&&be(t)&&!function(e){return fe.test(we(e))}(t)?t:""}function Ce(e,t){return t?"":(s=e,("string"==typeof s&&ge.test(s)?s:void 0)||"").toUpperCase();var s}function Ie(e){return Object.keys(e).filter(e=>-1===ye.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}const ke=/^[0-2]$/;function De(e){return Pe(e)&&"string"==typeof e.title&&""!==e.title.trim()}function Ee(e){return(Array.isArray(e.buttons)?e.buttons:[]).filter(De).slice(0,3).map((e,t)=>{const s="string"==typeof e.id&&ke.test(e.id);return function(e,t,s){const i=Se(e.url),a={id:t,title:ve(e.title),textColor:Ce(e.text_color,s),bgColor:Ce(e.bg_color,s),action:"custom",url:i,copyText:ve(e.copy_text),data:Pe(e.data)?e.data:{}};if(s){const t="dismiss"===e.action||"markRead"===e.action||"markread"===e.action;i&&!t?a.action="open":a.data=Ie(e)}else"open"===e.action||"copy"===e.action||"custom"===e.action?a.action=e.action:a.data=Ie(e);return a}(e,s?e.id:String(t),!s)})}function We(e,t){return t||e.image||""}function xe(e){const t=["displayType","carousel","buttons","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class Te{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new ue){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&be(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),l=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(de.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&le(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:We(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),g=We(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:g,iconUrl:g,heroUrl:d,layout:l,carousel:u,customData:xe(h),webPopupCode:c.wp||"",buttons:Ee(h),code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!pe.test(we(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async reportButtonClick(e,t){const s=await this.inboxModel.getMessage(e),i=3!==s.status;i&&await this.sendStatus(s.order,3),await this.sendStatus(s.order,6,t),i&&(s.status=3,await this.inboxModel.putMessage(s))}sendStatus(e,t,s){return new Promise(i=>{this.api.inboxStatus(e,t,s,{keepalive:!0,onSent:i}).catch(s=>te.write("error",`Pushwoosh: inbox status ${t} for "${e}" failed`,s)).finally(i)})}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class Ae{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class Re{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new Ae(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new Ae(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new Ae(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new Ae(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new Ae(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new Ae(i,e);return a.index=t,a.countByIndex(s)}}class _e{constructor(e,t,s,i=new Re,a=new ue){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new Te(this.data,this.api,this)})}}class Me extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const Le=e=>`params.${e}`;class Ne{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","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 t of e)await this.store.set(Le(t),void 0)}async setApplicationCode(e){await this.store.set(Le("applicationCode"),e)}async getApplicationCode(){return this.store.get(Le("applicationCode"))}async setApiToken(e){return await this.store.set(Le("apiToken"),e)}async getApiToken(){return this.store.get(Le("apiToken"))}async setHwid(e){await this.store.set(Le("hwid"),e)}async getHwid(){return this.store.get(Le("hwid"))}async setDeviceType(e){await this.store.set(Le("deviceType"),e)}async getDeviceType(){return this.store.get(Le("deviceType"))}async setFormFactor(e){await this.store.set(Le("formFactor"),e)}async getFormFactor(){return this.store.get(Le("formFactor"))}async setDeviceModel(e){await this.store.set(Le("deviceModel"),e)}async getDeviceModel(){return this.store.get(Le("deviceModel"))}async setLanguage(e){await this.store.set(Le("language"),e)}async getLanguage(){return this.store.get(Le("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(Le("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(Le("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(Le("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(Le("apiEntrypoint"),i)}async setTokens(e){await this.store.set(Le("tokens"),e)}getTokens(){return this.store.get(Le("tokens"))}async setApplicationServerKey(e){await this.store.set(Le("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(Le("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(Le("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(Le("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(Le("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(Le("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(Le("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(Le("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(Le("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(Le("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(Le("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(Le("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(Le("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(Le("userId"))}async getFeatureFlags(){return this.store.get(Le("featureFlags"))}async setFeatureFlags(e){await this.store.set(Le("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(Le("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(Le("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(Le("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(Le("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(Le("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(Le("email"))}async setStatusEmailWasChanged(e){await this.store.set(Le("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(Le("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(Le("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(Le("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(Le("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(Le("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(Le("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(Le("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(Le("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(Le("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(Le("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(Le("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(Le("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(Le("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(Le("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(Le("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(Le("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(Le("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(Le("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(Le("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(Le("sdkVersion"),e)}async getSdkVersion(){return this.store.get(Le("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(Le("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(Le("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(Le("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(Le("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(Le("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(Le("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(Le("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(Le("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(Le("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(Le("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(Le("features"),e)}async getFeatures(){return this.store.get(Le("features"))}async setInitParams(e){await this.store.set(Le("init"),e)}async getInitParams(){return this.store.get(Le("init"))}async setInboxLastRequestCode(e){await this.store.set(Le("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(Le("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(Le("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(Le("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(Le("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(Le("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(Le("delayedEvent"),e)}getDelayedEvent(){return this.store.get(Le("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(Le("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(Le("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(Le("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(Le("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(Le("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(Le("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(Le("logLevel"),e)}async getLogLevel(){return this.store.get(Le("logLevel"),"error")}async getShownWebPopups(){return this.store.get(Le("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(Le("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(Le("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(Le("isRecurringVisitor"),!1)}}class Ue{constructor(e=new Ne,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}getWebPlacements(e){return this.createRequest("getWebPlacements",e)}trackWebPlacement(e){return this.createRequest("trackWebPlacement",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e,t){return this.createRequest("inboxStatus",e,t)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:R().location.origin},credentials:"include"}:{},o=fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive});s.onSent?.();const c=await o,h=await this.checkResponse(c);return h.base_url&&await this.data.setApiEntrypoint(h.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(h.response)}`),h.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new Me(s,t)}const t=await e.json();if(200!==t.status_code)throw new Me(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Fe{constructor(e,t=new Ne,s=new Ue,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=L(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,locale:await this.getLocale(),page:he(),push_token:t.pushToken,auth_token:t.authToken,public_key:t.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 e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={},i){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s,...i?{button_id:i}:{}})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=qe(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return qe(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){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=`${e}`,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}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:_()}:s)}async getWebPlacements(){if(this.getIsCommunicationDisabled())return[];const e=await this.apiClient.getWebPlacements(await this.getRequestParams());return e?.web_placements??[]}async trackWebPlacement(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.trackWebPlacement({...await this.getRequestParams(),hash:e,action:t})}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h?.web_placements?.length&&this.eventBus.dispatchEvent("receive-web-placements",{placements:h.web_placements}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t,s,i){const a=await this.getRequestParams();return this.apiClient.inboxStatus({...a,inbox_code:e,status:t,time:(new Date).getTime(),...void 0===s?{}:{button_id:s}},i)}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(x);return e}}function qe(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class Oe{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class Be extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const je=/json\/1\.3\/?$/,Ve="api/v2/device-api/getFeatureFlags";const $e=18e5;class He{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new Oe(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<$e)){await this.deps.data.setFeatureFlagImpressions({...Ge(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new Be("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new Be("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(je.test(t))return t.replace(je,Ve);try{return`${new URL(t).origin}/${Ve}`}catch(e){return i.replace(je,Ve)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new Be(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new Be(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new Be("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!Ke(c.response))throw new Be(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:ze(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Je(this.cache.flags):""}}function Ke(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ze(e){const t={};return Ke(e)?(Object.keys(e).forEach(s=>{const i=e[s];Ke(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:Ke(i.properties)?i.properties:{}})}),t):t}function Ge(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<$e&&(s[i]=e[i])}),s}function Je(e){return Array.isArray(e)?`[${e.map(Je).join(",")}]`:Ke(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Je(e[t])}`).join(",")}}`:JSON.stringify(e)}const Ye=[["opera",/\bOPR\/|Opera/],["edge",/\bEdge?\//],["firefox",/firefox/i],["chrome",/\bChrome\/|\bCriOS\//],["safari",/\bSafari\//]];function Xe(e){const t=Ye.find(([,t])=>t.test(e));return t?t[0]:"unknown"}function Qe({userAgent:e,appName:t,appVersion:s}){const i=e.match(/\bOPR\/(\d+)/);if(null!==i)return`Opera ${i[1]}`;const a=e.match(/\bEdge?\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;const[,r="",n]=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[],o=n?[r,n]:[t,s,"-?"],c=e.match(/version\/([.\d]+)/i);return null!==c&&o.splice(1,1,c[1]),o.join(" ")}function Ze(e){return{name:Xe(e.userAgent),model:Qe(e)}}function et(e){const t=e.userAgentData?.mobile;return"boolean"==typeof t?t?"MOBILE":"DESKTOP":/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e.userAgent)?"MOBILE":"DESKTOP"}function tt(e){const t=e.navigator?.userAgent??"";return{webPush:!!e.navigator?.serviceWorker&&"PushManager"in e&&"Notification"in e,safariLegacy:"safari"in e&&t.includes("Safari")}}function st(e){return e.webPush||e.safariLegacy}function it({legacySafari:e,unifiedPlatform:t,browser:s}){return e?10:t?11:"firefox"===s?12:11}class at{constructor(e){this.browser=e.browser,this.capabilities=e.capabilities,this.formFactor=e.formFactor}get isAvailableNotifications(){return st(this.capabilities)}get isAvailableServiceWorker(){return this.capabilities.webPush}get isSafari(){return this.capabilities.safariLegacy}get isOpera(){return"opera"===this.browser.name}get isEdge(){return"edge"===this.browser.name}get browserVersion(){return this.browser.model}get isMobile(){return"MOBILE"===this.formFactor}get isDesktop(){return"DESKTOP"===this.formFactor}get platform(){return this.getPlatformType()}getPlatformType(){return it({legacySafari:this.capabilities.safariLegacy,unifiedPlatform:!1,browser:this.browser.name})}getBrowserVersion(){return this.browser.model}getFormFactor(){return this.formFactor}}const rt="pushwoosh-recommendations-views";function nt(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class ot{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:nt(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(rt));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(rt,JSON.stringify(i))}catch{}return!1}}const ct="sdkUsageReportedOn";class ht{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(ct)===t)return;localStorage.setItem(ct,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function ut(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function dt(e){return"safari"in e?e.safari?.pushNotification:void 0}function lt(e,t){try{return dt(e)?.permission(t)}catch{return}}function gt(e,t){const s=t?lt(e,t):void 0;return s?.permission===c&&!!s.deviceToken}class pt{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${_()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class mt{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class wt{constructor(){var e;this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=L(1e4),this.moduleRegistry={},this.sdkUsage=new ht,this.pendingWebPlacements=[],this.webPlacementsSink=null,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new Ne,this.apiClient=new Ue(this.data),this.api=new Fe(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new He({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new ot({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.environment={browser:Ze((e=R()).navigator),capabilities:tt(e),formFactor:et(e.navigator)},this.platformChecker=new at(this.environment),this.inboxModel=new _e(this.eventBus,this.data,this.api),this.pwinbox=new Te(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget()),this.eventBus.addEventHandler("receive-web-placements",({placements:e})=>this.deliverWebPlacements(e))}takeWebPlacements(){const e=this.pendingWebPlacements;return this.pendingWebPlacements=[],e}deliverWebPlacements(e){!1!==this.initParams?.webPlacements?.enable&&(this.webPlacementsSink?this.webPlacementsSink(e):(this.pendingWebPlacements.push(...e),this.loadWebPopupsWidget().catch(e=>{te.error(e,"Pushwoosh: failed to load the web popups widget for journey placements")})))}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(M(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return st(this.environment.capabilities)}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),function(e){ce(e).forEach(({key:e,suggestion:t})=>{const s=t?` Did you mean "${t}"?`:"";console.warn(`Pushwoosh: unknown init parameter "${e}" is ignored.${s}`)})}(e),this.initParams={...A,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.environment.formFactor),await this.data.setDeviceModel(this.environment.browser.model);if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.119.0"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.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)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==T.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){const{safariWebsitePushID:e,unifiedPlatform:t=!1}=this.initParams??{},{capabilities:s,browser:i}=this.environment;return this.isLegacySafari=function({capabilities:e,hasLegacySubscription:t,webVapidConfigured:s,unifiedPlatform:i}){return!(!e.safariLegacy||e.webPush&&!t&&(i||s))}({capabilities:s,hasLegacySubscription:s.safariLegacy&>(R(),e),webVapidConfigured:this.isWebVapidConfigured,unifiedPlatform:t}),it({legacySafari:this.isLegacySafari,unifiedPlatform:t,browser:i.name})}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+_();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(x)}catch(e){te.info(e,x)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void 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(t){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(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?ut(this.driver.getPermission()):function(e,t){const s=dt(e);if(s&&t){const s=lt(e,t);return s?ut(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?ut(e.Notification.permission):s?"not_determined":"unsupported"}(R(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=R();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_placements","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new mt(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}const{webPush:e}=this.environment.capabilities;te.info({isAvailableServiceWorker:e}),e&&(this.driver=new pt(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=he(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in N:this.eventBus.addEventHandler(N[e].name,s=>{const{prop:i}=N[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
2
2
|
//# sourceMappingURL=npm.js.map
|