@subiz/widget-v4 4.1.142 → 4.1.144

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 (62) hide show
  1. package/README.md +5 -1
  2. package/compiled_src/bot.js +1 -2
  3. package/compiled_src/call/call.js +1 -2
  4. package/compiled_src/chatbox/Event.js +1 -2
  5. package/compiled_src/chatbox/Widget.js +3 -4
  6. package/compiled_src/chatbox/main.js +1 -2
  7. package/compiled_src/contact/contact.js +1 -2
  8. package/compiled_src/form/FormPage.js +1 -2
  9. package/compiled_src/form/index.js +1 -2
  10. package/compiled_src/form.js +1 -2
  11. package/compiled_src/notif/notif.js +1 -2
  12. package/compiled_src/order/icon.js +1 -2
  13. package/compiled_src/order/index.js +1 -2
  14. package/compiled_src/order/order.js +1 -2
  15. package/compiled_src/plugin.js +1 -2
  16. package/compiled_src/popup/popup.js +1 -2
  17. package/compiled_src/store/store.js +1255 -0
  18. package/compiled_src/util/campaign.js +88 -0
  19. package/compiled_src/util/common.js +1294 -0
  20. package/compiled_src/util/common.test.js +496 -0
  21. package/compiled_src/util/extractor.test.js +299 -0
  22. package/compiled_src/util/gate.js +38 -0
  23. package/compiled_src/util/gate.test.js +18 -0
  24. package/compiled_src/util/index.js +19 -0
  25. package/compiled_src/util/mutex.js +31 -0
  26. package/compiled_src/util/op.js +55 -0
  27. package/compiled_src/util/pubsub.js +29 -0
  28. package/compiled_src/util/pubsub.test.js +35 -0
  29. package/dist/196d3465f26.278.js +1 -0
  30. package/dist/196d3465f26.339.js +1 -0
  31. package/dist/196d3465f26.app.js +1 -0
  32. package/dist/196d3465f26.form.html +1 -0
  33. package/dist/196d3465f26.form.js +1 -0
  34. package/dist/{1967c022bc1.index.html → 196d3465f26.index.html} +15 -1
  35. package/dist/{1967c022bc1.library.html → 196d3465f26.library.html} +15 -1
  36. package/dist/196d3465f26.library.js +1 -0
  37. package/dist/{1967c022bc1.preview.html → 196d3465f26.preview.html} +1 -1
  38. package/dist/196d3465f26.preview.js +1 -0
  39. package/dist/196d3465f26.webview.js +1 -0
  40. package/dist/278.js +81 -70
  41. package/dist/HASH +1 -1
  42. package/dist/assets/img/stars_v2.79cf728.png +0 -0
  43. package/dist/screenshoot.js +317 -118
  44. package/index.html +14 -0
  45. package/package.json +10 -10
  46. package/src/chatbox/Widget.js +2 -2
  47. package/src/store/store.js +1 -1
  48. package/dist/1967c022bc1.278.js +0 -1
  49. package/dist/1967c022bc1.app.js +0 -1
  50. package/dist/1967c022bc1.form.html +0 -1
  51. package/dist/1967c022bc1.form.js +0 -1
  52. package/dist/1967c022bc1.library.js +0 -1
  53. package/dist/1967c022bc1.preview.js +0 -1
  54. package/dist/1967c022bc1.webview.js +0 -1
  55. /package/dist/{1967c022bc1.127.js → 196d3465f26.127.js} +0 -0
  56. /package/dist/{1967c022bc1.132.js → 196d3465f26.132.js} +0 -0
  57. /package/dist/{1967c022bc1.185.js → 196d3465f26.185.js} +0 -0
  58. /package/dist/{1967c022bc1.27.js → 196d3465f26.27.js} +0 -0
  59. /package/dist/{1967c022bc1.459.js → 196d3465f26.459.js} +0 -0
  60. /package/dist/{1967c022bc1.490.js → 196d3465f26.490.js} +0 -0
  61. /package/dist/{1967c022bc1.74.js → 196d3465f26.74.js} +0 -0
  62. /package/dist/{1967c022bc1.997.js → 196d3465f26.997.js} +0 -0
@@ -0,0 +1,1255 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _index = _interopRequireDefault(require("../util/index.js"));
8
+ var _api = _interopRequireDefault(require("./api.js"));
9
+ var _lsdb = _interopRequireDefault(require("./lsdb.js"));
10
+ var _chain = _interopRequireDefault(require("./chain.js"));
11
+ var _kv = _interopRequireDefault(require("./kv.js"));
12
+ var _api_fake = _interopRequireDefault(require("./api_fake.js"));
13
+ var _realtime_fake = _interopRequireDefault(require("./realtime_fake.js"));
14
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
16
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
17
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
18
+ var flow = require('@subiz/flow');
19
+ var Realtime = require('@subiz/wsclient');
20
+ var cookie = require('cookie_js');
21
+ cookie.defaults.path = '/';
22
+ cookie.expiresMultiplier = 60 * 60 * 24;
23
+ cookie.defaults.expires = 3650;
24
+ const MAX_CONVO = 20;
25
+ const page_loaded = _index.default.Date.now();
26
+ class Store {
27
+ constructor(ApiURL, FileURL, RealtimeURL, inmem, fakeapi) {
28
+ _defineProperty(this, "inmem", false);
29
+ _defineProperty(this, "cookie", cookie);
30
+ _defineProperty(this, "getConnectionStatus", () => this.connectionStatus);
31
+ _defineProperty(this, "_currentViewingProduct", {});
32
+ _defineProperty(this, "new_visitor", true);
33
+ _defineProperty(this, "matchUser", () => {
34
+ this._touchAcc();
35
+ return this.cache.match('user');
36
+ });
37
+ _defineProperty(this, "suggest_addresses", keyword => this.api.suggest_address(keyword));
38
+ _defineProperty(this, "matchAccount", () => this.cache.match('account'));
39
+ _defineProperty(this, "matchPaymentMethods", () => this.cache.match('payment_methods'));
40
+ _defineProperty(this, "matchUnread", () => {
41
+ let user = this.matchUser();
42
+ let allconvos = this.matchConvo('*');
43
+ let unreadcount = 0;
44
+ _index.default.map(allconvos, convo => {
45
+ if (!_index.default.isConvoSeen(convo, user.id)) unreadcount++;
46
+ });
47
+ return unreadcount;
48
+ });
49
+ _defineProperty(this, "matchPlugin", () => {
50
+ if (_index.default.size(this.forcePlugins) > 0) return _index.default.cloneDeep(this.forcePlugins);
51
+ return _index.default.cloneDeep(this.cache.match('plugin')) || {};
52
+ });
53
+ _defineProperty(this, "device", {});
54
+ _defineProperty(this, "browserVisibility", 'visible');
55
+ _defineProperty(this, "matchAgent", id => {
56
+ let agentM = this.cache.match('agent') || {};
57
+ if (id === '*') return agentM;
58
+ return agentM[id];
59
+ });
60
+ _defineProperty(this, "matchConvo", id => {
61
+ if (!id) return;
62
+ if (id === '*') {
63
+ this._touchAcc();
64
+ return _index.default.filter(this.cache.all(), (value, k) => k.startsWith('convo_'));
65
+ }
66
+ if (!this.isInsync(id)) this.fetchConvo(id);
67
+ return this.cache.match('convo_' + id);
68
+ });
69
+ _defineProperty(this, "fetchConvo", async cid => {
70
+ if (this._die) return dieErr;
71
+ await this.readyGate.entry();
72
+ await this.reconnectGate.entry(undefined, true);
73
+ if (this.isInsync(cid)) return this.reconnectGate.open();
74
+ this.markSync(cid);
75
+ let {
76
+ body: convo,
77
+ error
78
+ } = await this.api.getConversation(cid);
79
+ if (convo && !error) this._setConvo(convo);
80
+ return this.reconnectGate.open();
81
+ });
82
+ _defineProperty(this, "list_provinces", () => this.api.list_provinces());
83
+ _defineProperty(this, "list_districts", p => this.api.list_districts(p));
84
+ _defineProperty(this, "list_wards", p => this.api.list_wards(p));
85
+ _defineProperty(this, "outofmsgM", {});
86
+ _defineProperty(this, "listEvents", id => {
87
+ if (!id || id === '*' || typeof id !== 'string') return;
88
+ return this.chain.listM(id);
89
+ });
90
+ _defineProperty(this, "fetchMoreEvents", async convoid => {
91
+ if (!this.isInsync('events' + convoid)) {
92
+ await this.readyGate.entry();
93
+ await this.reconnectGate.entry(undefined, true);
94
+ if (this.isInsync('events' + convoid)) {
95
+ this.reconnectGate.open();
96
+ return {};
97
+ }
98
+ this.markSync('events' + convoid);
99
+ await this.chain.reload(convoid, () => {
100
+ return [[], ''];
101
+ });
102
+ let out = await this._doFetchMsg(convoid);
103
+ this.reconnectGate.open();
104
+ return out;
105
+ }
106
+ return this._doFetchMsg(convoid);
107
+ });
108
+ _defineProperty(this, "_doFetchMsg", async convoid => {
109
+ let {
110
+ error
111
+ } = await this.chain.fetchMore(convoid, 150, async (type, anchor, limit) => {
112
+ if (this.outofmsgM[convoid]) return [[], ''];
113
+ let [events, newanchor, error, outofmsg] = await this.listmessageapi(type, anchor, limit);
114
+ if (outofmsg) this.outofmsgM[convoid] = true;
115
+ return [events, newanchor, error];
116
+ });
117
+ this.pubsub.publish('account');
118
+ return {
119
+ error
120
+ };
121
+ });
122
+ _defineProperty(this, "matchLocation", () => this.cache.match('location') || {});
123
+ _defineProperty(this, "matchBot", () => this.cache.match('bot') || {});
124
+ _defineProperty(this, "readyGate", new _index.default.Gate());
125
+ _defineProperty(this, "convoGate", new _index.default.Gate(true));
126
+ _defineProperty(this, "reconnectGate", new _index.default.Gate(true));
127
+ _defineProperty(this, "wsGate", new _index.default.Gate(true));
128
+ _defineProperty(this, "matchLastview", () => {
129
+ let lastView = this.kv.match('lastview') || {};
130
+ let user = this.cache.match('user') || {};
131
+ if (!user.id) return {};
132
+ if (lastView.user_id != user.id) return {};
133
+ return lastView;
134
+ });
135
+ _defineProperty(this, "matchIsOpen", () => !!this.kv.match('isopen'));
136
+ _defineProperty(this, "matchHasManuallyClosed", () => !!this.kv.match('hasManuallyClosed'));
137
+ _defineProperty(this, "matchClosePreviewAt", () => this.kv.match('close_preview_at') || 0);
138
+ _defineProperty(this, "checkFormToken", (accid, token) => this.api.checkFormToken(accid, token));
139
+ _defineProperty(this, "submitForm2", (accid, token, data) => this.api.submitForm2(accid, token, data));
140
+ _defineProperty(this, "sendPresence", _index.default.throttle(async () => {
141
+ if (this._die) return dieErr;
142
+ await this.readyGate.entry();
143
+ if (!_index.default.get(this.cache.match('user'), 'id')) return;
144
+ if (_index.default.isUserBanned(this.cache.match('user'))) return;
145
+ if (!this._track_page_view) return;
146
+ let hasfocus = this.browserVisibility === 'visible' && document.hasFocus();
147
+ if (!hasfocus) return this.api.sendLostFocus();
148
+ this.api.sendContentView(this.device, location.href, document.title, this._currentViewingProduct.id, this._currentViewingProduct.source_id, this._currentViewingProduct.sku);
149
+ }, 1000, {
150
+ leading: false
151
+ }));
152
+ _defineProperty(this, "now", () => _index.default.Date.now() + this.timeDiff);
153
+ _defineProperty(this, "seenQueue", []);
154
+ _defineProperty(this, "matchTrafficSource", () => this.kv.match('traffic_source'));
155
+ _defineProperty(this, "_alreadyReceived", {});
156
+ _defineProperty(this, "_typing", _index.default.throttle(convoid => this.api.sendTyping(convoid), 3000, {
157
+ trailing: false
158
+ }));
159
+ _defineProperty(this, "onConvoEvent", (o, cb) => this.pubsub.on2(o, 'events', cb));
160
+ _defineProperty(this, "onWidgetClose", (o, cb) => this.pubsub.on2(o, 'sbz_close_widget', cb));
161
+ _defineProperty(this, "seenConvo", id => {
162
+ if (!id || id === 'create') return;
163
+ this.seenQueue.push(id);
164
+ });
165
+ _defineProperty(this, "onUpdate", (o, cb) => this.pubsub.on2(o, 'account', cb));
166
+ _defineProperty(this, "onConnection", (o, cb) => this.pubsub.on2(o, 'connection', cb));
167
+ _defineProperty(this, "onResetCSS", (o, cb) => this.pubsub.on2(o, 'resetCSS', cb));
168
+ _defineProperty(this, "onHighlight", (o, cb) => this.pubsub.on2(o, 'highlight', cb));
169
+ _defineProperty(this, "setHasManuallyClosed", () => this.kv.put('hasManuallyClosed', true));
170
+ _defineProperty(this, "setIsOpen", isopen => {
171
+ let lastisopen = this.kv.match('isopen');
172
+ this.kv.put('isopen', isopen);
173
+ if (!lastisopen && isopen) {
174
+ sendEventToThirdParty('SUBIZ Chat', 'Opened', 'Subiz Windows');
175
+ }
176
+ });
177
+ _defineProperty(this, "closePreview", () => this.kv.put('close_preview_at', new _index.default.Date().getTime()));
178
+ _defineProperty(this, "setLastview", (view, opts) => {
179
+ let user = this.cache.match('user') || {};
180
+ if (!user.id) return;
181
+ this.kv.put('lastview', {
182
+ user_id: user.id,
183
+ view,
184
+ opts
185
+ });
186
+ });
187
+ _defineProperty(this, "timeDiff", 0);
188
+ this.connectionStatus = 'active';
189
+ this.CONNECTION_CHECK_INTERVAL = 3000;
190
+ this.reconnectTimestamp = 0;
191
+ this.g_sync = {};
192
+ this._die = false;
193
+ this.forceDevice = null;
194
+ this.forcePlugins = {};
195
+ this.forceAcc = {};
196
+ this.forceChatbox = {};
197
+ this.RealtimeURL = RealtimeURL;
198
+ this.fake = fakeapi;
199
+ this.FileURL = FileURL;
200
+ this._track_page_view = true;
201
+ this.device_type = 'desktop';
202
+ if (this.fake) this.api = new _api_fake.default(ApiURL, FileURL);else this.api = new _api.default(ApiURL, FileURL);
203
+ if (!inmem) {
204
+ try {
205
+ document.cookie;
206
+ localStorage;
207
+ } catch (e) {
208
+ inmem = true;
209
+ }
210
+ }
211
+ if (inmem) {
212
+ this.inmem = inmem;
213
+ this.cookie = inmemCookie;
214
+ }
215
+ cleanLocalStorage();
216
+ this.pubsub = new _index.default.Pubsub();
217
+ this.kv = new _kv.default(new _lsdb.default('sbz2023', this.inmem), 'kv');
218
+ this.cache = new _kv.default(new _lsdb.default('sbz2023', true), 'kv');
219
+ this.chain = new _chain.default(new _lsdb.default('cbz2023', true), 'ch');
220
+ this.getLocaleContent = this.api.getLocaleContent;
221
+ this.g_haveSentSeenM = {};
222
+ this.last_focused = _index.default.Date.now();
223
+ window.addEventListener('blur', () => {
224
+ this.last_focused = _index.default.Date.now();
225
+ this.sendPresence();
226
+ });
227
+ window.addEventListener('focus', () => {
228
+ this.last_focused = 0;
229
+ this.sendPresence();
230
+ });
231
+ window.addEventListener('beforeunload', () => this.api.sendLostFocus());
232
+ this.doNotStartBot = () => {
233
+ this._donotstartbot = true;
234
+ };
235
+ this.autoStartBot = () => {
236
+ this._donotstartbot = false;
237
+ };
238
+ this.matchAutoStartBot = () => !this._donotstartbot;
239
+ this._presenceInterval1 = _index.default.setInterval(() => {
240
+ if (this._die) return _index.default.clearInterval(this._presenceInterval1);
241
+ if (this.browserVisibility === 'visible' && document.hasFocus()) this.sendPresence();
242
+ }, 20000);
243
+ this._presenceInterval2 = _index.default.setInterval(() => {
244
+ if (this._die) return _index.default.clearInterval(this._presenceInterval2);
245
+ if (this.browserVisibility === 'visible' && document.hasFocus()) return;
246
+ if (this.last_focused && _index.default.Date.now() - this.last_focused > 30 * 60000) {
247
+ return;
248
+ }
249
+ this.sendPresence();
250
+ }, 60000);
251
+ onVisibilityChange(val => {
252
+ if (this._die) return;
253
+ this.browserVisibility = val;
254
+ this.sendPresence();
255
+ });
256
+ this.loopTime();
257
+ this.device = this.getDeviceInfo();
258
+ const _gaInterval = _index.default.setInterval(() => {
259
+ let user = this.cache.match('user') || {};
260
+ if (!user.id) return;
261
+ var dev = this.getDeviceInfo();
262
+ if (!dev.ga_tracking_ids || !dev.ga_client_id) return;
263
+ _index.default.clearInterval(_gaInterval);
264
+ this.device = dev;
265
+ let ga_client_id = dev.ga_client_id;
266
+ if (ga_client_id !== _index.default.getUserAttr(user, 'ga_client_id', 'text')) {
267
+ this.setUser({
268
+ attributes: [{
269
+ type: 'text',
270
+ text: ga_client_id,
271
+ key: 'ga_client_id'
272
+ }]
273
+ });
274
+ }
275
+ }, 2000);
276
+ }
277
+ async loopCheckConnectionStatus() {
278
+ while (true) {
279
+ if (this._die) break;
280
+ await _index.default.sleep(this.CONNECTION_CHECK_INTERVAL);
281
+ if (!this.realtime) continue;
282
+ if (!this.realtime.getStatus || !this.realtime.reconnect) continue;
283
+ if (this.connectionStatus === 'dead') {}
284
+ let currentStatus = this.connectionStatus;
285
+ this.connectionStatus = this.realtime.getStatus();
286
+ if (currentStatus !== this.connectionStatus) {
287
+ console.log('publish connectionStatus', this.connectionStatus);
288
+ this.pubsub.publish('connection');
289
+ }
290
+ }
291
+ }
292
+ linkProduct(p) {
293
+ if (!p) {
294
+ this._currentViewingProduct = {};
295
+ return;
296
+ }
297
+ if (p.id) this._currentViewingProduct.id = (p.id + '').trim();
298
+ if (p.source_id) this._currentViewingProduct.source_id = (p.source_id + '').trim();
299
+ if (p.sku) this._currentViewingProduct.sku = (p.sku + '').trim();
300
+ }
301
+ getTrackPageview() {
302
+ return this._track_page_view;
303
+ }
304
+ setTrackPageview(val) {
305
+ this._track_page_view = !!val;
306
+ }
307
+ getLinkedProduct() {
308
+ return _index.default.cloneDeep(this._currentViewingProduct);
309
+ }
310
+ isInsync(key) {
311
+ return _index.default.Date.now() - (this.g_sync[key] || 0) < 600000;
312
+ }
313
+ async fetchShippingAddresses() {
314
+ let out = await this.api.fetchShippingAddresses();
315
+ if (out.error) return null;
316
+ this.cache.put('shipping_address', out.body.shipping_addresses);
317
+ }
318
+ matchShippingAddresses() {
319
+ return this.cache.match('shipping_address');
320
+ }
321
+ updateOrder(order) {
322
+ return this.api.updateOrder(order);
323
+ }
324
+ createShippingAddress(addr) {
325
+ return this.api.createShippingAddress(addr);
326
+ }
327
+ createTicket(ticket) {
328
+ return this.api.create_ticket(ticket);
329
+ }
330
+ async overrideAcc(acc) {
331
+ this.forceAcc = _index.default.cloneDeep(acc);
332
+ await this.readyGate.entry();
333
+ this.reconnect();
334
+ }
335
+ async overrideChatbox(chatbox) {
336
+ this.forceChatbox = chatbox;
337
+ await this.readyGate.entry();
338
+ await this.reconnect();
339
+ _index.default.setTimeout(this.pubsub.publish('resetCSS'), 10);
340
+ }
341
+ getDeviceInfo() {
342
+ let device = {
343
+ screen_resolution: window.screen.width + 'x' + window.screen.height,
344
+ source_referrer: document.referrer,
345
+ platform: window.navigator.platform,
346
+ language: navigator.language,
347
+ page_url: document.URL,
348
+ page_title: document.title
349
+ };
350
+ let ga_client_id = getGaClientId();
351
+ if (ga_client_id) device.ga_client_id = ga_client_id;
352
+ let ga_tracking_ids = getGaTrackingIds();
353
+ if (ga_tracking_ids.length > 0) device.ga_tracking_ids = ga_tracking_ids;
354
+ return device;
355
+ }
356
+ highlight(pluginid, ref) {
357
+ this.pubsub.publish('highlight', pluginid, ref);
358
+ }
359
+ emitConvoEvent(ev) {
360
+ this.pubsub.publish('events', ev);
361
+ }
362
+ setAIDevMode(mode) {
363
+ this.ai_dev_mode = mode;
364
+ }
365
+ isAIDevMode() {
366
+ return this.ai_dev_mode;
367
+ }
368
+ overrideDeviceType(type) {
369
+ this.forceDevice = type;
370
+ this.pubsub.publish('account');
371
+ }
372
+ isMobile() {
373
+ if (this.forceDevice) return this.forceDevice === 'mobile';
374
+ return this.device_type == 'mobile' || _index.default.get(window, 'screen.width', 1000) < 576;
375
+ }
376
+ isTablet() {
377
+ if (this.forceDevice) return this.forceDevice === 'tablet';
378
+ return this.device_type == 'tablet';
379
+ }
380
+ isDesktop() {
381
+ if (this.forceDevice) return this.forceDevice === 'desktop';
382
+ return !this.isMobile() && !this.isTable();
383
+ }
384
+ disconnect(key) {
385
+ this.g_sync[key] = 0;
386
+ }
387
+ pageLoaded() {
388
+ return page_loaded;
389
+ }
390
+ overridePlugin(plugins) {
391
+ if (this._die) return dieErr;
392
+ if (!Array.isArray(plugins)) throw 'plugins must be be an array';
393
+ let pluginM = {};
394
+ _index.default.map(plugins, function (plugin) {
395
+ pluginM[plugin.id] = plugin;
396
+ });
397
+ this.forcePlugins = pluginM;
398
+ this.pubsub.publish('account');
399
+ this.pubsub.publish('resetCSS');
400
+ }
401
+ markSync(key) {
402
+ this.g_sync[key] = _index.default.Date.now();
403
+ }
404
+ async _touchAcc() {
405
+ if (this.isInsync('account')) return;
406
+ await this.readyGate.entry();
407
+ if (!this.isInsync('account')) this.reconnect();
408
+ }
409
+ async init(accid, mask, userRef, options) {
410
+ this.readyGate.close();
411
+ accid = (accid || '').trim();
412
+ this.g_sync = {};
413
+ if (!options || !options.use_subdomain_cookie) {
414
+ if (window && window.location && window.location.hostname) {
415
+ cookie.defaults.domain = '.' + window.location.hostname;
416
+ }
417
+ }
418
+ if (!userRef) {
419
+ try {
420
+ userRef = this.cookie.get('__sbref', '');
421
+ } catch (e) {}
422
+ if (!userRef) {
423
+ if (!mask) {
424
+ try {
425
+ mask = this.cookie.get('__sbmask', '');
426
+ } catch (e) {}
427
+ }
428
+ if (mask) {
429
+ let parts = mask.split('@');
430
+ if (parts[0] != accid) {
431
+ userRef = _index.default.randomString(40);
432
+ this.new_visitor = true;
433
+ }
434
+ this.new_visitor = false;
435
+ this.cookie.set('__sbmask', mask);
436
+ } else {
437
+ userRef = _index.default.randomString(40);
438
+ this.new_visitor = true;
439
+ }
440
+ }
441
+ }
442
+ if (this.cookie.get('__sbref', userRef) != userRef) cleanMyLocalStorage();
443
+ this.api.setAuth({
444
+ accid: accid
445
+ });
446
+ if (userRef) this.cookie.set('__sbref', userRef);
447
+ let user = await this.api.setAuth({
448
+ accid: accid,
449
+ mask: mask,
450
+ ref: userRef
451
+ });
452
+ if (user.error) return console.error(user);
453
+ if (this.realtime) this.realtime.stop();
454
+ if (this.fake) this.realtime = new _realtime_fake.default();else this.realtime = new Realtime(this.RealtimeURL, {
455
+ account_id: accid,
456
+ user_ref: userRef,
457
+ user_mask: mask
458
+ }, xhrsend);
459
+ this.realtime.onEvent(this.onWs.bind(this));
460
+ this.realtime.onInterrupted(async () => {
461
+ await this.reconnectWs(accid, user.id);
462
+ this.reconnect();
463
+ });
464
+ this.seenLoop();
465
+ await this.reconnect({
466
+ user: user
467
+ });
468
+ this.readyGate.open();
469
+ this.reconnectWs(accid, user.id);
470
+ this.loopCheckConnectionStatus();
471
+ return user;
472
+ }
473
+ async login(accid, user_id, tokenGenerator) {
474
+ if (this._die) return dieErr;
475
+ let user = await this.api.setAuth({
476
+ accid: accid,
477
+ profile_id: user_id,
478
+ tokenGenerator: tokenGenerator
479
+ });
480
+ if (user.error) return user;
481
+ this.clearBrowserData();
482
+ this.readyGate.close();
483
+ accid = (accid || '').trim();
484
+ this.g_sync = {};
485
+ this.new_visitor = false;
486
+ if (this.realtime) this.realtime.stop();
487
+ if (this.fake) this.realtime = new _realtime_fake.default();else this.realtime = new Realtime(this.RealtimeURL, {
488
+ getAccessToken: () => this.api.token_generator()
489
+ });
490
+ this.realtime.onEvent(this.onWs.bind(this));
491
+ this.realtime.onInterrupted(async () => {
492
+ await this.reconnectWs(accid, user.id);
493
+ this.reconnect();
494
+ });
495
+ this.seenLoop();
496
+ await this.reconnect();
497
+ this.readyGate.open();
498
+ this.reconnectWs(accid, user.id);
499
+ return user;
500
+ }
501
+ logout(userRef) {
502
+ return this.api.setAuth({
503
+ ref: userRef
504
+ });
505
+ }
506
+ seenLoop() {
507
+ this.seenQueue = [];
508
+ _index.default.clearInterval(this._seenInterval);
509
+ this._seenInterval = _index.default.setInterval(() => {
510
+ if (this._die) return _index.default.clearInterval(this._seenInterval);
511
+ this.seenQueue = [...new Set(this.seenQueue)];
512
+ let user = this.cache.match('user') || {};
513
+ _index.default.map(this.seenQueue, id => {
514
+ var events = this.listEvents(id);
515
+ if (!events) return;
516
+ if (_index.default.size(events) === 0) return;
517
+ events = _index.default.filter(events, ev => ev.type === 'message_sent');
518
+ var lastmsgsent = events[_index.default.size(events) - 1];
519
+ if (!lastmsgsent) return;
520
+ if (this.g_haveSentSeenM[lastmsgsent.id]) return;
521
+ if (lastmsgsent.id === lastmsgsent.data.message.idempotency_key) return;
522
+ this.api.markAsSeen(id, lastmsgsent.id);
523
+ this.pubsub.publish('events', {
524
+ created: _index.default.Date.now(),
525
+ type: 'message_pong',
526
+ by: {
527
+ type: 'user'
528
+ },
529
+ data: {
530
+ message: {
531
+ conversation_id: id,
532
+ id: '*',
533
+ pongs: [{
534
+ type: 'seen',
535
+ created: _index.default.Date.now()
536
+ }]
537
+ }
538
+ }
539
+ });
540
+ let convo = this.cache.match('convo_' + id) || {};
541
+ let mem = _index.default.find(convo.members, m => m.id === user.id);
542
+ if (mem) mem.seen_at = _index.default.Date.now();
543
+ this._setConvo(convo);
544
+ this.g_haveSentSeenM[lastmsgsent.id] = true;
545
+ });
546
+ this.seenQueue = [];
547
+ }, 1000);
548
+ }
549
+ async reconnectWs(accid, userid) {
550
+ await this.realtime.subscribe([`conversation_state_updated.account.${accid}.user.${userid}`, `conversation_joined.account.${accid}.user.${userid}`, `conversation_typing.account.${accid}.user.${userid}`, `message_sent.account.${accid}.user.${userid}`, `message_pong.account.${accid}.user.${userid}`, `conversation_rating_requested.account.${accid}.user.${userid}`, `conversation_rated.account.${accid}.user.${userid}`]);
551
+ await this.readyGate.entry();
552
+ }
553
+ async reconnect(p) {
554
+ if (this._die) return;
555
+ await this.reconnectGate.entry(undefined, true);
556
+ this.markSync('account');
557
+ let fetchuser = p && p.user ? Promise.resolve({
558
+ body: p.user
559
+ }) : this.api.getUser();
560
+ let outs = await Promise.all([fetchuser, this.api.getAccountSetting()]);
561
+ let error = _index.default.find(outs, out => out.error);
562
+ if (error) return console.error(error);
563
+ let set = outs[1].body;
564
+ set.user = outs[0].body;
565
+ await this._setSetting(set);
566
+ let convob = await this.api.listConversations();
567
+ error = convob.error;
568
+ let body = convob.body;
569
+ if (!error) {
570
+ let convos = _index.default.get(body, 'conversations', []);
571
+ _index.default.map(this.cache.all(), (value, k) => {
572
+ if (k.startsWith('convo_')) {
573
+ if (this.now() - _index.default.getMs(_index.default.get(value, 'actived')) > 1209600000) this.cache.del(k);
574
+ }
575
+ });
576
+ _index.default.map(convos, convo => this._setConvo(convo));
577
+ }
578
+ return this.reconnectGate.open();
579
+ }
580
+ async submitForm(formid, data, user) {
581
+ await this.readyGate.entry();
582
+ if (user) await this.setUser(user);
583
+ return this.api.submitForm(formid, document.URL, this.device, data, user);
584
+ }
585
+ async setUser(user) {
586
+ if (!user) return;
587
+ await this.readyGate.entry();
588
+ this._setUser(user);
589
+ return this.api.updateUser(user);
590
+ }
591
+ async setUserDiff(user) {
592
+ if (!user) return;
593
+ await this.readyGate.entry();
594
+ let out = await this.api.updateUser(user);
595
+ if (out && out.code == 200 && out.body.id) {
596
+ this._setUser(out.body);
597
+ }
598
+ }
599
+ _setUser(user) {
600
+ user = _index.default.cloneDeep(user);
601
+ let olduser = this.cache.match('user') || {};
602
+ var accid = olduser.account_id || user.account_id;
603
+ var id = olduser.id || user.id;
604
+ _index.default.each(user.attributes, newattr => {
605
+ if (!newattr) return;
606
+ olduser.attributes = _index.default.filter(olduser.attributes, oldattr => {
607
+ if (!oldattr) return false;
608
+ return oldattr.key !== newattr.key;
609
+ });
610
+ });
611
+ olduser.attributes = olduser.attributes || [];
612
+ olduser.attributes = olduser.attributes.concat(user.attributes);
613
+ olduser.account_id = accid;
614
+ olduser.id = id;
615
+ this.cache.put('user', olduser);
616
+ this.pubsub.publish('account');
617
+ }
618
+ async setSetting(setting) {
619
+ if (!setting) return;
620
+ await this.readyGate.entry();
621
+ return this._setSetting(setting);
622
+ }
623
+ async _setSetting(setting) {
624
+ setting = _index.default.cloneDeep(setting) || {};
625
+ setting.account = Object.assign({}, setting.account, this.forceAcc);
626
+ if (!setting.account.logo_url) {
627
+ setting.account.logo_url = 'https://vcdn.subiz-cdn.com/file/fiqpezhkmeyesdscyetk-default_logo.jpg';
628
+ }
629
+ if (setting.user) {
630
+ setting.user.account_id = setting.account.id;
631
+ delete setting.user.session;
632
+ this._setUser(setting.user);
633
+ }
634
+ if (setting.account) {
635
+ setting.account.is_online = setting.is_online;
636
+ setting.account.is_in_business_hour = setting.is_in_business_hour;
637
+ this.cache.put('account', setting.account);
638
+ delete setting.account;
639
+ }
640
+ let location = _index.default.get(setting, 'location', []);
641
+ this.cache.put('location', location);
642
+ let bots = _index.default.get(setting, 'bots', []);
643
+ let botM = {};
644
+ _index.default.map(bots, bot => {
645
+ botM[bot.id] = bot;
646
+ });
647
+ this.cache.put('bot', botM);
648
+ this.device_type = setting.device_type || 'desktop';
649
+ let plugins = _index.default.get(setting, 'plugins', []);
650
+ let pluginM = {};
651
+ _index.default.map(plugins, plugin => {
652
+ if (plugin.type === 'chatbox') {
653
+ plugin = _index.default.merge(plugin, this.forceChatbox);
654
+ }
655
+ pluginM[plugin.id] = plugin;
656
+ });
657
+ this.cache.put('plugin', pluginM);
658
+ var agents = _index.default.get(setting, 'agents', []);
659
+ if (_index.default.size(agents) > 0) {
660
+ let agentM = {};
661
+ this.api.setAgentId(agents[0].id);
662
+ _index.default.map(agents, agent => {
663
+ agentM[agent.id] = agent;
664
+ });
665
+ this.cache.put('agent', agentM);
666
+ }
667
+ let pms = _index.default.get(setting, 'payment_methods', []);
668
+ this.cache.put('payment_methods', pms);
669
+ this.pubsub.publish('account');
670
+ }
671
+ async track() {
672
+ let out = await this.api.sendContentView(this.device, location.href, document.title, this._currentViewingProduct.id, this._currentViewingProduct.source_id, this._currentViewingProduct.sku);
673
+ let traffic_source = _index.default.get(out, 'body.by.device.source', '');
674
+ if (traffic_source) this.kv.put('traffic_source', traffic_source);
675
+ }
676
+ async onWs(ev) {
677
+ await this.wsGate.entry();
678
+ this.wsGate.close();
679
+ await this._onWs(ev);
680
+ this.wsGate.open();
681
+ }
682
+ async _onWs(ev) {
683
+ if (this._die) return;
684
+ if (!ev || !ev.type) return;
685
+ ev.created = _index.default.getMs(ev.created);
686
+ if (ev.type === 'user_info_updated') {
687
+ return;
688
+ let user = _index.default.cloneDeep(this.cache.match('user'));
689
+ let attrs = _index.default.get(ev, 'data.user.attributes') || [];
690
+ _index.default.map(attrs, attr => _index.default.setUserAttr(user, attr));
691
+ this._setUser(user);
692
+ return;
693
+ }
694
+ let user = this.cache.match('user') || {};
695
+ let cid = _index.default.convoOfEv(ev);
696
+ let convo;
697
+ let alreadyFetched = false;
698
+ if (cid) {
699
+ convo = this.cache.match('convo_' + cid);
700
+ if (!convo || !convo.id) {
701
+ let {
702
+ body: apiconvo,
703
+ error
704
+ } = await this.api.getConversation(cid);
705
+ if (!apiconvo) return;
706
+ convo = apiconvo;
707
+ alreadyFetched = true;
708
+ this._setConvo(convo);
709
+ }
710
+ }
711
+ if (!convo) return;
712
+ this.pubsub.publish('events', ev);
713
+ if (ev.type === 'conversation_joined') {
714
+ let members = _index.default.get(ev, 'data.conversation.members', []);
715
+ let me = _index.default.find(members, m => m.id === this.cache.match('user').id);
716
+ if (me) {
717
+ if (!alreadyFetched) {
718
+ let {
719
+ body: apiconvo
720
+ } = await this.api.getConversation(cid);
721
+ if (apiconvo) {
722
+ convo = apiconvo;
723
+ this._setConvo(convo);
724
+ }
725
+ this.pubsub.publish('account');
726
+ }
727
+ }
728
+ }
729
+ if (ev.type === 'message_sent') {
730
+ if (_index.default.get(ev, 'by.id') !== user.id) {
731
+ if (!this._alreadyReceived[ev.id]) {
732
+ this._alreadyReceived[ev.id] = true;
733
+ this.api.markAsReceived(cid, ev.id);
734
+ }
735
+ }
736
+ }
737
+ if (_index.default.startsWith(ev.type, 'message_') || _index.default.startsWith(ev.type, 'conversation_')) {
738
+ this.restConvoEvent(ev);
739
+ if (ev.type === 'message_sent' && _index.default.get(ev, 'by.id') !== user.id) {
740
+ sendEventToThirdParty('SUBIZ Chat', 'Received', 'User');
741
+ }
742
+ return;
743
+ }
744
+ }
745
+ async restConvoEvent(ev) {
746
+ let user = this.cache.match('user');
747
+ let cid = _index.default.convoOfEv(ev);
748
+ let convo = this.cache.match('convo_' + cid) || {};
749
+ if (ev.type === 'conversation_state_updated') {
750
+ if (!_index.default.get(convo, 'id')) {
751
+ let {
752
+ body: convo,
753
+ error
754
+ } = await this.api.getConversation(cid);
755
+ if (error) return;
756
+ }
757
+ convo = Object.assign(convo, _index.default.get(ev, 'data.conversation'));
758
+ }
759
+ if (ev.type === 'message_pong') {
760
+ var msgid = _index.default.get(ev, 'data.message.id');
761
+ var oldev = this.chain.match(cid, msgid);
762
+ if (!_index.default.get(oldev, 'data.message')) return;
763
+ var pongs = _index.default.get(oldev, 'data.message.pongs', []);
764
+ let newpongs = _index.default.get(ev, 'data.message.pongs', []) || [];
765
+ pongs = pongs.concat(newpongs);
766
+ if (newpongs.length === 1) {
767
+ let pongtype = newpongs[0].type;
768
+ if (pongtype === 'like' || pongtype === 'remove_dislike') {
769
+ pongs = pongs.filter(pong => pong.type !== 'dislike');
770
+ }
771
+ if (pongtype === 'dislike' || pongtype === 'remove_like') {
772
+ pongs = pongs.filter(pong => pong.type !== 'like');
773
+ }
774
+ }
775
+ oldev.data.message.pongs = pongs;
776
+ _index.default.map(pongs, pong => {
777
+ if (pong.member_id == user.id && pong.type === 'seen') {
778
+ let mem = _index.default.find(convo.members, mem => mem.id === user.id);
779
+ if (mem) mem.seen_at = pong.created;
780
+ }
781
+ });
782
+ this.chain.put(cid, oldev.id, _index.default.getMs(oldev.created), oldev);
783
+ this.pubsub.publish('events', oldev);
784
+ }
785
+ if (ev.type === 'message_sent') {
786
+ let idemkey = _index.default.get(ev, 'data.message.idempotency_key');
787
+ let found = _index.default.find(this.listEvents(cid), oldev => oldev.id === idemkey);
788
+ if (found) {
789
+ this.chain.del(cid, found.id);
790
+ ev.created = found.created;
791
+ }
792
+ convo.last_message_sent = ev;
793
+ }
794
+ if (ev.type !== 'message_pong' && ev.type !== 'conversation_typing') {
795
+ this.chain.put(cid, ev.id, _index.default.getMs(ev.created), ev);
796
+ }
797
+ this._setConvo(convo);
798
+ this.pubsub.publish('account');
799
+ }
800
+ emitCloseWidgetEvent() {
801
+ this.pubsub.publish('sbz_close_widget', {
802
+ type: 'chatbox_closed'
803
+ });
804
+ }
805
+ typing(cid) {
806
+ if (!cid) return;
807
+ this._typing(cid);
808
+ }
809
+ async startConvo(req) {
810
+ if (!req) req = {};
811
+ await this.readyGate.entry();
812
+ this.convoGate.close();
813
+ if (!req.source) req.source = document.location.href;
814
+ let {
815
+ body: convo,
816
+ error
817
+ } = await this.api.start(req);
818
+ this.convoGate.open();
819
+ if (error) return {
820
+ error
821
+ };
822
+ this._setConvo(convo);
823
+ return {
824
+ convo
825
+ };
826
+ }
827
+ fetchOrder(id) {
828
+ return this.api.getOrder(id);
829
+ }
830
+ lookupOrder(key) {
831
+ return this.api.lookupOrder(key);
832
+ }
833
+ createPostback(cid, postback) {
834
+ return this.api.createPostback(cid, postback);
835
+ }
836
+ sendReaction(cid, ev) {
837
+ return this.api.sendConvoEvent(cid, ev);
838
+ }
839
+ async sendConvoEvent(cid, type, data) {
840
+ await this.readyGate.entry();
841
+ var idempotency = _index.default.randomString(36);
842
+ let user = this.cache.match('user') || {};
843
+ var event = {
844
+ id: idempotency,
845
+ by: {
846
+ id: user.id,
847
+ type: 'user',
848
+ device: this.device
849
+ },
850
+ data,
851
+ type,
852
+ created: this.now()
853
+ };
854
+ _index.default.convoToEv(cid, event);
855
+ let files = [];
856
+ if (type === 'message_sent') {
857
+ event.data.message.idempotency_key = idempotency;
858
+ event.data.message.conversation_id = cid;
859
+ await flow.map(event.data.message.attachments, 2, async (att, i) => {
860
+ if (att.type !== 'file') return;
861
+ if (!att._file) return;
862
+ files.push(att);
863
+ if (ImageTypes.includes(att._file.type)) {
864
+ let {
865
+ width,
866
+ height,
867
+ url
868
+ } = await loadImage(att._file);
869
+ att.url = url;
870
+ att.width = width;
871
+ att.height = height;
872
+ }
873
+ });
874
+ }
875
+ this.onWs(event);
876
+ await this.convoGate.entry();
877
+ await flow.map(files, 1, async att => {
878
+ const {
879
+ body,
880
+ url,
881
+ error
882
+ } = await this.api.uploadToS3(att._file);
883
+ if (_index.default.get(body, 'code') == 'invalid_field_size') {
884
+ event._error_message = 'cannot_send_too_big_file';
885
+ }
886
+ event._error = error;
887
+ att.url = url;
888
+ });
889
+ if (event._error) return this.onWs(event);
890
+ let {
891
+ body: ret,
892
+ error
893
+ } = await this.api.sendConvoEvent(cid, event);
894
+ if (error) {
895
+ event._error = error;
896
+ this.onWs(event);
897
+ return;
898
+ }
899
+ this.onWs(ret);
900
+ sendEventToThirdParty('SUBIZ Chat', 'Sent', 'User');
901
+ let lastMsgSent = this.kv.match('last_msg_sent');
902
+ if (!lastMsgSent) {
903
+ let dataLayer = window.dataLayer || [];
904
+ dataLayer.push({
905
+ event: 'SUBIZ Chat',
906
+ event_action: 'Sent',
907
+ event_label: 'User',
908
+ first_interaction: 1
909
+ });
910
+ }
911
+ this.kv.put('last_msg_sent', _index.default.Date.now());
912
+ return ret;
913
+ }
914
+ _setConvo(convo) {
915
+ let count = 0;
916
+ let user = this.cache.match('user');
917
+ let channel = _index.default.get(convo, 'touchpoint.channel', '');
918
+ if (channel && channel != 'subiz') return;
919
+ let allconvo = {};
920
+ _index.default.map(this.cache.all(), (value, key) => {
921
+ if (key.startsWith('convo_')) {
922
+ allconvo[key] = value;
923
+ }
924
+ });
925
+ if (_index.default.size(allconvo) > MAX_CONVO - 2) {
926
+ allconvo = _index.default.orderBy(_index.default.map(allconvo), 'created', 'desc');
927
+ for (var i = MAX_CONVO - 2; i < _index.default.size(allconvo); i++) {
928
+ let convo = allconvo[i];
929
+ this.cache.del('convo_' + convo.id);
930
+ }
931
+ }
932
+ this.markSync(convo.id);
933
+ this.pubsub.publish('account');
934
+ this.cache.put('convo_' + convo.id, convo);
935
+ }
936
+ matchLastPluginRun(pluginid) {
937
+ let log = this.kv.match('plugin_run_logs') || {};
938
+ return log[pluginid];
939
+ }
940
+ matchLastBotRun(botid) {
941
+ let log = this.kv.match('bot_run_logs') || {};
942
+ return log[botid];
943
+ }
944
+ logBotRun(botid) {
945
+ let log = this.kv.match('bot_run_logs') || {};
946
+ log[botid] = {
947
+ bot_id: botid,
948
+ created: this.now()
949
+ };
950
+ this.kv.put('bot_run_logs', log);
951
+ }
952
+ sendImpression(id) {
953
+ let user = this.cache.match('user') || {};
954
+ let log = this.kv.match('plugin_run_logs') || {};
955
+ log[id] = {
956
+ web_plugin_id: id,
957
+ created: this.now()
958
+ };
959
+ this.kv.put('plugin_run_logs', log);
960
+ return this.api.sendImpression({
961
+ account_id: user.account_id,
962
+ campaign_id: id,
963
+ web_plugin_id: id,
964
+ user_id: user.id,
965
+ url: window.location.href,
966
+ device: this.device
967
+ });
968
+ }
969
+ sendConversion(id, fields, impressionToken) {
970
+ let user = this.cache.match('user') || {};
971
+ let submission = {
972
+ account_id: user.account_id,
973
+ user_id: user.id,
974
+ fields: fields
975
+ };
976
+ let conv = this.kv.match('conversions') || {};
977
+ conv[id] = true;
978
+ this.kv.put('conversions', conv);
979
+ return this.api.sendConversion({
980
+ account_id: user.account_id,
981
+ web_plugin_id: id,
982
+ campaign_id: id,
983
+ user_id: _index.default.get(user, 'id'),
984
+ url: window.location.href,
985
+ device: this.device,
986
+ submission,
987
+ impression_token: impressionToken
988
+ });
989
+ }
990
+ isConverted(id) {
991
+ let conv = this.kv.match('conversions') || {};
992
+ return conv[id];
993
+ }
994
+ async listmessageapi(type, anchor, limit) {
995
+ let convoid = type;
996
+ let {
997
+ body: events,
998
+ code,
999
+ error
1000
+ } = await this.api.listMessages(convoid, -limit, anchor);
1001
+ if (error || code !== 200) return [[], anchor, error];
1002
+ anchor = _index.default.get(_index.default.last(events), 'id');
1003
+ events = _index.default.map(events, event => {
1004
+ event.created = _index.default.getMs(event.created);
1005
+ return {
1006
+ id: event.id,
1007
+ index: event.created,
1008
+ value: event
1009
+ };
1010
+ });
1011
+ let user = this.cache.match('user') || {};
1012
+ for (let i = 0; i < events.length; i++) {
1013
+ let ev = events[i].value;
1014
+ if (ev.type !== 'message_sent') continue;
1015
+ if (_index.default.get(ev, 'by.id') === user.id) continue;
1016
+ let pongbyme = _index.default.find(_index.default.get(ev, 'data.message.pongs'), p => p.member_id === user.id);
1017
+ if (pongbyme) break;
1018
+ if (!this._alreadyReceived[ev.id]) {
1019
+ this._alreadyReceived[ev.id] = true;
1020
+ this.api.markAsReceived(convoid, ev.id);
1021
+ }
1022
+ break;
1023
+ }
1024
+ let outofmsg = _index.default.size(events) < limit;
1025
+ return [events, anchor, undefined, outofmsg];
1026
+ }
1027
+ async loopTime() {
1028
+ if (this._die) return;
1029
+ let startms = _index.default.Date.now();
1030
+ if (!_index.default.get(this.cache.match('user'), 'id')) return _index.default.setTimeout(() => this.loopTime(), 240000);
1031
+ let {
1032
+ body: t,
1033
+ error
1034
+ } = await this.api.time();
1035
+ if (error) return _index.default.setTimeout(() => this.loopTime(), 30000);
1036
+ var latences = Math.abs(_index.default.Date.now() - startms) / 2;
1037
+ var serverMs = new _index.default.Date(t).getTime() + latences;
1038
+ var localMs = _index.default.Date.now();
1039
+ this.timeDiff = Math.floor(serverMs - localMs);
1040
+ _index.default.setTimeout(() => this.loopTime(), 240000);
1041
+ }
1042
+ replaceFileUrl(src) {
1043
+ if (!src) return '';
1044
+ if (_index.default.startsWith(src, '/')) return src;
1045
+ if (_index.default.startsWith(src, 'data:')) return src;
1046
+ if (!_index.default.startsWith(src, 'http://') && !_index.default.startsWith(src, 'https://') && !_index.default.startsWith(src, '//')) {
1047
+ src = _index.default.trim(this.FileURL, '/') + '/' + _index.default.trimStart(src, '/');
1048
+ }
1049
+ src = src.replace('https://file-subiz.com/', this.FileURL);
1050
+ src = src.replace('http://file-subiz.com/', this.FileURL);
1051
+ src = src.replace('https://file-v4.subiz.com/', this.FileURL);
1052
+ src = src.replace('http://file-v4.subiz.com/', this.FileURL);
1053
+ src = src.replace('https://filev4.subiz.com/', this.FileURL);
1054
+ src = src.replace('http://filev4.subiz.com/', this.FileURL);
1055
+ src = src.replace('https://filev4-1.subiz.com/', this.FileURL);
1056
+ src = src.replace('http://filev4-1.subiz.com/', this.FileURL);
1057
+ src = src.replace('https://file.subiz.com/', this.FileURL);
1058
+ src = src.replace('http://file.subiz.com/', this.FileURL);
1059
+ src = src.replace('https://file.mysubiz.com/', this.FileURL);
1060
+ src = src.replace('http://file.mysubiz.com/', this.FileURL);
1061
+ return src;
1062
+ }
1063
+ clearBrowserData() {
1064
+ _index.default.each(this.cookie.all(), (v, k) => {
1065
+ if ((k || '').startsWith('__sb')) this.cookie.remove(k);
1066
+ });
1067
+ this.kv.destroy();
1068
+ this.kv = new _kv.default(new _lsdb.default('sbz2023', this.inmem), 'kv');
1069
+ this.chain.destroy();
1070
+ this.chain = new _chain.default(new _lsdb.default('cbz2023', true), 'ch');
1071
+ }
1072
+ destroy() {
1073
+ this._die = true;
1074
+ if (this.kv) this.kv.destroy();
1075
+ if (this.chain) this.chain.destroy();
1076
+ _index.default.clearInterval(this._seenInterval);
1077
+ if (this.realtime) this.realtime.stop();
1078
+ this.readyGate.close();
1079
+ window.removeEventListener('blur', this.sendPresence);
1080
+ window.removeEventListener('focus', this.sendPresence);
1081
+ }
1082
+ }
1083
+ exports.default = Store;
1084
+ function loadImage(file) {
1085
+ return new Promise(rs => {
1086
+ var reader = new window.FileReader();
1087
+ reader.onload = e => {
1088
+ let src = e.target.result;
1089
+ let img = new Image();
1090
+ img.onload = () => {
1091
+ rs({
1092
+ url: src,
1093
+ width: img.width,
1094
+ height: img.height
1095
+ });
1096
+ };
1097
+ img.src = src;
1098
+ };
1099
+ reader.readAsDataURL(file);
1100
+ });
1101
+ }
1102
+ const ImageTypes = ['image/gif', 'image/jpeg', 'image/png', 'image/svg+xml'];
1103
+ function onVisibilityChange(cb) {
1104
+ var hidden = 'hidden';
1105
+ if (hidden in document) document.addEventListener('visibilitychange', onchange);else if ((hidden = 'mozHidden') in document) document.addEventListener('mozvisibilitychange', onchange);else if ((hidden = 'webkitHidden') in document) document.addEventListener('webkitvisibilitychange', onchange);else if ((hidden = 'msHidden') in document) document.addEventListener('msvisibilitychange', onchange);else if ('onfocusin' in document) document.onfocusin = document.onfocusout = onchange;else window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
1106
+ function onchange(evt) {
1107
+ var v = 'visible';
1108
+ var h = 'hidden';
1109
+ var evtMap = {
1110
+ focus: v,
1111
+ focusin: v,
1112
+ pageshow: v,
1113
+ blur: h,
1114
+ focusout: h,
1115
+ pagehide: h
1116
+ };
1117
+ evt = evt || window.event;
1118
+ if (evt.type in evtMap) cb(evtMap[evt.type]);else cb(this[hidden] ? 'hidden' : 'visible');
1119
+ }
1120
+ if (document[hidden] !== undefined) onchange({
1121
+ type: document[hidden] ? 'blur' : 'focus'
1122
+ });
1123
+ }
1124
+ const inmemCookie = {
1125
+ data: {},
1126
+ get(k, def) {
1127
+ return this.data[k] || def;
1128
+ },
1129
+ set(k, v) {
1130
+ return this.data[k] = k;
1131
+ },
1132
+ all() {
1133
+ return this.data;
1134
+ },
1135
+ remove(k) {
1136
+ delete this.data[k];
1137
+ }
1138
+ };
1139
+ function getGaClientId() {
1140
+ if (!window.ga) return;
1141
+ if (!window.ga.getAll) return;
1142
+ var allTrackers = window.ga.getAll() || [];
1143
+ let ga_client_id = '';
1144
+ allTrackers.forEach(function (tracker) {
1145
+ ga_client_id = tracker.get('clientId');
1146
+ });
1147
+ return ga_client_id;
1148
+ }
1149
+ function getGaTrackingIds() {
1150
+ var trackingIds = [];
1151
+ if (!(window.ga && window.ga.getAll)) return trackingIds;
1152
+ if (!window.ga) return [];
1153
+ if (!window.ga.getAll) return [];
1154
+ const allTrackers = window.ga.getAll() || [];
1155
+ allTrackers.forEach(function (tracker) {
1156
+ var trackingId = tracker.get('trackingId');
1157
+ if (trackingId) trackingIds.push(trackingId);
1158
+ });
1159
+ return trackingIds;
1160
+ }
1161
+ function sendToFBPixel(category, action, label) {
1162
+ if (!window.fbq) return;
1163
+ window.fbq('trackCustom', category, {
1164
+ action: action,
1165
+ label: label
1166
+ });
1167
+ }
1168
+ function sendToGA(category, action, label) {
1169
+ if (window.sbz_no_gtag) {
1170
+ console.log('SKIPSENT.', category, action, label);
1171
+ return;
1172
+ }
1173
+ let dataLayer = window.dataLayer || [];
1174
+ dataLayer.push({
1175
+ event: category,
1176
+ event_action: action,
1177
+ event_label: label
1178
+ });
1179
+ if (window.gtag) window.gtag('event', category, {
1180
+ Action: action,
1181
+ Label: label
1182
+ });
1183
+ if (window.ga && window.ga.getAll) {
1184
+ const allTrackers = window.ga.getAll() || [];
1185
+ allTrackers.forEach(function (tracker) {
1186
+ const name = tracker.get('name');
1187
+ window.ga(name + '.send', 'event', category, action, label);
1188
+ });
1189
+ }
1190
+ }
1191
+ function sendEventToThirdParty(category, action, label) {
1192
+ document.dispatchEvent(new CustomEvent('subiz', {
1193
+ detail: {
1194
+ category,
1195
+ action,
1196
+ label
1197
+ }
1198
+ }));
1199
+ sendToGA(category, action, label);
1200
+ sendToFBPixel(category, action, label);
1201
+ }
1202
+ let cleanLocalStorage = () => {
1203
+ try {
1204
+ localStorage;
1205
+ } catch (e) {
1206
+ return;
1207
+ }
1208
+ _index.default.setTimeout(() => {
1209
+ for (var key in localStorage) {
1210
+ if (key && (key.startsWith('cbz2020') || key.startsWith('sbz2020'))) {
1211
+ localStorage.removeItem(key);
1212
+ }
1213
+ }
1214
+ });
1215
+ };
1216
+ let cleanMyLocalStorage = () => {
1217
+ try {
1218
+ localStorage;
1219
+ } catch (e) {
1220
+ return;
1221
+ }
1222
+ _index.default.setTimeout(() => {
1223
+ for (var key in localStorage) {
1224
+ if (key && (key.startsWith('cbz2020') || key.startsWith('sbz2020') || key.startsWith('sbz2022') || key.startsWith('sbz2023'))) {
1225
+ localStorage.removeItem(key);
1226
+ }
1227
+ }
1228
+ });
1229
+ };
1230
+ function dofetch(method, url, body, cb) {
1231
+ let headers = {};
1232
+ if (body) headers['content-type'] = 'text/plain';
1233
+ fetch(url, {
1234
+ method: method,
1235
+ headers: headers,
1236
+ body: body
1237
+ }).then(res => res.text().then(text => cb && cb(text, res.status))).catch(err => cb && cb(err, -1));
1238
+ }
1239
+ var xhrsend = function (method, url, body, cb) {
1240
+ if (typeof _index.default.XMLHttpRequest === 'undefined') return dofetch(method, url, body, cb);
1241
+ var request = new _index.default.XMLHttpRequest();
1242
+ request.onreadystatechange = function (e) {
1243
+ if (request.readyState !== 4) return;
1244
+ cb && cb(request.responseText, request.status);
1245
+ cb = undefined;
1246
+ };
1247
+ request.onerror = function () {
1248
+ cb && cb(request.responseText, -1);
1249
+ cb = undefined;
1250
+ };
1251
+ request.open(method, url);
1252
+ if (body) request.setRequestHeader('content-type', 'text/plain');
1253
+ request.send(body);
1254
+ };
1255
+ const dieErr = new Error('sdk unloaded');