web-push-notifications 3.44.7 → 3.44.8

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.
Files changed (224) hide show
  1. package/core/Pushwoosh.d.ts +199 -0
  2. package/core/Pushwoosh.types.d.ts +213 -0
  3. package/core/Safari.types.d.ts +17 -0
  4. package/core/constants.d.ts +41 -0
  5. package/core/events.types.d.ts +55 -0
  6. package/core/functions.d.ts +5 -0
  7. package/core/legacyEventsMap.d.ts +5 -0
  8. package/core/logger.d.ts +14 -0
  9. package/core/modules/EventBus/EventBus.d.ts +10 -0
  10. package/core/storage.d.ts +27 -0
  11. package/helpers/logger.d.ts +11 -0
  12. package/helpers/pwlogger/Logger.constants.d.ts +21 -0
  13. package/helpers/pwlogger/Logger.d.ts +37 -0
  14. package/helpers/pwlogger/Logger.types.d.ts +44 -0
  15. package/helpers/pwlogger/handlers/handler-console/handler-console.d.ts +2 -0
  16. package/{src/helpers/unescape.ts → helpers/unescape.d.ts} +1 -18
  17. package/models/InboxMessages.d.ts +82 -0
  18. package/models/InboxMessages.types.d.ts +83 -0
  19. package/models/NotificationPayload.d.ts +39 -0
  20. package/models/NotificationPayload.types.d.ts +63 -0
  21. package/modules/Api/Api.d.ts +45 -0
  22. package/modules/Api/Api.types.d.ts +7 -0
  23. package/modules/ApiClient/ApiClient.d.ts +29 -0
  24. package/modules/ApiClient/ApiClient.types.d.ts +188 -0
  25. package/modules/Data/Data.d.ts +76 -0
  26. package/modules/DateModule.d.ts +27 -0
  27. package/modules/InboxMessagesPublic.d.ts +64 -0
  28. package/modules/PlatformChecker/PlatformChecker.d.ts +45 -0
  29. package/modules/PlatformChecker/PlatformChecker.types.d.ts +5 -0
  30. package/modules/storage/Storage.d.ts +63 -0
  31. package/{src/modules/storage/Storage.types.ts → modules/storage/Storage.types.d.ts} +7 -25
  32. package/modules/storage/Store.d.ts +22 -0
  33. package/modules/storage/migrations/26-11-2018.d.ts +2 -0
  34. package/modules/storage/migrations/MigrationExecutor.d.ts +9 -0
  35. package/modules/storage/migrations/Migrations.d.ts +15 -0
  36. package/modules/storage/migrations/constants.d.ts +6 -0
  37. package/modules/storage/migrations/helpers.d.ts +7 -0
  38. package/modules/storage/migrations/initial.d.ts +2 -0
  39. package/modules/storage/version.d.ts +2 -0
  40. package/npm.js +2 -0
  41. package/npm.js.map +1 -0
  42. package/package.json +1 -1
  43. package/service-worker.d.ts +1 -0
  44. package/service-worker.js +2 -0
  45. package/service-worker.js.map +1 -0
  46. package/services/PushService/PushService.types.d.ts +64 -0
  47. package/services/PushService/drivers/PushServiceDefault/PushServiceDefault.d.ts +29 -0
  48. package/{src/services/PushService/drivers/PushServiceDefault/PushServiceDefault.types.ts → services/PushService/drivers/PushServiceDefault/PushServiceDefault.types.d.ts} +1 -1
  49. package/services/PushService/drivers/PushServiceSafari/PushServiceSafari.d.ts +21 -0
  50. package/services/PushService/drivers/PushServiceSafari/PushServiceSafari.types.d.ts +4 -0
  51. package/widget-inbox.js +2 -0
  52. package/widget-inbox.js.map +1 -0
  53. package/widget-subscribe-popup.js +2 -0
  54. package/widget-subscribe-popup.js.map +1 -0
  55. package/widget-subscription-button.js +2 -0
  56. package/widget-subscription-button.js.map +1 -0
  57. package/widget-subscription-prompt.d.ts +2 -0
  58. package/widget-subscription-prompt.js +2 -0
  59. package/widget-subscription-prompt.js.map +1 -0
  60. package/widgets/Inbox/InboxWidget.d.ts +49 -0
  61. package/widgets/Inbox/constants.d.ts +7 -0
  62. package/widgets/Inbox/helpers.d.ts +4 -0
  63. package/widgets/Inbox/inbox_widget.types.d.ts +34 -0
  64. package/widgets/Inbox/widgetTemplates.d.ts +4 -0
  65. package/widgets/SubscribePopup/SubscribePopup.d.ts +20 -0
  66. package/widgets/SubscribePopup/constants.d.ts +6 -0
  67. package/widgets/SubscribePopup/helpers.d.ts +1 -0
  68. package/widgets/SubscribePopup/popupTemplates.d.ts +9 -0
  69. package/widgets/SubscribePopup/types/subscribe-popup.d.ts +43 -0
  70. package/widgets/SubscriptionButton/bell.d.ts +2 -0
  71. package/widgets/SubscriptionButton/constants.d.ts +7 -0
  72. package/widgets/SubscriptionButton/index.d.ts +90 -0
  73. package/widgets/SubscriptionButton/positioning.d.ts +11 -0
  74. package/widgets/SubscriptionButton/subscribe_widget.types.d.ts +35 -0
  75. package/widgets/SubscriptionPrompt/SubscriptionPromptWidget.constants.d.ts +1 -0
  76. package/widgets/SubscriptionPrompt/SubscriptionPromptWidget.d.ts +14 -0
  77. package/widgets/SubscriptionPrompt/SubscriptionPromptWidget.helpers.d.ts +3 -0
  78. package/widgets/SubscriptionPrompt/SubscriptionPromptWidget.types.d.ts +19 -0
  79. package/widgets/SubscriptionPrompt/constants.d.ts +21 -0
  80. package/widgets/SubscriptionPrompt/helpers.d.ts +5 -0
  81. package/worker/global.d.ts +16 -0
  82. package/worker/notification.d.ts +9 -0
  83. package/worker/worker.types.d.ts +4 -0
  84. package/.editorconfig +0 -11
  85. package/.gitlab-ci.yml +0 -193
  86. package/babel.config.js +0 -7
  87. package/ci/cdn/Dockerfile +0 -12
  88. package/ci/dev/Dockerfile +0 -30
  89. package/ci/dev/rootfs/entrypoint.sh +0 -18
  90. package/ci/dev/rootfs/entrypoint.sh.d/nginx.sh +0 -6
  91. package/ci/dev/rootfs/entrypoint.sh.d/supervisor.sh +0 -5
  92. package/ci/dev/rootfs/etc/nginx/_real_ip.conf +0 -2
  93. package/ci/dev/rootfs/etc/nginx/conf.d/default.conf +0 -20
  94. package/ci/dev/rootfs/etc/supervisor.d/nginx.ini +0 -11
  95. package/ci/github/Dockerfile +0 -59
  96. package/ci/github/release-zip.js +0 -61
  97. package/ci/npm/Dockerfile +0 -22
  98. package/config/config.js +0 -24
  99. package/config/configBuilder.js +0 -126
  100. package/config/helpers.js +0 -9
  101. package/config/index.js +0 -1
  102. package/develop/README.md +0 -42
  103. package/develop/favicon.png +0 -0
  104. package/develop/index.html +0 -511
  105. package/eslint.config.mjs +0 -114
  106. package/public/index.d.ts +0 -337
  107. package/scripts/zip.js +0 -26
  108. package/src/core/Pushwoosh.ts +0 -768
  109. package/src/core/Pushwoosh.types.ts +0 -254
  110. package/src/core/Safari.types.ts +0 -26
  111. package/src/core/constants.ts +0 -58
  112. package/src/core/events.types.ts +0 -46
  113. package/src/core/functions.ts +0 -33
  114. package/src/core/legacyEventsMap.ts +0 -64
  115. package/src/core/logger.ts +0 -64
  116. package/src/core/modules/EventBus/EventBus.ts +0 -66
  117. package/src/core/storage.ts +0 -254
  118. package/src/helpers/logger.ts +0 -81
  119. package/src/helpers/pwlogger/Logger.constants.ts +0 -31
  120. package/src/helpers/pwlogger/Logger.ts +0 -218
  121. package/src/helpers/pwlogger/Logger.types.ts +0 -66
  122. package/src/helpers/pwlogger/handlers/handler-console/handler-console.ts +0 -40
  123. package/src/models/InboxMessages.ts +0 -202
  124. package/src/models/InboxMessages.types.ts +0 -111
  125. package/src/models/NotificationPayload.ts +0 -216
  126. package/src/models/NotificationPayload.types.ts +0 -65
  127. package/src/modules/Api/Api.ts +0 -386
  128. package/src/modules/Api/Api.types.ts +0 -7
  129. package/src/modules/ApiClient/ApiClient.ts +0 -153
  130. package/src/modules/ApiClient/ApiClient.types.ts +0 -222
  131. package/src/modules/Data/Data.ts +0 -345
  132. package/src/modules/DateModule.ts +0 -53
  133. package/src/modules/InboxMessagesPublic.ts +0 -222
  134. package/src/modules/PlatformChecker/PlatformChecker.ts +0 -170
  135. package/src/modules/PlatformChecker/PlatformChecker.types.ts +0 -5
  136. package/src/modules/storage/Storage.ts +0 -164
  137. package/src/modules/storage/Store.ts +0 -104
  138. package/src/modules/storage/migrations/26-11-2018.ts +0 -25
  139. package/src/modules/storage/migrations/MigrationExecutor.ts +0 -31
  140. package/src/modules/storage/migrations/Migrations.ts +0 -41
  141. package/src/modules/storage/migrations/constants.ts +0 -8
  142. package/src/modules/storage/migrations/helpers.ts +0 -16
  143. package/src/modules/storage/migrations/initial.ts +0 -47
  144. package/src/modules/storage/version.ts +0 -2
  145. package/src/pushwoosh-web-notifications.ts +0 -47
  146. package/src/pushwoosh-widget-inbox.ts +0 -8
  147. package/src/pushwoosh-widget-subscribe-popup.ts +0 -9
  148. package/src/pushwoosh-widget-subscription-button.ts +0 -8
  149. package/src/pushwoosh-widget-subscription-prompt.ts +0 -6
  150. package/src/service-worker.ts +0 -455
  151. package/src/services/PushService/PushService.types.ts +0 -74
  152. package/src/services/PushService/drivers/PushServiceDefault/PushServiceDefault.ts +0 -235
  153. package/src/services/PushService/drivers/PushServiceSafari/PushServiceSafari.ts +0 -125
  154. package/src/services/PushService/drivers/PushServiceSafari/PushServiceSafari.types.ts +0 -4
  155. package/src/widget-subscription-prompt.ts +0 -33
  156. package/src/widgets/Inbox/InboxWidget.ts +0 -564
  157. package/src/widgets/Inbox/constants.ts +0 -49
  158. package/src/widgets/Inbox/css/inboxWidgetStyle.css +0 -274
  159. package/src/widgets/Inbox/helpers.ts +0 -63
  160. package/src/widgets/Inbox/inbox.d.ts +0 -9
  161. package/src/widgets/Inbox/inbox_widget.types.ts +0 -41
  162. package/src/widgets/Inbox/widgetTemplates.ts +0 -55
  163. package/src/widgets/SubscribePopup/SubscribePopup.ts +0 -241
  164. package/src/widgets/SubscribePopup/constants.ts +0 -66
  165. package/src/widgets/SubscribePopup/helpers.ts +0 -11
  166. package/src/widgets/SubscribePopup/popupTemplates.ts +0 -24
  167. package/src/widgets/SubscribePopup/styles/popup.css +0 -226
  168. package/src/widgets/SubscribePopup/types/subscribe-popup.ts +0 -68
  169. package/src/widgets/SubscriptionButton/assets/css/main.css +0 -205
  170. package/src/widgets/SubscriptionButton/bell.ts +0 -67
  171. package/src/widgets/SubscriptionButton/constants.ts +0 -28
  172. package/src/widgets/SubscriptionButton/index.ts +0 -377
  173. package/src/widgets/SubscriptionButton/positioning.ts +0 -165
  174. package/src/widgets/SubscriptionButton/subscribe_widget.types.ts +0 -53
  175. package/src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.constants.ts +0 -1
  176. package/src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.helpers.ts +0 -110
  177. package/src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.ts +0 -102
  178. package/src/widgets/SubscriptionPrompt/SubscriptionPromptWidget.types.ts +0 -23
  179. package/src/widgets/SubscriptionPrompt/constants.ts +0 -22
  180. package/src/widgets/SubscriptionPrompt/helpers.ts +0 -42
  181. package/src/widgets/widgets.d.ts +0 -4
  182. package/src/worker/global.ts +0 -36
  183. package/src/worker/notification.ts +0 -34
  184. package/src/worker/worker.types.ts +0 -4
  185. package/test/__helpers__/apiHelpers.ts +0 -22
  186. package/test/__helpers__/keyValueHelpers.ts +0 -15
  187. package/test/__helpers__/platformHelpers.ts +0 -54
  188. package/test/__helpers__/sinonHelpers.ts +0 -7
  189. package/test/__helpers__/storageHelpers.ts +0 -56
  190. package/test/__mocks__/apiRequests.ts +0 -26
  191. package/test/__mocks__/idbMock.ts +0 -12
  192. package/test/__mocks__/idbObjectStoreMock.ts +0 -38
  193. package/test/__mocks__/inboxMessages.ts +0 -292
  194. package/test/__mocks__/models/inboxModel.ts +0 -71
  195. package/test/__mocks__/modules/apiClientModule.ts +0 -18
  196. package/test/__mocks__/modules/dateModule.ts +0 -34
  197. package/test/__mocks__/modules/inboxParamsModule.ts +0 -21
  198. package/test/__mocks__/modules/paramsBuilder.ts +0 -12
  199. package/test/__mocks__/modules/paramsModule.ts +0 -35
  200. package/test/__mocks__/modules/payloadBuilderModule.ts +0 -15
  201. package/test/__mocks__/modules/storageModule.ts +0 -58
  202. package/test/__mocks__/navigator.ts +0 -38
  203. package/test/__mocks__/notification.ts +0 -84
  204. package/test/__mocks__/pushwoosh.ts +0 -12
  205. package/test/__mocks__/userAgents +0 -8
  206. package/test/functions.test.ts +0 -22
  207. package/test/ignore-html.js +0 -6
  208. package/test/mocha.opts +0 -6
  209. package/test/modules/DateModule/unit.test.ts +0 -80
  210. package/test/modules/storage/Storage/unit.test.ts +0 -180
  211. package/test/modules/storage/Store/unit.test.ts +0 -192
  212. package/testRegister.js +0 -24
  213. package/tsconfig.json +0 -31
  214. package/webpack.config.js +0 -163
  215. /package/{src/core/modules/EventBus/index.ts → core/modules/EventBus/index.d.ts} +0 -0
  216. /package/{src/helpers/pwlogger/index.ts → helpers/pwlogger/index.d.ts} +0 -0
  217. /package/{src/modules/PlatformChecker/index.ts → modules/PlatformChecker/index.d.ts} +0 -0
  218. /package/{src/npm.ts → npm.d.ts} +0 -0
  219. /package/{src/services/PushService/PushService.ts → services/PushService/PushService.d.ts} +0 -0
  220. /package/{src/widget-inbox.ts → widget-inbox.d.ts} +0 -0
  221. /package/{src/widget-subscribe-popup.ts → widget-subscribe-popup.d.ts} +0 -0
  222. /package/{src/widget-subscription-button.ts → widget-subscription-button.d.ts} +0 -0
  223. /package/{src/widgets/Inbox/index.ts → widgets/Inbox/index.d.ts} +0 -0
  224. /package/{src/widgets/SubscribePopup/index.ts → widgets/SubscribePopup/index.d.ts} +0 -0
@@ -0,0 +1,76 @@
1
+ import { keyValue } from '../../core/storage';
2
+ export declare class Data {
3
+ private readonly store;
4
+ constructor(store?: typeof keyValue);
5
+ clearAll(): Promise<void>;
6
+ setApplicationCode(application: string): Promise<void>;
7
+ getApplicationCode(): Promise<string>;
8
+ setApiToken(token: string): Promise<string>;
9
+ getApiToken(): Promise<string>;
10
+ setHwid(hwid: string): Promise<void>;
11
+ getHwid(): Promise<string>;
12
+ setDeviceType(type: number): Promise<void>;
13
+ getDeviceType(): Promise<number>;
14
+ setDeviceModel(model: string): Promise<void>;
15
+ getDeviceModel(): Promise<string>;
16
+ setLanguage(language: string): Promise<void>;
17
+ getLanguage(): Promise<string>;
18
+ setApiEntrypoint(url: string): Promise<void>;
19
+ getApiEntrypoint(): Promise<string>;
20
+ setTokens(tokens: any): Promise<void>;
21
+ getTokens(): Promise<any>;
22
+ setApplicationServerKey(key: string): Promise<void>;
23
+ getApplicationServerKey(): Promise<string | undefined>;
24
+ setIsVapidChanged(status: boolean): Promise<void>;
25
+ getIsVapidChanged(): Promise<boolean>;
26
+ setWebSitePushId(senderId: string): Promise<void>;
27
+ getWebSitePushId(): Promise<string>;
28
+ setDefaultNotificationImage(url?: string): Promise<void>;
29
+ getDefaultNotificationImage(): Promise<string>;
30
+ setDefaultNotificationTitle(text?: string): Promise<void>;
31
+ getDefaultNotificationTitle(): Promise<string>;
32
+ setUserId(userId?: string | number): Promise<void>;
33
+ getUserId(): Promise<string | undefined>;
34
+ setStatusUserIdWasChanged(status: boolean): Promise<void>;
35
+ getStatusUserIdWasChanged(): Promise<boolean>;
36
+ setEmail(email?: string): Promise<void>;
37
+ getEmail(): Promise<string | undefined>;
38
+ setStatusEmailWasChanged(status: boolean): Promise<void>;
39
+ getStatusEmailWasChanged(): Promise<boolean>;
40
+ setLastPermissionStatus(status: NotificationPermission): Promise<void>;
41
+ getLastPermissionStatus(): Promise<NotificationPermission | undefined>;
42
+ setStatusManualUnsubscribed(status: boolean): Promise<void>;
43
+ getStatusManualUnsubscribed(): Promise<boolean>;
44
+ setStatusCommunicationDisabled(status: boolean): Promise<void>;
45
+ getStatusCommunicationDisabled(): Promise<boolean>;
46
+ setStatusDropAllData(status: boolean): Promise<void>;
47
+ getStatusDropAllData(): Promise<boolean>;
48
+ setSdkVersion(version: string): Promise<void>;
49
+ getSdkVersion(): Promise<string>;
50
+ setServiceWorkerVersion(version: string): Promise<void>;
51
+ getServiceWorkerVersion(): Promise<string>;
52
+ setServiceWorkerUrl(url?: string | null): Promise<void>;
53
+ getServiceWorkerUrl(): Promise<string>;
54
+ setServiceWorkerScope(scope?: string): Promise<void>;
55
+ getServiceWorkerScope(): Promise<string>;
56
+ setLastOpenMessage(message: any): Promise<void>;
57
+ getLastOpenMessage(): Promise<any>;
58
+ setLastOpenApplicationTime(time: number): Promise<void>;
59
+ getLastOpenApplicationTime(): Promise<number>;
60
+ setFeatures(features: any): Promise<void>;
61
+ getFeatures(): Promise<any>;
62
+ setInitParams(params: any): Promise<any>;
63
+ getInitParams(): Promise<any>;
64
+ setInboxLastRequestCode(lastCode: string): Promise<void>;
65
+ getInboxLastRequestCode(): Promise<string>;
66
+ setInboxLastRequestTime(lastRequestTime: number): Promise<void>;
67
+ getInboxLastRequestTime(): Promise<number>;
68
+ setInboxNewMessagesCount(count: number): Promise<void>;
69
+ getInboxNewMessagesCount(): Promise<number>;
70
+ setDelayedEvent(event: any): Promise<void>;
71
+ getDelayedEvent(): Promise<any>;
72
+ setPromptDisplayCount(count: number): Promise<void>;
73
+ getPromptDisplayCount(): Promise<number>;
74
+ setPromptLastSeenTime(time: number): Promise<void>;
75
+ getPromptLastSeenTime(): Promise<number>;
76
+ }
@@ -0,0 +1,27 @@
1
+ export default class DateModule {
2
+ private _date;
3
+ constructor(date?: Date);
4
+ set date(date: Date);
5
+ get date(): Date;
6
+ /**
7
+ * Timestamp in UTC without milliseconds
8
+ */
9
+ getUtcTimestamp(): number;
10
+ /**
11
+ * Current date timestamp without milliseconds
12
+ */
13
+ getTimestamp(): number;
14
+ /**
15
+ * Set date to local timezone
16
+ */
17
+ setLocal(): void;
18
+ /**
19
+ * Add days to current date
20
+ * @param days
21
+ */
22
+ addDays(days: number): void;
23
+ /**
24
+ * Get inbox fake order
25
+ */
26
+ getInboxFakeOrder(): string;
27
+ }
@@ -0,0 +1,64 @@
1
+ import { type Api } from './Api/Api';
2
+ import { type Data } from './Data/Data';
3
+ import DateModule from './DateModule';
4
+ import { type default as InboxMessagesModel } from '../models/InboxMessages';
5
+ import { type IInboxMessage, type IInboxMessagePublic, type IInboxMessages } from '../models/InboxMessages.types';
6
+ export default class InboxMessages implements IInboxMessages {
7
+ private readonly data;
8
+ private readonly api;
9
+ private readonly inboxModel;
10
+ private dateModule;
11
+ constructor(data: Data, api: Api, inboxModel: InboxMessagesModel, dateModule?: DateModule);
12
+ /**
13
+ * Get message type by IInboxMessageActionParams
14
+ * @param actionParams
15
+ */
16
+ private messageTypeFactory;
17
+ /**
18
+ * Update messages status using codes from arguments
19
+ * @param codes
20
+ * @param messages
21
+ * @param status
22
+ */
23
+ private updateMessagesStatusWithCodes;
24
+ /**
25
+ * Build TInboxMessagePublic by TInboxMessage
26
+ * @param message
27
+ */
28
+ publicMessageBuilder({ action_type, action_params, image, title, send_date, inbox_id, text, status, }: IInboxMessage): Promise<IInboxMessagePublic>;
29
+ /**
30
+ * Count of messages with no action performed
31
+ */
32
+ messagesWithNoActionPerformedCount(): Promise<number>;
33
+ /**
34
+ * All unread messages
35
+ */
36
+ unreadMessagesCount(): Promise<number>;
37
+ /**
38
+ * All messages count
39
+ */
40
+ messagesCount(): Promise<number>;
41
+ /**
42
+ * Get all active messages
43
+ */
44
+ loadMessages(): Promise<Array<IInboxMessagePublic>>;
45
+ /**
46
+ * Mark messages as read
47
+ * @param codes
48
+ */
49
+ readMessagesWithCodes(codes: Array<string>): Promise<void>;
50
+ /**
51
+ * Execute message action. Type "richmedia" and "plain" does not support
52
+ * @param code
53
+ */
54
+ performActionForMessageWithCode(code: string): Promise<void>;
55
+ /**
56
+ * Delete messages by codes
57
+ * @param codes
58
+ */
59
+ deleteMessagesWithCodes(codes: Array<string>): Promise<void>;
60
+ /**
61
+ * Sync inbox messages with server
62
+ */
63
+ syncMessages(): Promise<void>;
64
+ }
@@ -0,0 +1,45 @@
1
+ import { type TPlatform } from './PlatformChecker.types';
2
+ export declare class PlatformChecker {
3
+ private readonly global;
4
+ private readonly _isSafari;
5
+ private readonly _isOpera;
6
+ private readonly _isEdge;
7
+ private readonly _isFirefox;
8
+ private readonly _isChrome;
9
+ private readonly _isMacOS;
10
+ private readonly _isAvailableServiceWorker;
11
+ private readonly _isAvailableNotifications;
12
+ /**
13
+ * Browser name + version
14
+ * Example: "Chrome 70"
15
+ */
16
+ private readonly _browserVersion;
17
+ private readonly _platform;
18
+ constructor(global: typeof globalThis);
19
+ get isEdge(): boolean;
20
+ get isSafari(): boolean;
21
+ get isOpera(): boolean;
22
+ get isAvailableServiceWorker(): boolean;
23
+ get isAvailableNotifications(): boolean;
24
+ get platform(): TPlatform;
25
+ get browserVersion(): string;
26
+ isSafariBrowser(): boolean;
27
+ isOperaBrowser(): boolean;
28
+ isEdgeBrowser(): boolean;
29
+ isFirefoxBrowser(): boolean;
30
+ isChromeBrowser(): boolean;
31
+ isMacOS(): boolean;
32
+ canUseServiceWorkers(): boolean;
33
+ /**
34
+ * Check availability ServiceWorker or safari browser on macos
35
+ */
36
+ canReceiveNotifications(): boolean;
37
+ /**
38
+ * Get Pushwoosh system platform code
39
+ */
40
+ getPlatformType(): TPlatform;
41
+ /**
42
+ * Get browser name + version from userAgent
43
+ */
44
+ getBrowserVersion(): string;
45
+ }
@@ -0,0 +1,5 @@
1
+ export type TPlatformSafari = 10;
2
+ export type TPlatformChrome = 11;
3
+ export type TPlatformFirefox = 12;
4
+ export type TPlatformEdge = 150;
5
+ export type TPlatform = TPlatformSafari | TPlatformChrome | TPlatformFirefox | TPlatformEdge;
@@ -0,0 +1,63 @@
1
+ import { type TIDBKeyType, type TIDBQueryValue, type TSdkStoreName } from './Storage.types';
2
+ export default class Storage {
3
+ db: Promise<IDBDatabase>;
4
+ /**
5
+ * Change database version handler
6
+ * @param db
7
+ * @param event
8
+ */
9
+ private dbVersionChangeHandler;
10
+ /**
11
+ * Success database request handler
12
+ * @param resolve
13
+ * @param event
14
+ */
15
+ private dbRequestSuccessHandler;
16
+ /**
17
+ * Need upgrade database version handler
18
+ * @param event
19
+ */
20
+ private dbRequestUpgradeNeededHandler;
21
+ /**
22
+ * Open db
23
+ */
24
+ getDB(): Promise<IDBDatabase>;
25
+ /**
26
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put
27
+ * @param storeName
28
+ * @param data
29
+ * @param key
30
+ */
31
+ put(storeName: TSdkStoreName, data: any, key?: string): Promise<TIDBKeyType>;
32
+ /**
33
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
34
+ * @param storeName
35
+ * @param key
36
+ */
37
+ delete(storeName: TSdkStoreName, key: string | number): Promise<void>;
38
+ /**
39
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get
40
+ * @param storeName
41
+ * @param key
42
+ * @param defaultValue
43
+ */
44
+ get<Response, D>(storeName: TSdkStoreName, key: TIDBKeyType, defaultValue?: D): Promise<Response | D>;
45
+ /**
46
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll
47
+ * @param storeName
48
+ */
49
+ getAll<Response>(storeName: TSdkStoreName): Promise<Array<Response>>;
50
+ /**
51
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count
52
+ * @param storeName
53
+ * @param query
54
+ */
55
+ count(storeName: TSdkStoreName, query?: IDBKeyRange): Promise<number>;
56
+ /**
57
+ * https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/count
58
+ * @param storeName
59
+ * @param indexName
60
+ * @param key
61
+ */
62
+ countByIndex(storeName: TSdkStoreName, indexName: string, key?: TIDBQueryValue): Promise<number>;
63
+ }
@@ -2,40 +2,26 @@ export type TKeyValueStoreName = 'keyValue';
2
2
  export type TMessageLogStoreName = 'messages';
3
3
  export type TMainLogStoreName = 'log';
4
4
  export type TInboxMessagesStoreName = 'inboxMessages';
5
- export type TSdkStoreName =
6
- | TKeyValueStoreName
7
- | TMessageLogStoreName
8
- | TInboxMessagesStoreName
9
- | TMainLogStoreName;
10
-
5
+ export type TSdkStoreName = TKeyValueStoreName | TMessageLogStoreName | TInboxMessagesStoreName | TMainLogStoreName;
11
6
  export type TMigrationType = (database: IDBDatabase) => void;
12
-
13
7
  export type TMigrationsObjectType = {
14
- initial: Array<TMigrationType>;
15
- [date: string]: Array<TMigrationType>; // date in YYYY/MM/DD format
8
+ initial: Array<TMigrationType>;
9
+ [date: string]: Array<TMigrationType>;
16
10
  };
17
-
18
11
  export interface IIDBOpenEventTargetWithResult extends EventTarget {
19
- result: IDBDatabase;
12
+ result: IDBDatabase;
20
13
  }
21
-
22
14
  export interface IIDBGetTransactionEventTargetWithResult extends EventTarget {
23
- result: any;
15
+ result: any;
24
16
  }
25
-
26
17
  export type TIDBKeyType = string | number | Date;
27
18
  export type TIDBQueryValue = TIDBKeyType | IDBKeyRange;
28
-
29
19
  export interface IDBIndex {
30
- getAll(query?: TIDBQueryValue, count?: number): IDBRequest;
20
+ getAll(query?: TIDBQueryValue, count?: number): IDBRequest;
31
21
  }
32
-
33
22
  export interface IDBObjectStore {
34
- getAll(query?: TIDBQueryValue, count?: number): IDBRequest;
23
+ getAll(query?: TIDBQueryValue, count?: number): IDBRequest;
35
24
  }
36
-
37
- // KeyValue Keys
38
-
39
25
  export type TIDBAppCodeKey = 'params.applicationCode';
40
26
  export type TIDBApiUrlKey = 'params.apiUrl';
41
27
  export type TIDBHwidKey = 'params.hwid';
@@ -44,11 +30,7 @@ export type TIDBDefaultNotificationTitleKey = 'params.defaultNotificationTitle';
44
30
  export type TIDBUserIdKey = 'params.userId';
45
31
  export type TIDBUserIdWasChangedKey = 'params.userIdWasChanged';
46
32
  export type TIDBDeviceType = 'params.deviceType';
47
-
48
33
  export type TSubscriptionPopupLastOpen = 'params.subscriptionPopupLastOpen';
49
-
50
34
  export type TIDBInboxLastRequestCodeKey = 'inbox.lastRequestCode';
51
35
  export type TIDBInboxLastRequestTimeKey = 'inbox.lastRequestTime';
52
36
  export type TIDBInboxNewMessagesCountKey = 'inbox.newMessagesCount';
53
-
54
- ///////////////////
@@ -0,0 +1,22 @@
1
+ import { type TIDBKeyType, type TIDBQueryValue, type TSdkStoreName } from './Storage.types';
2
+ export default class Store {
3
+ private readonly name;
4
+ private store;
5
+ private _index;
6
+ constructor(db: IDBDatabase, name: TSdkStoreName);
7
+ set index(index: string);
8
+ private writeRequestPromise;
9
+ private readRequestPromise;
10
+ put(data: any, key?: TIDBKeyType): Promise<TIDBKeyType>;
11
+ /**
12
+ * Fallback for old interface
13
+ * @param data
14
+ * @param key
15
+ */
16
+ add(data: any, key?: string): Promise<TIDBKeyType>;
17
+ delete(key: TIDBKeyType): Promise<void>;
18
+ get<Response, D>(key: TIDBKeyType, defaultValue?: D): Promise<Response | D>;
19
+ getAll<Response>(): Promise<Array<Response>>;
20
+ count(query?: IDBKeyRange): Promise<number>;
21
+ countByIndex(key?: TIDBQueryValue): Promise<number>;
22
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../Storage.types").TMigrationType[];
2
+ export default _default;
@@ -0,0 +1,9 @@
1
+ import Migrations from './Migrations';
2
+ import { type TMigrationType } from '../Storage.types';
3
+ export default class MigrationExecutor {
4
+ db: IDBDatabase;
5
+ migrationsBuilder: Migrations;
6
+ constructor(db: IDBDatabase, migrationsBuilder?: Migrations);
7
+ applyMigrations(): void;
8
+ applyMigrationsPack(migrationsPack: Array<TMigrationType>): void;
9
+ }
@@ -0,0 +1,15 @@
1
+ import DateModule from '../../DateModule';
2
+ import { type TMigrationsObjectType, type TMigrationType } from '../Storage.types';
3
+ export default class Migrations {
4
+ migrations: TMigrationsObjectType;
5
+ dateModule: DateModule;
6
+ constructor(dateModule?: DateModule);
7
+ /**
8
+ * Initial migration pack
9
+ */
10
+ get initial(): Array<TMigrationType>;
11
+ /**
12
+ * Return array of migrations packs sorted by date
13
+ */
14
+ get dateSorted(): Array<Array<TMigrationType>>;
15
+ }
@@ -0,0 +1,6 @@
1
+ import { type TInboxMessagesStoreName, type TKeyValueStoreName, type TMainLogStoreName, type TMessageLogStoreName } from '../Storage.types';
2
+ export declare const STORE_NAME_KEY_VALUE: TKeyValueStoreName;
3
+ export declare const STORE_NAME_MESSAGE_LOG: TMessageLogStoreName;
4
+ export declare const STORE_NAME_MAIN_LOG: TMainLogStoreName;
5
+ export declare const STORE_NAME_INBOX_MESSAGES: TInboxMessagesStoreName;
6
+ export declare const KEY_PATH_BASE_INCREMENT = "id";
@@ -0,0 +1,7 @@
1
+ import { type TMigrationType, type TSdkStoreName } from '../Storage.types';
2
+ /**
3
+ * Check existed store, before create
4
+ * @param name
5
+ * @param storeCreator
6
+ */
7
+ export declare function storeCreatorDecorator(name: TSdkStoreName, storeCreator: TMigrationType): TMigrationType;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../Storage.types").TMigrationType[];
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ declare const _default: 7;
2
+ export default _default;
package/npm.js ADDED
@@ -0,0 +1,2 @@
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var a in s)("object"==typeof exports?exports:e)[a]=s[a]}}(this,(()=>(()=>{"use strict";var e={d:(t,s)=>{for(var a in s)e.o(s,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:s[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Pushwoosh:()=>he});const s="deviceRegistrationStatus",a="registered",i="unregistered",r="denied",n="granted",o="default",c="onReady",h="onSubscribe",u="onUnsubscribe",d="onRegister",g="onPermissionPrompt",p="onPermissionDenied",l="onPermissionGranted",m="onSWInitError",w="onPushDelivery",v="onNotificationClick",b="onNotificationClose",y="onChangeCommunicationEnabled",f="onPutNewMessageToInboxStore",S="onUpdateInboxMessages",k="onShowNotificationPermissionDialog",P="onHideNotificationPermissionDialog",C="onShowSubscriptionWidget",x="onHideSubscriptionWidget",D="PW_SiteOpened";function I(){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=e=>"function"==typeof e,T={[d]:{name:"register"},[h]:{name:"subscribe"},[u]:{name:"unsubscribe"},[m]:{name:"initialize-service-worker-error",prop:"error"},[w]:{name:"receive-push",prop:"notification"},[v]:{name:"open-notification",prop:"notification"},[b]:{name:"hide-notification",prop:"notification"},[y]:{name:"change-enabled-communication",prop:"isEnabled"},[f]:{name:"receive-inbox-message",prop:"message"},[S]:{name:"update-inbox-messages",prop:"messages"},[k]:{name:"show-notification-permission-dialog"},[P]:{name:"hide-notification-permission-dialog",prop:"permission"},[C]:{name:"show-subscription-widget"},[x]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[g]:{name:"permission-default"},[l]:{name:"permission-granted"}},_="keyValue",R="messages",A="log",O="inboxMessages";function W(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const q=[W(O,(function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})}))];const N=[W(_,(function(e){e.createObjectStore(_,{keyPath:"key"})})),W(A,(function(e){const t=e.createObjectStore(A,{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})})),W(R,(function(e){e.createObjectStore(R,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}))];class U{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}class B{constructor(e=new U){this.migrations={initial:N,"2018/11/26":q},this.dateModule=e}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter((e=>"initial"!==e)).sort(((e,t)=>{const s=new U(new Date(e)),a=new U(new Date(t));return s.getTimestamp()-a.getTimestamp()})).map((e=>this.migrations[e]))}}class L{constructor(e,t=new B){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach((e=>{this.applyMigrationsPack(e)}))}applyMigrationsPack(e){e.forEach((e=>{e(this.db)}))}}function V(e,t){console.info("onversionchange",t),e.close()}let H;function j(e){return(H||(H=new Promise(((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const a=s.target.result;a.onversionchange=V.bind(null,a,t),e(a)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=V.bind(null,s,t),new L(s).applyMigrations()}}))),H).then((t=>new Promise(((s,a)=>e(t,s,a)))))}class F{_add(e){return j(((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);i.onsuccess=()=>{s(e)},i.onerror=()=>{a(i.error)}})).then((e=>this.getAll().then((t=>{if(Array.isArray(t)){const s=t.map((e=>e.id)).sort(((e,t)=>e==t?0:e<t?1:-1));if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map((e=>this.delete(e)))).then((()=>e))}return e}))))}delete(e){return j(((t,s,a)=>{const i=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);i.onsuccess=()=>{s(i.result)},i.onerror=()=>{a(i.error)}}))}getAll(){return j(((e,t,s)=>{const a=[],i=e.transaction(this.name).objectStore(this.name).openCursor();i.onsuccess=e=>{const s=e.target.result;s?(s.value&&a.push(s.value),s.continue()):t(a)},i.onerror=()=>{s(i.error)}}))}}const $=(K=_,{get:(e,t)=>j(((s,a,i)=>{const r=s.transaction(K).objectStore(K).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(r.result?.value||t):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})),getAll:()=>j(((e,t,s)=>{const a={},i=e.transaction(K).objectStore(K).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(a):o?s(i.error):r=setTimeout(c,0)};i.onsuccess=e=>{const t=e.target.result;t?(a[t.key]=t.value.value,t.continue()):n=!0},i.onerror=()=>o=!0,c()})),async extend(e,t){const s=await this.get(e),{...a}=t;await this.set(e,{...s,...a})},set:(e,t)=>j(((s,a,i)=>{const r=s.transaction([K],"readwrite").objectStore(K).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?a(e):c?i(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}))});var K;const G=new class extends F{constructor(){super(...arguments),this.name=A,this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const a={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(a.stack=t.stack),s&&(a.additional=s),this._add(a)}},z=new class extends F{constructor(){super(...arguments),this.name=R,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},J={error:1,info:2,debug:3};let Y=3;const Q={setLevel(e){J[e]||(e="error"),Y=J[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),G.add(e,t,s)}};Object.keys(J).forEach((e=>{const t=J[e];Q[e]=(...s)=>{t<=Y&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}}));class X{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter((e=>e!==t)))},this.dispatchEvent=(e,t)=>{const s=t.eventId||M(),a=this.handlers[e];return a?(a.forEach((e=>{E(e)&&setTimeout((()=>{e({...t,eventId:s})}),0)})),s):s},this.handlers={}}}class Z{constructor(e,t,s,a=new U){this.data=e,this.api=t,this.inboxModel=s,this.dateModule=a,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const a=[],i=[];t.forEach((async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,a.push(t),i.push(this.api.inboxStatus(t.order,t.status)))})),await this.inboxModel.putBulkMessages(a),await Promise.all(i)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:a,send_date:i,inbox_id:r,text:n,status:o}){const c=s||await this.data.getDefaultNotificationImage(),h=a||await this.data.getDefaultNotificationTitle(),u=JSON.parse(t);return this.dateModule.date=new Date(1e3*parseInt(i)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,u),link:u?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort(((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10))).sort(((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10))).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=JSON.parse(t.action_params),a=this.messageTypeFactory(t.action_type,s);2===a&&null!=s.l?document.location.href=s.l:3===a&&null!=s.l&&window.history.go(s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.inboxModel.updateMessages()}}class ee{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise(((s,a)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{a(e.error)}}))}readRequestPromise(e,t){return new Promise(((s,a)=>{e.onsuccess=e=>{const a=e.target;s(a.result||t)},e.onerror=()=>{a(e.error)}}))}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise(((s,a)=>{e.onsuccess=e=>{const a=e.target.result;a?(t.push(a.value),a.continue()):s(t)},e.onerror=()=>{a(e.error)}}))}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class te{dbVersionChangeHandler(e,t){console.info("onversionchange",t),e.close()}dbRequestSuccessHandler(e,t){const s=t.target.result;s.onversionchange=e=>{this.dbVersionChangeHandler(s,e)},e(s)}dbRequestUpgradeNeededHandler(e){const t=e.target.result;t.onversionchange=e=>{this.dbVersionChangeHandler(t,e)};new L(t).applyMigrations()}getDB(){return new Promise(((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=t=>{this.dbRequestSuccessHandler(e,t)},s.onupgradeneeded=e=>{this.dbRequestUpgradeNeededHandler(e)},s.onerror=()=>t(s.error)}))}async put(e,t,s){const a=await this.getDB(),i=new ee(a,e),r=await i.put(t,s);return a.close(),r}async delete(e,t){const s=await this.getDB(),a=new ee(s,e),i=await a.delete(t);return s.close(),i}async get(e,t,s){const a=await this.getDB(),i=new ee(a,e),r=await i.get(t,s);return a.close(),r}async getAll(e){const t=await this.getDB(),s=new ee(t,e),a=await s.getAll();return t.close(),a||[]}async count(e,t){const s=await this.getDB(),a=new ee(s,e),i=await a.count(t);return s.close(),i}async countByIndex(e,t,s){const a=await this.getDB(),i=new ee(a,e);i.index=t;const r=await i.countByIndex(s);return a.close(),r}}class se{constructor(e,t,s,a=new te,i=new U){this.eventBus=e,this.data=t,this.api=s,this.storage=a,this.storeName="inboxMessages",this.dateModule=i}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map((async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)}));return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map((e=>this.putMessage(e)));return Promise.all(t)}deleteMessages(e){const t=e.map((e=>this.storage.delete(this.storeName,e)));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter((t=>t.rt<e)).map((e=>e.inbox_id));return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter((e=>2===e.status||3===e.status))}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter((e=>1===e.status))}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new Z(this.data,this.api,this)})}}class ae{constructor(e=$){this.store=e}async clearAll(){await this.store.set("params.applicationCode",void 0),await this.store.set("params.hwid",void 0),await this.store.set("params.deviceType",void 0),await this.store.set("params.deviceModel",void 0),await this.store.set("params.language",void 0),await this.store.set("params.apiEntrypoint",void 0),await this.store.set("params.tokens",void 0),await this.store.set("params.applicationServerKey",void 0),await this.store.set("params.senderId",void 0),await this.store.set("params.webSitePushId",void 0),await this.store.set("params.defaultNotificationImage",void 0),await this.store.set("params.defaultNotificationTitle",void 0),await this.store.set("params.userId",void 0),await this.store.set("params.email",void 0),await this.store.set("params.userIdWasChanged",void 0),await this.store.set("params.isLastPermissionStatus",void 0),await this.store.set("params.isManualUnsubscribed",void 0),await this.store.set("params.isCommunicationDisabled",void 0),await this.store.set("params.isDropAllData",void 0),await this.store.set("params.sdkVersion",void 0),await this.store.set("params.serviceWorkerVersion",void 0),await this.store.set("params.serviceWorkerUrl",void 0),await this.store.set("params.serviceWorkerScope",void 0),await this.store.set("params.lastOpenMessage",void 0),await this.store.set("params.lastOpenApplicationTime",void 0),await this.store.set("params.features",void 0),await this.store.set("params.init",void 0)}async setApplicationCode(e){await this.store.set("params.applicationCode",e)}async getApplicationCode(){return await this.store.get("params.applicationCode")}async setApiToken(e){return await this.store.set("params.apiToken",e)}async getApiToken(){return await this.store.get("params.apiToken")}async setHwid(e){await this.store.set("params.hwid",e)}async getHwid(){return await this.store.get("params.hwid")}async setDeviceType(e){await this.store.set("params.deviceType",e)}async getDeviceType(){return await this.store.get("params.deviceType")}async setDeviceModel(e){await this.store.set("params.deviceModel",e)}async getDeviceModel(){return await this.store.get("params.deviceModel")}async setLanguage(e){await this.store.set("params.language",e)}async getLanguage(){return await this.store.get("params.language","en")}async setApiEntrypoint(e){await this.store.set("params.apiEntrypoint",e)}async getApiEntrypoint(){return await this.store.get("params.apiEntrypoint","https://cp.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set("params.tokens",e)}getTokens(){return this.store.get("params.tokens")}async setApplicationServerKey(e){await this.store.set("params.applicationServerKey",e)}async getApplicationServerKey(){return await this.store.get("params.applicationServerKey")}async setIsVapidChanged(e){await this.store.set("params.isVapidChanged",e)}async getIsVapidChanged(){return await this.store.get("params.isVapidChanged",!1)}async setWebSitePushId(e){await this.store.set("params.webSitePushId",e)}async getWebSitePushId(){return await this.store.get("params.webSitePushId")}async setDefaultNotificationImage(e){await this.store.set("params.defaultNotificationImage",e)}async getDefaultNotificationImage(){return await this.store.get("params.defaultNotificationImage","https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set("params.defaultNotificationTitle",e)}async getDefaultNotificationTitle(){return await this.store.get("params.defaultNotificationTitle","Pushwoosh notification")}async setUserId(e){e?await this.store.set("params.userId",e.toString()):await this.store.set("params.userId",void 0)}async getUserId(){return await this.store.get("params.userId")}async setStatusUserIdWasChanged(e){await this.store.set("params.userIdWasChanged",e)}async getStatusUserIdWasChanged(){return await this.store.get("params.userIdWasChanged",!1)}async setEmail(e){e?await this.store.set("params.email",e.toString()):await this.store.set("params.email",void 0)}async getEmail(){return await this.store.get("params.email")}async setStatusEmailWasChanged(e){await this.store.set("params.emailWasChanged",e)}async getStatusEmailWasChanged(){return await this.store.get("params.emailWasChanged",!1)}async setLastPermissionStatus(e){await this.store.set("params.isLastPermissionStatus",e)}async getLastPermissionStatus(){return await this.store.get("params.isLastPermissionStatus")}async setStatusManualUnsubscribed(e){await this.store.set("params.isManualUnsubscribed",e)}getStatusManualUnsubscribed(){return this.store.get("params.isManualUnsubscribed",!1)}async setStatusCommunicationDisabled(e){await this.store.set("params.isCommunicationDisabled",e)}getStatusCommunicationDisabled(){return this.store.get("params.isCommunicationDisabled",!1)}async setStatusDropAllData(e){await this.store.set("params.isDropAllData",e)}getStatusDropAllData(){return this.store.get("params.isDropAllData",!1)}async setSdkVersion(e){await this.store.set("params.sdkVersion",e)}async getSdkVersion(){return await this.store.get("params.sdkVersion")}async setServiceWorkerVersion(e){await this.store.set("params.serviceWorkerVersion",e)}getServiceWorkerVersion(){return this.store.get("params.serviceWorkerVersion")}async setServiceWorkerUrl(e){e&&await this.store.set("params.serviceWorkerUrl",e)}async getServiceWorkerUrl(){return await this.store.get("params.serviceWorkerUrl","/pushwoosh-service-worker.js")}async setServiceWorkerScope(e){e&&await this.store.set("params.serviceWorkerScope",e)}async getServiceWorkerScope(){return await this.store.get("params.serviceWorkerScope")}async setLastOpenMessage(e){await this.store.set("params.lastOpenMessage",e)}getLastOpenMessage(){return this.store.get("params.lastOpenMessage")}async setLastOpenApplicationTime(e){await this.store.set("params.lastOpenApplicationTime",e)}async getLastOpenApplicationTime(){return await this.store.get("params.lastOpenApplicationTime")}async setFeatures(e){await this.store.set("params.features",e)}async getFeatures(){return await this.store.get("params.features")}async setInitParams(e){await this.store.set("params.init",e)}async getInitParams(){return await this.store.get("params.init")}async setInboxLastRequestCode(e){await this.store.set("params.inbox.lastRequestCode",e)}async getInboxLastRequestCode(){return await this.store.get("params.inbox.lastRequestCode","")}async setInboxLastRequestTime(e){await this.store.set("params.inbox.lastRequestTime",e)}async getInboxLastRequestTime(){return this.store.get("params.inbox.lastRequestTime",0)}async setInboxNewMessagesCount(e){await this.store.set("params.inbox.newMessagesCount",e)}async getInboxNewMessagesCount(){return this.store.get("params.inbox.newMessagesCount",0)}async setDelayedEvent(e){await this.store.set("params.delayedEvent",e)}getDelayedEvent(){return this.store.get("params.delayedEvent")}async setPromptDisplayCount(e){await this.store.set("params.promptDisplayCount",e)}async getPromptDisplayCount(){return this.store.get("params.promptDisplayCount",0)}async setPromptLastSeenTime(e){await this.store.set("params.promptLastSeenTime",e)}async getPromptLastSeenTime(){return this.store.get("params.promptLastSeenTime",0)}}class ie{constructor(e=new ae,t=Q){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e,"",!0)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e){return this.createRequest("postEvent",e)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}pageVisit(e,t){return this.createRequest("pageVisit",e,t)}setPurchase(e){return this.createRequest("setPurchase",e)}async createRequest(e,t,s,a){const i=await this.data.getApiEntrypoint(),r=a?"":await this.data.getApiToken(),n=s||i+e,o=r?{headers:{Authorization:`Token ${r}`,"Content-Type":"text/plain;charset=UTF-8",Origin:I().location.origin},credentials:"include"}:{},c=await fetch(n,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...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)throw new Error(`Error code: ${e.status}. Error text: ${e.statusText}`);const t=await e.json();if(200!==t.status_code)throw new Error(`Error code: ${t.status_code}. Error text: ${t.status_message}`);return t}}class re{constructor(e,t=new ae,s=new ie){this.eventBus=e,this.data=t,this.apiClient=s}async checkDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(s);if(void 0===t||!e){const{exist:e,push_token_exist:r}=await this.checkDevice();localStorage.setItem(s,e&&r?a:i),t=localStorage.getItem(s)}return t===a}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(e)}async registerDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const i=await this.apiClient.registerDevice({...e,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(s,a),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),t=this.apiClient.unregisterDevice(e);return localStorage.setItem(s,i),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(s,i),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...a,hash:e,metaData:s})}async pushStat(e,t,s={}){const a=await this.getRequestParams();return await this.apiClient.pushStat({...a,hash:e,metaData:s})}async setTags(e){const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getEmail();return i&&await this.apiClient.setEmailTags({...a,email:i,tags:e}),this.apiClient.setTags({...a,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async registerUser(e){const{hwid:t,device_type:s,...a}=await this.getRequestParams(),i=await this.data.getDeviceType(),r=`${e}`,n=await this.data.getEmail(),o=await this.apiClient.registerUser({...a,hwid:t,userId:r,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:i});return n&&await this.apiClient.registerEmailUser({...a,email:n,userId:r,ts_offset:60*-(new Date).getTimezoneOffset()}),await this.data.setUserId(`${e}`),await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(e,t){const{hwid:s,device_type:a,...i}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...i,...t,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(`${e}`),await this.data.setStatusEmailWasChanged(!0),r}async postEvent(e,t){const s=await this.getRequestParams(),a=new Date,i=a.getTime(),r=Math.floor(i/1e3),n=r-a.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(t.msgHash)return Promise.reject("attribute msgHash already defined");t={...t,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:e,timestampUTC:r,timestampCurrent:n,attributes:t});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),a=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:a})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async triggerEvent(){throw new Error("Method has been deprecated, because we don't aggregate this statistics.")}async pageVisit(e){const t=await this.getRequestParams(),s=await this.data.getFeatures(),a=s&&s.page_visit&&s.page_visit.entrypoint;if(a)return this.apiClient.pageVisit({...t,...e},a)}async setPurchase(e){const t=await this.getRequestParams();return this.apiClient.setPurchase({...t,...e})}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}get params(){throw new Error('Property "Pushwoosh.api.params" have been deprecated. Use the async method "Pushwoosh.api.getParams()"')}async getRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId(),a=await this.data.getDeviceType(),i=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:e,hwid:t,userId:s||t,device_type:a,device_model:i,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class ne{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const a=e.match(/\bEdg\/(\d+)/);if(null!==a)return`Edge ${a[1]}`;let i=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=i;i=i[2]?[r,i[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&i.splice(1,1,n[1]),i.join(" ")}}class oe{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===n}checkIsPermissionDefault(){return this.getPermission()===o}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 Q.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),a=t.getKey("p256dh"),i=t.getKey("auth");if(!a||!i)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(a))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(i)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t)return await this.data.setLastPermissionStatus(t),!0;const s=await this.getCredentials(),a=this.getPushToken(s),i=await this.data.getTokens(),r=a===(i&&i.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${M()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){if(11===await this.data.getDeviceType())return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),a=new Uint8Array(s.length);for(let e=0;e<s.length;++e)a[e]=s.charCodeAt(e);return a}}class ce{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()===n}checkIsPermissionDefault(){return this.getPermission()===o}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 Q.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),a=this.getPermission();return s!==a?(await this.data.setLastPermissionStatus(a),!0):t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class he{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await G.getAll();console.log(e)},async showKeyValues(){const e=await $.getAll();console.log(e)},async showMessages(){(await z.getAll()).forEach((e=>console.log(e)))}},this.eventBus=new X,this.data=new ae,this.apiClient=new ie(this.data),this.api=new re(this.eventBus,this.data,this.apiClient),this.platformChecker=new ne(I()),this.inboxModel=new se(this.eventBus,this.data,this.api),this.pwinbox=new Z(this.data,this.api,this.inboxModel)}push(e){if(E(e))this.subscribeToLegacyEvents(c,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){this.isCommunicationDisabled&&Q.error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const e=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e})}const t=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(t===n){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!s||e)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(t===r)return this.eventBus.dispatchEvent("permission-denied",{}),void(a&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(e){Q.error(e,"Error occurred during the unsubscribe")}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(s)===a}isDeviceUnregistered(){return localStorage.getItem(s)===i}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){const t=await this.data.getDeviceType(),s=this.driver.checkIsPermissionGranted();await this.data.setStatusCommunicationDisabled(!e),e?(await this.data.setStatusDropAllData(!1),s&&await this.api.registerDevice()):await this.api.unregisterDevice(),this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e}),await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),await this.data.setStatusDropAllData(!0)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}async sendStatisticsVisitedPage(){const{document:{title:e},location:{origin:t,pathname:s,href:a}}=window;await this.api.pageVisit({title:e,url_path:`${t}${s}`,url:a})}async initialize(e){this.initParams=e;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Q.setLevel(t||e.logLevel||"error"),!this.platformChecker.isAvailableNotifications)return;if(!e.applicationCode)throw new Error("Can't find application code!");const s=await this.data.getApplicationCode();s&&s===e.applicationCode||(await this.data.clearAll(),await this.data.setApplicationCode(e.applicationCode));if(!await this.data.getHwid()){const t=e.applicationCode+"_"+M();await this.data.setHwid(t)}await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),await this.data.setLanguage(e.tags&&e.tags.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.44.8");const a=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]);this.onGetConfig(a&&a.features),this.isCommunicationDisabled=await this.data.getStatusCommunicationDisabled(),await this.open();const i=await this.data.getStatusUserIdWasChanged();e.userId&&"user_id"!==e.userId&&!i&&await this.api.registerUser(e.userId);const r=await this.data.getStatusEmailWasChanged();e.email&&""!==e.email&&!r&&(/^\S+@\S+\.\S+$/.test(e.email)?await this.api.registerEmail(e.email):Q.write("error",`can't register invalid email: ${e.email}`)),e.tags&&this.api.setTags(e.tags);const n=await this.data.getApplicationServerKey();this.platformChecker.isAvailableNotifications&&n&&await this.initPushNotifications(e);try{await this.inboxModel.updateMessages()}catch(e){Q.write("error",e)}this.ready=!0,this.eventBus.dispatchEvent("ready",{});const o=await this.data.getDelayedEvent();if(o){const{type:e,payload:t}=o;this.emitLegacyEventsFromServiceWorker(e,t),await this.data.setDelayedEvent(null)}if("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}})),this.platformChecker.isSafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then((()=>history.pushState(null,"","#")))}}async defaultProcess(){const e=this.driver.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const t=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),a=await this.driver.checkIsNeedResubscribe();if(t||s)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const i=await this.data.getStatusManualUnsubscribed(),c=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case o:this.eventBus.dispatchEvent("permission-default",{}),c&&await this.unsubscribe();break;case r:this.eventBus.dispatchEvent("permission-denied",{}),c&&await this.unsubscribe();break;case n:this.eventBus.dispatchEvent("permission-granted",{}),i&&c&&await this.unsubscribe(),(!c&&!i||a)&&await this.subscribe(!0)}}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:a={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,a)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}async onGetConfig(e){if(await this.data.setFeatures(e),e){if(e.page_visit&&e.page_visit.enabled&&(await $.set("PAGE_VISITED_URL",e.page_visit.entrypoint),this.sendStatisticsVisitedPage()),e.events&&e.events.length){e.events.some((e=>e===D))&&this.sendPostEventVisitedPage()}if(e.vapid_key){const t=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(e.vapid_key),t!==e.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async initPushNotifications(e){await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.data.setInitParams(e),await this.initDriver();try{await this.defaultProcess()}catch(e){Q.error(e,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new ce(this.api,this.data,{webSitePushId:e})):void Q.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}this.platformChecker.isAvailableServiceWorker&&(this.driver=new oe(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window;this.api.postEvent(D,{url:t,title:e,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===c:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",(()=>t(this.api)));break;case e in T:this.eventBus.addEventHandler(T[e].name,(s=>{const{prop:a}=T[e];t(this.api,a?s[a]:void 0)}));break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case w:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case v:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case b:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case f:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})()));
2
+ //# sourceMappingURL=npm.js.map