@suprsend/web-sdk 2.0.1 → 3.0.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/dist/es/index.js CHANGED
@@ -1,61 +1,65 @@
1
- var k = Object.defineProperty;
2
- var x = (i, e, t) => e in i ? k(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
- var d = (i, e, t) => x(i, typeof e != "symbol" ? e + "" : e, t);
4
- var p = /* @__PURE__ */ ((i) => (i.OPT_IN = "opt_in", i.OPT_OUT = "opt_out", i))(p || {}), v = /* @__PURE__ */ ((i) => (i.ALL = "all", i.REQUIRED = "required", i))(v || {}), o = /* @__PURE__ */ ((i) => (i.VALIDATION_ERROR = "VALIDATION_ERROR", i.NETWORK_ERROR = "NETWORK_ERROR", i.UNKNOWN_ERROR = "UNKNOWN_ERROR", i.PERMISSION_DENIED = "PERMISSION_DENIED", i.UNSUPPORTED_ACTION = "UNSUPPORTED_ACTION", i))(o || {}), n = /* @__PURE__ */ ((i) => (i.SUCCESS = "success", i.ERROR = "error", i))(n || {});
5
- function b() {
6
- let i = (/* @__PURE__ */ new Date()).getTime();
1
+ var K = Object.defineProperty;
2
+ var W = (a, e, t) => e in a ? K(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
+ var f = (a, e, t) => W(a, typeof e != "symbol" ? e + "" : e, t);
4
+ import L from "mitt";
5
+ import V from "jwt-decode";
6
+ import { createStore as z } from "zustand/vanilla";
7
+ import { io as B } from "socket.io-client";
8
+ var p = /* @__PURE__ */ ((a) => (a.OPT_IN = "opt_in", a.OPT_OUT = "opt_out", a))(p || {}), b = /* @__PURE__ */ ((a) => (a.ALL = "all", a.REQUIRED = "required", a))(b || {}), d = /* @__PURE__ */ ((a) => (a.VALIDATION_ERROR = "VALIDATION_ERROR", a.NETWORK_ERROR = "NETWORK_ERROR", a.UNKNOWN_ERROR = "UNKNOWN_ERROR", a.PERMISSION_DENIED = "PERMISSION_DENIED", a.UNSUPPORTED_ACTION = "UNSUPPORTED_ACTION", a.NOT_FOUND = "NOT_FOUND", a))(d || {}), n = /* @__PURE__ */ ((a) => (a.SUCCESS = "success", a.ERROR = "error", a))(n || {}), _ = /* @__PURE__ */ ((a) => (a.INITIAL = "INITIAL", a.LOADING = "LOADING", a.SUCCESS = "SUCCESS", a.ERROR = "ERROR", a.FETCHING_MORE = "FETCHING_MORE", a))(_ || {});
9
+ function A() {
10
+ let a = (/* @__PURE__ */ new Date()).getTime();
7
11
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
8
12
  /[xy]/g,
9
13
  function(t) {
10
- const r = (i + Math.random() * 16) % 16 | 0;
11
- return i = Math.floor(i / 16), (t == "x" ? r : r & 3 | 8).toString(16);
14
+ const s = (a + Math.random() * 16) % 16 | 0;
15
+ return a = Math.floor(a / 16), (t == "x" ? s : s & 3 | 8).toString(16);
12
16
  }
13
17
  );
14
18
  }
15
- function C() {
19
+ function N() {
16
20
  return Math.round(Date.now());
17
21
  }
18
- function f(i) {
19
- return Object.keys(i).length === 0;
22
+ function I(a) {
23
+ return Object.keys(a).length === 0;
20
24
  }
21
- function $(i) {
22
- return (i == null ? void 0 : i.length) <= 0;
25
+ function H(a) {
26
+ return (a == null ? void 0 : a.length) <= 0;
23
27
  }
24
- function j(i) {
25
- const e = "=".repeat((4 - i.length % 4) % 4), t = (i + e).replace(/-/g, "+").replace(/_/g, "/"), r = atob(t), s = new Uint8Array(r.length);
26
- for (let u = 0; u < r.length; ++u)
27
- s[u] = r.charCodeAt(u);
28
- return s;
28
+ function Q(a) {
29
+ const e = "=".repeat((4 - a.length % 4) % 4), t = (a + e).replace(/-/g, "+").replace(/_/g, "/"), s = atob(t), r = new Uint8Array(s.length);
30
+ for (let i = 0; i < s.length; ++i)
31
+ r[i] = s.charCodeAt(i);
32
+ return r;
29
33
  }
30
- function K(i, e) {
34
+ function G(a, e) {
31
35
  let t;
32
- return (...r) => (clearTimeout(t), new Promise((s) => {
33
- t = setTimeout(() => s(i(...r)), e);
36
+ return (...s) => (clearTimeout(t), new Promise((r) => {
37
+ t = setTimeout(() => r(a(...s)), e);
34
38
  }));
35
39
  }
36
- function P(i, e) {
40
+ function U(a, e) {
37
41
  const t = {};
38
- return (...r) => {
39
- const [s] = r, u = r.slice(1);
40
- return typeof t[s] == "function" ? t[s](...u) : (t[s] = K(i, e), t[s](...u));
42
+ return (...s) => {
43
+ const [r] = s, i = s.slice(1);
44
+ return typeof t[r] == "function" ? t[r](...i) : (t[r] = G(a, e), t[r](...i));
41
45
  };
42
46
  }
43
- function a(i) {
44
- const e = { status: i.status };
45
- return i.statusCode && (e.statusCode = i.statusCode), i.body && (e.body = i.body), i.status === n.ERROR && (e.error = {
46
- type: i.errorType,
47
- message: i.errorMessage
47
+ function o(a) {
48
+ const e = { status: a.status };
49
+ return a.statusCode && (e.statusCode = a.statusCode), a.body && (e.body = a.body), a.status === n.ERROR && (e.error = {
50
+ type: a.errorType,
51
+ message: a.errorMessage
48
52
  }), e;
49
53
  }
50
- function g() {
54
+ function E() {
51
55
  return typeof window < "u";
52
56
  }
53
- function M(i, e) {
54
- g() && (typeof e == "object" && (e = JSON.stringify(e)), localStorage.setItem(i, e));
57
+ function x(a, e) {
58
+ E() && (typeof e == "object" && (e = JSON.stringify(e)), localStorage.setItem(a, e));
55
59
  }
56
- function V(i) {
57
- if (!g()) return;
58
- const e = localStorage.getItem(i);
60
+ function $(a) {
61
+ if (!E()) return;
62
+ const e = localStorage.getItem(a);
59
63
  if (e)
60
64
  try {
61
65
  return JSON.parse(e);
@@ -63,65 +67,11 @@ function V(i) {
63
67
  return e;
64
68
  }
65
69
  }
66
- function W(i) {
67
- g() && localStorage.removeItem(i);
68
- }
69
- function N(i) {
70
- this.message = i;
71
- }
72
- N.prototype = new Error(), N.prototype.name = "InvalidCharacterError";
73
- var D = typeof window < "u" && window.atob && window.atob.bind(window) || function(i) {
74
- var e = String(i).replace(/=+$/, "");
75
- if (e.length % 4 == 1) throw new N("'atob' failed: The string to be decoded is not correctly encoded.");
76
- for (var t, r, s = 0, u = 0, c = ""; r = e.charAt(u++); ~r && (t = s % 4 ? 64 * t + r : r, s++ % 4) ? c += String.fromCharCode(255 & t >> (-2 * s & 6)) : 0) r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);
77
- return c;
78
- };
79
- function F(i) {
80
- var e = i.replace(/-/g, "+").replace(/_/g, "/");
81
- switch (e.length % 4) {
82
- case 0:
83
- break;
84
- case 2:
85
- e += "==";
86
- break;
87
- case 3:
88
- e += "=";
89
- break;
90
- default:
91
- throw "Illegal base64url string!";
92
- }
93
- try {
94
- return function(t) {
95
- return decodeURIComponent(D(t).replace(/(.)/g, function(r, s) {
96
- var u = s.charCodeAt(0).toString(16).toUpperCase();
97
- return u.length < 2 && (u = "0" + u), "%" + u;
98
- }));
99
- }(e);
100
- } catch {
101
- return D(e);
102
- }
103
- }
104
- function _(i) {
105
- this.message = i;
106
- }
107
- function L(i, e) {
108
- if (typeof i != "string") throw new _("Invalid token specified");
109
- var t = (e = e || {}).header === !0 ? 0 : 1;
110
- try {
111
- return JSON.parse(F(i.split(".")[t]));
112
- } catch (r) {
113
- throw new _("Invalid token specified: " + r.message);
114
- }
115
- }
116
- _.prototype = new Error(), _.prototype.name = "InvalidTokenError";
117
- class S {
70
+ class D {
118
71
  constructor(e) {
119
- d(this, "config");
72
+ f(this, "config");
120
73
  this.config = e;
121
74
  }
122
- getUrl(e) {
123
- return `${this.config.host}/${e}`;
124
- }
125
75
  getHeaders() {
126
76
  const e = {
127
77
  "Content-Type": "application/json",
@@ -132,101 +82,98 @@ class S {
132
82
  requestApiInstance(e) {
133
83
  switch (e.type) {
134
84
  case "get":
135
- return this.get(e.path);
85
+ return this.get(e.url);
136
86
  case "post":
137
- return this.post(e.path, (e == null ? void 0 : e.payload) || {});
87
+ return this.post(e.url, (e == null ? void 0 : e.payload) || {});
138
88
  case "patch":
139
- return this.patch(e.path, (e == null ? void 0 : e.payload) || {});
89
+ return this.patch(e.url, (e == null ? void 0 : e.payload) || {});
140
90
  default:
141
- return this.get(e.path);
91
+ return this.get(e.url);
142
92
  }
143
93
  }
144
94
  get(e) {
145
- const t = this.getUrl(e);
146
- return fetch(t, {
95
+ return fetch(e, {
147
96
  method: "GET",
148
97
  headers: this.getHeaders()
149
98
  });
150
99
  }
151
100
  post(e, t) {
152
- const r = this.getUrl(e);
153
- return fetch(r, {
101
+ return fetch(e, {
154
102
  method: "POST",
155
103
  body: JSON.stringify(t),
156
104
  headers: this.getHeaders()
157
105
  });
158
106
  }
159
107
  patch(e, t) {
160
- const r = this.getUrl(e);
161
- return fetch(r, {
108
+ return fetch(e, {
162
109
  method: "PATCH",
163
110
  body: JSON.stringify(t),
164
111
  headers: this.getHeaders()
165
112
  });
166
113
  }
167
114
  async request(e) {
168
- var t, r, s;
115
+ var t, s, r;
169
116
  if (!this.config.distinctId)
170
- return a({
117
+ return o({
171
118
  status: n.ERROR,
172
- errorType: o.VALIDATION_ERROR,
119
+ errorType: d.VALIDATION_ERROR,
173
120
  errorMessage: "User isn't authenticated. Call identify method before performing any action"
174
121
  });
175
122
  if ((t = this.config.authenticateOptions) != null && t.refreshUserToken && this.config.userToken) {
176
- const u = L(this.config.userToken), c = (u.exp || 0) * 1e3, h = Date.now();
177
- if (c <= h)
123
+ const i = V(this.config.userToken), c = (i.exp || 0) * 1e3, u = Date.now();
124
+ if (c <= u)
178
125
  try {
179
- const R = await this.config.authenticateOptions.refreshUserToken(
126
+ const h = await this.config.authenticateOptions.refreshUserToken(
180
127
  this.config.userToken,
181
- u
128
+ i
182
129
  );
183
- R && typeof R == "string" && this.config.identify(
130
+ h && typeof h == "string" && this.config.identify(
184
131
  this.config.distinctId,
185
- R,
132
+ h,
186
133
  this.config.authenticateOptions
187
134
  );
188
135
  } catch {
189
136
  }
190
137
  }
191
138
  try {
192
- const u = await this.requestApiInstance(e), c = await u.json(), h = (c == null ? void 0 : c.status) || (u.ok ? n.SUCCESS : n.ERROR);
193
- return a({
194
- status: h,
139
+ const i = await this.requestApiInstance(e), c = await i.json(), u = (c == null ? void 0 : c.status) || (i.ok ? n.SUCCESS : n.ERROR);
140
+ return o({
141
+ status: u,
195
142
  body: c,
196
- statusCode: u.status,
197
- errorMessage: (r = c == null ? void 0 : c.error) == null ? void 0 : r.message,
198
- errorType: (s = c == null ? void 0 : c.error) == null ? void 0 : s.type
143
+ statusCode: i.status,
144
+ errorMessage: (s = c == null ? void 0 : c.error) == null ? void 0 : s.message,
145
+ errorType: (r = c == null ? void 0 : c.error) == null ? void 0 : r.type
199
146
  });
200
- } catch (u) {
201
- return console.error(u), a({
147
+ } catch (i) {
148
+ return console.error(i), o({
202
149
  status: n.ERROR,
203
150
  statusCode: 500,
204
- errorMessage: (u == null ? void 0 : u.message) || "network error",
205
- errorType: o.NETWORK_ERROR
151
+ errorMessage: (i == null ? void 0 : i.message) || "network error",
152
+ errorType: d.NETWORK_ERROR
206
153
  });
207
154
  }
208
155
  }
209
156
  }
210
- class H {
157
+ class J {
211
158
  constructor(e) {
212
- d(this, "config");
213
- d(this, "preferenceData");
214
- d(this, "preferenceArgs");
215
- d(this, "debouncedUpdateCategoryPreferences");
216
- d(this, "debouncedUpdateChannelPreferences");
217
- d(this, "debounceTime", 1e3);
218
- this.config = e, this.debouncedUpdateCategoryPreferences = P(
159
+ f(this, "config");
160
+ f(this, "preferenceData");
161
+ f(this, "preferenceArgs");
162
+ f(this, "debouncedUpdateCategoryPreferences");
163
+ f(this, "debouncedUpdateChannelPreferences");
164
+ f(this, "debounceTime", 1e3);
165
+ this.config = e, this.debouncedUpdateCategoryPreferences = U(
219
166
  this._updateCategoryPreferences.bind(this),
220
167
  this.debounceTime
221
- ), this.debouncedUpdateChannelPreferences = P(
168
+ ), this.debouncedUpdateChannelPreferences = U(
222
169
  this._updateChannelPreferences.bind(this),
223
170
  this.debounceTime
224
171
  );
225
172
  }
226
173
  validateQueryParams(e = {}) {
227
174
  const t = {};
228
- for (const r in e)
229
- e[r] && (t[r] = String(e[r]));
175
+ for (const s in e)
176
+ e[s] && (t[s] = String(e[s]));
230
177
  return t;
231
178
  }
232
179
  set data(e) {
@@ -235,11 +182,11 @@ class H {
235
182
  get data() {
236
183
  return this.preferenceData;
237
184
  }
238
- getUrlPath(e, t) {
239
- const r = `v2/subscriber/${this.config.distinctId}/${e}`, s = this.validateQueryParams(t), u = new URLSearchParams(
240
- s
185
+ getUrl(e, t) {
186
+ const s = `${this.config.host}/v2/subscriber/${this.config.distinctId}/${e}`, r = this.validateQueryParams(t), i = new URLSearchParams(
187
+ r
241
188
  ).toString();
242
- return u ? `${r}/?${u}` : r;
189
+ return i ? `${s}/?${i}` : s;
243
190
  }
244
191
  /**
245
192
  * Used to get user's whole preferences data.
@@ -253,8 +200,8 @@ class H {
253
200
  tenantId: t == null ? void 0 : t.tenant_id,
254
201
  showOptOutChannels: t == null ? void 0 : t.show_opt_out_channels
255
202
  };
256
- const r = this.getUrlPath("full_preference", t), s = await this.config.client().request({ type: "get", path: r });
257
- return s.error || (this.data = s.body), s;
203
+ const s = this.getUrl("full_preference", t), r = await this.config.client().request({ type: "get", url: s });
204
+ return r.error || (this.data = r.body), r;
258
205
  }
259
206
  /**
260
207
  * Used to get user's preference of all categories.
@@ -265,119 +212,127 @@ class H {
265
212
  show_opt_out_channels: (e == null ? void 0 : e.showOptOutChannels) !== !1,
266
213
  limit: e == null ? void 0 : e.limit,
267
214
  offset: e == null ? void 0 : e.offset
268
- }, r = this.getUrlPath("category", t);
269
- return await this.config.client().request({ type: "get", path: r });
215
+ }, s = this.getUrl("category", t);
216
+ return await this.config.client().request({ type: "get", url: s });
270
217
  }
271
218
  /**
272
219
  * Used to get user's preference of specific category.
273
220
  */
274
221
  async getCategory(e, t) {
275
222
  if (!e)
276
- return a({
223
+ return o({
277
224
  status: n.ERROR,
278
- errorType: o.VALIDATION_ERROR,
225
+ errorType: d.VALIDATION_ERROR,
279
226
  errorMessage: "Category parameter is missing"
280
227
  });
281
- const r = {
228
+ const s = {
282
229
  tenant_id: t == null ? void 0 : t.tenantId,
283
230
  show_opt_out_channels: (t == null ? void 0 : t.showOptOutChannels) !== !1
284
- }, s = this.getUrlPath(`category/${e}`, r);
285
- return await this.config.client().request({ type: "get", path: s });
231
+ }, r = this.getUrl(`category/${e}`, s);
232
+ return await this.config.client().request({ type: "get", url: r });
286
233
  }
287
234
  /**
288
235
  * Used to get user's all channel level preference.
289
236
  */
290
237
  async getOverallChannelPreferences() {
291
- const e = this.getUrlPath("channel_preference");
292
- return await this.config.client().request({ type: "get", path: e });
293
- }
294
- async _updateCategoryPreferences(e, t, r, s) {
295
- const u = this.getUrlPath(`category/${e}`, s), c = await this.config.client().request({ type: "patch", path: u, payload: t });
296
- return c != null && c.error ? this.config.emitter.emit("preferences_error", c) : (Object.assign(r, c.body), this.config.emitter.emit("preferences_updated", {
238
+ const e = this.getUrl("channel_preference");
239
+ return await this.config.client().request({ type: "get", url: e });
240
+ }
241
+ async _updateCategoryPreferences(e, t, s, r) {
242
+ const i = this.getUrl(`category/${e}`, r), c = await this.config.client().request({
243
+ type: "patch",
244
+ url: i,
245
+ payload: t
246
+ });
247
+ return c != null && c.error ? this.config.emitter.emit("preferences_error", c) : (Object.assign(s, c.body), this.config.emitter.emit("preferences_updated", {
297
248
  status: n.SUCCESS,
298
249
  statusCode: 200,
299
250
  body: this.data
300
251
  })), c;
301
252
  }
302
253
  async _updateChannelPreferences(e) {
303
- const t = this.getUrlPath("channel_preference"), r = await this.config.client().request({ type: "patch", path: t, payload: e });
304
- return r != null && r.error ? this.config.emitter.emit("preferences_error", r) : (await this.getPreferences(this.preferenceArgs), this.config.emitter.emit("preferences_updated", {
254
+ const t = this.getUrl("channel_preference"), s = await this.config.client().request({
255
+ type: "patch",
256
+ url: t,
257
+ payload: e
258
+ });
259
+ return s != null && s.error ? this.config.emitter.emit("preferences_error", s) : (await this.getPreferences(this.preferenceArgs), this.config.emitter.emit("preferences_updated", {
305
260
  status: n.SUCCESS,
306
261
  statusCode: 200,
307
262
  body: this.data
308
- })), r;
263
+ })), s;
309
264
  }
310
265
  /**
311
266
  * Used to update user's category level preference.
312
267
  */
313
- async updateCategoryPreference(e, t, r) {
314
- var R;
268
+ async updateCategoryPreference(e, t, s) {
269
+ var h;
315
270
  if (!e || ![p.OPT_IN, p.OPT_OUT].includes(
316
271
  t
317
272
  ))
318
- return a({
273
+ return o({
319
274
  status: n.ERROR,
320
- errorType: o.VALIDATION_ERROR,
275
+ errorType: d.VALIDATION_ERROR,
321
276
  errorMessage: e ? "Preference parameter is invalid" : "Category parameter is missing"
322
277
  });
323
278
  if (!this.data)
324
- return a({
279
+ return o({
325
280
  status: n.ERROR,
326
- errorType: o.VALIDATION_ERROR,
281
+ errorType: d.VALIDATION_ERROR,
327
282
  errorMessage: "Call getPreferences method before performing action"
328
283
  });
329
284
  if (!this.data.sections)
330
- return a({
285
+ return o({
331
286
  status: n.ERROR,
332
- errorType: o.VALIDATION_ERROR,
287
+ errorType: d.VALIDATION_ERROR,
333
288
  errorMessage: "Sections doesn't exist"
334
289
  });
335
- let s = null, u = !1;
336
- for (const y of this.data.sections) {
337
- let E = !1;
338
- if (y.subcategories) {
339
- for (const l of y.subcategories)
340
- if (l.category === e)
341
- if (s = l, l.is_editable) {
342
- if (l.preference !== t) {
343
- l.preference = t, u = !0, E = !0;
290
+ let r = null, i = !1;
291
+ for (const R of this.data.sections) {
292
+ let S = !1;
293
+ if (R.subcategories) {
294
+ for (const g of R.subcategories)
295
+ if (g.category === e)
296
+ if (r = g, g.is_editable) {
297
+ if (g.preference !== t) {
298
+ g.preference = t, i = !0, S = !0;
344
299
  break;
345
300
  }
346
301
  } else
347
- return a({
302
+ return o({
348
303
  status: n.ERROR,
349
- errorType: o.VALIDATION_ERROR,
304
+ errorType: d.VALIDATION_ERROR,
350
305
  errorMessage: "Category preference is not editable"
351
306
  });
352
- if (E) break;
307
+ if (S) break;
353
308
  }
354
309
  }
355
- if (!s)
356
- return a({
310
+ if (!r)
311
+ return o({
357
312
  status: n.ERROR,
358
- errorType: o.VALIDATION_ERROR,
313
+ errorType: d.VALIDATION_ERROR,
359
314
  errorMessage: "Category not found"
360
315
  });
361
- if (!u)
362
- return a({
316
+ if (!i)
317
+ return o({
363
318
  status: n.SUCCESS,
364
319
  body: this.data
365
320
  });
366
321
  const c = [];
367
- (R = s == null ? void 0 : s.channels) == null || R.forEach((y) => {
368
- y.preference === p.OPT_OUT && c.push(y.channel);
322
+ (h = r == null ? void 0 : r.channels) == null || h.forEach((R) => {
323
+ R.preference === p.OPT_OUT && c.push(R.channel);
369
324
  });
370
- const h = (r == null ? void 0 : r.showOptOutChannels) !== !1, O = {
371
- preference: s.preference,
372
- opt_out_channels: h && t === p.OPT_IN ? null : c
325
+ const u = (s == null ? void 0 : s.showOptOutChannels) !== !1, l = {
326
+ preference: r.preference,
327
+ opt_out_channels: u && t === p.OPT_IN ? null : c
373
328
  };
374
329
  return this.debouncedUpdateCategoryPreferences(
375
330
  e,
376
331
  e,
377
- O,
378
- s,
379
- { tenant_id: r == null ? void 0 : r.tenantId, show_opt_out_channels: h }
380
- ), a({
332
+ l,
333
+ r,
334
+ { tenant_id: s == null ? void 0 : s.tenantId, show_opt_out_channels: u }
335
+ ), o({
381
336
  status: n.SUCCESS,
382
337
  body: this.data
383
338
  });
@@ -385,92 +340,92 @@ class H {
385
340
  /**
386
341
  * Used to update user's category level channel preference.
387
342
  */
388
- async updateChannelPreferenceInCategory(e, t, r, s) {
389
- var l;
390
- if (!e || !r)
391
- return a({
343
+ async updateChannelPreferenceInCategory(e, t, s, r) {
344
+ var g;
345
+ if (!e || !s)
346
+ return o({
392
347
  status: n.ERROR,
393
- errorType: o.VALIDATION_ERROR,
348
+ errorType: d.VALIDATION_ERROR,
394
349
  errorMessage: e ? "Category parameter is missing" : "Channel parameter is missing"
395
350
  });
396
351
  if (![p.OPT_IN, p.OPT_OUT].includes(
397
352
  t
398
353
  ))
399
- return a({
354
+ return o({
400
355
  status: n.ERROR,
401
- errorType: o.VALIDATION_ERROR,
356
+ errorType: d.VALIDATION_ERROR,
402
357
  errorMessage: "Preference parameter is invalid"
403
358
  });
404
359
  if (!this.data)
405
- return a({
360
+ return o({
406
361
  status: n.ERROR,
407
- errorType: o.VALIDATION_ERROR,
362
+ errorType: d.VALIDATION_ERROR,
408
363
  errorMessage: "Call getPreferences method before performing action"
409
364
  });
410
365
  if (!this.data.sections)
411
- return a({
366
+ return o({
412
367
  status: n.ERROR,
413
- errorType: o.VALIDATION_ERROR,
368
+ errorType: d.VALIDATION_ERROR,
414
369
  errorMessage: "Sections doesn't exist"
415
370
  });
416
- let u = null, c = null, h = !1;
417
- for (const T of this.data.sections) {
418
- let A = !1;
419
- if (T.subcategories) {
420
- for (const m of T.subcategories) {
421
- if (m.category === r) {
422
- if (u = m, !m.channels) continue;
423
- for (const I of m.channels)
424
- if (I.channel === e)
425
- if (c = I, I.is_editable) {
426
- if (I.preference !== t) {
427
- I.preference = t, t === p.OPT_IN && (m.preference = p.OPT_IN), h = !0, A = !0;
371
+ let i = null, c = null, u = !1;
372
+ for (const m of this.data.sections) {
373
+ let T = !1;
374
+ if (m.subcategories) {
375
+ for (const O of m.subcategories) {
376
+ if (O.category === s) {
377
+ if (i = O, !O.channels) continue;
378
+ for (const y of O.channels)
379
+ if (y.channel === e)
380
+ if (c = y, y.is_editable) {
381
+ if (y.preference !== t) {
382
+ y.preference = t, t === p.OPT_IN && (O.preference = p.OPT_IN), u = !0, T = !0;
428
383
  break;
429
384
  }
430
385
  } else
431
- return a({
386
+ return o({
432
387
  status: n.ERROR,
433
- errorType: o.VALIDATION_ERROR,
388
+ errorType: d.VALIDATION_ERROR,
434
389
  errorMessage: "Channel preference is not editable"
435
390
  });
436
391
  }
437
- if (A) break;
392
+ if (T) break;
438
393
  }
439
- if (A) break;
394
+ if (T) break;
440
395
  }
441
396
  }
442
- if (!u)
443
- return a({
397
+ if (!i)
398
+ return o({
444
399
  status: n.ERROR,
445
- errorType: o.VALIDATION_ERROR,
400
+ errorType: d.VALIDATION_ERROR,
446
401
  errorMessage: "Category not found"
447
402
  });
448
403
  if (!c)
449
- return a({
404
+ return o({
450
405
  status: n.ERROR,
451
- errorType: o.VALIDATION_ERROR,
406
+ errorType: d.VALIDATION_ERROR,
452
407
  errorMessage: "Category's channel not found"
453
408
  });
454
- if (!h)
455
- return a({
409
+ if (!u)
410
+ return o({
456
411
  status: n.SUCCESS,
457
412
  body: this.data
458
413
  });
459
- const O = [];
460
- (l = u == null ? void 0 : u.channels) == null || l.forEach((T) => {
461
- T.preference === p.OPT_OUT && O.push(T.channel);
414
+ const l = [];
415
+ (g = i == null ? void 0 : i.channels) == null || g.forEach((m) => {
416
+ m.preference === p.OPT_OUT && l.push(m.channel);
462
417
  });
463
- const R = (s == null ? void 0 : s.showOptOutChannels) !== !1, E = {
464
- preference: R && u.preference === p.OPT_OUT && t === p.OPT_IN ? p.OPT_IN : u.preference,
465
- opt_out_channels: O
418
+ const h = (r == null ? void 0 : r.showOptOutChannels) !== !1, S = {
419
+ preference: h && i.preference === p.OPT_OUT && t === p.OPT_IN ? p.OPT_IN : i.preference,
420
+ opt_out_channels: l
466
421
  };
467
422
  return this.debouncedUpdateCategoryPreferences(
468
- r,
469
- r,
470
- E,
471
- u,
472
- { tenant_id: s == null ? void 0 : s.tenantId, show_opt_out_channels: R }
473
- ), a({
423
+ s,
424
+ s,
425
+ S,
426
+ i,
427
+ { tenant_id: r == null ? void 0 : r.tenantId, show_opt_out_channels: h }
428
+ ), o({
474
429
  status: n.SUCCESS,
475
430
  body: this.data
476
431
  });
@@ -480,98 +435,98 @@ class H {
480
435
  */
481
436
  async updateOverallChannelPreference(e, t) {
482
437
  if (!e || ![
483
- v.ALL,
484
- v.REQUIRED
438
+ b.ALL,
439
+ b.REQUIRED
485
440
  ].includes(t))
486
- return a({
441
+ return o({
487
442
  status: n.ERROR,
488
- errorType: o.VALIDATION_ERROR,
443
+ errorType: d.VALIDATION_ERROR,
489
444
  errorMessage: e ? "Preference parameter is invalid" : "Channel parameter is missing"
490
445
  });
491
446
  if (!this.data)
492
- return a({
447
+ return o({
493
448
  status: n.ERROR,
494
- errorType: o.VALIDATION_ERROR,
449
+ errorType: d.VALIDATION_ERROR,
495
450
  errorMessage: "Call getPreferences method before performing action"
496
451
  });
497
452
  if (!this.data.channel_preferences)
498
- return a({
453
+ return o({
499
454
  status: n.ERROR,
500
- errorType: o.VALIDATION_ERROR,
455
+ errorType: d.VALIDATION_ERROR,
501
456
  errorMessage: "Channel preferences doesn't exist"
502
457
  });
503
- let r = null, s = !1;
504
- const u = t === v.REQUIRED;
458
+ let s = null, r = !1;
459
+ const i = t === b.REQUIRED;
505
460
  for (const c of this.data.channel_preferences)
506
- if (c.channel === e && (r = c, c.is_restricted !== u)) {
507
- c.is_restricted = u, s = !0;
461
+ if (c.channel === e && (s = c, c.is_restricted !== i)) {
462
+ c.is_restricted = i, r = !0;
508
463
  break;
509
464
  }
510
- return r ? s ? (this.debouncedUpdateChannelPreferences(r.channel, {
511
- channel_preferences: [r]
512
- }), a({
465
+ return s ? r ? (this.debouncedUpdateChannelPreferences(s.channel, {
466
+ channel_preferences: [s]
467
+ }), o({
513
468
  status: n.SUCCESS,
514
469
  body: this.data
515
- })) : a({
470
+ })) : o({
516
471
  status: n.SUCCESS,
517
472
  body: this.data
518
- }) : a({
473
+ }) : o({
519
474
  status: n.ERROR,
520
- errorType: o.VALIDATION_ERROR,
475
+ errorType: d.VALIDATION_ERROR,
521
476
  errorMessage: "Channel data not found"
522
477
  });
523
478
  }
524
479
  }
525
- const U = "ss_device_id";
526
- class Q {
480
+ const k = "ss_device_id";
481
+ class Z {
527
482
  constructor(e) {
528
- d(this, "config");
529
- d(this, "preferences");
530
- this.config = e, this.preferences = new H(e);
483
+ f(this, "config");
484
+ f(this, "preferences");
485
+ this.config = e, this.preferences = new J(e);
531
486
  }
532
487
  isReservedKey(e) {
533
488
  var t;
534
489
  return e.startsWith("$") || ((t = e == null ? void 0 : e.toLowerCase()) == null ? void 0 : t.startsWith("ss_"));
535
490
  }
536
491
  formatParamsToObj(e, t) {
537
- let r = null;
538
- return typeof e == "object" && t === void 0 ? r = e : typeof e == "string" && t !== void 0 ? r = { [e]: t } : console.warn("[SuprSend]: Invalid input parameters"), r;
492
+ let s = null;
493
+ return typeof e == "object" && t === void 0 ? s = e : typeof e == "string" && t !== void 0 ? s = { [e]: t } : console.warn("[SuprSend]: Invalid input parameters"), s;
539
494
  }
540
495
  formatParamsToArray(e) {
541
496
  if (e)
542
497
  return Array.isArray(e) ? e : [e];
543
498
  }
544
499
  validateObjData(e, t) {
545
- const r = {}, s = (t == null ? void 0 : t.allowReservedKeys) || !1, u = (t == null ? void 0 : t.valueType) || "";
500
+ const s = {}, r = (t == null ? void 0 : t.allowReservedKeys) || !1, i = (t == null ? void 0 : t.valueType) || "";
546
501
  for (const c in e) {
547
- let h = e[c];
548
- if (!(c && h === void 0)) {
549
- if (!s && this.isReservedKey(c)) {
502
+ let u = e[c];
503
+ if (!(c && u === void 0)) {
504
+ if (!r && this.isReservedKey(c)) {
550
505
  console.warn("[SuprSend]: key cannot start with $ or ss_");
551
506
  continue;
552
507
  }
553
- u === "number" ? h = Number(h) : u === "boolean" && (h = !!h), r[c] = h;
508
+ i === "number" ? u = Number(u) : i === "boolean" && (u = !!u), s[c] = u;
554
509
  }
555
510
  }
556
- return r;
511
+ return s;
557
512
  }
558
513
  validateArrayData(e) {
559
514
  const t = [];
560
- for (const r of e)
561
- if (r != null) {
562
- if (this.isReservedKey(r)) {
515
+ for (const s of e)
516
+ if (s != null) {
517
+ if (this.isReservedKey(s)) {
563
518
  console.warn("[SuprSend]: key cannot start with $ or ss_");
564
519
  continue;
565
520
  }
566
- t.push(String(r));
521
+ t.push(String(s));
567
522
  }
568
523
  return t;
569
524
  }
570
525
  async triggerUserEvent(e) {
571
526
  return this.config.eventApi({
572
527
  distinct_id: this.config.distinctId,
573
- $insert_id: b(),
574
- $time: C(),
528
+ $insert_id: A(),
529
+ $time: N(),
575
530
  ...e
576
531
  });
577
532
  }
@@ -579,95 +534,95 @@ class Q {
579
534
  * Used to set user properties. Keys with $ and ss_ will be removed.
580
535
  */
581
536
  async set(e, t) {
582
- const r = this.formatParamsToObj(e, t);
583
- if (!r)
584
- return a({
537
+ const s = this.formatParamsToObj(e, t);
538
+ if (!s)
539
+ return o({
585
540
  status: n.ERROR,
586
- errorType: o.VALIDATION_ERROR,
541
+ errorType: d.VALIDATION_ERROR,
587
542
  errorMessage: "data provided is empty"
588
543
  });
589
- const s = this.validateObjData(r);
590
- return f(s) ? a({
544
+ const r = this.validateObjData(s);
545
+ return I(r) ? o({
591
546
  status: n.ERROR,
592
- errorType: o.VALIDATION_ERROR,
547
+ errorType: d.VALIDATION_ERROR,
593
548
  errorMessage: "data provided is empty"
594
- }) : this.triggerUserEvent({ $set: s });
549
+ }) : this.triggerUserEvent({ $set: r });
595
550
  }
596
551
  /**
597
552
  * Used to set user properties only once. Properties once set cannot be changed later.
598
553
  * Keys with $ and ss_ will be removed.
599
554
  */
600
555
  async setOnce(e, t) {
601
- const r = this.formatParamsToObj(e, t);
602
- if (!r)
603
- return a({
556
+ const s = this.formatParamsToObj(e, t);
557
+ if (!s)
558
+ return o({
604
559
  status: n.ERROR,
605
- errorType: o.VALIDATION_ERROR,
560
+ errorType: d.VALIDATION_ERROR,
606
561
  errorMessage: "data provided is empty"
607
562
  });
608
- const s = this.validateObjData(r);
609
- return f(s) ? a({
563
+ const r = this.validateObjData(s);
564
+ return I(r) ? o({
610
565
  status: n.ERROR,
611
- errorType: o.VALIDATION_ERROR,
566
+ errorType: d.VALIDATION_ERROR,
612
567
  errorMessage: "data provided is empty"
613
- }) : this.triggerUserEvent({ $set_once: s });
568
+ }) : this.triggerUserEvent({ $set_once: r });
614
569
  }
615
570
  /**
616
571
  * Used to increment/decrement user properties whose values are numbers. To decrement use -ve values.
617
572
  * Keys with $ and ss_ will be removed.
618
573
  */
619
574
  async increment(e, t) {
620
- const r = this.formatParamsToObj(e, t);
621
- if (!r)
622
- return a({
575
+ const s = this.formatParamsToObj(e, t);
576
+ if (!s)
577
+ return o({
623
578
  status: n.ERROR,
624
- errorType: o.VALIDATION_ERROR,
579
+ errorType: d.VALIDATION_ERROR,
625
580
  errorMessage: "data provided is empty"
626
581
  });
627
- const s = this.validateObjData(r, { valueType: "number" });
628
- return f(s) ? a({
582
+ const r = this.validateObjData(s, { valueType: "number" });
583
+ return I(r) ? o({
629
584
  status: n.ERROR,
630
- errorType: o.VALIDATION_ERROR,
585
+ errorType: d.VALIDATION_ERROR,
631
586
  errorMessage: "data provided is empty"
632
- }) : this.triggerUserEvent({ $add: s });
587
+ }) : this.triggerUserEvent({ $add: r });
633
588
  }
634
589
  /**
635
590
  * Used to add items to list if user property is list (example: wishlist: [iphone, macbook]).
636
591
  * Keys with $ and ss_ will be removed.
637
592
  */
638
593
  async append(e, t) {
639
- const r = this.formatParamsToObj(e, t);
640
- if (!r)
641
- return a({
594
+ const s = this.formatParamsToObj(e, t);
595
+ if (!s)
596
+ return o({
642
597
  status: n.ERROR,
643
- errorType: o.VALIDATION_ERROR,
598
+ errorType: d.VALIDATION_ERROR,
644
599
  errorMessage: "data provided is empty"
645
600
  });
646
- const s = this.validateObjData(r);
647
- return f(s) ? a({
601
+ const r = this.validateObjData(s);
602
+ return I(r) ? o({
648
603
  status: n.ERROR,
649
- errorType: o.VALIDATION_ERROR,
604
+ errorType: d.VALIDATION_ERROR,
650
605
  errorMessage: "data provided is empty"
651
- }) : this.triggerUserEvent({ $append: s });
606
+ }) : this.triggerUserEvent({ $append: r });
652
607
  }
653
608
  /**
654
609
  * Used to remove items from list if user property is list.
655
610
  * Keys with $ and ss_ will be removed.
656
611
  */
657
612
  async remove(e, t) {
658
- const r = this.formatParamsToObj(e, t);
659
- if (!r)
660
- return a({
613
+ const s = this.formatParamsToObj(e, t);
614
+ if (!s)
615
+ return o({
661
616
  status: n.ERROR,
662
- errorType: o.VALIDATION_ERROR,
617
+ errorType: d.VALIDATION_ERROR,
663
618
  errorMessage: "data provided is empty"
664
619
  });
665
- const s = this.validateObjData(r);
666
- return f(s) ? a({
620
+ const r = this.validateObjData(s);
621
+ return I(r) ? o({
667
622
  status: n.ERROR,
668
- errorType: o.VALIDATION_ERROR,
623
+ errorType: d.VALIDATION_ERROR,
669
624
  errorMessage: "data provided is empty"
670
- }) : this.triggerUserEvent({ $remove: s });
625
+ }) : this.triggerUserEvent({ $remove: r });
671
626
  }
672
627
  /**
673
628
  * Used to remove user property. Keys with $ and ss_ will be removed.
@@ -675,70 +630,70 @@ class Q {
675
630
  async unset(e) {
676
631
  const t = this.formatParamsToArray(e);
677
632
  if (!t)
678
- return a({
633
+ return o({
679
634
  status: n.ERROR,
680
- errorType: o.VALIDATION_ERROR,
635
+ errorType: d.VALIDATION_ERROR,
681
636
  errorMessage: "data provided is empty"
682
637
  });
683
- const r = this.validateArrayData(t);
684
- return $(r) ? a({
638
+ const s = this.validateArrayData(t);
639
+ return H(s) ? o({
685
640
  status: n.ERROR,
686
- errorType: o.VALIDATION_ERROR,
641
+ errorType: d.VALIDATION_ERROR,
687
642
  errorMessage: "data provided is empty"
688
- }) : this.triggerUserEvent({ $unset: r });
643
+ }) : this.triggerUserEvent({ $unset: s });
689
644
  }
690
645
  // this append is only used internally since it allows internal events
691
646
  appendInternal(e, t) {
692
- const r = this.formatParamsToObj(e, t);
693
- if (!r)
694
- return a({
647
+ const s = this.formatParamsToObj(e, t);
648
+ if (!s)
649
+ return o({
695
650
  status: n.ERROR,
696
- errorType: o.VALIDATION_ERROR,
651
+ errorType: d.VALIDATION_ERROR,
697
652
  errorMessage: "data provided is empty"
698
653
  });
699
- const s = this.validateObjData(r, {
654
+ const r = this.validateObjData(s, {
700
655
  allowReservedKeys: !0
701
656
  });
702
- return f(s) ? a({
657
+ return I(r) ? o({
703
658
  status: n.ERROR,
704
- errorType: o.VALIDATION_ERROR,
659
+ errorType: d.VALIDATION_ERROR,
705
660
  errorMessage: "data provided is empty"
706
- }) : this.triggerUserEvent({ $append: s });
661
+ }) : this.triggerUserEvent({ $append: r });
707
662
  }
708
663
  // this remove is only used internally since it allows internal events
709
664
  removeInternal(e, t) {
710
- const r = this.formatParamsToObj(e, t);
711
- if (!r)
712
- return a({
665
+ const s = this.formatParamsToObj(e, t);
666
+ if (!s)
667
+ return o({
713
668
  status: n.ERROR,
714
- errorType: o.VALIDATION_ERROR,
669
+ errorType: d.VALIDATION_ERROR,
715
670
  errorMessage: "data provided is empty"
716
671
  });
717
- const s = this.validateObjData(r, {
672
+ const r = this.validateObjData(s, {
718
673
  allowReservedKeys: !0
719
674
  });
720
- return f(s) ? a({
675
+ return I(r) ? o({
721
676
  status: n.ERROR,
722
- errorType: o.VALIDATION_ERROR,
677
+ errorType: d.VALIDATION_ERROR,
723
678
  errorMessage: "data provided is empty"
724
- }) : this.triggerUserEvent({ $remove: s });
679
+ }) : this.triggerUserEvent({ $remove: r });
725
680
  }
726
681
  setInternal(e, t) {
727
- const r = this.formatParamsToObj(e, t);
728
- if (!r)
729
- return a({
682
+ const s = this.formatParamsToObj(e, t);
683
+ if (!s)
684
+ return o({
730
685
  status: n.ERROR,
731
- errorType: o.VALIDATION_ERROR,
686
+ errorType: d.VALIDATION_ERROR,
732
687
  errorMessage: "data provided is empty"
733
688
  });
734
- const s = this.validateObjData(r, {
689
+ const r = this.validateObjData(s, {
735
690
  allowReservedKeys: !0
736
691
  });
737
- return f(s) ? a({
692
+ return I(r) ? o({
738
693
  status: n.ERROR,
739
- errorType: o.VALIDATION_ERROR,
694
+ errorType: d.VALIDATION_ERROR,
740
695
  errorMessage: "data provided is empty"
741
- }) : this.triggerUserEvent({ $set: s });
696
+ }) : this.triggerUserEvent({ $set: r });
742
697
  }
743
698
  validateEmail(e) {
744
699
  return /\S+@\S+\.\S+/.test(e);
@@ -747,16 +702,16 @@ class Q {
747
702
  return /^\+[1-9]\d{1,14}$/.test(e);
748
703
  }
749
704
  async addEmail(e) {
750
- return this.validateEmail(e) ? this.appendInternal({ $email: e }) : a({
705
+ return this.validateEmail(e) ? this.appendInternal({ $email: e }) : o({
751
706
  status: n.ERROR,
752
- errorType: o.VALIDATION_ERROR,
707
+ errorType: d.VALIDATION_ERROR,
753
708
  errorMessage: "provided email is invalid"
754
709
  });
755
710
  }
756
711
  async removeEmail(e) {
757
- return this.validateEmail(e) ? this.removeInternal({ $email: e }) : a({
712
+ return this.validateEmail(e) ? this.removeInternal({ $email: e }) : o({
758
713
  status: n.ERROR,
759
- errorType: o.VALIDATION_ERROR,
714
+ errorType: d.VALIDATION_ERROR,
760
715
  errorMessage: "provided email is invalid"
761
716
  });
762
717
  }
@@ -764,9 +719,9 @@ class Q {
764
719
  * Mobile number must be as per {@link https://www.twilio.com/docs/glossary/what-e164 E.164 standard}.
765
720
  */
766
721
  async addSms(e) {
767
- return this.validateMobile(e) ? this.appendInternal({ $sms: e }) : a({
722
+ return this.validateMobile(e) ? this.appendInternal({ $sms: e }) : o({
768
723
  status: n.ERROR,
769
- errorType: o.VALIDATION_ERROR,
724
+ errorType: d.VALIDATION_ERROR,
770
725
  errorMessage: "provided mobile number is invalid, must be as per E.164 standard"
771
726
  });
772
727
  }
@@ -774,9 +729,9 @@ class Q {
774
729
  * Mobile number must be as per {@link https://www.twilio.com/docs/glossary/what-e164 E.164 standard}.
775
730
  */
776
731
  async removeSms(e) {
777
- return this.validateMobile(e) ? this.removeInternal({ $sms: e }) : a({
732
+ return this.validateMobile(e) ? this.removeInternal({ $sms: e }) : o({
778
733
  status: n.ERROR,
779
- errorType: o.VALIDATION_ERROR,
734
+ errorType: d.VALIDATION_ERROR,
780
735
  errorMessage: "provided mobile number is invalid, must be as per E.164 standard"
781
736
  });
782
737
  }
@@ -784,9 +739,9 @@ class Q {
784
739
  * Mobile number must be as per {@link https://www.twilio.com/docs/glossary/what-e164 E.164 standard}.
785
740
  */
786
741
  async addWhatsapp(e) {
787
- return this.validateMobile(e) ? this.appendInternal({ $whatsapp: e }) : a({
742
+ return this.validateMobile(e) ? this.appendInternal({ $whatsapp: e }) : o({
788
743
  status: n.ERROR,
789
- errorType: o.VALIDATION_ERROR,
744
+ errorType: d.VALIDATION_ERROR,
790
745
  errorMessage: "provided mobile number is invalid, must be as per E.164 standard"
791
746
  });
792
747
  }
@@ -794,21 +749,21 @@ class Q {
794
749
  * Mobile number must be as per {@link https://www.twilio.com/docs/glossary/what-e164 E.164 standard}.
795
750
  */
796
751
  async removeWhatsapp(e) {
797
- return this.validateMobile(e) ? this.removeInternal({ $whatsapp: e }) : a({
752
+ return this.validateMobile(e) ? this.removeInternal({ $whatsapp: e }) : o({
798
753
  status: n.ERROR,
799
- errorType: o.VALIDATION_ERROR,
754
+ errorType: d.VALIDATION_ERROR,
800
755
  errorMessage: "provided mobile number is invalid, must be as per E.164 standard"
801
756
  });
802
757
  }
803
758
  getDeviceId() {
804
- let e = V(U);
805
- return e || (e = b(), M(U, e)), e;
759
+ let e = $(k);
760
+ return e || (e = A(), x(k, e)), e;
806
761
  }
807
762
  async addWebPush(e) {
808
763
  if (typeof e != "object")
809
- return a({
764
+ return o({
810
765
  status: n.ERROR,
811
- errorType: o.VALIDATION_ERROR,
766
+ errorType: d.VALIDATION_ERROR,
812
767
  errorMessage: "provided push subscription is invalid, must be an object"
813
768
  });
814
769
  const t = this.getDeviceId();
@@ -820,9 +775,9 @@ class Q {
820
775
  }
821
776
  async removeWebPush(e) {
822
777
  if (typeof e != "object")
823
- return a({
778
+ return o({
824
779
  status: n.ERROR,
825
- errorType: o.VALIDATION_ERROR,
780
+ errorType: d.VALIDATION_ERROR,
826
781
  errorMessage: "provided push subscription is invalid, must be an object"
827
782
  });
828
783
  const t = this.getDeviceId();
@@ -833,30 +788,30 @@ class Q {
833
788
  });
834
789
  }
835
790
  async addSlack(e) {
836
- return typeof e != "object" ? a({
791
+ return typeof e != "object" ? o({
837
792
  status: n.ERROR,
838
- errorType: o.VALIDATION_ERROR,
793
+ errorType: d.VALIDATION_ERROR,
839
794
  errorMessage: "provided slack data is invalid, must be an object"
840
795
  }) : this.appendInternal({ $slack: e });
841
796
  }
842
797
  async removeSlack(e) {
843
- return typeof e != "object" ? a({
798
+ return typeof e != "object" ? o({
844
799
  status: n.ERROR,
845
- errorType: o.VALIDATION_ERROR,
800
+ errorType: d.VALIDATION_ERROR,
846
801
  errorMessage: "provided slack data is invalid, must be an object"
847
802
  }) : this.removeInternal({ $slack: e });
848
803
  }
849
804
  async addMSTeams(e) {
850
- return typeof e != "object" ? a({
805
+ return typeof e != "object" ? o({
851
806
  status: n.ERROR,
852
- errorType: o.VALIDATION_ERROR,
807
+ errorType: d.VALIDATION_ERROR,
853
808
  errorMessage: "provided ms_teams data is invalid, must be object"
854
809
  }) : this.appendInternal({ $ms_teams: e });
855
810
  }
856
811
  async removeMSTeams(e) {
857
- return typeof e != "object" ? a({
812
+ return typeof e != "object" ? o({
858
813
  status: n.ERROR,
859
- errorType: o.VALIDATION_ERROR,
814
+ errorType: d.VALIDATION_ERROR,
860
815
  errorMessage: "provided ms_teams data is invalid, must be object"
861
816
  }) : this.removeInternal({ $ms_teams: e });
862
817
  }
@@ -865,9 +820,9 @@ class Q {
865
820
  * e.g. en (for English), es (for Spanish), fr (for French) etc.
866
821
  */
867
822
  async setPreferredLanguage(e) {
868
- return typeof e != "string" ? a({
823
+ return typeof e != "string" ? o({
869
824
  status: n.ERROR,
870
- errorType: o.VALIDATION_ERROR,
825
+ errorType: d.VALIDATION_ERROR,
871
826
  errorMessage: "provided language is invalid, must be string"
872
827
  }) : this.setInternal({ $preferred_language: e });
873
828
  }
@@ -875,20 +830,20 @@ class Q {
875
830
  * Timezone passed should be in {@link https://timeapi.io/documentation/iana-timezones IANA timezone format}.
876
831
  */
877
832
  async setTimezone(e) {
878
- return typeof e != "string" ? a({
833
+ return typeof e != "string" ? o({
879
834
  status: n.ERROR,
880
- errorType: o.VALIDATION_ERROR,
835
+ errorType: d.VALIDATION_ERROR,
881
836
  errorMessage: "provided timezone is invalid, must be string"
882
837
  }) : this.setInternal({ $timezone: e });
883
838
  }
884
839
  }
885
- class J {
840
+ class X {
886
841
  constructor(e) {
887
- d(this, "config");
842
+ f(this, "config");
888
843
  this.config = e;
889
844
  }
890
845
  async getPushSubscription() {
891
- if (!g()) return;
846
+ if (!E()) return;
892
847
  const e = await navigator.serviceWorker.getRegistration();
893
848
  if (!e) return;
894
849
  const t = e.pushManager.getSubscription();
@@ -898,31 +853,31 @@ class J {
898
853
  async handleRegisterPush() {
899
854
  try {
900
855
  if (await navigator.serviceWorker.register(`/${this.config.swFileName}`), await Notification.requestPermission() !== "granted")
901
- return console.warn("[SuprSend]: Notification permission isnt granted"), a({
856
+ return console.warn("[SuprSend]: Notification permission isnt granted"), o({
902
857
  status: n.ERROR,
903
- errorType: o.PERMISSION_DENIED,
858
+ errorType: d.PERMISSION_DENIED,
904
859
  errorMessage: "Notification permission isn't granted"
905
860
  });
906
- const t = await navigator.serviceWorker.ready, r = await t.pushManager.getSubscription();
907
- if (r)
908
- return this.config.user.addWebPush(r);
861
+ const t = await navigator.serviceWorker.ready, s = await t.pushManager.getSubscription();
862
+ if (s)
863
+ return this.config.user.addWebPush(s);
909
864
  if (!this.config.vapidKey)
910
865
  return console.warn(
911
866
  "[SuprSend]: Vapid key is missing. Add it while creating SuprSend instance"
912
- ), a({
867
+ ), o({
913
868
  status: n.ERROR,
914
- errorType: o.VALIDATION_ERROR,
869
+ errorType: d.VALIDATION_ERROR,
915
870
  errorMessage: "Vapid key is missing. Add it while creating SuprSend instance"
916
871
  });
917
- const s = await t.pushManager.subscribe({
872
+ const r = await t.pushManager.subscribe({
918
873
  userVisibleOnly: !0,
919
- applicationServerKey: j(this.config.vapidKey)
874
+ applicationServerKey: Q(this.config.vapidKey)
920
875
  });
921
- return this.config.user.addWebPush(s);
876
+ return this.config.user.addWebPush(r);
922
877
  } catch (e) {
923
- return console.warn("SuprSend: Error getting push subscription", e), a({
878
+ return console.warn("SuprSend: Error getting push subscription", e), o({
924
879
  status: n.ERROR,
925
- errorType: o.UNKNOWN_ERROR,
880
+ errorType: d.UNKNOWN_ERROR,
926
881
  errorMessage: (e == null ? void 0 : e.message) || "Unknown error occured while registering for push"
927
882
  });
928
883
  }
@@ -934,9 +889,9 @@ class J {
934
889
  * 3. Send webpush token to SuprSend.
935
890
  */
936
891
  async registerPush() {
937
- return g() && "serviceWorker" in navigator && "PushManager" in window ? this.handleRegisterPush() : (console.warn("[SuprSend]: Webpush isn't supported"), a({
892
+ return E() && "serviceWorker" in navigator && "PushManager" in window ? this.handleRegisterPush() : (console.warn("[SuprSend]: Webpush isn't supported"), o({
938
893
  status: n.ERROR,
939
- errorType: o.UNSUPPORTED_ACTION,
894
+ errorType: d.UNSUPPORTED_ACTION,
940
895
  errorMessage: "Webpush isn't supported"
941
896
  }));
942
897
  }
@@ -963,111 +918,558 @@ class J {
963
918
  return !!await this.getPushSubscription();
964
919
  }
965
920
  }
966
- function z(i) {
967
- return { all: i = i || /* @__PURE__ */ new Map(), on: function(e, t) {
968
- var r = i.get(e);
969
- r ? r.push(t) : i.set(e, [t]);
970
- }, off: function(e, t) {
971
- var r = i.get(e);
972
- r && (t ? r.splice(r.indexOf(t) >>> 0, 1) : i.set(e, []));
973
- }, emit: function(e, t) {
974
- var r = i.get(e);
975
- r && r.slice().map(function(s) {
976
- s(t);
977
- }), (r = i.get("*")) && r.slice().map(function(s) {
978
- s(e, t);
921
+ const j = 20, q = "default", Y = 100, v = {
922
+ storeId: "$suprsend_default_store",
923
+ label: ""
924
+ }, ee = {
925
+ tenantId: q,
926
+ pageSize: j,
927
+ stores: null,
928
+ host: {
929
+ apiHost: "https://inboxs.live",
930
+ socketHost: "https://betainbox.suprsend.com"
931
+ }
932
+ }, w = {
933
+ notifications: [],
934
+ store: v,
935
+ pageInfo: {
936
+ total: 0,
937
+ currentPage: 0,
938
+ totalPages: 0,
939
+ pageSize: j
940
+ },
941
+ meta: { badge: 0 },
942
+ apiStatus: _.INITIAL,
943
+ _firstFetchedTimeStamp: null
944
+ };
945
+ class te {
946
+ constructor(e) {
947
+ f(this, "config");
948
+ f(this, "feedInstances", []);
949
+ this.config = e;
950
+ }
951
+ initialize(e = {}) {
952
+ const t = new se(this.config, e);
953
+ return this.feedInstances.push(t), t;
954
+ }
955
+ removeInstance(e) {
956
+ this.feedInstances = this.feedInstances.filter(
957
+ (t) => t !== e
958
+ );
959
+ }
960
+ removeAll() {
961
+ for (const e of this.feedInstances)
962
+ e.remove();
963
+ this.feedInstances = [];
964
+ }
965
+ }
966
+ class se {
967
+ constructor(e, t) {
968
+ f(this, "feedOptions");
969
+ f(this, "config");
970
+ f(this, "store");
971
+ f(this, "socket");
972
+ f(this, "expiryTimerId");
973
+ f(this, "emitter", L());
974
+ this.config = e, this.setOptions(t), this.store = this.createFeedStore();
975
+ }
976
+ setOptions(e) {
977
+ this.feedOptions = { ...ee }, e != null && e.tenantId && (this.feedOptions.tenantId = e.tenantId), e != null && e.host && (this.feedOptions.host = e.host), typeof (e == null ? void 0 : e.pageSize) == "number" && e.pageSize > 0 && (this.feedOptions.pageSize = Math.min(e.pageSize, Y)), e != null && e.stores && (this.feedOptions.stores = e.stores), this.validateStore();
978
+ }
979
+ validateStore() {
980
+ const e = this.feedOptions.stores;
981
+ if (!e) return;
982
+ if (!Array.isArray(e) || (e == null ? void 0 : e.length) <= 0) {
983
+ console.warn("SuprSend: stores should be an array of objects");
984
+ return;
985
+ }
986
+ const t = [];
987
+ e.forEach((s) => {
988
+ if (!s.storeId) {
989
+ console.warn(
990
+ "SuprSend: storeId is mandatory for each store. Ignoring store without storeId"
991
+ );
992
+ return;
993
+ }
994
+ const r = s == null ? void 0 : s.query;
995
+ let i, c, u = [], l = [];
996
+ typeof (r == null ? void 0 : r.read) == "boolean" && (i = r.read), typeof (r == null ? void 0 : r.archived) == "boolean" && (c = r.archived), typeof (r == null ? void 0 : r.tags) == "string" ? u = [r.tags] : Array.isArray(r == null ? void 0 : r.tags) && (u = r == null ? void 0 : r.tags.filter((h) => typeof h == "string")), typeof (r == null ? void 0 : r.categories) == "string" ? l = [r.categories] : Array.isArray(r == null ? void 0 : r.categories) && (l = r == null ? void 0 : r.categories.filter((h) => typeof h == "string")), t.push({
997
+ storeId: s.storeId,
998
+ label: s.label || s.storeId,
999
+ query: {
1000
+ archived: c,
1001
+ read: i,
1002
+ tags: u,
1003
+ categories: l
1004
+ }
1005
+ });
1006
+ }), this.feedOptions.stores = t;
1007
+ }
1008
+ createFeedStore() {
1009
+ return z()(() => {
1010
+ var e;
1011
+ return {
1012
+ ...w,
1013
+ store: ((e = this.feedOptions.stores) == null ? void 0 : e[0]) || v
1014
+ };
979
1015
  });
980
- } };
1016
+ }
1017
+ initializeSocketEvents() {
1018
+ this.socket.on(
1019
+ "new_notification",
1020
+ this.handleNewNotificationSocketEvent.bind(this)
1021
+ ), this.socket.on(
1022
+ "notification_update",
1023
+ this.handleNoticationUpdateSocketEvent.bind(this)
1024
+ ), this.socket.on(
1025
+ "bulk_notification_update",
1026
+ this.handleBulkNotificationUpdateSocketEvent.bind(this)
1027
+ ), this.socket.on("reset_badge", async () => {
1028
+ const e = this.store.getState();
1029
+ this.store.setState({
1030
+ meta: { ...e.meta, badge: 0 }
1031
+ }), this.emitter.emit("feed.store_update", this.data);
1032
+ });
1033
+ }
1034
+ async handleNewNotificationSocketEvent(e) {
1035
+ var u, l;
1036
+ if (!e.n_id) return;
1037
+ const t = await this.fetchDetails(e.n_id);
1038
+ if (t.status === n.ERROR)
1039
+ return;
1040
+ const s = t.body, r = this.store.getState();
1041
+ let i = !1;
1042
+ const c = { ...r.meta };
1043
+ this.notificationBelongToStore(s, r.store) && (i = !0, this.store.setState({
1044
+ notifications: this.orderNotificationsBasedOnPinFlag(
1045
+ s,
1046
+ r.notifications
1047
+ )
1048
+ })), (l = (u = this.feedOptions.stores) == null ? void 0 : u.map) == null || l.call(u, (h) => {
1049
+ this.notificationBelongToStore(s, h) && (i = !0, c[h.storeId] = (r.meta[h.storeId] || 0) + 1);
1050
+ }), this.store.setState({
1051
+ meta: {
1052
+ ...c,
1053
+ badge: i ? c.badge + 1 : c.badge
1054
+ }
1055
+ }), i && this.emitter.emit("feed.new_notification", s), this.emitter.emit("feed.store_update", this.data);
1056
+ }
1057
+ async handleNoticationUpdateSocketEvent(e) {
1058
+ var l;
1059
+ if (!e.n_id) return;
1060
+ const t = await Promise.allSettled([
1061
+ this.fetchDetails(e.n_id),
1062
+ this.fetchCount()
1063
+ ]), s = this.store.getState();
1064
+ if (t[0].status !== "fulfilled") return;
1065
+ const r = t[0].value;
1066
+ if (r.status === n.ERROR) return;
1067
+ const i = r.body, c = (l = s.notifications) == null ? void 0 : l.some(
1068
+ (h) => h.n_id === i.n_id
1069
+ );
1070
+ this.notificationBelongToStore(
1071
+ i,
1072
+ s.store
1073
+ ) ? c ? this.store.setState({
1074
+ notifications: s.notifications.map((h) => h.n_id === i.n_id ? i : h)
1075
+ }) : this.store.setState({
1076
+ notifications: this.orderNotificationsBasedOnPinFlag(
1077
+ i,
1078
+ s.notifications
1079
+ )
1080
+ }) : this.store.setState({
1081
+ notifications: s.notifications.filter(
1082
+ (h) => h.n_id !== i.n_id
1083
+ )
1084
+ }), this.emitter.emit("feed.store_update", this.data);
1085
+ }
1086
+ async handleBulkNotificationUpdateSocketEvent(e) {
1087
+ const t = this.store.getState();
1088
+ if (e.action === "read" && e.notification_ids === "all") {
1089
+ for (const s in t.meta)
1090
+ t.meta[s] = 0;
1091
+ this.store.setState({
1092
+ notifications: t.notifications.map((s) => (s.read_on || (s.read_on = Date.now()), s)),
1093
+ meta: t.meta
1094
+ });
1095
+ }
1096
+ e.action === "seen" && Array.isArray(e.notification_ids) && this.store.setState({
1097
+ notifications: t.notifications.map((s) => (e.notification_ids.includes(s.n_id) && (s.seen_on = Date.now()), s))
1098
+ }), this.emitter.emit("feed.store_update", this.data);
1099
+ }
1100
+ notificationBelongToStore(e, t) {
1101
+ var O, y, C, P;
1102
+ const s = !!e.read_on, r = e.archived, i = e.tags, c = e.n_category, u = (O = t == null ? void 0 : t.query) == null ? void 0 : O.read, l = (y = t == null ? void 0 : t.query) == null ? void 0 : y.archived, h = (C = t == null ? void 0 : t.query) == null ? void 0 : C.tags, R = (P = t == null ? void 0 : t.query) == null ? void 0 : P.categories, S = u == null || s === u, g = !!r == !!l;
1103
+ let m = !1, T = !1;
1104
+ return Array.isArray(h) && h.length > 0 ? h.forEach((F) => {
1105
+ i != null && i.includes(F) && (m = !0);
1106
+ }) : m = !0, Array.isArray(R) && R.length > 0 ? R.includes(c) && (T = !0) : T = !0, S && m && T && g;
1107
+ }
1108
+ orderNotificationsBasedOnPinFlag(e, t) {
1109
+ if (e.is_pinned)
1110
+ return [e, ...t];
1111
+ {
1112
+ let s = !1;
1113
+ const r = [];
1114
+ return t.forEach((i) => {
1115
+ i.is_pinned || s ? r.push(i) : (r.push(e), r.push(i), s = !0);
1116
+ }), s ? r : [...t, e];
1117
+ }
1118
+ }
1119
+ startExpiryTimer() {
1120
+ this.expiryTimerId || (this.expiryTimerId = setInterval(this.removeExpiredFeed.bind(this), 3e4));
1121
+ }
1122
+ async removeExpiredFeed() {
1123
+ const e = this.store.getState();
1124
+ let t = !1;
1125
+ const s = e.notifications.filter(
1126
+ (r) => (r.expiry ? Date.now() > r.expiry : !1) ? (t = !0, !1) : !0
1127
+ );
1128
+ t && (this.store.setState({ notifications: s }), await this.fetchCount(), this.emitter.emit("feed.store_update", this.data));
1129
+ }
1130
+ getUrl(e, t) {
1131
+ var c;
1132
+ const s = `${(c = this.feedOptions.host) == null ? void 0 : c.apiHost}/v1/feed/${e}`, r = this.validateQueryParams(t), i = new URLSearchParams(
1133
+ r
1134
+ ).toString();
1135
+ return i ? `${s}?${i}` : s;
1136
+ }
1137
+ validateQueryParams(e = {}) {
1138
+ const t = {};
1139
+ for (const s in e) {
1140
+ const r = e[s];
1141
+ r == null || r === "" || (typeof r == "object" ? t[s] = JSON.stringify(r) : t[s] = String(r));
1142
+ }
1143
+ return t;
1144
+ }
1145
+ requestInprogress() {
1146
+ const e = this.store.getState();
1147
+ return [
1148
+ _.LOADING,
1149
+ _.FETCHING_MORE
1150
+ ].includes(e.apiStatus);
1151
+ }
1152
+ storesQueryParamObj(e) {
1153
+ return e == null ? void 0 : e.map((s) => this.storeQueryParamObj(s));
1154
+ }
1155
+ storeQueryParamObj(e) {
1156
+ const t = e == null ? void 0 : e.query, s = (t == null ? void 0 : t.tags) || [], r = (t == null ? void 0 : t.categories) || [], i = t == null ? void 0 : t.read, c = t == null ? void 0 : t.archived;
1157
+ return {
1158
+ store_id: e.storeId,
1159
+ query: {
1160
+ read: i,
1161
+ archived: c,
1162
+ tags: { or: s },
1163
+ categories: { or: r }
1164
+ }
1165
+ };
1166
+ }
1167
+ async changeActiveStore(e) {
1168
+ var r;
1169
+ const t = this.store.getState();
1170
+ if (t.store.storeId === e) return;
1171
+ const s = (r = this.feedOptions.stores) == null ? void 0 : r.find(
1172
+ (i) => i.storeId === e
1173
+ );
1174
+ return s ? (this.store.setState({
1175
+ ...w,
1176
+ store: s,
1177
+ meta: t.meta
1178
+ }), await this.fetch()) : {
1179
+ status: n.ERROR,
1180
+ error: {
1181
+ type: d.NOT_FOUND,
1182
+ message: `store with storeId ${e} doesnt exist`
1183
+ }
1184
+ };
1185
+ }
1186
+ get data() {
1187
+ const e = this.store.getState();
1188
+ return {
1189
+ notifications: e.notifications,
1190
+ pageInfo: e.pageInfo,
1191
+ meta: e.meta,
1192
+ apiStatus: e.apiStatus,
1193
+ store: e.store
1194
+ };
1195
+ }
1196
+ initializeSocketConnection() {
1197
+ var e;
1198
+ this.socket || (this.socket = B((e = this.feedOptions.host) == null ? void 0 : e.socketHost, {
1199
+ transports: ["websocket"],
1200
+ auth: {
1201
+ authorization: this.config.publicApiKey,
1202
+ "x-ss-signature": this.config.userToken,
1203
+ distinct_id: this.config.distinctId,
1204
+ tenant_id: this.feedOptions.tenantId,
1205
+ schema: "1"
1206
+ },
1207
+ reconnectionAttempts: 25,
1208
+ reconnectionDelay: 5e3,
1209
+ reconnectionDelayMax: 1e4
1210
+ }), this.initializeSocketEvents());
1211
+ }
1212
+ // TODO: support other stores and pages
1213
+ async fetch(e = {}) {
1214
+ const t = this.store.getState();
1215
+ if (this.requestInprogress()) return;
1216
+ const s = (e == null ? void 0 : e.page) || 1, r = (e == null ? void 0 : e.pageSize) || this.feedOptions.pageSize, i = t._firstFetchedTimeStamp || Date.now();
1217
+ s > 1 ? this.store.setState({
1218
+ apiStatus: _.FETCHING_MORE
1219
+ }) : (this.store.setState({
1220
+ apiStatus: _.LOADING
1221
+ }), this.fetchCount()), this.emitter.emit("feed.store_update", this.data);
1222
+ const c = {
1223
+ distinct_id: this.config.distinctId,
1224
+ tenant_id: this.feedOptions.tenantId,
1225
+ page_size: r,
1226
+ page_no: s,
1227
+ before: i,
1228
+ store: t.store.storeId !== v.storeId ? this.storeQueryParamObj(t.store) : null
1229
+ }, u = this.getUrl("notifications", c), l = await this.config.client().request({ type: "get", url: u });
1230
+ if (l.status === n.ERROR)
1231
+ return this.store.setState({ apiStatus: _.ERROR }), this.emitter.emit("feed.store_update", this.data), l;
1232
+ const h = l.body.meta.current_page === 1;
1233
+ return this.store.setState({
1234
+ apiStatus: _.SUCCESS,
1235
+ notifications: h ? l.body.results : [...t.notifications, ...l.body.results],
1236
+ pageInfo: {
1237
+ ...t.pageInfo,
1238
+ total: l.body.meta.total_count,
1239
+ currentPage: l.body.meta.current_page,
1240
+ totalPages: l.body.meta.total_pages
1241
+ },
1242
+ _firstFetchedTimeStamp: i
1243
+ }), this.emitter.emit("feed.store_update", this.data), this.startExpiryTimer(), l;
1244
+ }
1245
+ // TODO: support other stores
1246
+ async fetchNextPage() {
1247
+ const e = this.store.getState();
1248
+ return e.pageInfo.currentPage >= e.pageInfo.totalPages ? {
1249
+ status: n.ERROR,
1250
+ error: {
1251
+ type: d.VALIDATION_ERROR,
1252
+ message: "No more pages to fetch"
1253
+ }
1254
+ } : this.fetch({ page: e.pageInfo.currentPage + 1 });
1255
+ }
1256
+ async fetchCount() {
1257
+ const e = {
1258
+ distinct_id: this.config.distinctId,
1259
+ tenant_id: this.feedOptions.tenantId,
1260
+ stores: this.feedOptions.stores ? this.storesQueryParamObj(this.feedOptions.stores) : null
1261
+ }, t = this.getUrl("notifications_count", e), s = await this.config.client().request({ type: "get", url: t });
1262
+ return s.status === n.SUCCESS && this.store.setState({ meta: s.body }), this.emitter.emit("feed.store_update", this.data), s;
1263
+ }
1264
+ async fetchDetails(e) {
1265
+ const t = this.getUrl(`notifications/${e}`, {
1266
+ tenant_id: this.feedOptions.tenantId,
1267
+ distinct_id: this.config.distinctId
1268
+ });
1269
+ return await this.config.client().request({ type: "get", url: t });
1270
+ }
1271
+ async markAsSeen(e) {
1272
+ const t = this.store.getState();
1273
+ let s = !1;
1274
+ if (this.store.setState({
1275
+ notifications: t.notifications.map((i) => (i.n_id === e && (i.seen_on ? s = !0 : i.seen_on = Date.now()), i))
1276
+ }), s) return { status: n.SUCCESS };
1277
+ const r = this.getUrl(`notifications/${e}/seen`, {
1278
+ tenant_id: this.feedOptions.tenantId,
1279
+ distinct_id: this.config.distinctId
1280
+ });
1281
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: r });
1282
+ }
1283
+ async markAsRead(e) {
1284
+ const t = this.store.getState();
1285
+ let s = !1;
1286
+ if (this.store.setState({
1287
+ notifications: t.notifications.map((i) => (i.n_id === e && (i.read_on ? s = !0 : (i.read_on = Date.now(), i.seen_on = Date.now())), i))
1288
+ }), s) return { status: n.SUCCESS };
1289
+ const r = this.getUrl(`notifications/${e}/read`, {
1290
+ tenant_id: this.feedOptions.tenantId,
1291
+ distinct_id: this.config.distinctId
1292
+ });
1293
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: r });
1294
+ }
1295
+ async markAsUnread(e) {
1296
+ const t = this.store.getState();
1297
+ let s = !1;
1298
+ if (this.store.setState({
1299
+ notifications: t.notifications.map((i) => (i.n_id === e && (i.read_on ? i.read_on = null : s = !0), i))
1300
+ }), s) return { status: n.SUCCESS };
1301
+ const r = this.getUrl(`notifications/${e}/unread`, {
1302
+ tenant_id: this.feedOptions.tenantId,
1303
+ distinct_id: this.config.distinctId
1304
+ });
1305
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: r });
1306
+ }
1307
+ // TODO: improve logic for already interacted cases
1308
+ async markAsInteracted(e) {
1309
+ const t = this.store.getState();
1310
+ this.store.setState({
1311
+ notifications: t.notifications.map((r) => (r.n_id === e && (r.interacted_on || (r.interacted_on = Date.now()), r.read_on || (r.read_on = Date.now())), r))
1312
+ });
1313
+ const s = this.getUrl(`notifications/${e}/interacted`, {
1314
+ tenant_id: this.feedOptions.tenantId,
1315
+ distinct_id: this.config.distinctId
1316
+ });
1317
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: s });
1318
+ }
1319
+ async markAsArchived(e) {
1320
+ const t = this.store.getState();
1321
+ let s = !1;
1322
+ if (this.store.setState({
1323
+ notifications: t.notifications.filter((i) => i.n_id === e ? (s = !!i.archived, !1) : !0)
1324
+ }), s) return { status: n.SUCCESS };
1325
+ const r = this.getUrl(`notifications/${e}/archive`, {
1326
+ tenant_id: this.feedOptions.tenantId,
1327
+ distinct_id: this.config.distinctId
1328
+ });
1329
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: r });
1330
+ }
1331
+ async markBulkAsSeen(e) {
1332
+ const t = this.store.getState();
1333
+ this.store.setState({
1334
+ notifications: t.notifications.map((r) => (e.includes(r.n_id) && (r.seen_on || (r.seen_on = Date.now())), r))
1335
+ });
1336
+ const s = this.getUrl("bulk/notifications/seen", {
1337
+ tenant_id: this.feedOptions.tenantId,
1338
+ distinct_id: this.config.distinctId
1339
+ });
1340
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({
1341
+ type: "post",
1342
+ url: s,
1343
+ payload: { notification_ids: e }
1344
+ });
1345
+ }
1346
+ async resetBadgeCount() {
1347
+ const e = this.store.getState();
1348
+ this.store.setState({ meta: { ...e.meta, badge: 0 } });
1349
+ const t = this.getUrl("reset_bell_count", {
1350
+ tenant_id: this.feedOptions.tenantId,
1351
+ distinct_id: this.config.distinctId
1352
+ });
1353
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: t });
1354
+ }
1355
+ async markAllAsRead() {
1356
+ const e = this.store.getState();
1357
+ this.store.setState({
1358
+ meta: { ...e.meta, badge: 0 },
1359
+ notifications: e.notifications.map((s) => (s.read_on = Date.now(), s))
1360
+ });
1361
+ const t = this.getUrl("mark_all_read", {
1362
+ tenant_id: this.feedOptions.tenantId,
1363
+ distinct_id: this.config.distinctId
1364
+ });
1365
+ return this.emitter.emit("feed.store_update", this.data), await this.config.client().request({ type: "patch", url: t });
1366
+ }
1367
+ reset() {
1368
+ var e;
1369
+ this.store.setState({
1370
+ ...w,
1371
+ store: ((e = this.feedOptions.stores) == null ? void 0 : e[0]) || v
1372
+ }), this.emitter.emit("feed.store_update", this.data), this.expiryTimerId && (clearInterval(this.expiryTimerId), this.expiryTimerId = void 0);
1373
+ }
1374
+ remove() {
1375
+ var e;
1376
+ this.reset(), this.emitter.off("*"), (e = this.socket) == null || e.disconnect(), this.config.feeds.removeInstance(this);
1377
+ }
981
1378
  }
982
- const B = "https://hub.suprsend.com", G = "serviceworker.js", w = "ss_distinct_id";
983
- class Z {
1379
+ const re = "https://hub.suprsend.com", ie = "serviceworker.js", M = "ss_distinct_id";
1380
+ class ue {
984
1381
  constructor(e, t) {
985
- d(this, "host");
986
- d(this, "publicApiKey");
987
- d(this, "distinctId");
988
- d(this, "userToken");
989
- d(this, "vapidKey");
990
- d(this, "swFileName");
991
- d(this, "apiClient", null);
992
- d(this, "userTokenExpirationTimer", null);
993
- d(this, "authenticateOptions");
994
- d(this, "user", new Q(this));
995
- d(this, "webpush", new J(this));
996
- d(this, "emitter", z());
1382
+ f(this, "host");
1383
+ f(this, "publicApiKey");
1384
+ f(this, "distinctId");
1385
+ f(this, "userToken");
1386
+ f(this, "vapidKey");
1387
+ f(this, "swFileName");
1388
+ f(this, "apiClient", null);
1389
+ f(this, "userTokenExpirationTimer", null);
1390
+ f(this, "authenticateOptions");
1391
+ f(this, "user", new Z(this));
1392
+ f(this, "webpush", new X(this));
1393
+ f(this, "feeds", new te(this));
1394
+ f(this, "emitter", L());
997
1395
  if (!e)
998
1396
  throw new Error("[SuprSend]: publicApiKey is missing");
999
- this.publicApiKey = e, this.host = (t == null ? void 0 : t.host) || B, this.vapidKey = (t == null ? void 0 : t.vapidKey) || "", this.swFileName = (t == null ? void 0 : t.swFileName) || G;
1397
+ this.publicApiKey = e, this.host = (t == null ? void 0 : t.host) || re, this.vapidKey = (t == null ? void 0 : t.vapidKey) || "", this.swFileName = (t == null ? void 0 : t.swFileName) || ie;
1000
1398
  }
1001
1399
  handleRefreshUserToken(e) {
1002
- if (!this.userToken || !g()) return;
1003
- const t = L(this.userToken), r = (t.exp || 0) * 1e3, s = Date.now(), u = 1e3 * 30;
1004
- if (r && r > s) {
1005
- const c = r - s - u;
1400
+ if (!this.userToken || !E()) return;
1401
+ const t = V(this.userToken), s = (t.exp || 0) * 1e3, r = Date.now(), i = 1e3 * 30;
1402
+ if (s && s > r) {
1403
+ const c = s - r - i;
1006
1404
  this.userTokenExpirationTimer && clearTimeout(this.userTokenExpirationTimer), this.userTokenExpirationTimer = setTimeout(async () => {
1007
- let h = "";
1405
+ let u = "";
1008
1406
  try {
1009
- h = await e(
1407
+ u = await e(
1010
1408
  this.userToken,
1011
1409
  t
1012
1410
  );
1013
1411
  } catch {
1014
1412
  try {
1015
- h = await e(
1413
+ u = await e(
1016
1414
  this.userToken,
1017
1415
  t
1018
1416
  );
1019
- } catch (R) {
1020
- console.warn("[SuprSend]: Couldn't fetch new userToken", R);
1417
+ } catch (h) {
1418
+ console.warn("[SuprSend]: Couldn't fetch new userToken", h);
1021
1419
  }
1022
1420
  }
1023
- h && typeof h == "string" && this.identify(this.distinctId, h, this.authenticateOptions);
1421
+ u && typeof u == "string" && this.identify(this.distinctId, u, this.authenticateOptions);
1024
1422
  }, c);
1025
1423
  }
1026
1424
  }
1027
1425
  client() {
1028
1426
  return this.distinctId || console.warn(
1029
1427
  "[SuprSend]: distinctId is missing. User should be authenticated"
1030
- ), this.apiClient || (this.apiClient = new S(this)), this.apiClient;
1428
+ ), this.apiClient || (this.apiClient = new D(this)), this.apiClient;
1031
1429
  }
1032
1430
  eventApi(e) {
1033
- return this.client().request({ path: "v2/event", payload: e, type: "post" });
1431
+ return this.client().request({
1432
+ url: `${this.host}/v2/event`,
1433
+ payload: e,
1434
+ type: "post"
1435
+ });
1034
1436
  }
1035
1437
  /**
1036
1438
  * Used to authenticate user. Usually called just after successful login and on reload of loggedin route to re-authenticate loggedin user.
1037
1439
  * In production env's userToken is mandatory for security purposes.
1038
1440
  */
1039
- async identify(e, t, r) {
1441
+ async identify(e, t, s) {
1040
1442
  if (!e)
1041
- return a({
1443
+ return o({
1042
1444
  status: n.ERROR,
1043
- errorType: o.VALIDATION_ERROR,
1445
+ errorType: d.VALIDATION_ERROR,
1044
1446
  errorMessage: "distinctId is missing"
1045
1447
  });
1046
1448
  if (this.apiClient && this.distinctId && this.distinctId !== e)
1047
- return a({
1449
+ return o({
1048
1450
  status: n.ERROR,
1049
- errorType: o.VALIDATION_ERROR,
1451
+ errorType: d.VALIDATION_ERROR,
1050
1452
  errorMessage: "User already loggedin, reset current user to login new user"
1051
1453
  });
1052
1454
  if (this.apiClient && this.distinctId === e && this.userToken !== t)
1053
- return this.userToken = t, this.apiClient = new S(this), r != null && r.refreshUserToken && this.handleRefreshUserToken(r.refreshUserToken), a({ status: n.SUCCESS });
1455
+ return this.userToken = t, this.apiClient = new D(this), s != null && s.refreshUserToken && this.handleRefreshUserToken(s.refreshUserToken), o({ status: n.SUCCESS });
1054
1456
  if (this.distinctId && this.apiClient)
1055
- return a({ status: n.SUCCESS });
1056
- this.distinctId = e, this.userToken = t, this.apiClient = new S(this), this.authenticateOptions = r;
1057
- const s = V(
1058
- w
1457
+ return o({ status: n.SUCCESS });
1458
+ this.distinctId = e, this.userToken = t, this.apiClient = new D(this), this.authenticateOptions = s;
1459
+ const r = $(
1460
+ M
1059
1461
  );
1060
- if (r != null && r.refreshUserToken && this.handleRefreshUserToken(r.refreshUserToken), s == this.distinctId)
1061
- return this.webpush.updatePushSubscription(), a({ status: n.SUCCESS });
1062
- const u = await this.eventApi({
1462
+ if (s != null && s.refreshUserToken && this.handleRefreshUserToken(s.refreshUserToken), r == this.distinctId)
1463
+ return this.webpush.updatePushSubscription(), o({ status: n.SUCCESS });
1464
+ const i = await this.eventApi({
1063
1465
  event: "$identify",
1064
- $insert_id: b(),
1065
- $time: C(),
1466
+ $insert_id: A(),
1467
+ $time: N(),
1066
1468
  properties: {
1067
1469
  $identified_id: e
1068
1470
  }
1069
1471
  });
1070
- return u.status === n.SUCCESS ? (this.webpush.updatePushSubscription(), M(w, this.distinctId)) : this.reset({ unsubscribePush: !1 }), u;
1472
+ return i.status === n.SUCCESS ? (this.webpush.updatePushSubscription(), x(M, this.distinctId)) : this.reset({ unsubscribePush: !1 }), i;
1071
1473
  }
1072
1474
  /**
1073
1475
  * Check's if SuprSend instance is authenticated. To check if userToken is also present pass true.
@@ -1079,16 +1481,16 @@ class Z {
1079
1481
  * Used to trigger events to suprsend.
1080
1482
  */
1081
1483
  async track(e, t) {
1082
- let r = {};
1083
- return e ? (typeof t == "object" && (r = { ...r, ...t }), this.eventApi({
1484
+ let s = {};
1485
+ return e ? (typeof t == "object" && (s = { ...s, ...t }), this.eventApi({
1084
1486
  event: String(e),
1085
- $insert_id: b(),
1086
- $time: C(),
1487
+ $insert_id: A(),
1488
+ $time: N(),
1087
1489
  distinct_id: this.distinctId,
1088
- properties: r
1089
- })) : a({
1490
+ properties: s
1491
+ })) : o({
1090
1492
  status: n.ERROR,
1091
- errorType: o.VALIDATION_ERROR,
1493
+ errorType: d.VALIDATION_ERROR,
1092
1494
  errorMessage: "event name is missing"
1093
1495
  });
1094
1496
  }
@@ -1096,16 +1498,17 @@ class Z {
1096
1498
  * Clears user related data attached to SuprSend instance. Usually called during logout.
1097
1499
  */
1098
1500
  async reset(e) {
1099
- var r;
1100
- return (e == null ? void 0 : e.unsubscribePush) !== !1 && await ((r = this.webpush) == null ? void 0 : r.removePushSubscription()), this.apiClient = null, this.distinctId = null, this.userToken = "", W(w), this.userTokenExpirationTimer && clearTimeout(this.userTokenExpirationTimer), a({ status: n.SUCCESS });
1501
+ var s, r;
1502
+ return (e == null ? void 0 : e.unsubscribePush) !== !1 && await ((s = this.webpush) == null ? void 0 : s.removePushSubscription()), this.apiClient = null, this.distinctId = null, this.userToken = "", this.userTokenExpirationTimer && clearTimeout(this.userTokenExpirationTimer), ((r = this.feeds.feedInstances) == null ? void 0 : r.length) > 0 && this.feeds.removeAll(), o({ status: n.SUCCESS });
1101
1503
  }
1102
1504
  }
1103
1505
  export {
1104
- v as ChannelLevelPreferenceOptions,
1105
- o as ERROR_TYPE,
1506
+ _ as ApiResponseStatus,
1507
+ b as ChannelLevelPreferenceOptions,
1508
+ d as ERROR_TYPE,
1509
+ se as Feed,
1106
1510
  p as PreferenceOptions,
1107
1511
  n as RESPONSE_STATUS,
1108
- Z as SuprSend,
1109
- Z as default
1512
+ ue as SuprSend
1110
1513
  };
1111
1514
  //# sourceMappingURL=index.js.map