@rudderstack/analytics-js 3.2.2 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +9 -15
- package/dist/npm/index.d.ts +4 -8
- package/dist/npm/legacy/cjs/index.js +309 -359
- package/dist/npm/legacy/esm/index.js +309 -359
- package/dist/npm/legacy/umd/index.js +309 -359
- package/dist/npm/modern/bundled/cjs/index.js +131 -136
- package/dist/npm/modern/bundled/esm/index.js +131 -136
- package/dist/npm/modern/bundled/umd/index.js +131 -136
- package/dist/npm/modern/cjs/index.js +110 -125
- package/dist/npm/modern/content-script/cjs/index.js +126 -133
- package/dist/npm/modern/content-script/esm/index.js +126 -133
- package/dist/npm/modern/content-script/umd/index.js +126 -133
- package/dist/npm/modern/esm/index.js +110 -125
- package/dist/npm/modern/umd/index.js +110 -125
- package/package.json +2 -60
@@ -4,9 +4,49 @@
|
|
4
4
|
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rudderanalytics = {}));
|
5
5
|
})(this, (function (exports) { 'use strict';
|
6
6
|
|
7
|
+
function _arrayLikeToArray(r, a) {
|
8
|
+
(null == a || a > r.length) && (a = r.length);
|
9
|
+
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
|
10
|
+
return n;
|
11
|
+
}
|
12
|
+
function _arrayWithoutHoles(r) {
|
13
|
+
if (Array.isArray(r)) return _arrayLikeToArray(r);
|
14
|
+
}
|
15
|
+
function _assertThisInitialized(e) {
|
16
|
+
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
17
|
+
return e;
|
18
|
+
}
|
19
|
+
function asyncGeneratorStep(n, t, e, r, o, a, c) {
|
20
|
+
try {
|
21
|
+
var i = n[a](c),
|
22
|
+
u = i.value;
|
23
|
+
} catch (n) {
|
24
|
+
return void e(n);
|
25
|
+
}
|
26
|
+
i.done ? t(u) : Promise.resolve(u).then(r, o);
|
27
|
+
}
|
28
|
+
function _asyncToGenerator(n) {
|
29
|
+
return function () {
|
30
|
+
var t = this,
|
31
|
+
e = arguments;
|
32
|
+
return new Promise(function (r, o) {
|
33
|
+
var a = n.apply(t, e);
|
34
|
+
function _next(n) {
|
35
|
+
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
|
36
|
+
}
|
37
|
+
function _throw(n) {
|
38
|
+
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
|
39
|
+
}
|
40
|
+
_next(void 0);
|
41
|
+
});
|
42
|
+
};
|
43
|
+
}
|
7
44
|
function _callSuper(t, o, e) {
|
8
45
|
return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
|
9
46
|
}
|
47
|
+
function _classCallCheck(a, n) {
|
48
|
+
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
|
49
|
+
}
|
10
50
|
function _construct(t, e, r) {
|
11
51
|
if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
|
12
52
|
var o = [null];
|
@@ -14,6 +54,99 @@
|
|
14
54
|
var p = new (t.bind.apply(t, o))();
|
15
55
|
return p;
|
16
56
|
}
|
57
|
+
function _defineProperties(e, r) {
|
58
|
+
for (var t = 0; t < r.length; t++) {
|
59
|
+
var o = r[t];
|
60
|
+
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
|
61
|
+
}
|
62
|
+
}
|
63
|
+
function _createClass(e, r, t) {
|
64
|
+
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
|
65
|
+
writable: !1
|
66
|
+
}), e;
|
67
|
+
}
|
68
|
+
function _createForOfIteratorHelper(r, e) {
|
69
|
+
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
|
70
|
+
if (!t) {
|
71
|
+
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) {
|
72
|
+
t && (r = t);
|
73
|
+
var n = 0,
|
74
|
+
F = function () {};
|
75
|
+
return {
|
76
|
+
s: F,
|
77
|
+
n: function () {
|
78
|
+
return n >= r.length ? {
|
79
|
+
done: !0
|
80
|
+
} : {
|
81
|
+
done: !1,
|
82
|
+
value: r[n++]
|
83
|
+
};
|
84
|
+
},
|
85
|
+
e: function (r) {
|
86
|
+
throw r;
|
87
|
+
},
|
88
|
+
f: F
|
89
|
+
};
|
90
|
+
}
|
91
|
+
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
92
|
+
}
|
93
|
+
var o,
|
94
|
+
a = !0,
|
95
|
+
u = !1;
|
96
|
+
return {
|
97
|
+
s: function () {
|
98
|
+
t = t.call(r);
|
99
|
+
},
|
100
|
+
n: function () {
|
101
|
+
var r = t.next();
|
102
|
+
return a = r.done, r;
|
103
|
+
},
|
104
|
+
e: function (r) {
|
105
|
+
u = !0, o = r;
|
106
|
+
},
|
107
|
+
f: function () {
|
108
|
+
try {
|
109
|
+
a || null == t.return || t.return();
|
110
|
+
} finally {
|
111
|
+
if (u) throw o;
|
112
|
+
}
|
113
|
+
}
|
114
|
+
};
|
115
|
+
}
|
116
|
+
function _defineProperty(e, r, t) {
|
117
|
+
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
118
|
+
value: t,
|
119
|
+
enumerable: !0,
|
120
|
+
configurable: !0,
|
121
|
+
writable: !0
|
122
|
+
}) : e[r] = t, e;
|
123
|
+
}
|
124
|
+
function _get() {
|
125
|
+
return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
|
126
|
+
var p = _superPropBase(e, t);
|
127
|
+
if (p) {
|
128
|
+
var n = Object.getOwnPropertyDescriptor(p, t);
|
129
|
+
return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
|
130
|
+
}
|
131
|
+
}, _get.apply(null, arguments);
|
132
|
+
}
|
133
|
+
function _getPrototypeOf(t) {
|
134
|
+
return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
|
135
|
+
return t.__proto__ || Object.getPrototypeOf(t);
|
136
|
+
}, _getPrototypeOf(t);
|
137
|
+
}
|
138
|
+
function _inherits(t, e) {
|
139
|
+
if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
|
140
|
+
t.prototype = Object.create(e && e.prototype, {
|
141
|
+
constructor: {
|
142
|
+
value: t,
|
143
|
+
writable: !0,
|
144
|
+
configurable: !0
|
145
|
+
}
|
146
|
+
}), Object.defineProperty(t, "prototype", {
|
147
|
+
writable: !1
|
148
|
+
}), e && _setPrototypeOf(t, e);
|
149
|
+
}
|
17
150
|
function _isNativeReflectConstruct() {
|
18
151
|
try {
|
19
152
|
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
|
@@ -22,6 +155,12 @@
|
|
22
155
|
return !!t;
|
23
156
|
})();
|
24
157
|
}
|
158
|
+
function _iterableToArray(r) {
|
159
|
+
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
|
160
|
+
}
|
161
|
+
function _nonIterableSpread() {
|
162
|
+
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
163
|
+
}
|
25
164
|
function ownKeys(e, r) {
|
26
165
|
var t = Object.keys(e);
|
27
166
|
if (Object.getOwnPropertySymbols) {
|
@@ -43,6 +182,11 @@
|
|
43
182
|
}
|
44
183
|
return e;
|
45
184
|
}
|
185
|
+
function _possibleConstructorReturn(t, e) {
|
186
|
+
if (e && ("object" == typeof e || "function" == typeof e)) return e;
|
187
|
+
if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
|
188
|
+
return _assertThisInitialized(t);
|
189
|
+
}
|
46
190
|
function _regeneratorRuntime() {
|
47
191
|
_regeneratorRuntime = function () {
|
48
192
|
return e;
|
@@ -344,6 +488,18 @@
|
|
344
488
|
}
|
345
489
|
}, e;
|
346
490
|
}
|
491
|
+
function _setPrototypeOf(t, e) {
|
492
|
+
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
|
493
|
+
return t.__proto__ = e, t;
|
494
|
+
}, _setPrototypeOf(t, e);
|
495
|
+
}
|
496
|
+
function _superPropBase(t, o) {
|
497
|
+
for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
|
498
|
+
return t;
|
499
|
+
}
|
500
|
+
function _toConsumableArray(r) {
|
501
|
+
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
|
502
|
+
}
|
347
503
|
function _toPrimitive(t, r) {
|
348
504
|
if ("object" != typeof t || !t) return t;
|
349
505
|
var e = t[Symbol.toPrimitive];
|
@@ -367,218 +523,15 @@
|
|
367
523
|
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
368
524
|
}, _typeof(o);
|
369
525
|
}
|
370
|
-
function
|
371
|
-
|
372
|
-
|
373
|
-
var
|
374
|
-
|
375
|
-
reject(error);
|
376
|
-
return;
|
377
|
-
}
|
378
|
-
if (info.done) {
|
379
|
-
resolve(value);
|
380
|
-
} else {
|
381
|
-
Promise.resolve(value).then(_next, _throw);
|
382
|
-
}
|
383
|
-
}
|
384
|
-
function _asyncToGenerator(fn) {
|
385
|
-
return function () {
|
386
|
-
var self = this,
|
387
|
-
args = arguments;
|
388
|
-
return new Promise(function (resolve, reject) {
|
389
|
-
var gen = fn.apply(self, args);
|
390
|
-
function _next(value) {
|
391
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
392
|
-
}
|
393
|
-
function _throw(err) {
|
394
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
395
|
-
}
|
396
|
-
_next(undefined);
|
397
|
-
});
|
398
|
-
};
|
399
|
-
}
|
400
|
-
function _classCallCheck(instance, Constructor) {
|
401
|
-
if (!(instance instanceof Constructor)) {
|
402
|
-
throw new TypeError("Cannot call a class as a function");
|
526
|
+
function _unsupportedIterableToArray(r, a) {
|
527
|
+
if (r) {
|
528
|
+
if ("string" == typeof r) return _arrayLikeToArray(r, a);
|
529
|
+
var t = {}.toString.call(r).slice(8, -1);
|
530
|
+
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
|
403
531
|
}
|
404
532
|
}
|
405
|
-
function _defineProperties(target, props) {
|
406
|
-
for (var i = 0; i < props.length; i++) {
|
407
|
-
var descriptor = props[i];
|
408
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
409
|
-
descriptor.configurable = true;
|
410
|
-
if ("value" in descriptor) descriptor.writable = true;
|
411
|
-
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
|
412
|
-
}
|
413
|
-
}
|
414
|
-
function _createClass(Constructor, protoProps, staticProps) {
|
415
|
-
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
416
|
-
if (staticProps) _defineProperties(Constructor, staticProps);
|
417
|
-
Object.defineProperty(Constructor, "prototype", {
|
418
|
-
writable: false
|
419
|
-
});
|
420
|
-
return Constructor;
|
421
|
-
}
|
422
|
-
function _defineProperty(obj, key, value) {
|
423
|
-
key = _toPropertyKey(key);
|
424
|
-
if (key in obj) {
|
425
|
-
Object.defineProperty(obj, key, {
|
426
|
-
value: value,
|
427
|
-
enumerable: true,
|
428
|
-
configurable: true,
|
429
|
-
writable: true
|
430
|
-
});
|
431
|
-
} else {
|
432
|
-
obj[key] = value;
|
433
|
-
}
|
434
|
-
return obj;
|
435
|
-
}
|
436
|
-
function _inherits(subClass, superClass) {
|
437
|
-
if (typeof superClass !== "function" && superClass !== null) {
|
438
|
-
throw new TypeError("Super expression must either be null or a function");
|
439
|
-
}
|
440
|
-
subClass.prototype = Object.create(superClass && superClass.prototype, {
|
441
|
-
constructor: {
|
442
|
-
value: subClass,
|
443
|
-
writable: true,
|
444
|
-
configurable: true
|
445
|
-
}
|
446
|
-
});
|
447
|
-
Object.defineProperty(subClass, "prototype", {
|
448
|
-
writable: false
|
449
|
-
});
|
450
|
-
if (superClass) _setPrototypeOf(subClass, superClass);
|
451
|
-
}
|
452
|
-
function _getPrototypeOf(o) {
|
453
|
-
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
|
454
|
-
return o.__proto__ || Object.getPrototypeOf(o);
|
455
|
-
};
|
456
|
-
return _getPrototypeOf(o);
|
457
|
-
}
|
458
|
-
function _setPrototypeOf(o, p) {
|
459
|
-
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
|
460
|
-
o.__proto__ = p;
|
461
|
-
return o;
|
462
|
-
};
|
463
|
-
return _setPrototypeOf(o, p);
|
464
|
-
}
|
465
|
-
function _assertThisInitialized(self) {
|
466
|
-
if (self === void 0) {
|
467
|
-
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
468
|
-
}
|
469
|
-
return self;
|
470
|
-
}
|
471
|
-
function _possibleConstructorReturn(self, call) {
|
472
|
-
if (call && (typeof call === "object" || typeof call === "function")) {
|
473
|
-
return call;
|
474
|
-
} else if (call !== void 0) {
|
475
|
-
throw new TypeError("Derived constructors may only return object or undefined");
|
476
|
-
}
|
477
|
-
return _assertThisInitialized(self);
|
478
|
-
}
|
479
|
-
function _superPropBase(object, property) {
|
480
|
-
while (!Object.prototype.hasOwnProperty.call(object, property)) {
|
481
|
-
object = _getPrototypeOf(object);
|
482
|
-
if (object === null) break;
|
483
|
-
}
|
484
|
-
return object;
|
485
|
-
}
|
486
|
-
function _get() {
|
487
|
-
if (typeof Reflect !== "undefined" && Reflect.get) {
|
488
|
-
_get = Reflect.get.bind();
|
489
|
-
} else {
|
490
|
-
_get = function _get(target, property, receiver) {
|
491
|
-
var base = _superPropBase(target, property);
|
492
|
-
if (!base) return;
|
493
|
-
var desc = Object.getOwnPropertyDescriptor(base, property);
|
494
|
-
if (desc.get) {
|
495
|
-
return desc.get.call(arguments.length < 3 ? target : receiver);
|
496
|
-
}
|
497
|
-
return desc.value;
|
498
|
-
};
|
499
|
-
}
|
500
|
-
return _get.apply(this, arguments);
|
501
|
-
}
|
502
|
-
function _toConsumableArray(arr) {
|
503
|
-
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
|
504
|
-
}
|
505
|
-
function _arrayWithoutHoles(arr) {
|
506
|
-
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
|
507
|
-
}
|
508
|
-
function _iterableToArray(iter) {
|
509
|
-
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
510
|
-
}
|
511
|
-
function _unsupportedIterableToArray(o, minLen) {
|
512
|
-
if (!o) return;
|
513
|
-
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
514
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
515
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
516
|
-
if (n === "Map" || n === "Set") return Array.from(o);
|
517
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
518
|
-
}
|
519
|
-
function _arrayLikeToArray(arr, len) {
|
520
|
-
if (len == null || len > arr.length) len = arr.length;
|
521
|
-
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
522
|
-
return arr2;
|
523
|
-
}
|
524
|
-
function _nonIterableSpread() {
|
525
|
-
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
526
|
-
}
|
527
|
-
function _createForOfIteratorHelper(o, allowArrayLike) {
|
528
|
-
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
|
529
|
-
if (!it) {
|
530
|
-
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike ) {
|
531
|
-
if (it) o = it;
|
532
|
-
var i = 0;
|
533
|
-
var F = function () {};
|
534
|
-
return {
|
535
|
-
s: F,
|
536
|
-
n: function () {
|
537
|
-
if (i >= o.length) return {
|
538
|
-
done: true
|
539
|
-
};
|
540
|
-
return {
|
541
|
-
done: false,
|
542
|
-
value: o[i++]
|
543
|
-
};
|
544
|
-
},
|
545
|
-
e: function (e) {
|
546
|
-
throw e;
|
547
|
-
},
|
548
|
-
f: F
|
549
|
-
};
|
550
|
-
}
|
551
|
-
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
552
|
-
}
|
553
|
-
var normalCompletion = true,
|
554
|
-
didErr = false,
|
555
|
-
err;
|
556
|
-
return {
|
557
|
-
s: function () {
|
558
|
-
it = it.call(o);
|
559
|
-
},
|
560
|
-
n: function () {
|
561
|
-
var step = it.next();
|
562
|
-
normalCompletion = step.done;
|
563
|
-
return step;
|
564
|
-
},
|
565
|
-
e: function (e) {
|
566
|
-
didErr = true;
|
567
|
-
err = e;
|
568
|
-
},
|
569
|
-
f: function () {
|
570
|
-
try {
|
571
|
-
if (!normalCompletion && it.return != null) it.return();
|
572
|
-
} finally {
|
573
|
-
if (didErr) throw err;
|
574
|
-
}
|
575
|
-
}
|
576
|
-
};
|
577
|
-
}
|
578
|
-
|
579
|
-
var _placeholder = {'@@functional/placeholder':true};
|
580
533
|
|
581
|
-
function _isPlaceholder(a){return a===
|
534
|
+
function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
|
582
535
|
|
583
536
|
/**
|
584
537
|
* Optimized internal one-arity curry function.
|
@@ -952,7 +905,7 @@
|
|
952
905
|
|
953
906
|
var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
|
954
907
|
|
955
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.
|
908
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.4.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
956
909
|
|
957
910
|
var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
958
911
|
|
@@ -1035,7 +988,7 @@
|
|
1035
988
|
* @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
|
1036
989
|
*
|
1037
990
|
* @returns HTMLScriptElement
|
1038
|
-
*/var createScriptElement=function createScriptElement(url,id){var async=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var onload=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var onerror=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var extraAttributes=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};var scriptElement=document.createElement('script');scriptElement.type='text/javascript';scriptElement.onload=onload;scriptElement.onerror=onerror;scriptElement.src=url;scriptElement.id=id;scriptElement.async=async;
|
991
|
+
*/var createScriptElement=function createScriptElement(url,id){var async=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var onload=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var onerror=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var extraAttributes=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};var scriptElement=document.createElement('script');scriptElement.type='text/javascript';scriptElement.onload=onload;scriptElement.onerror=onerror;scriptElement.src=url;scriptElement.id=id;scriptElement.async=async;Object.keys(extraAttributes).forEach(function(attributeName){scriptElement.setAttribute(attributeName,extraAttributes[attributeName]);});scriptElement.setAttribute('data-loader',EXTERNAL_SOURCE_LOAD_ORIGIN);return scriptElement;};/**
|
1039
992
|
* Add script DOM element to DOM
|
1040
993
|
*
|
1041
994
|
* @param {*} newScriptElement the script element to add
|
@@ -1091,19 +1044,28 @@
|
|
1091
1044
|
// default is v3
|
1092
1045
|
var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
|
1093
1046
|
|
1094
|
-
var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var
|
1095
|
-
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var
|
1096
|
-
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var
|
1097
|
-
|
1098
|
-
var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';
|
1047
|
+
var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(component){return "Failed to load the SDK as the base URL for ".concat(component," is not valid.");};// ERROR
|
1048
|
+
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
|
1049
|
+
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var NATIVE_DEST_PLUGIN_INITIALIZE_ERROR="NativeDestinationQueuePlugin initialization failed";var DATAPLANE_PLUGIN_INITIALIZE_ERROR="XhrQueuePlugin initialization failed";var DMT_PLUGIN_INITIALIZE_ERROR="DeviceModeTransformationPlugin initialization failed";var NATIVE_DEST_PLUGIN_ENQUEUE_ERROR="NativeDestinationQueuePlugin event enqueue failed";var DATAPLANE_PLUGIN_ENQUEUE_ERROR="XhrQueuePlugin event enqueue failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};// DEBUG
|
1050
|
+
|
1051
|
+
var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=new RegExp('^(https?:\\/\\/)'+// protocol
|
1052
|
+
'('+'((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|'+// domain name
|
1053
|
+
'localhost|'+// localhost
|
1054
|
+
'((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}'+// OR IP (v4) address first 3 octets
|
1055
|
+
'(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?))'+// last octet of IP address
|
1056
|
+
')'+'(\\:\\d+)?'+// port
|
1057
|
+
'(\\/[-a-zA-Z\\d%_.~+]*)*'+// path
|
1058
|
+
'(\\?[;&a-zA-Z\\d%_.~+=-]*)?'+// query string
|
1059
|
+
'(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
|
1060
|
+
;
|
1099
1061
|
|
1100
1062
|
var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEST_SDK_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
|
1101
1063
|
|
1102
1064
|
var DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var ErrorReportingProvidersToPluginNameMap=_defineProperty({},DEFAULT_ERROR_REPORTING_PROVIDER,'Bugsnag');var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');var DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';
|
1103
1065
|
|
1104
|
-
var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true},sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
|
1066
|
+
var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true},sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
|
1105
1067
|
|
1106
|
-
var USER_SESSION_STORAGE_KEYS={userId:'rl_user_id',userTraits:'rl_trait',anonymousId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session',authToken:'rl_auth_token'};var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};
|
1068
|
+
var USER_SESSION_STORAGE_KEYS={userId:'rl_user_id',userTraits:'rl_trait',anonymousId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session',authToken:'rl_auth_token'};var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
|
1107
1069
|
|
1108
1070
|
var defaultSessionConfiguration={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};var sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
|
1109
1071
|
|
@@ -1119,7 +1081,7 @@
|
|
1119
1081
|
|
1120
1082
|
var metricsState={retries:d$1(0),dropped:d$1(0),sent:d$1(0),queued:d$1(0),triggered:d$1(0)};
|
1121
1083
|
|
1122
|
-
var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(''),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
|
1084
|
+
var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION,installType:MODULE_TYPE}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(''),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
|
1123
1085
|
|
1124
1086
|
var nativeDestinationsState={configuredDestinations:d$1([]),activeDestinations:d$1([]),loadOnlyIntegrations:d$1({}),failedDestinations:d$1([]),loadIntegration:d$1(true),initializedDestinations:d$1([]),clientDestinationsReady:d$1(false),integrationsConfig:d$1({})};
|
1125
1087
|
|
@@ -1178,7 +1140,7 @@
|
|
1178
1140
|
* Send handled errors to external error monitoring service via a plugin
|
1179
1141
|
*
|
1180
1142
|
* @param {Error} error Error instance from handled error
|
1181
|
-
*/},{key:"notifyError",value:function notifyError(error){if(this.
|
1143
|
+
*/},{key:"notifyError",value:function notifyError(error){if(this.errReportingClient&&isAllowedToBeNotified(error)){try{var _this$pluginEngine;(_this$pluginEngine=this.pluginEngine)===null||_this$pluginEngine===void 0||_this$pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,this.errReportingClient,error,state,this.logger);}catch(err){var _this$logger2;// Not calling onError here as we don't want to go into infinite loop
|
1182
1144
|
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1183
1145
|
|
1184
1146
|
/**
|
@@ -1205,7 +1167,14 @@
|
|
1205
1167
|
|
1206
1168
|
var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
|
1207
1169
|
|
1208
|
-
var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');}
|
1170
|
+
var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};/**
|
1171
|
+
* Checks if provided url is valid or not
|
1172
|
+
* @param url
|
1173
|
+
* @returns true if `url` is valid and false otherwise
|
1174
|
+
*/var isValidURL=function isValidURL(url){if(!isString(url)){return false;}try{// If URL is supported by the browser, we can use it to validate the URL
|
1175
|
+
// Otherwise, we can at least check if the URL matches the pattern
|
1176
|
+
if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
|
1177
|
+
new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
1209
1178
|
|
1210
1179
|
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
1211
1180
|
|
@@ -1259,6 +1228,17 @@
|
|
1259
1228
|
|
1260
1229
|
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1261
1230
|
|
1231
|
+
var onPageLeave=function onPageLeave(callback){// To ensure the callback is only called once even if more than one events
|
1232
|
+
// are fired at once.
|
1233
|
+
var pageLeft=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback();}// Catches the unloading of the page (e.g., closing the tab or navigating away).
|
1234
|
+
// Includes user actions like clicking a link, entering a new URL,
|
1235
|
+
// refreshing the page, or closing the browser tab
|
1236
|
+
// Note that 'pagehide' is not supported in IE.
|
1237
|
+
// So, this is a fallback.
|
1238
|
+
globalThis.addEventListener('beforeunload',handleOnLeave);// Catches the page being hidden, including scenarios like closing the tab.
|
1239
|
+
document.addEventListener('pagehide',handleOnLeave);// Catches visibility changes, such as switching tabs or minimizing the browser.
|
1240
|
+
document.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
|
1241
|
+
|
1262
1242
|
var ScheduleModes=/*#__PURE__*/function(ScheduleModes){ScheduleModes[ScheduleModes["ASAP"]=1]="ASAP";ScheduleModes[ScheduleModes["RESCHEDULE"]=2]="RESCHEDULE";ScheduleModes[ScheduleModes["ABANDON"]=3]="ABANDON";return ScheduleModes;}({});var DEFAULT_CLOCK_LATE_FACTOR=2;var DEFAULT_CLOCK={setTimeout:function setTimeout(fn,ms){return globalThis.setTimeout(fn,ms);},clearTimeout:function clearTimeout(id){return globalThis.clearTimeout(id);},Date:globalThis.Date,clockLateFactor:DEFAULT_CLOCK_LATE_FACTOR};var Schedule=/*#__PURE__*/function(){function Schedule(){_classCallCheck(this,Schedule);this.tasks={};this.nextId=1;this.clock=DEFAULT_CLOCK;}return _createClass(Schedule,[{key:"now",value:function now(){return +new this.clock.Date();}},{key:"run",value:function run(task,timeout,mode){var id=(this.nextId+1).toString();this.tasks[id]=this.clock.setTimeout(this.handle(id,task,timeout,mode||ScheduleModes.ASAP),timeout);return id;}},{key:"handle",value:function handle(id,callback,timeout,mode){var _this=this;var start=this.now();return function(){delete _this.tasks[id];var elapsedTimeoutTime=start+timeout*(_this.clock.clockLateFactor||DEFAULT_CLOCK_LATE_FACTOR);var currentTime=_this.now();var notCompletedOrTimedOut=mode>=ScheduleModes.RESCHEDULE&&elapsedTimeoutTime<currentTime;if(notCompletedOrTimedOut){if(mode===ScheduleModes.RESCHEDULE){_this.run(callback,timeout,mode);}return undefined;}return callback();};}},{key:"cancel",value:function cancel(id){if(this.tasks[id]){this.clock.clearTimeout(this.tasks[id]);delete this.tasks[id];}}},{key:"cancelAll",value:function cancelAll(){Object.values(this.tasks).forEach(this.clock.clearTimeout);this.tasks={};}}]);}();
|
1263
1243
|
|
1264
1244
|
var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};var RETRY_QUEUE_ENTRY_REMOVE_ERROR=function RETRY_QUEUE_ENTRY_REMOVE_ERROR(context,entry,attempt){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to remove local storage entry \"").concat(entry,"\" (attempt: ").concat(attempt,".");};
|
@@ -1278,9 +1258,9 @@
|
|
1278
1258
|
timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
|
1279
1259
|
this.timeouts={ackTimer:Math.round(timerScaleFactor*DEFAULT_ACK_TIMER_MS),reclaimTimer:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMER_MS),reclaimTimeout:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMEOUT_MS),reclaimWait:Math.round(timerScaleFactor*DEFAULT_RECLAIM_WAIT_MS)};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
|
1280
1260
|
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
|
1281
|
-
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);//
|
1282
|
-
this.
|
1283
|
-
this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==void 0?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==void 0?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==void 0?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"
|
1261
|
+
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);// Flush the queue on page leave
|
1262
|
+
this.flushBatchOnPageLeave();this.scheduleTimeoutActive=false;}return _createClass(RetryQueue,[{key:"setDefaultQueueEntries",value:function setDefaultQueueEntries(){this.setStorageEntry(QueueStatuses.IN_PROGRESS,{});this.setStorageEntry(QueueStatuses.QUEUE,[]);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);}},{key:"configureBatchMode",value:function configureBatchMode(options){this.batchingInProgress=false;if(!isObjectLiteralAndNotNull(options.batch)){return;}var batchOptions=options.batch;this.batch.enabled=batchOptions.enabled===true;if(this.batch.enabled){var _batchOptions$maxSize,_batchOptions$maxItem,_batchOptions$flushIn;// Set upper cap on the batch payload size
|
1263
|
+
this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==void 0?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==void 0?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==void 0?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"flushBatchOnPageLeave",value:function flushBatchOnPageLeave(){if(this.batch.enabled){onPageLeave(this.flushBatch);}}},{key:"getStorageEntry",value:function getStorageEntry(name){return this.store.get(name);}// TODO: fix the type of different queues to be the same if possible
|
1284
1264
|
},{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
|
1285
1265
|
* Stops processing the queue
|
1286
1266
|
*/},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
|
@@ -1329,27 +1309,27 @@
|
|
1329
1309
|
* Returns the information about whether the batch criteria is met or exceeded
|
1330
1310
|
* @param batchItems Prospective batch items
|
1331
1311
|
* @returns Batch dispatch info
|
1332
|
-
*/},{key:"getBatchDispatchInfo",value:function getBatchDispatchInfo(batchItems){var _this$batch2,_this$batch3;var lengthCriteriaMet=false;var lengthCriteriaExceeded=false;var configuredBatchMaxItems=(_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems;if(isDefined(configuredBatchMaxItems)){lengthCriteriaMet=batchItems.length===configuredBatchMaxItems;lengthCriteriaExceeded=batchItems.length>configuredBatchMaxItems;}if(lengthCriteriaMet||lengthCriteriaExceeded){return {criteriaMet:lengthCriteriaMet,criteriaExceeded:lengthCriteriaExceeded};}var sizeCriteriaMet=false;var sizeCriteriaExceeded=false;var configuredBatchMaxSize=(_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize;if(isDefined(configuredBatchMaxSize)&&isDefined(this.batchSizeCalcCb)){var curBatchSize=this.batchSizeCalcCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize===configuredBatchMaxSize;sizeCriteriaExceeded=curBatchSize>configuredBatchMaxSize;}return {criteriaMet:sizeCriteriaMet,criteriaExceeded:sizeCriteriaExceeded};}},{key:"processHead",value:function processHead(){var _ref4,_ref5,
|
1312
|
+
*/},{key:"getBatchDispatchInfo",value:function getBatchDispatchInfo(batchItems){var _this$batch2,_this$batch3;var lengthCriteriaMet=false;var lengthCriteriaExceeded=false;var configuredBatchMaxItems=(_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems;if(isDefined(configuredBatchMaxItems)){lengthCriteriaMet=batchItems.length===configuredBatchMaxItems;lengthCriteriaExceeded=batchItems.length>configuredBatchMaxItems;}if(lengthCriteriaMet||lengthCriteriaExceeded){return {criteriaMet:lengthCriteriaMet,criteriaExceeded:lengthCriteriaExceeded};}var sizeCriteriaMet=false;var sizeCriteriaExceeded=false;var configuredBatchMaxSize=(_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize;if(isDefined(configuredBatchMaxSize)&&isDefined(this.batchSizeCalcCb)){var curBatchSize=this.batchSizeCalcCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize===configuredBatchMaxSize;sizeCriteriaExceeded=curBatchSize>configuredBatchMaxSize;}return {criteriaMet:sizeCriteriaMet,criteriaExceeded:sizeCriteriaExceeded};}},{key:"processHead",value:function processHead(){var _ref4,_ref5,_this=this,_ref7;// cancel the scheduled task if it exists
|
1333
1313
|
this.schedule.cancel(this.processId);// Pop the head off the queue
|
1334
1314
|
var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==void 0?_ref4:[];var inProgress=(_ref5=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1335
|
-
var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref6;var inProgress=(_ref6=
|
1315
|
+
var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref6;var inProgress=(_ref6=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==void 0?_ref6:{};delete inProgress[id];_this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this.requeue(el.item,el.attemptNumber+1,err,el.id);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
|
1336
1316
|
while(queue.length>0&&queue[0].time<=now&&inProgressSize++<this.maxItems){var el=queue.shift();if(el){var id=generateUUID();// Save this to the in progress map
|
1337
1317
|
inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now()};enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
|
1338
|
-
try{var willBeRetried=
|
1318
|
+
try{var willBeRetried=_this.shouldRetry(el.item,el.attemptNumber+1);_this.processQueueCb(el.item,el.done,el.attemptNumber,_this.maxAttempts,willBeRetried);}catch(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE),err);}});// re-read the queue in case the process function finished immediately or added another item
|
1339
1319
|
queue=(_ref7=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref7!==void 0?_ref7:[];this.schedule.cancel(this.processId);if(queue.length>0){var nextProcessExecutionTime=queue[0].time-now;this.processId=this.schedule.run(this.processHead,nextProcessExecutionTime,ScheduleModes.ASAP);}}// Ack continuously to prevent other tabs from claiming our queue
|
1340
|
-
},{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,
|
1320
|
+
},{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==void 0?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==void 0?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==void 0?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==void 0?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==void 0?_el$id:generateUUID();if(trackMessageIds.includes(id));else {our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id});trackMessageIds.push(id);}};if(Array.isArray(queue)){queue.forEach(concatIterator);}else if(queue){Object.values(queue).forEach(concatIterator);}};// add their queue to ours, resetting run-time to immediate and copying the attempt#
|
1341
1321
|
addConcatQueue(their.queue,0);// Process batch queue items
|
1342
|
-
if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();if(trackMessageIds.includes(id));else {
|
1322
|
+
if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();if(trackMessageIds.includes(id));else {_this2.enqueue(el);trackMessageIds.push(id);}});}else {// if batching is not enabled in the current instance, add those items to the main queue directly
|
1343
1323
|
addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
|
1344
1324
|
addConcatQueue(their.inProgress,1);our.queue=our.queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
|
1345
1325
|
this.clearQueueEntries(other,1);// process the new items we claimed
|
1346
1326
|
this.processHead();}// eslint-disable-next-line class-methods-use-this
|
1347
|
-
},{key:"clearQueueEntries",value:function clearQueueEntries(other,localStorageBackoff){this.removeStorageEntry(other,0,localStorageBackoff);}},{key:"removeStorageEntry",value:function removeStorageEntry(store,entryIdx,backoff){var
|
1348
|
-
if(entryIdx+1<queueEntryKeys.length){
|
1349
|
-
|
1350
|
-
if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){
|
1327
|
+
},{key:"clearQueueEntries",value:function clearQueueEntries(other,localStorageBackoff){this.removeStorageEntry(other,0,localStorageBackoff);}},{key:"removeStorageEntry",value:function removeStorageEntry(store,entryIdx,backoff){var _this3=this;var attempt=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var maxAttempts=2;var queueEntryKeys=Object.keys(QueueStatuses);var entry=QueueStatuses[queueEntryKeys[entryIdx]];globalThis.setTimeout(function(){try{store.remove(entry);// clear the next entry
|
1328
|
+
if(entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}catch(err){var storageBusyErr='NS_ERROR_STORAGE_BUSY';var isLocalStorageBusy=err.name===storageBusyErr||err.code===storageBusyErr||err.code===0x80630001;if(isLocalStorageBusy&&attempt<maxAttempts){// Try clearing the same entry again with some extra delay
|
1329
|
+
_this3.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===void 0||_this3$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
|
1330
|
+
if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this4=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this4.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}_this4.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}store.set(QueueStatuses.RECLAIM_END,_this4.id);_this4.schedule.run(createReclaimStartTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this4.id);store.set(QueueStatuses.ACK,_this4.schedule.now());_this4.schedule.run(createReclaimEndTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storageEngine=_this4.store.getOriginalEngine();var storageKeys=[];// 'keys' API is not supported by all the core SDK versions
|
1351
1331
|
// Hence, we need this backward compatibility check
|
1352
|
-
if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==
|
1332
|
+
if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_this4.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this4.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this4.schedule.now()-store.get(QueueStatuses.ACK)<_this4.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);}();
|
1353
1333
|
|
1354
1334
|
var pluginName$e='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},dataplaneEventsQueue:{/**
|
1355
1335
|
* Initialize the queue for delivery
|
@@ -1375,7 +1355,7 @@
|
|
1375
1355
|
// It'll be updated to the latest timestamp during actual delivery
|
1376
1356
|
event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);eventsQueue.addItem({event:event});}}};};
|
1377
1357
|
|
1378
|
-
var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var BUGSNAG_SDK_LOAD_TIMEOUT_ERROR=function BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(timeout){return "A timeout ".concat(timeout," ms occurred while trying to load the Bugsnag SDK.");};var BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};
|
1358
|
+
var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var BUGSNAG_SDK_LOAD_TIMEOUT_ERROR=function BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(timeout){return "A timeout ".concat(timeout," ms occurred while trying to load the Bugsnag SDK.");};var BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};var FAILED_TO_FILTER_ERROR=function FAILED_TO_FILTER_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to filter the error.");};
|
1379
1359
|
|
1380
1360
|
var BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME='bugsnag';// For version 6 and below
|
1381
1361
|
var BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME='Bugsnag';var GLOBAL_LIBRARY_OBJECT_NAMES=[BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];var BUGSNAG_CDN_URL='https://d2wy8f7a9ursnm.cloudfront.net/v6/bugsnag.min.js';var ERROR_REPORT_PROVIDER_NAME_BUGSNAG='rs-bugsnag';// This API key token is parsed in the CI pipeline
|
@@ -1394,24 +1374,23 @@
|
|
1394
1374
|
var version=globalLibInstance===null||globalLibInstance===void 0||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===void 0||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===void 0?void 0:_globalLibInstance$_c.version;// For versions older than 7
|
1395
1375
|
if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
|
1396
1376
|
beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===void 0?void 0:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}// Prefix folder for all the destination SDK scripts
|
1397
|
-
var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var enhanceErrorEventMutator=function enhanceErrorEventMutator(event
|
1377
|
+
var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):undefined;};var enhanceErrorEventMutator=function enhanceErrorEventMutator(state,event){var _getAppStateForMetada;event.updateMetaData('source',{snippetVersion:globalThis.RudderSnippetVersion});event.updateMetaData('state',(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
|
1398
1378
|
event.context=errorMessage;// Hack for easily grouping the script load errors
|
1399
1379
|
// on the dashboard
|
1400
1380
|
if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
|
1401
1381
|
event.context='Script load failures';}// eslint-disable-next-line no-param-reassign
|
1402
|
-
event.severity='error';};var onError=function onError(state){
|
1403
|
-
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event
|
1382
|
+
event.severity='error';};var onError=function onError(state,logger){return function(event){try{// Discard the event if it's not originated at the SDK
|
1383
|
+
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(state,event);return true;}catch(_unused){logger===null||logger===void 0||logger.error(FAILED_TO_FILTER_ERROR(BUGSNAG_PLUGIN));// Drop the error event if it couldn't be filtered as
|
1404
1384
|
// it is most likely a non-SDK error
|
1405
|
-
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'
|
1406
|
-
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1385
|
+
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var _state$source$value;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:state.context.app.value.version,metaData:{SDK:{name:'JS',installType:state.context.app.value.installType}},beforeSend:onError(state,logger),autoCaptureSessions:false,// auto capture sessions is disabled
|
1407
1386
|
collectUserIp:false,// collecting user's IP is disabled
|
1408
1387
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
1409
|
-
maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:state.lifecycle.writeKey.value},logger:logger,networkBreadcrumbsEnabled:false};var client=globalBugsnagLibInstance(clientConfig);return client;};var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};var loadBugsnagSDK=function loadBugsnagSDK(externalSrcLoader,logger){var isNotLoaded=GLOBAL_LIBRARY_OBJECT_NAMES.every(function(globalKeyName){return !globalThis[globalKeyName];});if(!isNotLoaded){return;}externalSrcLoader.loadJSFile({url:BUGSNAG_CDN_URL,id:ERROR_REPORT_PROVIDER_NAME_BUGSNAG,callback:function callback(id){if(!id){logger===null||logger===void 0||logger.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));}}});};var initBugsnagClient=function initBugsnagClient(state,promiseResolve,promiseReject,logger){var time=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();if(typeof globalBugsnagLibInstance==='function'){if(isValidVersion(globalBugsnagLibInstance)){var client=getNewClient(state,logger);promiseResolve(client);}}else if(time>=MAX_WAIT_FOR_SDK_LOAD_MS){promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));}else {// Try to initialize the client after a delay
|
1410
|
-
globalThis.setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};
|
1388
|
+
maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:((_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)||state.lifecycle.writeKey.value},logger:logger,networkBreadcrumbsEnabled:false};var client=globalBugsnagLibInstance(clientConfig);return client;};var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};var loadBugsnagSDK=function loadBugsnagSDK(externalSrcLoader,logger){var isNotLoaded=GLOBAL_LIBRARY_OBJECT_NAMES.every(function(globalKeyName){return !globalThis[globalKeyName];});if(!isNotLoaded){return;}externalSrcLoader.loadJSFile({url:BUGSNAG_CDN_URL,id:ERROR_REPORT_PROVIDER_NAME_BUGSNAG,callback:function callback(id){if(!id){logger===null||logger===void 0||logger.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));}}});};var initBugsnagClient=function initBugsnagClient(state,promiseResolve,promiseReject,logger){var time=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();if(typeof globalBugsnagLibInstance==='function'){if(isValidVersion(globalBugsnagLibInstance)){var client=getNewClient(state,logger);promiseResolve(client);}}else if(time>=MAX_WAIT_FOR_SDK_LOAD_MS){promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));}else {// Try to initialize the client after a delay
|
1389
|
+
globalThis.setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};
|
1411
1390
|
|
1412
1391
|
var pluginName$d='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},errorReportingProvider:{init:function init(state,externalSrcLoader,logger){return new Promise(function(resolve,reject){// If API key token is not parsed or invalid, don't proceed to initialize the client
|
1413
1392
|
if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}// If SDK URL is empty, don't proceed to initialize the client
|
1414
|
-
loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client
|
1393
|
+
loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client.notify(error);},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0||client.leaveBreadcrumb(message);}}};};
|
1415
1394
|
|
1416
1395
|
var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
|
1417
1396
|
|
@@ -2919,7 +2898,7 @@
|
|
2919
2898
|
*/ // eslint-disable-next-line class-methods-use-this
|
2920
2899
|
},{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _this=this;// This contains the default plugins if load option has been omitted by user
|
2921
2900
|
var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}var pluginGroupsToProcess=[{configurationStatus:function configurationStatus(){return isDefined(state.dataPlaneEvents.eventsQueuePluginName.value);},configurationStatusStr:'Data plane events delivery is enabled',activePluginName:state.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(DataPlaneEventsTransportToPluginNameMap),shouldAddMissingPlugins:true},{configurationStatus:function configurationStatus(){return isDefined(state.reporting.errorReportingProviderPluginName.value);},configurationStatusStr:'Error reporting is enabled',activePluginName:state.reporting.errorReportingProviderPluginName.value,basePlugins:['ErrorReporting'],supportedPlugins:Object.values(ErrorReportingProvidersToPluginNameMap)},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length>0;},configurationStatusStr:'Device mode destinations are connected to the source',supportedPlugins:['DeviceModeDestinations','NativeDestinationQueue']},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(function(destination){return destination.shouldApplyDeviceModeTransformation;});},configurationStatusStr:'Device mode transformations are enabled for at least one destination',supportedPlugins:['DeviceModeTransformation']},{configurationStatus:function configurationStatus(){return isDefined(state.consents.activeConsentManagerPluginName.value);},configurationStatusStr:'Consent management is enabled',activePluginName:state.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(ConsentManagersToPluginNameMap)},{configurationStatus:function configurationStatus(){return isDefined(state.storage.encryptionPluginName.value);},configurationStatusStr:'Storage encryption is enabled',activePluginName:state.storage.encryptionPluginName.value,supportedPlugins:Object.values(StorageEncryptionVersionsToPluginNameMap)},{configurationStatus:function configurationStatus(){return state.storage.migrate.value;},configurationStatusStr:'Storage migration is enabled',supportedPlugins:['StorageMigrator']}];var addMissingPlugins=false;pluginGroupsToProcess.forEach(function(group){if(group.configurationStatus()){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.activePluginName?function(pluginName){return !(pluginName!==group.activePluginName&&group.supportedPlugins.includes(pluginName));}:function(pluginName){return isDefined(pluginName);}// pass through
|
2922
|
-
);_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){var _this$logger;if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(
|
2901
|
+
);_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){var _this$logger;if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
|
2923
2902
|
* Determine the list of plugins that should be activated
|
2924
2903
|
*/},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
2925
2904
|
var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error("Ignoring loading of unknown plugins: ".concat(failedPlugins.join(','),". Mandatory plugins: ").concat(Object.keys(getMandatoryPluginsMap()).join(','),". Load option plugins: ").concat(state.plugins.pluginsToLoadFromConfig.value.join(','))));}r(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
|
@@ -2950,7 +2929,7 @@
|
|
2950
2929
|
* this is not supported by our sourceConfig API
|
2951
2930
|
*/var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
|
2952
2931
|
return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
2953
|
-
var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url)
|
2932
|
+
var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
|
2954
2933
|
// and the first call to the send method in legacy browsers
|
2955
2934
|
xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
|
2956
2935
|
|
@@ -3045,7 +3024,7 @@
|
|
3045
3024
|
if(cookie(cname)){// Remove cookie from domain
|
3046
3025
|
cookie(cname,null,opts);return _domain;}}return '';};
|
3047
3026
|
|
3048
|
-
var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=domain(globalThis.location.href);return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultSessionStorageOptions=function getDefaultSessionStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
|
3027
|
+
var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=".".concat(domain(globalThis.location.href));return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultSessionStorageOptions=function getDefaultSessionStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
|
3049
3028
|
|
3050
3029
|
/**
|
3051
3030
|
* A storage utility to persist values in cookies via Storage interface
|
@@ -3162,20 +3141,30 @@
|
|
3162
3141
|
* Handle errors
|
3163
3142
|
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);}();
|
3164
3143
|
|
3144
|
+
var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(!isValidURL(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomainUrl=function getTopDomainUrl(url){// Create a URL object
|
3145
|
+
var urlObj=new URL(url);// Extract the host and protocol
|
3146
|
+
var host=urlObj.host,protocol=urlObj.protocol;// Split the host into parts
|
3147
|
+
var parts=host.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
3148
|
+
if(parts.length>2){// Join the last two parts for the top-level domain
|
3149
|
+
topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
|
3150
|
+
topDomain=host;}return "".concat(protocol,"//").concat(topDomain);};var getDataServiceUrl=function getDataServiceUrl(endpoint){var url=getTopDomainUrl(window.location.href);var formattedEndpoint=endpoint.startsWith('/')?endpoint.substring(1):endpoint;return "".concat(url,"/").concat(formattedEndpoint);};
|
3151
|
+
|
3152
|
+
/**
|
3153
|
+
* A function to filter enabled destinations and map to required properties only
|
3154
|
+
* @param destinations
|
3155
|
+
*
|
3156
|
+
* @returns Destination[]
|
3157
|
+
*/var filterEnabledDestination=function filterEnabledDestination(destinations){var nativeDestinations=[];destinations.forEach(function(destination){if(destination.enabled&&!destination.deleted){nativeDestinations.push({id:destination.id,displayName:destination.destinationDefinition.displayName,config:destination.config,shouldApplyDeviceModeTransformation:destination.shouldApplyDeviceModeTransformation||false,propagateEventsUntransformedOnError:destination.propagateEventsUntransformedOnError||false,userFriendlyId:"".concat(destination.destinationDefinition.displayName.replaceAll(' ','-'),"___").concat(destination.id)});}});return nativeDestinations;};
|
3158
|
+
|
3165
3159
|
/**
|
3166
3160
|
* Removes trailing slash from url
|
3167
3161
|
* @param url
|
3168
3162
|
* @returns url
|
3169
|
-
*/var removeTrailingSlashes=function removeTrailingSlashes(url){return url&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;};/**
|
3170
|
-
* Checks if provided url is valid or not
|
3171
|
-
* @param url
|
3172
|
-
* @returns true if `url` is valid and false otherwise
|
3173
|
-
*/var isValidUrl=function isValidUrl(url){try{var validUrl=new URL(url);return Boolean(validUrl);}catch(err){return false;}};/**
|
3163
|
+
*/var removeTrailingSlashes=function removeTrailingSlashes(url){return url!==null&&url!==void 0&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;};var getDomain=function getDomain(url){try{var urlObj=new URL(url);return urlObj.host;}catch(error){return null;}};/**
|
3174
3164
|
* Get the referring domain from the referrer URL
|
3175
3165
|
* @param referrer Page referrer
|
3176
3166
|
* @returns Page referring domain
|
3177
|
-
*/var getReferringDomain=function getReferringDomain(referrer){var
|
3178
|
-
}return referringDomain;};/**
|
3167
|
+
*/var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
|
3179
3168
|
* Extracts UTM parameters from the URL
|
3180
3169
|
* @param url Page URL
|
3181
3170
|
* @returns UTM parameters
|
@@ -3188,62 +3177,6 @@
|
|
3188
3177
|
*/var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
3189
3178
|
}return urlWithoutHash;};
|
3190
3179
|
|
3191
|
-
var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(dataPlaneUrl&&!isValidUrl(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomainUrl=function getTopDomainUrl(url){// Create a URL object
|
3192
|
-
var urlObj=new URL(url);// Extract the hostname and protocol
|
3193
|
-
var hostname=urlObj.hostname,protocol=urlObj.protocol;// Split the hostname into parts
|
3194
|
-
var parts=hostname.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
3195
|
-
if(parts.length>2){// Join the last two parts for the top-level domain
|
3196
|
-
topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
|
3197
|
-
topDomain=hostname;}return "".concat(protocol,"//").concat(topDomain);};var getDataServiceUrl=function getDataServiceUrl(endpoint){var url=getTopDomainUrl(window.location.href);var formattedEndpoint=endpoint.startsWith('/')?endpoint.substring(1):endpoint;return "".concat(url,"/").concat(formattedEndpoint);};
|
3198
|
-
|
3199
|
-
/**
|
3200
|
-
* Plugins to be loaded in the plugins loadOption is not defined
|
3201
|
-
*/var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
|
3202
|
-
|
3203
|
-
/**
|
3204
|
-
* A function to check given value is a number or not
|
3205
|
-
* @param num input value
|
3206
|
-
* @returns boolean
|
3207
|
-
*/var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
|
3208
|
-
* A function to check given number has minimum length or not
|
3209
|
-
* @param minimumLength minimum length
|
3210
|
-
* @param num input number
|
3211
|
-
* @returns boolean
|
3212
|
-
*/var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
|
3213
|
-
* A function to check given value is a positive integer or not
|
3214
|
-
* @param num input value
|
3215
|
-
* @returns boolean
|
3216
|
-
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3217
|
-
|
3218
|
-
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
|
3219
|
-
var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;normalizedLoadOpts.useServerSideCookies=normalizedLoadOpts.useServerSideCookies===true;if(normalizedLoadOpts.dataServiceEndpoint&&typeof normalizedLoadOpts.dataServiceEndpoint!=='string'){delete normalizedLoadOpts.dataServiceEndpoint;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
|
3220
|
-
// doesn't seem to throw errors for empty URLs
|
3221
|
-
// TODO: Need to improve this check to find out if the URL is valid or not
|
3222
|
-
if(configUrl){try{var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}catch(err){logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
|
3223
|
-
|
3224
|
-
/**
|
3225
|
-
* A function to filter enabled destinations and map to required properties only
|
3226
|
-
* @param destinations
|
3227
|
-
*
|
3228
|
-
* @returns Destination[]
|
3229
|
-
*/var filterEnabledDestination=function filterEnabledDestination(destinations){var nativeDestinations=[];destinations.forEach(function(destination){if(destination.enabled&&!destination.deleted){nativeDestinations.push({id:destination.id,displayName:destination.destinationDefinition.displayName,config:destination.config,shouldApplyDeviceModeTransformation:destination.shouldApplyDeviceModeTransformation||false,propagateEventsUntransformedOnError:destination.propagateEventsUntransformedOnError||false,userFriendlyId:"".concat(destination.destinationDefinition.displayName.replaceAll(' ','-'),"___").concat(destination.id)});}});return nativeDestinations;};
|
3230
|
-
|
3231
|
-
var DEFAULT_REGION='US';/**
|
3232
|
-
* A function to get url from source config response
|
3233
|
-
* @param {array} urls An array of objects containing urls
|
3234
|
-
* @returns
|
3235
|
-
*/var getDefaultUrlOfRegion=function getDefaultUrlOfRegion(urls){var url;if(Array.isArray(urls)&&urls.length>0){var obj=urls.find(function(elem){return elem.default===true;});if(obj&&isValidUrl(obj.url)){return obj.url;}}return url;};var validateResidencyServerRegion=function validateResidencyServerRegion(residencyServerRegion,logger){var residencyServerRegions=['US','EU'];if(residencyServerRegion&&!residencyServerRegions.includes(residencyServerRegion)){logger===null||logger===void 0||logger.warn(UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(CONFIG_MANAGER,residencyServerRegion,DEFAULT_REGION));return undefined;}return residencyServerRegion;};/**
|
3236
|
-
* A function to determine the dataPlaneUrl
|
3237
|
-
* @param {Object} dataplanes An object containing dataPlaneUrl for different region
|
3238
|
-
* @param {String} serverUrl dataPlaneUrl provided in the load call
|
3239
|
-
* @param {String} residencyServerRegion User provided residency server region
|
3240
|
-
* @param {Logger} logger logger instance
|
3241
|
-
* @returns The data plane URL string to use
|
3242
|
-
*/var resolveDataPlaneUrl=function resolveDataPlaneUrl(dataplanes,serverUrl,residencyServerRegion,logger){// Check if dataPlanes object is present in source config
|
3243
|
-
if(dataplanes&&Object.keys(dataplanes).length>0){var _validateResidencySer;var region=(_validateResidencySer=validateResidencyServerRegion(residencyServerRegion,logger))!==null&&_validateResidencySer!==void 0?_validateResidencySer:DEFAULT_REGION;var regionUrlArr=dataplanes[region]||dataplanes[DEFAULT_REGION];var defaultUrl=getDefaultUrlOfRegion(regionUrlArr);if(defaultUrl){return defaultUrl;}}// return the dataPlaneUrl provided in load API(if available)
|
3244
|
-
if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
|
3245
|
-
return undefined;};
|
3246
|
-
|
3247
3180
|
/**
|
3248
3181
|
* Determines if the SDK is running inside a chrome extension
|
3249
3182
|
* @returns boolean
|
@@ -3278,7 +3211,7 @@
|
|
3278
3211
|
enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
|
3279
3212
|
|
3280
3213
|
/**
|
3281
|
-
* Determines the SDK
|
3214
|
+
* Determines the SDK URL
|
3282
3215
|
* @returns sdkURL
|
3283
3216
|
*/var getSDKUrl=function getSDKUrl(){var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
|
3284
3217
|
var _iterator=_createForOfIteratorHelper(scripts),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var script=_step.value;var src=script.getAttribute('src');if(src&&sdkFileNameRegex.test(src)){return src;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};/**
|
@@ -3287,63 +3220,61 @@
|
|
3287
3220
|
* @param logger Logger instance
|
3288
3221
|
*/var updateReportingState=function updateReportingState(res,logger){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){var errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
|
3289
3222
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3290
|
-
logger===null||logger===void 0||logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var
|
3223
|
+
logger===null||logger===void 0||logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
3291
3224
|
logger===null||logger===void 0||logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
|
3292
|
-
var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(function(){state.storage.type.value=storageType;
|
3293
|
-
|
3225
|
+
var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(function(){var _storageOptsFromLoad$2;state.storage.type.value=storageType;var cookieOptions=(_storageOptsFromLoad$2=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie)!==null&&_storageOptsFromLoad$2!==void 0?_storageOptsFromLoad$2:{};if(useServerSideCookies){state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT);if(isValidURL(dataServiceUrl)){state.serverCookies.dataServiceUrl.value=removeTrailingSlashes(dataServiceUrl);var curHost=getDomain(window.location.href);var dataServiceHost=getDomain(dataServiceUrl);// If the current host is different from the data service host, then it is a cross-site request
|
3226
|
+
// For server-side cookies to work, we need to set the SameSite=None and Secure attributes
|
3227
|
+
if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},cookieOptions),{},{samesite:'None',secure:true});}}else {state.serverCookies.isEnabledServerSideCookies.value=false;}}state.storage.cookie.value=cookieOptions;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
|
3228
|
+
var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===void 0?void 0:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==void 0?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===void 0?void 0:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===void 0?void 0:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==void 0?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===void 0?void 0:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(function(){var _state$loadOptions$va2;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
|
3294
3229
|
// if it is not already initialized and
|
3295
3230
|
// if consent management is enabled
|
3296
|
-
enabled:((_state$loadOptions$
|
3231
|
+
enabled:((_state$loadOptions$va2=state.loadOptions.value.preConsent)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
|
3297
3232
|
* Determines the consent management state variables from the source config data
|
3298
3233
|
* @param resp Source config response
|
3299
3234
|
* @param logger Logger instance
|
3300
3235
|
*/var updateConsentsState=function updateConsentsState(resp){var resolutionStrategy=state.consents.resolutionStrategy.value;var cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(function(p){return p.provider===state.consents.provider.value;}))===null||_resp$consentManageme2===void 0?void 0:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==void 0?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
|
3301
|
-
if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger===null||logger===void 0||logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}r(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};
|
3236
|
+
if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger===null||logger===void 0||logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}r(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';if(isValidURL(configUrl)){var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
|
3302
3237
|
|
3303
|
-
|
3238
|
+
var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,baseURL,currentVersion,lockVersion,customURL){var sdkComponentURL='';if(customURL){if(!isValidURL(customURL)){throw new Error(COMPONENT_BASE_URL_ERROR(componentType));}return removeTrailingSlashes(customURL);}var sdkURL=getSDKUrl();sdkComponentURL=sdkURL?sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/'):baseURL;if(lockVersion){sdkComponentURL=sdkComponentURL.replace("/".concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(pathSuffix),"/".concat(currentVersion,"/").concat(BUILD_TYPE,"/").concat(pathSuffix));}return sdkComponentURL;};/**
|
3304
3239
|
* A function that determines integration SDK loading path
|
3305
|
-
* @param
|
3240
|
+
* @param currentVersion
|
3306
3241
|
* @param lockIntegrationsVersion
|
3307
3242
|
* @param customIntegrationsCDNPath
|
3308
3243
|
* @returns
|
3309
|
-
*/var getIntegrationsCDNPath=function getIntegrationsCDNPath(
|
3310
|
-
if(customIntegrationsCDNPath){integrationsCDNPath=removeTrailingSlashes(customIntegrationsCDNPath);if(!integrationsCDNPath||integrationsCDNPath&&!isValidUrl(integrationsCDNPath)){throw new Error(INTG_CDN_BASE_URL_ERROR);}return integrationsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
|
3311
|
-
var sdkURL=getSDKUrl();integrationsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_INT_DIR).join('/'):DEST_SDK_BASE_URL;// If version is not locked it will always get the latest version of the integrations
|
3312
|
-
if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_ARCH_VERSION_DIR,requiredVersion);}return integrationsCDNPath;};/**
|
3244
|
+
*/var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEST_SDK_BASE_URL,currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath);};/**
|
3313
3245
|
* A function that determines plugins SDK loading path
|
3314
|
-
* @param
|
3315
|
-
* @
|
3316
|
-
|
3317
|
-
|
3318
|
-
|
3246
|
+
* @param currentVersion Current SDK version
|
3247
|
+
* @param lockPluginsVersion Flag to lock the plugins version
|
3248
|
+
* @param customPluginsCDNPath URL to load the plugins from
|
3249
|
+
* @returns Final plugins CDN path
|
3250
|
+
*/var getPluginsCDNPath=function getPluginsCDNPath(currentVersion,lockPluginsVersion,customPluginsCDNPath){return getSDKComponentBaseURL('plugins',CDN_PLUGINS_DIR,PLUGINS_BASE_URL,currentVersion,lockPluginsVersion,customPluginsCDNPath);};
|
3319
3251
|
|
3320
3252
|
var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;E(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
3321
3253
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3322
3254
|
* config related information in global state
|
3323
|
-
*/},{key:"init",value:function init(){var _this2=this;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var
|
3324
|
-
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,
|
3325
|
-
var pluginsCDNPath=getPluginsCDNPath(
|
3326
|
-
r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,_this2.logger);
|
3255
|
+
*/},{key:"init",value:function init(){var _this2=this;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL,pluginsSDKBaseURL=_state$loadOptions$va.pluginsSDKBaseURL;state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
3256
|
+
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL);// determine the path to fetch remote plugins from
|
3257
|
+
var pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
|
3258
|
+
r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,lockPluginsVersion,_this2.logger);});this.getConfig();}/**
|
3327
3259
|
* Handle errors
|
3328
3260
|
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
|
3329
3261
|
* A callback function that is executed once we fetch the source config response.
|
3330
3262
|
* Use to construct and store information that are dependent on the sourceConfig.
|
3331
3263
|
*/},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
3332
3264
|
// We can use isErrRetryable utility method
|
3333
|
-
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===void 0?void 0:details.error));return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR),undefined,true);return;}//
|
3334
|
-
|
3335
|
-
|
3265
|
+
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===void 0?void 0:details.error));return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR),undefined,true);return;}// Log error and abort if source is disabled
|
3266
|
+
if(res.source.enabled===false){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
|
3267
|
+
updateReportingState(res,this.logger);var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
3336
3268
|
r(function(){var _state$loadOptions$va2;// set source related information in state
|
3337
3269
|
state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
|
3338
3270
|
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
3339
3271
|
state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va2=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:[];updateConsentsState(res);// set application lifecycle state
|
3340
|
-
|
3341
|
-
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value='configured';});}/**
|
3272
|
+
state.lifecycle.status.value='configured';});}/**
|
3342
3273
|
* A function to fetch source config either from /sourceConfig endpoint
|
3343
3274
|
* or from getSourceConfig load option
|
3344
3275
|
* @returns
|
3345
|
-
*/},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}//
|
3346
|
-
var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {//
|
3276
|
+
*/},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// Fetch source config from the function
|
3277
|
+
var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// Fetch source configuration from the configured URL
|
3347
3278
|
this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
|
3348
3279
|
|
3349
3280
|
/**
|
@@ -3365,8 +3296,8 @@
|
|
3365
3296
|
var matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent="".concat(userAgent," Brave/").concat(matchedArr[2]);}}return userAgent;};var getLanguage=function getLanguage(){var _globalThis$navigator;if(isUndefined(globalThis.navigator)){return null;}return (_globalThis$navigator=globalThis.navigator.language)!==null&&_globalThis$navigator!==void 0?_globalThis$navigator:globalThis.navigator.browserLanguage;};/**
|
3366
3297
|
* Default page properties
|
3367
3298
|
* @returns Default page properties
|
3368
|
-
*/var getDefaultPageProperties=function getDefaultPageProperties(){var canonicalUrl=getCanonicalUrl();var path=globalThis.location.pathname;var tabUrl=globalThis.location.href;var pageUrl=tabUrl;var search=globalThis.location.search;// If valid canonical
|
3369
|
-
if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical
|
3299
|
+
*/var getDefaultPageProperties=function getDefaultPageProperties(){var canonicalUrl=getCanonicalUrl();var path=globalThis.location.pathname;var tabUrl=globalThis.location.href;var pageUrl=tabUrl;var search=globalThis.location.search;// If valid canonical URL is provided use this as page URL.
|
3300
|
+
if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical URL will be used instead of the location.search ones
|
3370
3301
|
if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
|
3371
3302
|
}}var url=getUrlWithoutHash(pageUrl);var _document2=document,title=_document2.title;var referrer=getReferrer();return {path:path,referrer:referrer,referring_domain:getReferringDomain(referrer),search:search,title:title,url:url,tab_url:tabUrl};};
|
3372
3303
|
|
@@ -3382,10 +3313,10 @@
|
|
3382
3313
|
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
3383
3314
|
E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3384
3315
|
* Detect if polyfills are required and then load script from polyfill URL
|
3385
|
-
*/},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var
|
3316
|
+
*/},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var customPolyfillUrl=state.loadOptions.value.polyfillURL;var polyfillUrl=POLYFILL_URL;if(isDefinedAndNotNull(customPolyfillUrl)){if(isValidURL(customPolyfillUrl)){polyfillUrl=customPolyfillUrl;}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER,customPolyfillUrl));}}var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&isValidURL(polyfillUrl);if(shouldLoadPolyfill){var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
|
3386
3317
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
3387
3318
|
var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);var polyfillCallback=function polyfillCallback(){_this2.onReady();// Remove the entry from window so we don't leave room for calling it again
|
3388
|
-
delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}
|
3319
|
+
delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}this.externalSrcLoader.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
|
3389
3320
|
* Attach listeners to window to observe event that update capabilities state values
|
3390
3321
|
*/},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
|
3391
3322
|
* Set the lifecycle status to next phase
|
@@ -3401,6 +3332,21 @@
|
|
3401
3332
|
var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
3402
3333
|
var RESERVED_ELEMENTS=['id','anonymous_id','user_id','sent_at','timestamp','received_at','original_timestamp','event','event_text','channel','context_ip','context_request_ip','context_passed_ip','group_id','previous_id'];
|
3403
3334
|
|
3335
|
+
/**
|
3336
|
+
* A function to check given value is a number or not
|
3337
|
+
* @param num input value
|
3338
|
+
* @returns boolean
|
3339
|
+
*/var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
|
3340
|
+
* A function to check given number has minimum length or not
|
3341
|
+
* @param minimumLength minimum length
|
3342
|
+
* @param num input number
|
3343
|
+
* @returns boolean
|
3344
|
+
*/var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
|
3345
|
+
* A function to check given value is a positive integer or not
|
3346
|
+
* @param num input value
|
3347
|
+
* @returns boolean
|
3348
|
+
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3349
|
+
|
3404
3350
|
var MIN_SESSION_ID_LENGTH=10;/**
|
3405
3351
|
* A function to validate current session and return true/false depending on that
|
3406
3352
|
* @returns boolean
|
@@ -3432,12 +3378,12 @@
|
|
3432
3378
|
* To get the page properties for context object
|
3433
3379
|
* @param pageProps Page properties
|
3434
3380
|
* @returns page properties object for context
|
3435
|
-
*/var getContextPageProperties=function getContextPageProperties(pageProps){// Need to get updated page details on each event as an event to notify on SPA
|
3381
|
+
*/var getContextPageProperties=function getContextPageProperties(pageProps){// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
|
3436
3382
|
var curPageProps=getDefaultPageProperties();var ctxPageProps={};Object.keys(curPageProps).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
|
3437
3383
|
* Add any missing default page properties using values from options and defaults
|
3438
3384
|
* @param properties Input page properties
|
3439
3385
|
* @param options API options
|
3440
|
-
*/var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA
|
3386
|
+
*/var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
|
3441
3387
|
var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(function(key){if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||curPageProps[key];}});if(isUndefined(pageProps.initial_referrer)){pageProps.initial_referrer=optionsPageProps.initial_referrer||state.session.initialReferrer.value;}if(isUndefined(pageProps.initial_referring_domain)){pageProps.initial_referring_domain=optionsPageProps.initial_referring_domain||state.session.initialReferringDomain.value;}return pageProps;};/**
|
3442
3388
|
* Utility to check for reserved keys in the input object
|
3443
3389
|
* @param obj Generic object
|
@@ -3539,7 +3485,7 @@
|
|
3539
3485
|
* @param error The error object
|
3540
3486
|
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3541
3487
|
|
3542
|
-
var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager,httpClient){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);}/**
|
3488
|
+
var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager,httpClient){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.serverSideCookieDebounceFuncs={};}/**
|
3543
3489
|
* Initialize User session with values from storage
|
3544
3490
|
*/return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
3545
3491
|
this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
@@ -3555,32 +3501,29 @@
|
|
3555
3501
|
* @param error The error object
|
3556
3502
|
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
|
3557
3503
|
* A function to encrypt the cookie value and return the encrypted data
|
3558
|
-
* @param
|
3504
|
+
* @param cookiesData
|
3559
3505
|
* @param store
|
3560
3506
|
* @returns
|
3561
|
-
*/},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(
|
3507
|
+
*/},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var _this3=this;var encryptedCookieData=[];cookiesData.forEach(function(cData){var encryptedValue=store===null||store===void 0?void 0:store.encrypt(stringifyWithoutCircular(cData.value,false,[],_this3.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
|
3562
3508
|
* A function that makes request to data service to set the cookie
|
3563
3509
|
* @param encryptedCookieData
|
3564
3510
|
* @param callback
|
3565
|
-
*/},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true},isRawResponse:true,callback:callback});}/**
|
3511
|
+
*/},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true,withCredentials:true},isRawResponse:true,callback:callback});}/**
|
3566
3512
|
* A function to make an external request to set the cookie from server side
|
3567
3513
|
* @param key cookie name
|
3568
3514
|
* @param value encrypted cookie value
|
3569
|
-
*/},{key:"
|
3570
|
-
var encryptedCookieData=this.getEncryptedCookieData(
|
3571
|
-
this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){
|
3515
|
+
*/},{key:"setServerSideCookies",value:function setServerSideCookies(cookiesData,cb,store){var _this4=this;try{// encrypt cookies values
|
3516
|
+
var encryptedCookieData=this.getEncryptedCookieData(cookiesData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
3517
|
+
this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=stringifyWithoutCircular(cData.value,false,[]);var after=stringifyWithoutCircular(cookieValue,false,[]);if(after!==before){var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));if(cb){cb(cData.name,cData.value);}}});}else {var _this4$logger2,_details$xhr2;(_this4$logger2=_this4.logger)===null||_this4$logger2===void 0||_this4$logger2.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
|
3572
3518
|
* A function to sync values in storage
|
3573
3519
|
* @param sessionKey
|
3574
3520
|
* @param value
|
3575
|
-
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
|
3521
|
+
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey,_this5=this;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
|
3576
3522
|
// set the cookie from server side
|
3577
|
-
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){this.
|
3578
|
-
// TODO: Test cookies set from server side can be cleared from client side
|
3579
|
-
// and make appropriate changes.
|
3580
|
-
this.setServerSideCookie([{name:key,value:''}],undefined,curStore);}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
|
3523
|
+
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){if(this.serverSideCookieDebounceFuncs[sessionKey]){globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[sessionKey]);}this.serverSideCookieDebounceFuncs[sessionKey]=globalThis.setTimeout(function(){_this5.setServerSideCookies([{name:key,value:value}],function(cookieName,cookieValue){curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===void 0||curStore.set(key,value);}}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
|
3581
3524
|
* Function to update storage whenever state value changes
|
3582
|
-
*/},{key:"registerEffects",value:function registerEffects(){var
|
3583
|
-
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){
|
3525
|
+
*/},{key:"registerEffects",value:function registerEffects(){var _this6=this;// This will work as long as the user session entry key names are same as the state keys
|
3526
|
+
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this6.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
|
3584
3527
|
* Sets anonymous id in the following precedence:
|
3585
3528
|
*
|
3586
3529
|
* 1. anonymousId: Id directly provided to the function.
|
@@ -3638,8 +3581,8 @@
|
|
3638
3581
|
* @param resetAnonymousId
|
3639
3582
|
* @param noNewSessionStart
|
3640
3583
|
* @returns
|
3641
|
-
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var
|
3642
|
-
|
3584
|
+
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this7=this;var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack;r(function(){session.userId.value=DEFAULT_USER_SESSION_VALUES.userId;session.userTraits.value=DEFAULT_USER_SESSION_VALUES.userTraits;session.groupId.value=DEFAULT_USER_SESSION_VALUES.groupId;session.groupTraits.value=DEFAULT_USER_SESSION_VALUES.groupTraits;session.authToken.value=DEFAULT_USER_SESSION_VALUES.authToken;if(resetAnonymousId){// This will generate a new anonymous ID
|
3585
|
+
_this7.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;_this7.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){_this7.startManualTrackingInternal();}});}/**
|
3643
3586
|
* Set user Id
|
3644
3587
|
* @param userId
|
3645
3588
|
*/},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -3673,6 +3616,13 @@
|
|
3673
3616
|
* @param userId
|
3674
3617
|
*/},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
|
3675
3618
|
|
3619
|
+
/**
|
3620
|
+
* Plugins to be loaded in the plugins loadOption is not defined
|
3621
|
+
*/var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
|
3622
|
+
|
3623
|
+
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
|
3624
|
+
var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;normalizedLoadOpts.useServerSideCookies=normalizedLoadOpts.useServerSideCookies===true;if(normalizedLoadOpts.dataServiceEndpoint&&typeof normalizedLoadOpts.dataServiceEndpoint!=='string'){delete normalizedLoadOpts.dataServiceEndpoint;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;normalizedLoadOpts.lockPluginsVersion=normalizedLoadOpts.lockPluginsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};
|
3625
|
+
|
3676
3626
|
var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
|
3677
3627
|
|
3678
3628
|
/**
|