@subiz/widget-v4 4.1.142 → 4.1.143

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