core-outline 1.1.21 → 1.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,7 +4,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var React = require('react');
6
6
  var uuid = require('uuid');
7
- var engine_ioClient = require('engine.io-client');
8
7
 
9
8
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
9
 
@@ -46,6 +45,14 @@ function _asyncToGenerator(n) {
46
45
  });
47
46
  };
48
47
  }
48
+ function _defineProperty(e, r, t) {
49
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
50
+ value: t,
51
+ enumerable: !0,
52
+ configurable: !0,
53
+ writable: !0
54
+ }) : e[r] = t, e;
55
+ }
49
56
  function _iterableToArray(r) {
50
57
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
51
58
  }
@@ -82,6 +89,27 @@ function _nonIterableRest() {
82
89
  function _nonIterableSpread() {
83
90
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
84
91
  }
92
+ function ownKeys(e, r) {
93
+ var t = Object.keys(e);
94
+ if (Object.getOwnPropertySymbols) {
95
+ var o = Object.getOwnPropertySymbols(e);
96
+ r && (o = o.filter(function (r) {
97
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
98
+ })), t.push.apply(t, o);
99
+ }
100
+ return t;
101
+ }
102
+ function _objectSpread2(e) {
103
+ for (var r = 1; r < arguments.length; r++) {
104
+ var t = null != arguments[r] ? arguments[r] : {};
105
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
106
+ _defineProperty(e, r, t[r]);
107
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
108
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
109
+ });
110
+ }
111
+ return e;
112
+ }
85
113
  function _regeneratorRuntime() {
86
114
  _regeneratorRuntime = function () {
87
115
  return e;
@@ -389,6 +417,20 @@ function _slicedToArray(r, e) {
389
417
  function _toConsumableArray(r) {
390
418
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
391
419
  }
420
+ function _toPrimitive(t, r) {
421
+ if ("object" != typeof t || !t) return t;
422
+ var e = t[Symbol.toPrimitive];
423
+ if (void 0 !== e) {
424
+ var i = e.call(t, r || "default");
425
+ if ("object" != typeof i) return i;
426
+ throw new TypeError("@@toPrimitive must return a primitive value.");
427
+ }
428
+ return ("string" === r ? String : Number)(t);
429
+ }
430
+ function _toPropertyKey(t) {
431
+ var i = _toPrimitive(t, "string");
432
+ return "symbol" == typeof i ? i : i + "";
433
+ }
392
434
  function _unsupportedIterableToArray(r, a) {
393
435
  if (r) {
394
436
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
@@ -1419,7 +1461,7 @@ function snapshot(n, options) {
1419
1461
  });
1420
1462
  }
1421
1463
 
1422
- function on$1(type, fn, target = document) {
1464
+ function on(type, fn, target = document) {
1423
1465
  const options = { capture: true, passive: true };
1424
1466
  target.addEventListener(type, fn, options);
1425
1467
  return () => target.removeEventListener(type, fn, options);
@@ -2322,9 +2364,9 @@ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
2322
2364
  trailing: false,
2323
2365
  });
2324
2366
  const handlers = [
2325
- on$1('mousemove', updatePosition, doc),
2326
- on$1('touchmove', updatePosition, doc),
2327
- on$1('drag', updatePosition, doc),
2367
+ on('mousemove', updatePosition, doc),
2368
+ on('touchmove', updatePosition, doc),
2369
+ on('drag', updatePosition, doc),
2328
2370
  ];
2329
2371
  return () => {
2330
2372
  handlers.forEach((h) => h());
@@ -2367,7 +2409,7 @@ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockCl
2367
2409
  .forEach((eventKey) => {
2368
2410
  const eventName = eventKey.toLowerCase();
2369
2411
  const handler = getHandler(eventKey);
2370
- handlers.push(on$1(eventName, handler, doc));
2412
+ handlers.push(on(eventName, handler, doc));
2371
2413
  });
2372
2414
  return () => {
2373
2415
  handlers.forEach((h) => h());
@@ -2396,7 +2438,7 @@ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector,
2396
2438
  });
2397
2439
  }
2398
2440
  }, sampling.scroll || 100);
2399
- return on$1('scroll', updatePosition, doc);
2441
+ return on('scroll', updatePosition, doc);
2400
2442
  }
2401
2443
  function initViewportResizeObserver({ viewportResizeCb, }) {
2402
2444
  let lastH = -1;
@@ -2413,7 +2455,7 @@ function initViewportResizeObserver({ viewportResizeCb, }) {
2413
2455
  lastW = width;
2414
2456
  }
2415
2457
  }, 200);
2416
- return on$1('resize', updateDimension, window);
2458
+ return on('resize', updateDimension, window);
2417
2459
  }
2418
2460
  function wrapEventWithUserTriggeredFlag(v, enable) {
2419
2461
  const value = Object.assign({}, v);
@@ -2481,7 +2523,7 @@ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ig
2481
2523
  }
2482
2524
  }
2483
2525
  const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
2484
- const handlers = events.map((eventName) => on$1(eventName, eventHandler, doc));
2526
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
2485
2527
  const currentWindow = doc.defaultView;
2486
2528
  if (!currentWindow) {
2487
2529
  return () => {
@@ -2775,11 +2817,11 @@ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSel
2775
2817
  });
2776
2818
  }, sampling.media || 500);
2777
2819
  const handlers = [
2778
- on$1('play', handler(0)),
2779
- on$1('pause', handler(1)),
2780
- on$1('seeked', handler(2)),
2781
- on$1('volumechange', handler(3)),
2782
- on$1('ratechange', handler(4)),
2820
+ on('play', handler(0)),
2821
+ on('pause', handler(1)),
2822
+ on('seeked', handler(2)),
2823
+ on('volumechange', handler(3)),
2824
+ on('ratechange', handler(4)),
2783
2825
  ];
2784
2826
  return () => {
2785
2827
  handlers.forEach((h) => h());
@@ -2853,7 +2895,7 @@ function initSelectionObserver(param) {
2853
2895
  selectionCb({ ranges });
2854
2896
  };
2855
2897
  updateSelection();
2856
- return on$1('selectionchange', updateSelection);
2898
+ return on('selectionchange', updateSelection);
2857
2899
  }
2858
2900
  function mergeHooks(o, hooks) {
2859
2901
  const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
@@ -3329,9 +3371,9 @@ function __awaiter(thisArg, _arguments, P, generator) {
3329
3371
  */
3330
3372
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3331
3373
  // Use a lookup table to find the index.
3332
- var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3374
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3333
3375
  for (var i = 0; i < chars.length; i++) {
3334
- lookup$1[chars.charCodeAt(i)] = i;
3376
+ lookup[chars.charCodeAt(i)] = i;
3335
3377
  }
3336
3378
  var encode = function (arraybuffer) {
3337
3379
  var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
@@ -4174,7 +4216,7 @@ function record(options = {}) {
4174
4216
  };
4175
4217
  try {
4176
4218
  const handlers = [];
4177
- handlers.push(on$1('DOMContentLoaded', () => {
4219
+ handlers.push(on('DOMContentLoaded', () => {
4178
4220
  wrappedEmit(wrapEvent({
4179
4221
  type: EventType.DomContentLoaded,
4180
4222
  data: {},
@@ -4277,7 +4319,7 @@ function record(options = {}) {
4277
4319
  init();
4278
4320
  }
4279
4321
  else {
4280
- handlers.push(on$1('load', () => {
4322
+ handlers.push(on('load', () => {
4281
4323
  wrappedEmit(wrapEvent({
4282
4324
  type: EventType.Load,
4283
4325
  data: {},
@@ -4317,2250 +4359,334 @@ record.takeFullSnapshot = (isCheckout) => {
4317
4359
  };
4318
4360
  record.mirror = mirror;
4319
4361
 
4320
- /**
4321
- * URL parser.
4322
- *
4323
- * @param uri - url
4324
- * @param path - the request path of the connection
4325
- * @param loc - An object meant to mimic window.location.
4326
- * Defaults to window.location.
4327
- * @public
4328
- */
4329
- function url(uri, path = "", loc) {
4330
- let obj = uri;
4331
- // default to window.location
4332
- loc = loc || (typeof location !== "undefined" && location);
4333
- if (null == uri)
4334
- uri = loc.protocol + "//" + loc.host;
4335
- // relative path support
4336
- if (typeof uri === "string") {
4337
- if ("/" === uri.charAt(0)) {
4338
- if ("/" === uri.charAt(1)) {
4339
- uri = loc.protocol + uri;
4340
- }
4341
- else {
4342
- uri = loc.host + uri;
4343
- }
4344
- }
4345
- if (!/^(https?|wss?):\/\//.test(uri)) {
4346
- if ("undefined" !== typeof loc) {
4347
- uri = loc.protocol + "//" + uri;
4348
- }
4349
- else {
4350
- uri = "https://" + uri;
4351
- }
4352
- }
4353
- // parse
4354
- obj = engine_ioClient.parse(uri);
4355
- }
4356
- // make sure we treat `localhost:80` and `localhost` equally
4357
- if (!obj.port) {
4358
- if (/^(http|ws)$/.test(obj.protocol)) {
4359
- obj.port = "80";
4360
- }
4361
- else if (/^(http|ws)s$/.test(obj.protocol)) {
4362
- obj.port = "443";
4363
- }
4364
- }
4365
- obj.path = obj.path || "/";
4366
- const ipv6 = obj.host.indexOf(":") !== -1;
4367
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
4368
- // define unique id
4369
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
4370
- // define href
4371
- obj.href =
4372
- obj.protocol +
4373
- "://" +
4374
- host +
4375
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
4376
- return obj;
4377
- }
4378
-
4379
- /**
4380
- * Initialize a new `Emitter`.
4381
- *
4382
- * @api public
4383
- */
4384
-
4385
- function Emitter(obj) {
4386
- if (obj) return mixin(obj);
4387
- }
4388
-
4389
- /**
4390
- * Mixin the emitter properties.
4391
- *
4392
- * @param {Object} obj
4393
- * @return {Object}
4394
- * @api private
4395
- */
4396
-
4397
- function mixin(obj) {
4398
- for (var key in Emitter.prototype) {
4399
- obj[key] = Emitter.prototype[key];
4362
+ var ANON_ID_KEY = 'co_anon_id';
4363
+ var SESSION_ID_KEY = 'co_session_id';
4364
+ function getAnonymousId() {
4365
+ var id = localStorage.getItem(ANON_ID_KEY);
4366
+ if (!id) {
4367
+ id = uuid.v4();
4368
+ localStorage.setItem(ANON_ID_KEY, id);
4400
4369
  }
4401
- return obj;
4370
+ return id;
4402
4371
  }
4403
-
4404
- /**
4405
- * Listen on the given `event` with `fn`.
4406
- *
4407
- * @param {String} event
4408
- * @param {Function} fn
4409
- * @return {Emitter}
4410
- * @api public
4411
- */
4412
-
4413
- Emitter.prototype.on =
4414
- Emitter.prototype.addEventListener = function(event, fn){
4415
- this._callbacks = this._callbacks || {};
4416
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
4417
- .push(fn);
4418
- return this;
4419
- };
4420
-
4421
- /**
4422
- * Adds an `event` listener that will be invoked a single
4423
- * time then automatically removed.
4424
- *
4425
- * @param {String} event
4426
- * @param {Function} fn
4427
- * @return {Emitter}
4428
- * @api public
4429
- */
4430
-
4431
- Emitter.prototype.once = function(event, fn){
4432
- function on() {
4433
- this.off(event, on);
4434
- fn.apply(this, arguments);
4372
+ function getSessionId() {
4373
+ var id = sessionStorage.getItem(SESSION_ID_KEY);
4374
+ if (!id) {
4375
+ id = uuid.v4();
4376
+ sessionStorage.setItem(SESSION_ID_KEY, id);
4435
4377
  }
4436
-
4437
- on.fn = fn;
4438
- this.on(event, on);
4439
- return this;
4440
- };
4441
-
4442
- /**
4443
- * Remove the given callback for `event` or all
4444
- * registered callbacks.
4445
- *
4446
- * @param {String} event
4447
- * @param {Function} fn
4448
- * @return {Emitter}
4449
- * @api public
4450
- */
4451
-
4452
- Emitter.prototype.off =
4453
- Emitter.prototype.removeListener =
4454
- Emitter.prototype.removeAllListeners =
4455
- Emitter.prototype.removeEventListener = function(event, fn){
4456
- this._callbacks = this._callbacks || {};
4457
-
4458
- // all
4459
- if (0 == arguments.length) {
4460
- this._callbacks = {};
4461
- return this;
4462
- }
4463
-
4464
- // specific event
4465
- var callbacks = this._callbacks['$' + event];
4466
- if (!callbacks) return this;
4467
-
4468
- // remove all handlers
4469
- if (1 == arguments.length) {
4470
- delete this._callbacks['$' + event];
4471
- return this;
4472
- }
4473
-
4474
- // remove specific handler
4475
- var cb;
4476
- for (var i = 0; i < callbacks.length; i++) {
4477
- cb = callbacks[i];
4478
- if (cb === fn || cb.fn === fn) {
4479
- callbacks.splice(i, 1);
4480
- break;
4481
- }
4482
- }
4483
-
4484
- // Remove event specific arrays for event types that no
4485
- // one is subscribed for to avoid memory leak.
4486
- if (callbacks.length === 0) {
4487
- delete this._callbacks['$' + event];
4488
- }
4489
-
4490
- return this;
4491
- };
4492
-
4493
- /**
4494
- * Emit `event` with the given args.
4495
- *
4496
- * @param {String} event
4497
- * @param {Mixed} ...
4498
- * @return {Emitter}
4499
- */
4500
-
4501
- Emitter.prototype.emit = function(event){
4502
- this._callbacks = this._callbacks || {};
4503
-
4504
- var args = new Array(arguments.length - 1)
4505
- , callbacks = this._callbacks['$' + event];
4506
-
4507
- for (var i = 1; i < arguments.length; i++) {
4508
- args[i - 1] = arguments[i];
4509
- }
4510
-
4511
- if (callbacks) {
4512
- callbacks = callbacks.slice(0);
4513
- for (var i = 0, len = callbacks.length; i < len; ++i) {
4514
- callbacks[i].apply(this, args);
4515
- }
4516
- }
4517
-
4518
- return this;
4519
- };
4520
-
4521
- // alias used for reserved events (protected method)
4522
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
4523
-
4524
- /**
4525
- * Return array of callbacks for `event`.
4526
- *
4527
- * @param {String} event
4528
- * @return {Array}
4529
- * @api public
4530
- */
4531
-
4532
- Emitter.prototype.listeners = function(event){
4533
- this._callbacks = this._callbacks || {};
4534
- return this._callbacks['$' + event] || [];
4535
- };
4536
-
4537
- /**
4538
- * Check if this emitter has `event` handlers.
4539
- *
4540
- * @param {String} event
4541
- * @return {Boolean}
4542
- * @api public
4543
- */
4544
-
4545
- Emitter.prototype.hasListeners = function(event){
4546
- return !! this.listeners(event).length;
4547
- };
4548
-
4549
- const withNativeArrayBuffer = typeof ArrayBuffer === "function";
4550
- const isView = (obj) => {
4551
- return typeof ArrayBuffer.isView === "function"
4552
- ? ArrayBuffer.isView(obj)
4553
- : obj.buffer instanceof ArrayBuffer;
4554
- };
4555
- const toString = Object.prototype.toString;
4556
- const withNativeBlob = typeof Blob === "function" ||
4557
- (typeof Blob !== "undefined" &&
4558
- toString.call(Blob) === "[object BlobConstructor]");
4559
- const withNativeFile = typeof File === "function" ||
4560
- (typeof File !== "undefined" &&
4561
- toString.call(File) === "[object FileConstructor]");
4562
- /**
4563
- * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
4564
- *
4565
- * @private
4566
- */
4567
- function isBinary(obj) {
4568
- return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
4569
- (withNativeBlob && obj instanceof Blob) ||
4570
- (withNativeFile && obj instanceof File));
4378
+ return id;
4571
4379
  }
4572
- function hasBinary(obj, toJSON) {
4573
- if (!obj || typeof obj !== "object") {
4574
- return false;
4575
- }
4576
- if (Array.isArray(obj)) {
4577
- for (let i = 0, l = obj.length; i < l; i++) {
4578
- if (hasBinary(obj[i])) {
4579
- return true;
4580
- }
4581
- }
4582
- return false;
4583
- }
4584
- if (isBinary(obj)) {
4585
- return true;
4586
- }
4587
- if (obj.toJSON &&
4588
- typeof obj.toJSON === "function" &&
4589
- arguments.length === 1) {
4590
- return hasBinary(obj.toJSON(), true);
4591
- }
4592
- for (const key in obj) {
4593
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
4594
- return true;
4595
- }
4596
- }
4597
- return false;
4380
+ function getUtmParams() {
4381
+ var params = new URLSearchParams(window.location.search);
4382
+ return {
4383
+ utm_source: params.get('utm_source') || undefined,
4384
+ utm_medium: params.get('utm_medium') || undefined,
4385
+ utm_campaign: params.get('utm_campaign') || undefined,
4386
+ utm_term: params.get('utm_term') || undefined,
4387
+ utm_content: params.get('utm_content') || undefined
4388
+ };
4598
4389
  }
4599
-
4600
- /**
4601
- * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
4602
- *
4603
- * @param {Object} packet - socket.io event packet
4604
- * @return {Object} with deconstructed packet and list of buffers
4605
- * @public
4606
- */
4607
- function deconstructPacket(packet) {
4608
- const buffers = [];
4609
- const packetData = packet.data;
4610
- const pack = packet;
4611
- pack.data = _deconstructPacket(packetData, buffers);
4612
- pack.attachments = buffers.length; // number of binary 'attachments'
4613
- return { packet: pack, buffers: buffers };
4390
+ function detectDeviceType() {
4391
+ var ua = navigator.userAgent;
4392
+ if (/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua)) {
4393
+ if (/iPad|Tablet/i.test(ua)) return 'tablet';
4394
+ return 'mobile';
4395
+ }
4396
+ return 'desktop';
4614
4397
  }
4615
- function _deconstructPacket(data, buffers) {
4616
- if (!data)
4617
- return data;
4618
- if (isBinary(data)) {
4619
- const placeholder = { _placeholder: true, num: buffers.length };
4620
- buffers.push(data);
4621
- return placeholder;
4622
- }
4623
- else if (Array.isArray(data)) {
4624
- const newData = new Array(data.length);
4625
- for (let i = 0; i < data.length; i++) {
4626
- newData[i] = _deconstructPacket(data[i], buffers);
4627
- }
4628
- return newData;
4629
- }
4630
- else if (typeof data === "object" && !(data instanceof Date)) {
4631
- const newData = {};
4632
- for (const key in data) {
4633
- if (Object.prototype.hasOwnProperty.call(data, key)) {
4634
- newData[key] = _deconstructPacket(data[key], buffers);
4635
- }
4636
- }
4637
- return newData;
4638
- }
4639
- return data;
4398
+ function detectOS() {
4399
+ var ua = navigator.userAgent;
4400
+ if (/iPhone|iPad|iPod/i.test(ua)) return 'iOS';
4401
+ if (/Android/i.test(ua)) return 'Android';
4402
+ if (/Win/i.test(ua)) return 'Windows';
4403
+ if (/Mac/i.test(ua)) return 'macOS';
4404
+ if (/Linux/i.test(ua)) return 'Linux';
4405
+ return 'Other';
4640
4406
  }
4641
- /**
4642
- * Reconstructs a binary packet from its placeholder packet and buffers
4643
- *
4644
- * @param {Object} packet - event packet with placeholders
4645
- * @param {Array} buffers - binary buffers to put in placeholder positions
4646
- * @return {Object} reconstructed packet
4647
- * @public
4648
- */
4649
- function reconstructPacket(packet, buffers) {
4650
- packet.data = _reconstructPacket(packet.data, buffers);
4651
- delete packet.attachments; // no longer useful
4652
- return packet;
4407
+ function getBrowserName() {
4408
+ var ua = navigator.userAgent;
4409
+ if (ua.indexOf('Firefox') > -1) return 'Firefox';
4410
+ if (ua.indexOf('Opera') > -1 || ua.indexOf('OPR') > -1) return 'Opera';
4411
+ if (ua.indexOf('Chrome') > -1) return 'Chrome';
4412
+ if (ua.indexOf('Safari') > -1) return 'Safari';
4413
+ if (ua.indexOf('MSIE') > -1 || ua.indexOf('Trident/') > -1) return 'IE';
4414
+ return 'Unknown';
4653
4415
  }
4654
- function _reconstructPacket(data, buffers) {
4655
- if (!data)
4656
- return data;
4657
- if (data && data._placeholder === true) {
4658
- const isIndexValid = typeof data.num === "number" &&
4659
- data.num >= 0 &&
4660
- data.num < buffers.length;
4661
- if (isIndexValid) {
4662
- return buffers[data.num]; // appropriate buffer (should be natural order anyway)
4663
- }
4664
- else {
4665
- throw new Error("illegal attachments");
4666
- }
4667
- }
4668
- else if (Array.isArray(data)) {
4669
- for (let i = 0; i < data.length; i++) {
4670
- data[i] = _reconstructPacket(data[i], buffers);
4671
- }
4672
- }
4673
- else if (typeof data === "object") {
4674
- for (const key in data) {
4675
- if (Object.prototype.hasOwnProperty.call(data, key)) {
4676
- data[key] = _reconstructPacket(data[key], buffers);
4677
- }
4678
- }
4679
- }
4680
- return data;
4416
+ function getPagePath() {
4417
+ return window.location.pathname;
4681
4418
  }
4682
4419
 
4683
- /**
4684
- * These strings must not be used as event names, as they have a special meaning.
4685
- */
4686
- const RESERVED_EVENTS$1 = [
4687
- "connect",
4688
- "connect_error",
4689
- "disconnect",
4690
- "disconnecting",
4691
- "newListener",
4692
- "removeListener", // used by the Node.js EventEmitter
4693
- ];
4694
- /**
4695
- * Protocol version.
4696
- *
4697
- * @public
4698
- */
4699
- const protocol = 5;
4700
- var PacketType;
4701
- (function (PacketType) {
4702
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
4703
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
4704
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
4705
- PacketType[PacketType["ACK"] = 3] = "ACK";
4706
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
4707
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
4708
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
4709
- })(PacketType || (PacketType = {}));
4710
- /**
4711
- * A socket.io Encoder instance
4712
- */
4713
- class Encoder {
4714
- /**
4715
- * Encoder constructor
4716
- *
4717
- * @param {function} replacer - custom replacer to pass down to JSON.parse
4718
- */
4719
- constructor(replacer) {
4720
- this.replacer = replacer;
4721
- }
4722
- /**
4723
- * Encode a packet as a single string if non-binary, or as a
4724
- * buffer sequence, depending on packet type.
4725
- *
4726
- * @param {Object} obj - packet object
4727
- */
4728
- encode(obj) {
4729
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
4730
- if (hasBinary(obj)) {
4731
- return this.encodeAsBinary({
4732
- type: obj.type === PacketType.EVENT
4733
- ? PacketType.BINARY_EVENT
4734
- : PacketType.BINARY_ACK,
4735
- nsp: obj.nsp,
4736
- data: obj.data,
4737
- id: obj.id,
4738
- });
4739
- }
4740
- }
4741
- return [this.encodeAsString(obj)];
4742
- }
4743
- /**
4744
- * Encode packet as string.
4745
- */
4746
- encodeAsString(obj) {
4747
- // first is type
4748
- let str = "" + obj.type;
4749
- // attachments if we have them
4750
- if (obj.type === PacketType.BINARY_EVENT ||
4751
- obj.type === PacketType.BINARY_ACK) {
4752
- str += obj.attachments + "-";
4753
- }
4754
- // if we have a namespace other than `/`
4755
- // we append it followed by a comma `,`
4756
- if (obj.nsp && "/" !== obj.nsp) {
4757
- str += obj.nsp + ",";
4758
- }
4759
- // immediately followed by the id
4760
- if (null != obj.id) {
4761
- str += obj.id;
4762
- }
4763
- // json data
4764
- if (null != obj.data) {
4765
- str += JSON.stringify(obj.data, this.replacer);
4766
- }
4767
- return str;
4768
- }
4769
- /**
4770
- * Encode packet as 'buffer sequence' by removing blobs, and
4771
- * deconstructing packet into object with placeholders and
4772
- * a list of buffers.
4773
- */
4774
- encodeAsBinary(obj) {
4775
- const deconstruction = deconstructPacket(obj);
4776
- const pack = this.encodeAsString(deconstruction.packet);
4777
- const buffers = deconstruction.buffers;
4778
- buffers.unshift(pack); // add packet info to beginning of data list
4779
- return buffers; // write all the buffers
4780
- }
4781
- }
4782
- // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
4783
- function isObject(value) {
4784
- return Object.prototype.toString.call(value) === "[object Object]";
4785
- }
4786
- /**
4787
- * A socket.io Decoder instance
4788
- *
4789
- * @return {Object} decoder
4790
- */
4791
- class Decoder extends Emitter {
4792
- /**
4793
- * Decoder constructor
4794
- *
4795
- * @param {function} reviver - custom reviver to pass down to JSON.stringify
4796
- */
4797
- constructor(reviver) {
4798
- super();
4799
- this.reviver = reviver;
4800
- }
4801
- /**
4802
- * Decodes an encoded packet string into packet JSON.
4803
- *
4804
- * @param {String} obj - encoded packet
4805
- */
4806
- add(obj) {
4807
- let packet;
4808
- if (typeof obj === "string") {
4809
- if (this.reconstructor) {
4810
- throw new Error("got plaintext data when reconstructing a packet");
4811
- }
4812
- packet = this.decodeString(obj);
4813
- const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
4814
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
4815
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
4816
- // binary packet's json
4817
- this.reconstructor = new BinaryReconstructor(packet);
4818
- // no attachments, labeled binary but no binary data to follow
4819
- if (packet.attachments === 0) {
4820
- super.emitReserved("decoded", packet);
4821
- }
4822
- }
4823
- else {
4824
- // non-binary full packet
4825
- super.emitReserved("decoded", packet);
4826
- }
4827
- }
4828
- else if (isBinary(obj) || obj.base64) {
4829
- // raw binary data
4830
- if (!this.reconstructor) {
4831
- throw new Error("got binary data when not reconstructing a packet");
4832
- }
4833
- else {
4834
- packet = this.reconstructor.takeBinaryData(obj);
4835
- if (packet) {
4836
- // received final buffer
4837
- this.reconstructor = null;
4838
- super.emitReserved("decoded", packet);
4839
- }
4840
- }
4841
- }
4842
- else {
4843
- throw new Error("Unknown type: " + obj);
4844
- }
4845
- }
4846
- /**
4847
- * Decode a packet String (JSON data)
4848
- *
4849
- * @param {String} str
4850
- * @return {Object} packet
4851
- */
4852
- decodeString(str) {
4853
- let i = 0;
4854
- // look up type
4855
- const p = {
4856
- type: Number(str.charAt(0)),
4857
- };
4858
- if (PacketType[p.type] === undefined) {
4859
- throw new Error("unknown packet type " + p.type);
4860
- }
4861
- // look up attachments if type binary
4862
- if (p.type === PacketType.BINARY_EVENT ||
4863
- p.type === PacketType.BINARY_ACK) {
4864
- const start = i + 1;
4865
- while (str.charAt(++i) !== "-" && i != str.length) { }
4866
- const buf = str.substring(start, i);
4867
- if (buf != Number(buf) || str.charAt(i) !== "-") {
4868
- throw new Error("Illegal attachments");
4869
- }
4870
- p.attachments = Number(buf);
4871
- }
4872
- // look up namespace (if any)
4873
- if ("/" === str.charAt(i + 1)) {
4874
- const start = i + 1;
4875
- while (++i) {
4876
- const c = str.charAt(i);
4877
- if ("," === c)
4878
- break;
4879
- if (i === str.length)
4880
- break;
4881
- }
4882
- p.nsp = str.substring(start, i);
4883
- }
4884
- else {
4885
- p.nsp = "/";
4886
- }
4887
- // look up id
4888
- const next = str.charAt(i + 1);
4889
- if ("" !== next && Number(next) == next) {
4890
- const start = i + 1;
4891
- while (++i) {
4892
- const c = str.charAt(i);
4893
- if (null == c || Number(c) != c) {
4894
- --i;
4895
- break;
4896
- }
4897
- if (i === str.length)
4898
- break;
4899
- }
4900
- p.id = Number(str.substring(start, i + 1));
4901
- }
4902
- // look up json data
4903
- if (str.charAt(++i)) {
4904
- const payload = this.tryParse(str.substr(i));
4905
- if (Decoder.isPayloadValid(p.type, payload)) {
4906
- p.data = payload;
4907
- }
4908
- else {
4909
- throw new Error("invalid payload");
4910
- }
4911
- }
4912
- return p;
4913
- }
4914
- tryParse(str) {
4915
- try {
4916
- return JSON.parse(str, this.reviver);
4917
- }
4918
- catch (e) {
4919
- return false;
4920
- }
4921
- }
4922
- static isPayloadValid(type, payload) {
4923
- switch (type) {
4924
- case PacketType.CONNECT:
4925
- return isObject(payload);
4926
- case PacketType.DISCONNECT:
4927
- return payload === undefined;
4928
- case PacketType.CONNECT_ERROR:
4929
- return typeof payload === "string" || isObject(payload);
4930
- case PacketType.EVENT:
4931
- case PacketType.BINARY_EVENT:
4932
- return (Array.isArray(payload) &&
4933
- (typeof payload[0] === "number" ||
4934
- (typeof payload[0] === "string" &&
4935
- RESERVED_EVENTS$1.indexOf(payload[0]) === -1)));
4936
- case PacketType.ACK:
4937
- case PacketType.BINARY_ACK:
4938
- return Array.isArray(payload);
4939
- }
4940
- }
4941
- /**
4942
- * Deallocates a parser's resources
4943
- */
4944
- destroy() {
4945
- if (this.reconstructor) {
4946
- this.reconstructor.finishedReconstruction();
4947
- this.reconstructor = null;
4948
- }
4949
- }
4420
+ var INGEST_BASE = 'https://atlas-orchestrator.atlas.coreoutline.com';
4421
+ var FLUSH_INTERVAL_MS = 5000;
4422
+ var _token = null;
4423
+ var _warehouseId = null;
4424
+ var _organizationId = null;
4425
+ var _dataSourceId = null;
4426
+ var _buffer = [];
4427
+ var _flushInterval = null;
4428
+ function initIngest(_x, _x2, _x3) {
4429
+ return _initIngest.apply(this, arguments);
4950
4430
  }
4951
- /**
4952
- * A manager of a binary event's 'buffer sequence'. Should
4953
- * be constructed whenever a packet of type BINARY_EVENT is
4954
- * decoded.
4955
- *
4956
- * @param {Object} packet
4957
- * @return {BinaryReconstructor} initialized reconstructor
4958
- */
4959
- class BinaryReconstructor {
4960
- constructor(packet) {
4961
- this.packet = packet;
4962
- this.buffers = [];
4963
- this.reconPack = packet;
4964
- }
4965
- /**
4966
- * Method to be called when binary data received from connection
4967
- * after a BINARY_EVENT packet.
4968
- *
4969
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
4970
- * @return {null | Object} returns null if more binary data is expected or
4971
- * a reconstructed packet object if all buffers have been received.
4972
- */
4973
- takeBinaryData(binData) {
4974
- this.buffers.push(binData);
4975
- if (this.buffers.length === this.reconPack.attachments) {
4976
- // done with buffer list
4977
- const packet = reconstructPacket(this.reconPack, this.buffers);
4978
- this.finishedReconstruction();
4979
- return packet;
4980
- }
4981
- return null;
4982
- }
4983
- /**
4984
- * Cleans up binary packet reconstruction variables.
4985
- */
4986
- finishedReconstruction() {
4987
- this.reconPack = null;
4988
- this.buffers = [];
4989
- }
4431
+ function _initIngest() {
4432
+ _initIngest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(warehouseId, dataSourceId, dataSourceSecret) {
4433
+ var res, data;
4434
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4435
+ while (1) switch (_context.prev = _context.next) {
4436
+ case 0:
4437
+ _warehouseId = warehouseId;
4438
+ _dataSourceId = dataSourceId;
4439
+ _context.prev = 2;
4440
+ _context.next = 5;
4441
+ return fetch("".concat(INGEST_BASE, "/api/ingest/authorize"), {
4442
+ method: 'POST',
4443
+ headers: {
4444
+ 'Content-Type': 'application/json'
4445
+ },
4446
+ body: JSON.stringify({
4447
+ warehouse_id: warehouseId,
4448
+ data_source_id: dataSourceId,
4449
+ data_source_secret: dataSourceSecret
4450
+ })
4451
+ });
4452
+ case 5:
4453
+ res = _context.sent;
4454
+ if (res.ok) {
4455
+ _context.next = 9;
4456
+ break;
4457
+ }
4458
+ console.error('[CoreOutline] Authorization failed:', res.status);
4459
+ return _context.abrupt("return", false);
4460
+ case 9:
4461
+ _context.next = 11;
4462
+ return res.json();
4463
+ case 11:
4464
+ data = _context.sent;
4465
+ _token = data.access_token;
4466
+ _organizationId = data.organization_id;
4467
+ return _context.abrupt("return", true);
4468
+ case 17:
4469
+ _context.prev = 17;
4470
+ _context.t0 = _context["catch"](2);
4471
+ console.error('[CoreOutline] Authorization error:', _context.t0);
4472
+ return _context.abrupt("return", false);
4473
+ case 21:
4474
+ case "end":
4475
+ return _context.stop();
4476
+ }
4477
+ }, _callee, null, [[2, 17]]);
4478
+ }));
4479
+ return _initIngest.apply(this, arguments);
4990
4480
  }
4991
-
4992
- var parser = /*#__PURE__*/Object.freeze({
4993
- __proto__: null,
4994
- protocol: protocol,
4995
- get PacketType () { return PacketType; },
4996
- Encoder: Encoder,
4997
- Decoder: Decoder
4998
- });
4999
-
5000
- function on(obj, ev, fn) {
5001
- obj.on(ev, fn);
5002
- return function subDestroy() {
5003
- obj.off(ev, fn);
5004
- };
4481
+ function trackEvent(eventType, payload) {
4482
+ if (!_token) return;
4483
+ var event = _objectSpread2({
4484
+ event_id: uuid.v4(),
4485
+ event_type: eventType,
4486
+ event_ts: new Date().toISOString()
4487
+ }, payload);
4488
+ _buffer.push(event);
4489
+ if (!_flushInterval) {
4490
+ _flushInterval = setInterval(flush, FLUSH_INTERVAL_MS);
4491
+ }
5005
4492
  }
5006
-
5007
- /**
5008
- * Internal events.
5009
- * These events can't be emitted by the user.
5010
- */
5011
- const RESERVED_EVENTS = Object.freeze({
5012
- connect: 1,
5013
- connect_error: 1,
5014
- disconnect: 1,
5015
- disconnecting: 1,
5016
- // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
5017
- newListener: 1,
5018
- removeListener: 1,
5019
- });
5020
- /**
5021
- * A Socket is the fundamental class for interacting with the server.
5022
- *
5023
- * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
5024
- *
5025
- * @example
5026
- * const socket = io();
5027
- *
5028
- * socket.on("connect", () => {
5029
- * console.log("connected");
5030
- * });
5031
- *
5032
- * // send an event to the server
5033
- * socket.emit("foo", "bar");
5034
- *
5035
- * socket.on("foobar", () => {
5036
- * // an event was received from the server
5037
- * });
5038
- *
5039
- * // upon disconnection
5040
- * socket.on("disconnect", (reason) => {
5041
- * console.log(`disconnected due to ${reason}`);
5042
- * });
5043
- */
5044
- class Socket extends Emitter {
5045
- /**
5046
- * `Socket` constructor.
5047
- */
5048
- constructor(io, nsp, opts) {
5049
- super();
5050
- /**
5051
- * Whether the socket is currently connected to the server.
5052
- *
5053
- * @example
5054
- * const socket = io();
5055
- *
5056
- * socket.on("connect", () => {
5057
- * console.log(socket.connected); // true
5058
- * });
5059
- *
5060
- * socket.on("disconnect", () => {
5061
- * console.log(socket.connected); // false
5062
- * });
5063
- */
5064
- this.connected = false;
5065
- /**
5066
- * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
5067
- * be transmitted by the server.
5068
- */
5069
- this.recovered = false;
5070
- /**
5071
- * Buffer for packets received before the CONNECT packet
5072
- */
5073
- this.receiveBuffer = [];
5074
- /**
5075
- * Buffer for packets that will be sent once the socket is connected
5076
- */
5077
- this.sendBuffer = [];
5078
- /**
5079
- * The queue of packets to be sent with retry in case of failure.
5080
- *
5081
- * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
5082
- * @private
5083
- */
5084
- this._queue = [];
5085
- /**
5086
- * A sequence to generate the ID of the {@link QueuedPacket}.
5087
- * @private
5088
- */
5089
- this._queueSeq = 0;
5090
- this.ids = 0;
5091
- /**
5092
- * A map containing acknowledgement handlers.
5093
- *
5094
- * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
5095
- *
5096
- * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
5097
- * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
5098
- * - `const value = await socket.emitWithAck("test")`
5099
- *
5100
- * From those that don't:
5101
- *
5102
- * - `socket.emit("test", (value) => { ... });`
5103
- *
5104
- * In the first case, the handlers will be called with an error when:
5105
- *
5106
- * - the timeout is reached
5107
- * - the socket gets disconnected
5108
- *
5109
- * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
5110
- * an acknowledgement from the server.
5111
- *
5112
- * @private
5113
- */
5114
- this.acks = {};
5115
- this.flags = {};
5116
- this.io = io;
5117
- this.nsp = nsp;
5118
- if (opts && opts.auth) {
5119
- this.auth = opts.auth;
5120
- }
5121
- this._opts = Object.assign({}, opts);
5122
- if (this.io._autoConnect)
5123
- this.open();
5124
- }
5125
- /**
5126
- * Whether the socket is currently disconnected
5127
- *
5128
- * @example
5129
- * const socket = io();
5130
- *
5131
- * socket.on("connect", () => {
5132
- * console.log(socket.disconnected); // false
5133
- * });
5134
- *
5135
- * socket.on("disconnect", () => {
5136
- * console.log(socket.disconnected); // true
5137
- * });
5138
- */
5139
- get disconnected() {
5140
- return !this.connected;
5141
- }
5142
- /**
5143
- * Subscribe to open, close and packet events
5144
- *
5145
- * @private
5146
- */
5147
- subEvents() {
5148
- if (this.subs)
5149
- return;
5150
- const io = this.io;
5151
- this.subs = [
5152
- on(io, "open", this.onopen.bind(this)),
5153
- on(io, "packet", this.onpacket.bind(this)),
5154
- on(io, "error", this.onerror.bind(this)),
5155
- on(io, "close", this.onclose.bind(this)),
5156
- ];
5157
- }
5158
- /**
5159
- * Whether the Socket will try to reconnect when its Manager connects or reconnects.
5160
- *
5161
- * @example
5162
- * const socket = io();
5163
- *
5164
- * console.log(socket.active); // true
5165
- *
5166
- * socket.on("disconnect", (reason) => {
5167
- * if (reason === "io server disconnect") {
5168
- * // the disconnection was initiated by the server, you need to manually reconnect
5169
- * console.log(socket.active); // false
5170
- * }
5171
- * // else the socket will automatically try to reconnect
5172
- * console.log(socket.active); // true
5173
- * });
5174
- */
5175
- get active() {
5176
- return !!this.subs;
5177
- }
5178
- /**
5179
- * "Opens" the socket.
5180
- *
5181
- * @example
5182
- * const socket = io({
5183
- * autoConnect: false
5184
- * });
5185
- *
5186
- * socket.connect();
5187
- */
5188
- connect() {
5189
- if (this.connected)
5190
- return this;
5191
- this.subEvents();
5192
- if (!this.io["_reconnecting"])
5193
- this.io.open(); // ensure open
5194
- if ("open" === this.io._readyState)
5195
- this.onopen();
5196
- return this;
5197
- }
5198
- /**
5199
- * Alias for {@link connect()}.
5200
- */
5201
- open() {
5202
- return this.connect();
5203
- }
5204
- /**
5205
- * Sends a `message` event.
5206
- *
5207
- * This method mimics the WebSocket.send() method.
5208
- *
5209
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
5210
- *
5211
- * @example
5212
- * socket.send("hello");
5213
- *
5214
- * // this is equivalent to
5215
- * socket.emit("message", "hello");
5216
- *
5217
- * @return self
5218
- */
5219
- send(...args) {
5220
- args.unshift("message");
5221
- this.emit.apply(this, args);
5222
- return this;
5223
- }
5224
- /**
5225
- * Override `emit`.
5226
- * If the event is in `events`, it's emitted normally.
5227
- *
5228
- * @example
5229
- * socket.emit("hello", "world");
5230
- *
5231
- * // all serializable datastructures are supported (no need to call JSON.stringify)
5232
- * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
5233
- *
5234
- * // with an acknowledgement from the server
5235
- * socket.emit("hello", "world", (val) => {
5236
- * // ...
5237
- * });
5238
- *
5239
- * @return self
5240
- */
5241
- emit(ev, ...args) {
5242
- var _a, _b, _c;
5243
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
5244
- throw new Error('"' + ev.toString() + '" is a reserved event name');
5245
- }
5246
- args.unshift(ev);
5247
- if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
5248
- this._addToQueue(args);
5249
- return this;
5250
- }
5251
- const packet = {
5252
- type: PacketType.EVENT,
5253
- data: args,
5254
- };
5255
- packet.options = {};
5256
- packet.options.compress = this.flags.compress !== false;
5257
- // event ack callback
5258
- if ("function" === typeof args[args.length - 1]) {
5259
- const id = this.ids++;
5260
- const ack = args.pop();
5261
- this._registerAckCallback(id, ack);
5262
- packet.id = id;
5263
- }
5264
- const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
5265
- const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
5266
- const discardPacket = this.flags.volatile && !isTransportWritable;
5267
- if (discardPacket) ;
5268
- else if (isConnected) {
5269
- this.notifyOutgoingListeners(packet);
5270
- this.packet(packet);
5271
- }
5272
- else {
5273
- this.sendBuffer.push(packet);
5274
- }
5275
- this.flags = {};
5276
- return this;
5277
- }
5278
- /**
5279
- * @private
5280
- */
5281
- _registerAckCallback(id, ack) {
5282
- var _a;
5283
- const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
5284
- if (timeout === undefined) {
5285
- this.acks[id] = ack;
5286
- return;
5287
- }
5288
- // @ts-ignore
5289
- const timer = this.io.setTimeoutFn(() => {
5290
- delete this.acks[id];
5291
- for (let i = 0; i < this.sendBuffer.length; i++) {
5292
- if (this.sendBuffer[i].id === id) {
5293
- this.sendBuffer.splice(i, 1);
5294
- }
5295
- }
5296
- ack.call(this, new Error("operation has timed out"));
5297
- }, timeout);
5298
- const fn = (...args) => {
5299
- // @ts-ignore
5300
- this.io.clearTimeoutFn(timer);
5301
- ack.apply(this, args);
5302
- };
5303
- fn.withError = true;
5304
- this.acks[id] = fn;
5305
- }
5306
- /**
5307
- * Emits an event and waits for an acknowledgement
5308
- *
5309
- * @example
5310
- * // without timeout
5311
- * const response = await socket.emitWithAck("hello", "world");
5312
- *
5313
- * // with a specific timeout
5314
- * try {
5315
- * const response = await socket.timeout(1000).emitWithAck("hello", "world");
5316
- * } catch (err) {
5317
- * // the server did not acknowledge the event in the given delay
5318
- * }
5319
- *
5320
- * @return a Promise that will be fulfilled when the server acknowledges the event
5321
- */
5322
- emitWithAck(ev, ...args) {
5323
- return new Promise((resolve, reject) => {
5324
- const fn = (arg1, arg2) => {
5325
- return arg1 ? reject(arg1) : resolve(arg2);
5326
- };
5327
- fn.withError = true;
5328
- args.push(fn);
5329
- this.emit(ev, ...args);
5330
- });
5331
- }
5332
- /**
5333
- * Add the packet to the queue.
5334
- * @param args
5335
- * @private
5336
- */
5337
- _addToQueue(args) {
5338
- let ack;
5339
- if (typeof args[args.length - 1] === "function") {
5340
- ack = args.pop();
5341
- }
5342
- const packet = {
5343
- id: this._queueSeq++,
5344
- tryCount: 0,
5345
- pending: false,
5346
- args,
5347
- flags: Object.assign({ fromQueue: true }, this.flags),
5348
- };
5349
- args.push((err, ...responseArgs) => {
5350
- if (packet !== this._queue[0]) {
5351
- // the packet has already been acknowledged
5352
- return;
5353
- }
5354
- const hasError = err !== null;
5355
- if (hasError) {
5356
- if (packet.tryCount > this._opts.retries) {
5357
- this._queue.shift();
5358
- if (ack) {
5359
- ack(err);
5360
- }
5361
- }
5362
- }
5363
- else {
5364
- this._queue.shift();
5365
- if (ack) {
5366
- ack(null, ...responseArgs);
5367
- }
5368
- }
5369
- packet.pending = false;
5370
- return this._drainQueue();
5371
- });
5372
- this._queue.push(packet);
5373
- this._drainQueue();
5374
- }
5375
- /**
5376
- * Send the first packet of the queue, and wait for an acknowledgement from the server.
5377
- * @param force - whether to resend a packet that has not been acknowledged yet
5378
- *
5379
- * @private
5380
- */
5381
- _drainQueue(force = false) {
5382
- if (!this.connected || this._queue.length === 0) {
5383
- return;
5384
- }
5385
- const packet = this._queue[0];
5386
- if (packet.pending && !force) {
5387
- return;
5388
- }
5389
- packet.pending = true;
5390
- packet.tryCount++;
5391
- this.flags = packet.flags;
5392
- this.emit.apply(this, packet.args);
5393
- }
5394
- /**
5395
- * Sends a packet.
5396
- *
5397
- * @param packet
5398
- * @private
5399
- */
5400
- packet(packet) {
5401
- packet.nsp = this.nsp;
5402
- this.io._packet(packet);
5403
- }
5404
- /**
5405
- * Called upon engine `open`.
5406
- *
5407
- * @private
5408
- */
5409
- onopen() {
5410
- if (typeof this.auth == "function") {
5411
- this.auth((data) => {
5412
- this._sendConnectPacket(data);
5413
- });
5414
- }
5415
- else {
5416
- this._sendConnectPacket(this.auth);
5417
- }
5418
- }
5419
- /**
5420
- * Sends a CONNECT packet to initiate the Socket.IO session.
5421
- *
5422
- * @param data
5423
- * @private
5424
- */
5425
- _sendConnectPacket(data) {
5426
- this.packet({
5427
- type: PacketType.CONNECT,
5428
- data: this._pid
5429
- ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
5430
- : data,
5431
- });
5432
- }
5433
- /**
5434
- * Called upon engine or manager `error`.
5435
- *
5436
- * @param err
5437
- * @private
5438
- */
5439
- onerror(err) {
5440
- if (!this.connected) {
5441
- this.emitReserved("connect_error", err);
5442
- }
5443
- }
5444
- /**
5445
- * Called upon engine `close`.
5446
- *
5447
- * @param reason
5448
- * @param description
5449
- * @private
5450
- */
5451
- onclose(reason, description) {
5452
- this.connected = false;
5453
- delete this.id;
5454
- this.emitReserved("disconnect", reason, description);
5455
- this._clearAcks();
5456
- }
5457
- /**
5458
- * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
5459
- * the server.
5460
- *
5461
- * @private
5462
- */
5463
- _clearAcks() {
5464
- Object.keys(this.acks).forEach((id) => {
5465
- const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
5466
- if (!isBuffered) {
5467
- // note: handlers that do not accept an error as first argument are ignored here
5468
- const ack = this.acks[id];
5469
- delete this.acks[id];
5470
- if (ack.withError) {
5471
- ack.call(this, new Error("socket has been disconnected"));
5472
- }
5473
- }
5474
- });
5475
- }
5476
- /**
5477
- * Called with socket packet.
5478
- *
5479
- * @param packet
5480
- * @private
5481
- */
5482
- onpacket(packet) {
5483
- const sameNamespace = packet.nsp === this.nsp;
5484
- if (!sameNamespace)
5485
- return;
5486
- switch (packet.type) {
5487
- case PacketType.CONNECT:
5488
- if (packet.data && packet.data.sid) {
5489
- this.onconnect(packet.data.sid, packet.data.pid);
5490
- }
5491
- else {
5492
- this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
5493
- }
5494
- break;
5495
- case PacketType.EVENT:
5496
- case PacketType.BINARY_EVENT:
5497
- this.onevent(packet);
5498
- break;
5499
- case PacketType.ACK:
5500
- case PacketType.BINARY_ACK:
5501
- this.onack(packet);
5502
- break;
5503
- case PacketType.DISCONNECT:
5504
- this.ondisconnect();
5505
- break;
5506
- case PacketType.CONNECT_ERROR:
5507
- this.destroy();
5508
- const err = new Error(packet.data.message);
5509
- // @ts-ignore
5510
- err.data = packet.data.data;
5511
- this.emitReserved("connect_error", err);
5512
- break;
5513
- }
5514
- }
5515
- /**
5516
- * Called upon a server event.
5517
- *
5518
- * @param packet
5519
- * @private
5520
- */
5521
- onevent(packet) {
5522
- const args = packet.data || [];
5523
- if (null != packet.id) {
5524
- args.push(this.ack(packet.id));
5525
- }
5526
- if (this.connected) {
5527
- this.emitEvent(args);
5528
- }
5529
- else {
5530
- this.receiveBuffer.push(Object.freeze(args));
5531
- }
5532
- }
5533
- emitEvent(args) {
5534
- if (this._anyListeners && this._anyListeners.length) {
5535
- const listeners = this._anyListeners.slice();
5536
- for (const listener of listeners) {
5537
- listener.apply(this, args);
5538
- }
5539
- }
5540
- super.emit.apply(this, args);
5541
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
5542
- this._lastOffset = args[args.length - 1];
5543
- }
5544
- }
5545
- /**
5546
- * Produces an ack callback to emit with an event.
5547
- *
5548
- * @private
5549
- */
5550
- ack(id) {
5551
- const self = this;
5552
- let sent = false;
5553
- return function (...args) {
5554
- // prevent double callbacks
5555
- if (sent)
5556
- return;
5557
- sent = true;
5558
- self.packet({
5559
- type: PacketType.ACK,
5560
- id: id,
5561
- data: args,
5562
- });
5563
- };
5564
- }
5565
- /**
5566
- * Called upon a server acknowledgement.
5567
- *
5568
- * @param packet
5569
- * @private
5570
- */
5571
- onack(packet) {
5572
- const ack = this.acks[packet.id];
5573
- if (typeof ack !== "function") {
5574
- return;
5575
- }
5576
- delete this.acks[packet.id];
5577
- // @ts-ignore FIXME ack is incorrectly inferred as 'never'
5578
- if (ack.withError) {
5579
- packet.data.unshift(null);
5580
- }
5581
- // @ts-ignore
5582
- ack.apply(this, packet.data);
5583
- }
5584
- /**
5585
- * Called upon server connect.
5586
- *
5587
- * @private
5588
- */
5589
- onconnect(id, pid) {
5590
- this.id = id;
5591
- this.recovered = pid && this._pid === pid;
5592
- this._pid = pid; // defined only if connection state recovery is enabled
5593
- this.connected = true;
5594
- this.emitBuffered();
5595
- this.emitReserved("connect");
5596
- this._drainQueue(true);
5597
- }
5598
- /**
5599
- * Emit buffered events (received and emitted).
5600
- *
5601
- * @private
5602
- */
5603
- emitBuffered() {
5604
- this.receiveBuffer.forEach((args) => this.emitEvent(args));
5605
- this.receiveBuffer = [];
5606
- this.sendBuffer.forEach((packet) => {
5607
- this.notifyOutgoingListeners(packet);
5608
- this.packet(packet);
5609
- });
5610
- this.sendBuffer = [];
5611
- }
5612
- /**
5613
- * Called upon server disconnect.
5614
- *
5615
- * @private
5616
- */
5617
- ondisconnect() {
5618
- this.destroy();
5619
- this.onclose("io server disconnect");
5620
- }
5621
- /**
5622
- * Called upon forced client/server side disconnections,
5623
- * this method ensures the manager stops tracking us and
5624
- * that reconnections don't get triggered for this.
5625
- *
5626
- * @private
5627
- */
5628
- destroy() {
5629
- if (this.subs) {
5630
- // clean subscriptions to avoid reconnections
5631
- this.subs.forEach((subDestroy) => subDestroy());
5632
- this.subs = undefined;
5633
- }
5634
- this.io["_destroy"](this);
5635
- }
5636
- /**
5637
- * Disconnects the socket manually. In that case, the socket will not try to reconnect.
5638
- *
5639
- * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
5640
- *
5641
- * @example
5642
- * const socket = io();
5643
- *
5644
- * socket.on("disconnect", (reason) => {
5645
- * // console.log(reason); prints "io client disconnect"
5646
- * });
5647
- *
5648
- * socket.disconnect();
5649
- *
5650
- * @return self
5651
- */
5652
- disconnect() {
5653
- if (this.connected) {
5654
- this.packet({ type: PacketType.DISCONNECT });
5655
- }
5656
- // remove socket from pool
5657
- this.destroy();
5658
- if (this.connected) {
5659
- // fire events
5660
- this.onclose("io client disconnect");
5661
- }
5662
- return this;
5663
- }
5664
- /**
5665
- * Alias for {@link disconnect()}.
5666
- *
5667
- * @return self
5668
- */
5669
- close() {
5670
- return this.disconnect();
5671
- }
5672
- /**
5673
- * Sets the compress flag.
5674
- *
5675
- * @example
5676
- * socket.compress(false).emit("hello");
5677
- *
5678
- * @param compress - if `true`, compresses the sending data
5679
- * @return self
5680
- */
5681
- compress(compress) {
5682
- this.flags.compress = compress;
5683
- return this;
5684
- }
5685
- /**
5686
- * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
5687
- * ready to send messages.
5688
- *
5689
- * @example
5690
- * socket.volatile.emit("hello"); // the server may or may not receive it
5691
- *
5692
- * @returns self
5693
- */
5694
- get volatile() {
5695
- this.flags.volatile = true;
5696
- return this;
5697
- }
5698
- /**
5699
- * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
5700
- * given number of milliseconds have elapsed without an acknowledgement from the server:
5701
- *
5702
- * @example
5703
- * socket.timeout(5000).emit("my-event", (err) => {
5704
- * if (err) {
5705
- * // the server did not acknowledge the event in the given delay
5706
- * }
5707
- * });
5708
- *
5709
- * @returns self
5710
- */
5711
- timeout(timeout) {
5712
- this.flags.timeout = timeout;
5713
- return this;
5714
- }
5715
- /**
5716
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5717
- * callback.
5718
- *
5719
- * @example
5720
- * socket.onAny((event, ...args) => {
5721
- * console.log(`got ${event}`);
5722
- * });
5723
- *
5724
- * @param listener
5725
- */
5726
- onAny(listener) {
5727
- this._anyListeners = this._anyListeners || [];
5728
- this._anyListeners.push(listener);
5729
- return this;
5730
- }
5731
- /**
5732
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5733
- * callback. The listener is added to the beginning of the listeners array.
5734
- *
5735
- * @example
5736
- * socket.prependAny((event, ...args) => {
5737
- * console.log(`got event ${event}`);
5738
- * });
5739
- *
5740
- * @param listener
5741
- */
5742
- prependAny(listener) {
5743
- this._anyListeners = this._anyListeners || [];
5744
- this._anyListeners.unshift(listener);
5745
- return this;
5746
- }
5747
- /**
5748
- * Removes the listener that will be fired when any event is emitted.
5749
- *
5750
- * @example
5751
- * const catchAllListener = (event, ...args) => {
5752
- * console.log(`got event ${event}`);
5753
- * }
5754
- *
5755
- * socket.onAny(catchAllListener);
5756
- *
5757
- * // remove a specific listener
5758
- * socket.offAny(catchAllListener);
5759
- *
5760
- * // or remove all listeners
5761
- * socket.offAny();
5762
- *
5763
- * @param listener
5764
- */
5765
- offAny(listener) {
5766
- if (!this._anyListeners) {
5767
- return this;
5768
- }
5769
- if (listener) {
5770
- const listeners = this._anyListeners;
5771
- for (let i = 0; i < listeners.length; i++) {
5772
- if (listener === listeners[i]) {
5773
- listeners.splice(i, 1);
5774
- return this;
5775
- }
5776
- }
5777
- }
5778
- else {
5779
- this._anyListeners = [];
5780
- }
5781
- return this;
5782
- }
5783
- /**
5784
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
5785
- * e.g. to remove listeners.
5786
- */
5787
- listenersAny() {
5788
- return this._anyListeners || [];
5789
- }
5790
- /**
5791
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5792
- * callback.
5793
- *
5794
- * Note: acknowledgements sent to the server are not included.
5795
- *
5796
- * @example
5797
- * socket.onAnyOutgoing((event, ...args) => {
5798
- * console.log(`sent event ${event}`);
5799
- * });
5800
- *
5801
- * @param listener
5802
- */
5803
- onAnyOutgoing(listener) {
5804
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
5805
- this._anyOutgoingListeners.push(listener);
5806
- return this;
5807
- }
5808
- /**
5809
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
5810
- * callback. The listener is added to the beginning of the listeners array.
5811
- *
5812
- * Note: acknowledgements sent to the server are not included.
5813
- *
5814
- * @example
5815
- * socket.prependAnyOutgoing((event, ...args) => {
5816
- * console.log(`sent event ${event}`);
5817
- * });
5818
- *
5819
- * @param listener
5820
- */
5821
- prependAnyOutgoing(listener) {
5822
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
5823
- this._anyOutgoingListeners.unshift(listener);
5824
- return this;
5825
- }
5826
- /**
5827
- * Removes the listener that will be fired when any event is emitted.
5828
- *
5829
- * @example
5830
- * const catchAllListener = (event, ...args) => {
5831
- * console.log(`sent event ${event}`);
5832
- * }
5833
- *
5834
- * socket.onAnyOutgoing(catchAllListener);
5835
- *
5836
- * // remove a specific listener
5837
- * socket.offAnyOutgoing(catchAllListener);
5838
- *
5839
- * // or remove all listeners
5840
- * socket.offAnyOutgoing();
5841
- *
5842
- * @param [listener] - the catch-all listener (optional)
5843
- */
5844
- offAnyOutgoing(listener) {
5845
- if (!this._anyOutgoingListeners) {
5846
- return this;
5847
- }
5848
- if (listener) {
5849
- const listeners = this._anyOutgoingListeners;
5850
- for (let i = 0; i < listeners.length; i++) {
5851
- if (listener === listeners[i]) {
5852
- listeners.splice(i, 1);
5853
- return this;
5854
- }
5855
- }
5856
- }
5857
- else {
5858
- this._anyOutgoingListeners = [];
5859
- }
5860
- return this;
5861
- }
5862
- /**
5863
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
5864
- * e.g. to remove listeners.
5865
- */
5866
- listenersAnyOutgoing() {
5867
- return this._anyOutgoingListeners || [];
5868
- }
5869
- /**
5870
- * Notify the listeners for each packet sent
5871
- *
5872
- * @param packet
5873
- *
5874
- * @private
5875
- */
5876
- notifyOutgoingListeners(packet) {
5877
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
5878
- const listeners = this._anyOutgoingListeners.slice();
5879
- for (const listener of listeners) {
5880
- listener.apply(this, packet.data);
5881
- }
5882
- }
5883
- }
4493
+ function flush() {
4494
+ if (!_token || _buffer.length === 0) return;
4495
+ var events = _buffer.splice(0, _buffer.length);
4496
+ var body = JSON.stringify({
4497
+ warehouse_id: _warehouseId,
4498
+ organization_id: _organizationId,
4499
+ events: events
4500
+ });
4501
+ var headers = {
4502
+ 'Content-Type': 'application/json',
4503
+ Authorization: "Bearer ".concat(_token)
4504
+ };
4505
+ if (navigator.sendBeacon) {
4506
+ var blob = new Blob([body], {
4507
+ type: 'application/json'
4508
+ });
4509
+ navigator.sendBeacon("".concat(INGEST_BASE, "/api/ingest/events"), blob);
4510
+ } else {
4511
+ fetch("".concat(INGEST_BASE, "/api/ingest/events"), {
4512
+ method: 'POST',
4513
+ headers: headers,
4514
+ body: body,
4515
+ keepalive: true
4516
+ })["catch"](function (err) {
4517
+ return console.error('[CoreOutline] Flush error:', err);
4518
+ });
4519
+ }
5884
4520
  }
5885
-
5886
- /**
5887
- * Initialize backoff timer with `opts`.
5888
- *
5889
- * - `min` initial timeout in milliseconds [100]
5890
- * - `max` max timeout [10000]
5891
- * - `jitter` [0]
5892
- * - `factor` [2]
5893
- *
5894
- * @param {Object} opts
5895
- * @api public
5896
- */
5897
- function Backoff(opts) {
5898
- opts = opts || {};
5899
- this.ms = opts.min || 100;
5900
- this.max = opts.max || 10000;
5901
- this.factor = opts.factor || 2;
5902
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
5903
- this.attempts = 0;
4521
+ function sendRrwebBatch(_x4, _x5) {
4522
+ return _sendRrwebBatch.apply(this, arguments);
5904
4523
  }
5905
- /**
5906
- * Return the backoff duration.
5907
- *
5908
- * @return {Number}
5909
- * @api public
5910
- */
5911
- Backoff.prototype.duration = function () {
5912
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
5913
- if (this.jitter) {
5914
- var rand = Math.random();
5915
- var deviation = Math.floor(rand * this.jitter * ms);
5916
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
5917
- }
5918
- return Math.min(ms, this.max) | 0;
5919
- };
5920
- /**
5921
- * Reset the number of attempts.
5922
- *
5923
- * @api public
5924
- */
5925
- Backoff.prototype.reset = function () {
5926
- this.attempts = 0;
5927
- };
5928
- /**
5929
- * Set the minimum duration
5930
- *
5931
- * @api public
5932
- */
5933
- Backoff.prototype.setMin = function (min) {
5934
- this.ms = min;
5935
- };
5936
- /**
5937
- * Set the maximum duration
5938
- *
5939
- * @api public
5940
- */
5941
- Backoff.prototype.setMax = function (max) {
5942
- this.max = max;
5943
- };
5944
- /**
5945
- * Set the jitter
5946
- *
5947
- * @api public
5948
- */
5949
- Backoff.prototype.setJitter = function (jitter) {
5950
- this.jitter = jitter;
5951
- };
5952
-
5953
- class Manager extends Emitter {
5954
- constructor(uri, opts) {
5955
- var _a;
5956
- super();
5957
- this.nsps = {};
5958
- this.subs = [];
5959
- if (uri && "object" === typeof uri) {
5960
- opts = uri;
5961
- uri = undefined;
5962
- }
5963
- opts = opts || {};
5964
- opts.path = opts.path || "/socket.io";
5965
- this.opts = opts;
5966
- engine_ioClient.installTimerFunctions(this, opts);
5967
- this.reconnection(opts.reconnection !== false);
5968
- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
5969
- this.reconnectionDelay(opts.reconnectionDelay || 1000);
5970
- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
5971
- this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
5972
- this.backoff = new Backoff({
5973
- min: this.reconnectionDelay(),
5974
- max: this.reconnectionDelayMax(),
5975
- jitter: this.randomizationFactor(),
5976
- });
5977
- this.timeout(null == opts.timeout ? 20000 : opts.timeout);
5978
- this._readyState = "closed";
5979
- this.uri = uri;
5980
- const _parser = opts.parser || parser;
5981
- this.encoder = new _parser.Encoder();
5982
- this.decoder = new _parser.Decoder();
5983
- this._autoConnect = opts.autoConnect !== false;
5984
- if (this._autoConnect)
5985
- this.open();
5986
- }
5987
- reconnection(v) {
5988
- if (!arguments.length)
5989
- return this._reconnection;
5990
- this._reconnection = !!v;
5991
- if (!v) {
5992
- this.skipReconnect = true;
5993
- }
5994
- return this;
5995
- }
5996
- reconnectionAttempts(v) {
5997
- if (v === undefined)
5998
- return this._reconnectionAttempts;
5999
- this._reconnectionAttempts = v;
6000
- return this;
6001
- }
6002
- reconnectionDelay(v) {
6003
- var _a;
6004
- if (v === undefined)
6005
- return this._reconnectionDelay;
6006
- this._reconnectionDelay = v;
6007
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
6008
- return this;
6009
- }
6010
- randomizationFactor(v) {
6011
- var _a;
6012
- if (v === undefined)
6013
- return this._randomizationFactor;
6014
- this._randomizationFactor = v;
6015
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
6016
- return this;
6017
- }
6018
- reconnectionDelayMax(v) {
6019
- var _a;
6020
- if (v === undefined)
6021
- return this._reconnectionDelayMax;
6022
- this._reconnectionDelayMax = v;
6023
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
6024
- return this;
6025
- }
6026
- timeout(v) {
6027
- if (!arguments.length)
6028
- return this._timeout;
6029
- this._timeout = v;
6030
- return this;
6031
- }
6032
- /**
6033
- * Starts trying to reconnect if reconnection is enabled and we have not
6034
- * started reconnecting yet
6035
- *
6036
- * @private
6037
- */
6038
- maybeReconnectOnOpen() {
6039
- // Only try to reconnect if it's the first time we're connecting
6040
- if (!this._reconnecting &&
6041
- this._reconnection &&
6042
- this.backoff.attempts === 0) {
6043
- // keeps reconnection from firing twice for the same reconnection loop
6044
- this.reconnect();
6045
- }
6046
- }
6047
- /**
6048
- * Sets the current transport `socket`.
6049
- *
6050
- * @param {Function} fn - optional, callback
6051
- * @return self
6052
- * @public
6053
- */
6054
- open(fn) {
6055
- if (~this._readyState.indexOf("open"))
6056
- return this;
6057
- this.engine = new engine_ioClient.Socket(this.uri, this.opts);
6058
- const socket = this.engine;
6059
- const self = this;
6060
- this._readyState = "opening";
6061
- this.skipReconnect = false;
6062
- // emit `open`
6063
- const openSubDestroy = on(socket, "open", function () {
6064
- self.onopen();
6065
- fn && fn();
6066
- });
6067
- const onError = (err) => {
6068
- this.cleanup();
6069
- this._readyState = "closed";
6070
- this.emitReserved("error", err);
6071
- if (fn) {
6072
- fn(err);
6073
- }
6074
- else {
6075
- // Only do this if there is no fn to handle the error
6076
- this.maybeReconnectOnOpen();
6077
- }
6078
- };
6079
- // emit `error`
6080
- const errorSub = on(socket, "error", onError);
6081
- if (false !== this._timeout) {
6082
- const timeout = this._timeout;
6083
- // set timer
6084
- const timer = this.setTimeoutFn(() => {
6085
- openSubDestroy();
6086
- onError(new Error("timeout"));
6087
- socket.close();
6088
- }, timeout);
6089
- if (this.opts.autoUnref) {
6090
- timer.unref();
6091
- }
6092
- this.subs.push(() => {
6093
- this.clearTimeoutFn(timer);
6094
- });
6095
- }
6096
- this.subs.push(openSubDestroy);
6097
- this.subs.push(errorSub);
6098
- return this;
6099
- }
6100
- /**
6101
- * Alias for open()
6102
- *
6103
- * @return self
6104
- * @public
6105
- */
6106
- connect(fn) {
6107
- return this.open(fn);
6108
- }
6109
- /**
6110
- * Called upon transport open.
6111
- *
6112
- * @private
6113
- */
6114
- onopen() {
6115
- // clear old subs
6116
- this.cleanup();
6117
- // mark as open
6118
- this._readyState = "open";
6119
- this.emitReserved("open");
6120
- // add new subs
6121
- const socket = this.engine;
6122
- this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
6123
- // @ts-ignore
6124
- on(this.decoder, "decoded", this.ondecoded.bind(this)));
6125
- }
6126
- /**
6127
- * Called upon a ping.
6128
- *
6129
- * @private
6130
- */
6131
- onping() {
6132
- this.emitReserved("ping");
6133
- }
6134
- /**
6135
- * Called with data.
6136
- *
6137
- * @private
6138
- */
6139
- ondata(data) {
6140
- try {
6141
- this.decoder.add(data);
6142
- }
6143
- catch (e) {
6144
- this.onclose("parse error", e);
6145
- }
6146
- }
6147
- /**
6148
- * Called when parser fully decodes a packet.
6149
- *
6150
- * @private
6151
- */
6152
- ondecoded(packet) {
6153
- // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
6154
- engine_ioClient.nextTick(() => {
6155
- this.emitReserved("packet", packet);
6156
- }, this.setTimeoutFn);
6157
- }
6158
- /**
6159
- * Called upon socket error.
6160
- *
6161
- * @private
6162
- */
6163
- onerror(err) {
6164
- this.emitReserved("error", err);
6165
- }
6166
- /**
6167
- * Creates a new socket for the given `nsp`.
6168
- *
6169
- * @return {Socket}
6170
- * @public
6171
- */
6172
- socket(nsp, opts) {
6173
- let socket = this.nsps[nsp];
6174
- if (!socket) {
6175
- socket = new Socket(this, nsp, opts);
6176
- this.nsps[nsp] = socket;
6177
- }
6178
- else if (this._autoConnect && !socket.active) {
6179
- socket.connect();
6180
- }
6181
- return socket;
6182
- }
6183
- /**
6184
- * Called upon a socket close.
6185
- *
6186
- * @param socket
6187
- * @private
6188
- */
6189
- _destroy(socket) {
6190
- const nsps = Object.keys(this.nsps);
6191
- for (const nsp of nsps) {
6192
- const socket = this.nsps[nsp];
6193
- if (socket.active) {
6194
- return;
6195
- }
6196
- }
6197
- this._close();
6198
- }
6199
- /**
6200
- * Writes a packet.
6201
- *
6202
- * @param packet
6203
- * @private
6204
- */
6205
- _packet(packet) {
6206
- const encodedPackets = this.encoder.encode(packet);
6207
- for (let i = 0; i < encodedPackets.length; i++) {
6208
- this.engine.write(encodedPackets[i], packet.options);
6209
- }
6210
- }
6211
- /**
6212
- * Clean up transport subscriptions and packet buffer.
6213
- *
6214
- * @private
6215
- */
6216
- cleanup() {
6217
- this.subs.forEach((subDestroy) => subDestroy());
6218
- this.subs.length = 0;
6219
- this.decoder.destroy();
6220
- }
6221
- /**
6222
- * Close the current socket.
6223
- *
6224
- * @private
6225
- */
6226
- _close() {
6227
- this.skipReconnect = true;
6228
- this._reconnecting = false;
6229
- this.onclose("forced close");
6230
- }
6231
- /**
6232
- * Alias for close()
6233
- *
6234
- * @private
6235
- */
6236
- disconnect() {
6237
- return this._close();
6238
- }
6239
- /**
6240
- * Called when:
6241
- *
6242
- * - the low-level engine is closed
6243
- * - the parser encountered a badly formatted packet
6244
- * - all sockets are disconnected
6245
- *
6246
- * @private
6247
- */
6248
- onclose(reason, description) {
6249
- var _a;
6250
- this.cleanup();
6251
- (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
6252
- this.backoff.reset();
6253
- this._readyState = "closed";
6254
- this.emitReserved("close", reason, description);
6255
- if (this._reconnection && !this.skipReconnect) {
6256
- this.reconnect();
6257
- }
6258
- }
6259
- /**
6260
- * Attempt a reconnection.
6261
- *
6262
- * @private
6263
- */
6264
- reconnect() {
6265
- if (this._reconnecting || this.skipReconnect)
6266
- return this;
6267
- const self = this;
6268
- if (this.backoff.attempts >= this._reconnectionAttempts) {
6269
- this.backoff.reset();
6270
- this.emitReserved("reconnect_failed");
6271
- this._reconnecting = false;
6272
- }
6273
- else {
6274
- const delay = this.backoff.duration();
6275
- this._reconnecting = true;
6276
- const timer = this.setTimeoutFn(() => {
6277
- if (self.skipReconnect)
6278
- return;
6279
- this.emitReserved("reconnect_attempt", self.backoff.attempts);
6280
- // check again for the case socket closed in above events
6281
- if (self.skipReconnect)
6282
- return;
6283
- self.open((err) => {
6284
- if (err) {
6285
- self._reconnecting = false;
6286
- self.reconnect();
6287
- this.emitReserved("reconnect_error", err);
6288
- }
6289
- else {
6290
- self.onreconnect();
6291
- }
6292
- });
6293
- }, delay);
6294
- if (this.opts.autoUnref) {
6295
- timer.unref();
6296
- }
6297
- this.subs.push(() => {
6298
- this.clearTimeoutFn(timer);
6299
- });
6300
- }
6301
- }
6302
- /**
6303
- * Called upon successful reconnect.
6304
- *
6305
- * @private
6306
- */
6307
- onreconnect() {
6308
- const attempt = this.backoff.attempts;
6309
- this._reconnecting = false;
6310
- this.backoff.reset();
6311
- this.emitReserved("reconnect", attempt);
6312
- }
4524
+ function _sendRrwebBatch() {
4525
+ _sendRrwebBatch = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(chunks, sessionId) {
4526
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4527
+ while (1) switch (_context2.prev = _context2.next) {
4528
+ case 0:
4529
+ if (!(!_token || !chunks || chunks.length === 0)) {
4530
+ _context2.next = 2;
4531
+ break;
4532
+ }
4533
+ return _context2.abrupt("return");
4534
+ case 2:
4535
+ _context2.prev = 2;
4536
+ _context2.next = 5;
4537
+ return fetch("".concat(INGEST_BASE, "/api/ingest/rrweb"), {
4538
+ method: 'POST',
4539
+ headers: {
4540
+ 'Content-Type': 'application/json',
4541
+ Authorization: "Bearer ".concat(_token)
4542
+ },
4543
+ body: JSON.stringify({
4544
+ warehouse_id: _warehouseId,
4545
+ organization_id: _organizationId,
4546
+ session_id: sessionId,
4547
+ data_source_id: _dataSourceId,
4548
+ chunks: chunks
4549
+ }),
4550
+ keepalive: true
4551
+ });
4552
+ case 5:
4553
+ _context2.next = 10;
4554
+ break;
4555
+ case 7:
4556
+ _context2.prev = 7;
4557
+ _context2.t0 = _context2["catch"](2);
4558
+ console.error('[CoreOutline] rrweb upload error:', _context2.t0);
4559
+ case 10:
4560
+ case "end":
4561
+ return _context2.stop();
4562
+ }
4563
+ }, _callee2, null, [[2, 7]]);
4564
+ }));
4565
+ return _sendRrwebBatch.apply(this, arguments);
6313
4566
  }
6314
-
6315
- /**
6316
- * Managers cache.
6317
- */
6318
- const cache = {};
6319
- function lookup(uri, opts) {
6320
- if (typeof uri === "object") {
6321
- opts = uri;
6322
- uri = undefined;
6323
- }
6324
- opts = opts || {};
6325
- const parsed = url(uri, opts.path || "/socket.io");
6326
- const source = parsed.source;
6327
- const id = parsed.id;
6328
- const path = parsed.path;
6329
- const sameNamespace = cache[id] && path in cache[id]["nsps"];
6330
- const newConnection = opts.forceNew ||
6331
- opts["force new connection"] ||
6332
- false === opts.multiplex ||
6333
- sameNamespace;
6334
- let io;
6335
- if (newConnection) {
6336
- io = new Manager(source, opts);
6337
- }
6338
- else {
6339
- if (!cache[id]) {
6340
- cache[id] = new Manager(source, opts);
6341
- }
6342
- io = cache[id];
6343
- }
6344
- if (parsed.query && !opts.query) {
6345
- opts.query = parsed.queryKey;
6346
- }
6347
- return io.socket(parsed.path, opts);
4567
+ function stopFlushInterval() {
4568
+ if (_flushInterval) {
4569
+ clearInterval(_flushInterval);
4570
+ _flushInterval = null;
4571
+ }
6348
4572
  }
6349
- // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
6350
- // namespace (e.g. `io.connect(...)`), for backward compatibility
6351
- Object.assign(lookup, {
6352
- Manager,
6353
- Socket,
6354
- io: lookup,
6355
- connect: lookup,
6356
- });
6357
-
6358
- var socket = lookup('http://streams.coreoutline.com');
6359
4573
 
6360
4574
  var CoreOutline = function CoreOutline(_ref) {
6361
4575
  var children = _ref.children,
6362
4576
  data_source_id = _ref.data_source_id,
6363
- data_source_secret = _ref.data_source_secret;
4577
+ data_source_secret = _ref.data_source_secret,
4578
+ warehouse_id = _ref.warehouse_id;
6364
4579
  var _useState = React.useState([]),
6365
4580
  _useState2 = _slicedToArray(_useState, 2),
6366
- events = _useState2[0],
6367
- setEvents = _useState2[1];
6368
- var _useState3 = React.useState([]),
6369
- _useState4 = _slicedToArray(_useState3, 2),
6370
- replayEvents = _useState4[0],
6371
- setReplayEvents = _useState4[1];
4581
+ replayEvents = _useState2[0],
4582
+ setReplayEvents = _useState2[1];
6372
4583
  var recorderActive = React.useRef(false);
6373
- var _useState5 = React.useState(window.location.href),
6374
- _useState6 = _slicedToArray(_useState5, 2),
6375
- currentPage = _useState6[0],
6376
- setCurrentPage = _useState6[1];
6377
- var _useState7 = React.useState({
6378
- latitude: null,
6379
- longitude: null
6380
- }),
6381
- _useState8 = _slicedToArray(_useState7, 2),
6382
- location = _useState8[0],
6383
- setLocation = _useState8[1];
6384
- var _useState9 = React.useState(getBrowserInfo()),
6385
- _useState10 = _slicedToArray(_useState9, 2),
6386
- browser = _useState10[0];
6387
- _useState10[1];
6388
- var _useState11 = React.useState(''),
6389
- _useState12 = _slicedToArray(_useState11, 2);
6390
- _useState12[0];
6391
- var setAppToken = _useState12[1];
6392
- var _useState13 = React.useState(uuid.v4()),
6393
- _useState14 = _slicedToArray(_useState13, 2),
6394
- sessionId = _useState14[0];
6395
- _useState14[1];
6396
- function authorizeApp(_x, _x2) {
6397
- return _authorizeApp.apply(this, arguments);
6398
- }
6399
- function _authorizeApp() {
6400
- _authorizeApp = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data_source_id, data_source_secret) {
6401
- var requestOptions, response;
6402
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
6403
- while (1) switch (_context2.prev = _context2.next) {
6404
- case 0:
6405
- requestOptions = {
6406
- method: 'POST',
6407
- headers: {
6408
- 'Content-Type': 'application/json'
6409
- },
6410
- body: JSON.stringify({
6411
- data_source_id: data_source_id,
6412
- data_source_secret: data_source_secret
6413
- })
6414
- };
6415
- response = fetch("http://api.coreoutline.com/data-source/authorize", requestOptions).then(function (response) {
6416
- return response.json();
6417
- }).then(function (data) {
6418
- setAppToken(data.app_token);
6419
- return data;
6420
- })["catch"](function (error) {
6421
- console.error('Error:', error);
6422
- return error;
6423
- });
6424
- return _context2.abrupt("return", response);
6425
- case 3:
6426
- case "end":
6427
- return _context2.stop();
6428
- }
6429
- }, _callee2);
6430
- }));
6431
- return _authorizeApp.apply(this, arguments);
6432
- }
6433
- var offLoadFunctionality = function offLoadFunctionality() {
6434
- var formattedEvents = events;
6435
- var rawEvents = replayEvents;
6436
- var data = JSON.stringify({
6437
- data_source_id: data_source_id,
6438
- sessionId: sessionId,
6439
- formatted_events: formattedEvents,
6440
- raw_events: rawEvents
6441
- });
6442
- socket.send({
6443
- topic: 'session-data',
6444
- data_source_id: data_source_id,
6445
- session_id: localStorage.getItem('coreOutlineSessionId'),
6446
- start_date: new Date().toLocaleString(),
6447
- latitude: location.latitude,
6448
- longitude: location.longitude,
6449
- browser: browser,
6450
- event_id: 'SESSION_END'
6451
- });
6452
- if (navigator.sendBeacon) {
6453
- navigator.sendBeacon("http://data.coreoutline.com/upload-events", data);
6454
- } else {
6455
- fetch("http://data.coreoutline.com/upload-events", {
6456
- method: 'POST',
6457
- body: data,
6458
- keepalive: true,
6459
- headers: {
6460
- 'Content-Type': 'application/json'
6461
- }
6462
- })["catch"](function (err) {
6463
- return console.error('Upload failed:', err);
6464
- });
6465
- }
6466
- };
6467
- React.useEffect(function () {}, [events, replayEvents]);
6468
- React.useEffect(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
6469
- var handleBeforeUnload, handleVisibilityChange;
6470
- return _regeneratorRuntime().wrap(function _callee$(_context) {
6471
- while (1) switch (_context.prev = _context.next) {
6472
- case 0:
6473
- handleBeforeUnload = function handleBeforeUnload() {
6474
- offLoadFunctionality();
6475
- };
6476
- handleVisibilityChange = function handleVisibilityChange() {
6477
- if (document.visibilityState === 'hidden') {
6478
- offLoadFunctionality();
6479
- }
6480
- };
6481
- window.addEventListener('beforeunload', handleBeforeUnload);
6482
- document.addEventListener('visibilitychange', handleVisibilityChange);
6483
- _context.next = 6;
6484
- return authorizeApp(data_source_id, data_source_secret);
6485
- case 6:
6486
- localStorage.setItem('coreOutlineSessionId', sessionId);
6487
- localStorage.setItem('coreOutlineDataSourceIdId', data_source_id);
6488
- console.log('Session', sessionId);
6489
- socket.send({
6490
- topic: 'session-data',
6491
- data_source_id: data_source_id,
6492
- session_id: localStorage.getItem('coreOutlineSessionId'),
6493
- start_date: new Date().toLocaleString(),
6494
- latitude: location.latitude,
6495
- longitude: location.longitude,
6496
- browser: browser,
6497
- event_id: 'SESSION_START'
6498
- });
6499
- return _context.abrupt("return", function () {
6500
- offLoadFunctionality();
6501
- window.removeEventListener('beforeunload', handleBeforeUnload);
6502
- document.removeEventListener('visibilitychange', handleVisibilityChange);
6503
- socket.send({
6504
- topic: 'session-data',
6505
- data_source_id: data_source_id,
6506
- session_id: localStorage.getItem('coreOutlineSessionId'),
6507
- start_date: new Date().toLocaleString(),
6508
- latitude: location.latitude,
6509
- longitude: location.longitude,
6510
- browser: browser,
6511
- event_id: 'SESSION_END'
6512
- });
6513
- });
6514
- case 11:
6515
- case "end":
6516
- return _context.stop();
6517
- }
6518
- }, _callee);
6519
- })), []);
4584
+ var _useState3 = React.useState(window.location.href),
4585
+ _useState4 = _slicedToArray(_useState3, 2),
4586
+ currentPage = _useState4[0],
4587
+ setCurrentPage = _useState4[1];
4588
+ var pageviewCountRef = React.useRef(0);
4589
+ var eventCountRef = React.useRef(0);
4590
+ var sessionStartRef = React.useRef(Date.now());
4591
+ var sessionId = getSessionId();
4592
+ var anonymousId = getAnonymousId();
6520
4593
  React.useEffect(function () {
6521
- var navigationEvent = {
6522
- type: 4,
6523
- data: {
6524
- href: window.location.href,
6525
- width: 1536,
6526
- height: 730
6527
- },
6528
- timestamp: Date.now()
4594
+ var utmParams = getUtmParams();
4595
+ var deviceType = detectDeviceType();
4596
+ var os = detectOS();
4597
+ var browser = getBrowserName();
4598
+ var referrer = document.referrer || 'direct';
4599
+ var basePayload = _objectSpread2({
4600
+ session_id: sessionId,
4601
+ anonymous_id: anonymousId,
4602
+ account_id: data_source_id,
4603
+ platform: 'web',
4604
+ device_type: deviceType,
4605
+ os: os,
4606
+ browser: browser,
4607
+ referrer: referrer,
4608
+ page_url: window.location.href,
4609
+ page_path: getPagePath()
4610
+ }, utmParams);
4611
+ var initialized = false;
4612
+ var init = /*#__PURE__*/function () {
4613
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
4614
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4615
+ while (1) switch (_context.prev = _context.next) {
4616
+ case 0:
4617
+ _context.next = 2;
4618
+ return initIngest(warehouse_id, data_source_id, data_source_secret);
4619
+ case 2:
4620
+ initialized = _context.sent;
4621
+ if (initialized) {
4622
+ _context.next = 5;
4623
+ break;
4624
+ }
4625
+ return _context.abrupt("return");
4626
+ case 5:
4627
+ pageviewCountRef.current += 1;
4628
+ trackEvent('pageview', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4629
+ event_name: 'pageview',
4630
+ event_category: 'navigation'
4631
+ }));
4632
+ trackEvent('session_start', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4633
+ event_name: 'session_start',
4634
+ event_category: 'session',
4635
+ session_start_ts: new Date().toISOString()
4636
+ }));
4637
+ case 8:
4638
+ case "end":
4639
+ return _context.stop();
4640
+ }
4641
+ }, _callee);
4642
+ }));
4643
+ return function init() {
4644
+ return _ref2.apply(this, arguments);
4645
+ };
4646
+ }();
4647
+ init();
4648
+ var handleSessionEnd = function handleSessionEnd() {
4649
+ if (!initialized) return;
4650
+ var durationMs = Date.now() - sessionStartRef.current;
4651
+ trackEvent('session_end', _objectSpread2(_objectSpread2({}, basePayload), {}, {
4652
+ event_name: 'session_end',
4653
+ event_category: 'session',
4654
+ session_end_ts: new Date().toISOString(),
4655
+ pageviews: pageviewCountRef.current,
4656
+ events_count: eventCountRef.current,
4657
+ duration_ms: durationMs
4658
+ }));
4659
+ flush();
4660
+ stopFlushInterval();
4661
+ sendRrwebBatch(replayEvents, sessionId);
6529
4662
  };
6530
- var startTime = performance.now();
6531
- var observer = new MutationObserver(function () {
6532
- var endTime = performance.now();
6533
- var loadTime = endTime - startTime;
6534
- navigationEvent.data.loadTime = loadTime;
6535
- var hours = Math.floor(loadTime / 3600000);
6536
- var minutes = Math.floor(loadTime % 3600000 / 60000);
6537
- var seconds = Math.floor(loadTime % 60000 / 1000);
6538
- navigationEvent.data.loadTimeFormatted = "".concat(hours, " hours ").concat(minutes, " minutes ").concat(seconds, " seconds");
6539
- observer.disconnect();
6540
- });
6541
- observer.observe(document, {
6542
- childList: true,
6543
- subtree: true
6544
- });
6545
- setEvents(function (prevEvents) {
6546
- return [].concat(_toConsumableArray(prevEvents), [navigationEvent]);
6547
- });
6548
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6549
- return [].concat(_toConsumableArray(prevEvents), [navigationEvent]);
6550
- }));
4663
+ var handleVisibilityChange = function handleVisibilityChange() {
4664
+ if (document.visibilityState === 'hidden') handleSessionEnd();
4665
+ };
4666
+ window.addEventListener('beforeunload', handleSessionEnd);
4667
+ document.addEventListener('visibilitychange', handleVisibilityChange);
4668
+ return function () {
4669
+ handleSessionEnd();
4670
+ window.removeEventListener('beforeunload', handleSessionEnd);
4671
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
4672
+ };
4673
+ }, []);
4674
+ React.useEffect(function () {
4675
+ var utmParams = getUtmParams();
6551
4676
  var handleNavigation = function handleNavigation() {
6552
4677
  setCurrentPage(window.location.href);
6553
- socket.send({
6554
- topic: 'session-data',
6555
- data_source_id: data_source_id,
6556
- session_id: localStorage.getItem('coreOutlineSessionId'),
6557
- start_date: new Date().toLocaleString(),
6558
- latitude: location.latitude,
6559
- longitude: location.longitude,
6560
- browser: browser,
6561
- page_name: window.location.href,
6562
- event_id: 'PAGE_NAVIGATION'
6563
- });
4678
+ pageviewCountRef.current += 1;
4679
+ trackEvent('pageview', _objectSpread2({
4680
+ session_id: sessionId,
4681
+ anonymous_id: anonymousId,
4682
+ account_id: data_source_id,
4683
+ platform: 'web',
4684
+ page_url: window.location.href,
4685
+ page_path: getPagePath(),
4686
+ referrer: document.referrer || 'direct',
4687
+ event_name: 'pageview',
4688
+ event_category: 'navigation'
4689
+ }, utmParams));
6564
4690
  };
6565
4691
  window.addEventListener('popstate', handleNavigation);
6566
4692
  var originalPushState = window.history.pushState;
@@ -6576,61 +4702,14 @@ var CoreOutline = function CoreOutline(_ref) {
6576
4702
  window.history.pushState = originalPushState;
6577
4703
  };
6578
4704
  }, [currentPage]);
6579
- React.useEffect(function () {
6580
- console.log('Location', location);
6581
- getLocation();
6582
- }, []);
6583
4705
  React.useEffect(function () {
6584
4706
  var stopFn;
6585
4707
  if (!recorderActive.current) {
6586
4708
  stopFn = record({
6587
4709
  emit: function emit(event) {
6588
- setReplayEvents(function (prevEvents) {
6589
- return [].concat(_toConsumableArray(prevEvents), [event]);
4710
+ setReplayEvents(function (prev) {
4711
+ return [].concat(_toConsumableArray(prev), [event]);
6590
4712
  });
6591
- localStorage.setItem('coreoutlineRawEvents', JSON.stringify(function (prevEvents) {
6592
- return [].concat(_toConsumableArray(replayEvents), [event]);
6593
- }));
6594
- },
6595
- maskAllInputs: false,
6596
- maskTextSelector: null
6597
- });
6598
- recorderActive.current = true;
6599
- }
6600
- return function () {
6601
- if (stopFn) {
6602
- stopFn();
6603
- recorderActive.current = false;
6604
- }
6605
- };
6606
- }, []);
6607
- React.useEffect(function () {
6608
- var stopFn;
6609
- if (!recorderActive.current) {
6610
- stopFn = record({
6611
- emit: function emit(event) {
6612
- console.log('Event:', event);
6613
- if (event.type == 3 && event.data.type == 2) {
6614
- return;
6615
- }
6616
- if (event.type == 4) {
6617
- return;
6618
- }
6619
- if (event.type == 3 && event.data.source == 0) {
6620
- return;
6621
- }
6622
- if (event.type == 3 && event.data.source == 1) {
6623
- return;
6624
- }
6625
- if (event.type == 3 && event.data.type == 3) {
6626
- console.log('Contextmenu Event:', event);
6627
- }
6628
- setEvents(function (prevEvents) {
6629
- return [].concat(_toConsumableArray(prevEvents), [event]);
6630
- });
6631
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6632
- return [].concat(_toConsumableArray(prevEvents), [event]);
6633
- }));
6634
4713
  },
6635
4714
  maskAllInputs: false,
6636
4715
  maskTextSelector: null
@@ -6646,122 +4725,45 @@ var CoreOutline = function CoreOutline(_ref) {
6646
4725
  }, []);
6647
4726
  React.useEffect(function () {
6648
4727
  var handleClick = function handleClick(event) {
6649
- console.log('Inner text:', event.target.innerText);
6650
- var clickEvent = {
6651
- type: EventType.IncrementalSnapshot,
6652
- data: {
6653
- source: IncrementalSource.MouseInteraction,
6654
- type: MouseInteractions.Click,
6655
- id: event.target.id,
6656
- x: event.clientX,
6657
- y: event.clientY
6658
- },
6659
- timestamp: Date.now()
6660
- };
6661
- var clickedElement = document.elementFromPoint(clickEvent.data.x, clickEvent.data.y);
6662
- if (clickedElement) {
6663
- clickEvent.data.metadata = {
6664
- label: clickedElement.getAttribute('data-label') || clickedElement.innerText || null,
6665
- value: clickedElement.getAttribute('value') || clickedElement.innerText || null,
6666
- id: clickedElement.getAttribute('id') || clickedElement.innerText || null,
6667
- name: clickedElement.getAttribute('name') || clickedElement.innerText || null,
6668
- "class": clickedElement.getAttribute('class') || clickedElement.innerText || null,
6669
- tag: clickedElement.tagName,
6670
- html: String(clickedElement.getHTML()),
6671
- innerText: event.target.innerText
6672
- };
6673
- }
6674
- setEvents(function (prevEvents) {
6675
- return [].concat(_toConsumableArray(prevEvents), [clickEvent]);
6676
- });
6677
- localStorage.setItem('coreoutlineFormattedEvents', JSON.stringify(function (prevEvents) {
6678
- return [].concat(_toConsumableArray(prevEvents), [clickEvent]);
6679
- }));
6680
- socket.send({
6681
- topic: 'session-data',
6682
- data_source_id: data_source_id,
6683
- session_id: localStorage.getItem('coreOutlineSessionId'),
6684
- start_date: new Date().toLocaleString(),
6685
- latitude: location.latitude,
6686
- longitude: location.longitude,
6687
- browser: browser,
6688
- event_id: 'ITEM_CLICKED'
6689
- // item_clicked: event.target,
4728
+ var clickedElement = document.elementFromPoint(event.clientX, event.clientY);
4729
+ var metadata = clickedElement ? {
4730
+ label: clickedElement.getAttribute('data-label') || clickedElement.innerText || null,
4731
+ value: clickedElement.getAttribute('value') || clickedElement.innerText || null,
4732
+ id: clickedElement.getAttribute('id') || null,
4733
+ name: clickedElement.getAttribute('name') || null,
4734
+ "class": clickedElement.getAttribute('class') || null,
4735
+ tag: clickedElement.tagName,
4736
+ inner_text: event.target.innerText || null
4737
+ } : {};
4738
+ eventCountRef.current += 1;
4739
+ trackEvent('item_clicked', {
4740
+ session_id: sessionId,
4741
+ anonymous_id: anonymousId,
4742
+ account_id: data_source_id,
4743
+ platform: 'web',
4744
+ page_url: window.location.href,
4745
+ page_path: getPagePath(),
4746
+ event_name: 'item_clicked',
4747
+ event_category: 'interaction',
4748
+ properties_json: JSON.stringify(metadata)
6690
4749
  });
6691
4750
  };
6692
4751
  document.addEventListener('click', handleClick);
6693
4752
  return function () {
6694
- document.removeEventListener('click', handleClick);
4753
+ return document.removeEventListener('click', handleClick);
6695
4754
  };
6696
4755
  }, []);
6697
- function saveEventsLocally() {
6698
- var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'formatted' ;
6699
- var blob = '';
6700
- if (type === 'formatted') {
6701
- blob = new Blob([JSON.stringify(events, null, 2)], {
6702
- type: 'application/json'
6703
- });
6704
- } else if (type === 'raw') {
6705
- blob = new Blob([JSON.stringify(replayEvents, null, 2)], {
6706
- type: 'application/json'
6707
- });
6708
- }
6709
- var url = URL.createObjectURL(blob);
6710
- var a = document.createElement('a');
6711
- a.href = url;
6712
- a.download = "".concat(type, "_events.json");
6713
- a.click();
6714
- URL.revokeObjectURL(url);
6715
- }
6716
- function getBrowserInfo() {
6717
- var userAgent = navigator.userAgent;
6718
- var browserName = 'Unknown';
6719
- if (userAgent.indexOf('Firefox') > -1) {
6720
- browserName = 'Firefox';
6721
- } else if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) {
6722
- browserName = 'Opera';
6723
- } else if (userAgent.indexOf('Chrome') > -1) {
6724
- browserName = 'Chrome';
6725
- } else if (userAgent.indexOf('Safari') > -1) {
6726
- browserName = 'Safari';
6727
- } else if (userAgent.indexOf('MSIE') > -1 || userAgent.indexOf('Trident/') > -1) {
6728
- browserName = 'Internet Explorer';
6729
- }
6730
- return browserName;
6731
- }
6732
- function getLocation() {
6733
- if (navigator.geolocation) {
6734
- navigator.geolocation.getCurrentPosition(function (position) {
6735
- setLocation({
6736
- latitude: position.coords.latitude,
6737
- longitude: position.coords.longitude
6738
- });
6739
- }, function (error) {
6740
- console.error('Error getting location:', error);
6741
- });
6742
- } else {
6743
- console.error('Geolocation is not supported by this browser.');
6744
- }
6745
- }
6746
- return /*#__PURE__*/React__default["default"].createElement("div", null, /*#__PURE__*/React__default["default"].createElement("button", {
6747
- onClick: function onClick() {
6748
- saveEventsLocally('formatted');
6749
- saveEventsLocally('raw');
6750
- }
6751
- }, "Save Events Locally"), children);
4756
+ return /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, children);
6752
4757
  };
6753
4758
  var flag_item_clicked = function flag_item_clicked(item_id) {
6754
- var sessionId = localStorage.getItem('coreOutlineSessionId');
6755
- var dataSourceId = localStorage.getItem('coreOutlineDataSourceIdId');
6756
- console.log('Session', sessionId);
6757
- console.log('Data Source', dataSourceId);
6758
- socket.send({
6759
- topic: 'session-data',
6760
- data_source_id: dataSourceId,
6761
- session_id: localStorage.getItem('coreOutlineSessionId'),
6762
- start_date: new Date().toLocaleString(),
6763
- event_id: 'PRODUCT_CLICKED',
6764
- item_clicked: item_id
4759
+ var sessionId = sessionStorage.getItem('co_session_id') || '';
4760
+ var anonymousId = localStorage.getItem('co_anon_id') || '';
4761
+ trackEvent('product_clicked', {
4762
+ session_id: sessionId,
4763
+ anonymous_id: anonymousId,
4764
+ event_name: 'product_clicked',
4765
+ event_category: 'commerce',
4766
+ feature_key: item_id
6765
4767
  });
6766
4768
  return {
6767
4769
  status: 'success',
@@ -6769,17 +4771,16 @@ var flag_item_clicked = function flag_item_clicked(item_id) {
6769
4771
  };
6770
4772
  };
6771
4773
  var flag_item_purchased = function flag_item_purchased(item_id) {
6772
- var sessionId = localStorage.getItem('coreOutlineSessionId');
6773
- var dataSourceId = localStorage.getItem('coreOutlineDataSourceIdId');
6774
- console.log('Session', sessionId);
6775
- console.log('Data Source', dataSourceId);
6776
- socket.send({
6777
- topic: 'session-data',
6778
- data_source_id: dataSourceId,
6779
- session_id: localStorage.getItem('coreOutlineSessionId'),
6780
- start_date: new Date().toLocaleString(),
6781
- event_id: 'PRODUCT_PURCHASED',
6782
- item_clicked: item_id
4774
+ var price = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
4775
+ var sessionId = sessionStorage.getItem('co_session_id') || '';
4776
+ var anonymousId = localStorage.getItem('co_anon_id') || '';
4777
+ trackEvent('product_purchased', {
4778
+ session_id: sessionId,
4779
+ anonymous_id: anonymousId,
4780
+ event_name: 'product_purchased',
4781
+ event_category: 'commerce',
4782
+ feature_key: item_id,
4783
+ value_num: price != null ? Number(price) : null
6783
4784
  });
6784
4785
  return {
6785
4786
  status: 'success',