@rudderstack/analytics-js 3.11.17 → 3.12.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -10,7 +10,7 @@ function _arrayWithoutHoles(r) {
10
10
  if (Array.isArray(r)) return _arrayLikeToArray(r);
11
11
  }
12
12
  function _assertThisInitialized(e) {
13
- if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
13
+ if (undefined === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
14
14
  return e;
15
15
  }
16
16
  function asyncGeneratorStep(n, t, e, r, o, a, c) {
@@ -34,7 +34,7 @@ function _asyncToGenerator(n) {
34
34
  function _throw(n) {
35
35
  asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
36
36
  }
37
- _next(void 0);
37
+ _next(undefined);
38
38
  });
39
39
  };
40
40
  }
@@ -54,12 +54,12 @@ function _construct(t, e, r) {
54
54
  function _defineProperties(e, r) {
55
55
  for (var t = 0; t < r.length; t++) {
56
56
  var o = r[t];
57
- o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
57
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
58
58
  }
59
59
  }
60
60
  function _createClass(e, r, t) {
61
61
  return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
62
- writable: !1
62
+ writable: false
63
63
  }), e;
64
64
  }
65
65
  function _createForOfIteratorHelper(r, e) {
@@ -73,9 +73,9 @@ function _createForOfIteratorHelper(r, e) {
73
73
  s: F,
74
74
  n: function () {
75
75
  return n >= r.length ? {
76
- done: !0
76
+ done: true
77
77
  } : {
78
- done: !1,
78
+ done: false,
79
79
  value: r[n++]
80
80
  };
81
81
  },
@@ -88,8 +88,8 @@ function _createForOfIteratorHelper(r, e) {
88
88
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
89
89
  }
90
90
  var o,
91
- a = !0,
92
- u = !1;
91
+ a = true,
92
+ u = false;
93
93
  return {
94
94
  s: function () {
95
95
  t = t.call(r);
@@ -99,7 +99,7 @@ function _createForOfIteratorHelper(r, e) {
99
99
  return a = r.done, r;
100
100
  },
101
101
  e: function (r) {
102
- u = !0, o = r;
102
+ u = true, o = r;
103
103
  },
104
104
  f: function () {
105
105
  try {
@@ -113,9 +113,9 @@ function _createForOfIteratorHelper(r, e) {
113
113
  function _defineProperty(e, r, t) {
114
114
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
115
115
  value: t,
116
- enumerable: !0,
117
- configurable: !0,
118
- writable: !0
116
+ enumerable: true,
117
+ configurable: true,
118
+ writable: true
119
119
  }) : e[r] = t, e;
120
120
  }
121
121
  function _get() {
@@ -137,11 +137,11 @@ function _inherits(t, e) {
137
137
  t.prototype = Object.create(e && e.prototype, {
138
138
  constructor: {
139
139
  value: t,
140
- writable: !0,
141
- configurable: !0
140
+ writable: true,
141
+ configurable: true
142
142
  }
143
143
  }), Object.defineProperty(t, "prototype", {
144
- writable: !1
144
+ writable: false
145
145
  }), e && _setPrototypeOf(t, e);
146
146
  }
147
147
  function _isNativeReflectConstruct() {
@@ -163,12 +163,12 @@ function _iterableToArrayLimit(r, l) {
163
163
  i,
164
164
  u,
165
165
  a = [],
166
- f = !0,
167
- o = !1;
166
+ f = true,
167
+ o = false;
168
168
  try {
169
169
  if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
170
170
  } catch (r) {
171
- o = !0, n = r;
171
+ o = true, n = r;
172
172
  } finally {
173
173
  try {
174
174
  if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
@@ -198,7 +198,7 @@ function ownKeys(e, r) {
198
198
  function _objectSpread2(e) {
199
199
  for (var r = 1; r < arguments.length; r++) {
200
200
  var t = null != arguments[r] ? arguments[r] : {};
201
- r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
201
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
202
202
  _defineProperty(e, r, t[r]);
203
203
  }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
204
204
  Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
@@ -208,7 +208,7 @@ function _objectSpread2(e) {
208
208
  }
209
209
  function _possibleConstructorReturn(t, e) {
210
210
  if (e && ("object" == typeof e || "function" == typeof e)) return e;
211
- if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
211
+ if (undefined !== e) throw new TypeError("Derived constructors may only return object or undefined");
212
212
  return _assertThisInitialized(t);
213
213
  }
214
214
  function _regeneratorRuntime() {
@@ -229,9 +229,9 @@ function _regeneratorRuntime() {
229
229
  function define(t, e, r) {
230
230
  return Object.defineProperty(t, e, {
231
231
  value: r,
232
- enumerable: !0,
233
- configurable: !0,
234
- writable: !0
232
+ enumerable: true,
233
+ configurable: true,
234
+ writable: true
235
235
  }), t[e];
236
236
  }
237
237
  try {
@@ -324,7 +324,7 @@ function _regeneratorRuntime() {
324
324
  if ("throw" === i) throw a;
325
325
  return {
326
326
  value: t,
327
- done: !0
327
+ done: true
328
328
  };
329
329
  }
330
330
  for (n.method = i, n.arg = a;;) {
@@ -375,7 +375,7 @@ function _regeneratorRuntime() {
375
375
  function Context(t) {
376
376
  this.tryEntries = [{
377
377
  tryLoc: "root"
378
- }], t.forEach(pushTryEntry, this), this.reset(!0);
378
+ }], t.forEach(pushTryEntry, this), this.reset(true);
379
379
  }
380
380
  function values(e) {
381
381
  if (e || "" === e) {
@@ -385,8 +385,8 @@ function _regeneratorRuntime() {
385
385
  if (!isNaN(e.length)) {
386
386
  var o = -1,
387
387
  i = function next() {
388
- for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
389
- return next.value = t, next.done = !0, next;
388
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = false, next;
389
+ return next.value = t, next.done = true, next;
390
390
  };
391
391
  return i.next = i;
392
392
  }
@@ -395,10 +395,10 @@ function _regeneratorRuntime() {
395
395
  }
396
396
  return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
397
397
  value: GeneratorFunctionPrototype,
398
- configurable: !0
398
+ configurable: true
399
399
  }), o(GeneratorFunctionPrototype, "constructor", {
400
400
  value: GeneratorFunction,
401
- configurable: !0
401
+ configurable: true
402
402
  }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
403
403
  var e = "function" == typeof t && t.constructor;
404
404
  return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
@@ -411,7 +411,7 @@ function _regeneratorRuntime() {
411
411
  }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
412
412
  return this;
413
413
  }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
414
- void 0 === i && (i = Promise);
414
+ undefined === i && (i = Promise);
415
415
  var a = new AsyncIterator(wrap(t, r, n, o), i);
416
416
  return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
417
417
  return t.done ? t.value : a.next();
@@ -427,17 +427,17 @@ function _regeneratorRuntime() {
427
427
  return r.reverse(), function next() {
428
428
  for (; r.length;) {
429
429
  var t = r.pop();
430
- if (t in e) return next.value = t, next.done = !1, next;
430
+ if (t in e) return next.value = t, next.done = false, next;
431
431
  }
432
- return next.done = !0, next;
432
+ return next.done = true, next;
433
433
  };
434
434
  }, e.values = values, Context.prototype = {
435
435
  constructor: Context,
436
436
  reset: function (e) {
437
- if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
437
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = false, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
438
438
  },
439
439
  stop: function () {
440
- this.done = !0;
440
+ this.done = true;
441
441
  var t = this.tryEntries[0].completion;
442
442
  if ("throw" === t.type) throw t.arg;
443
443
  return this.rval;
@@ -456,10 +456,10 @@ function _regeneratorRuntime() {
456
456
  var c = n.call(i, "catchLoc"),
457
457
  u = n.call(i, "finallyLoc");
458
458
  if (c && u) {
459
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
459
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, true);
460
460
  if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
461
461
  } else if (c) {
462
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
462
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, true);
463
463
  } else {
464
464
  if (!u) throw Error("try statement without catch or finally");
465
465
  if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
@@ -524,10 +524,10 @@ function _superPropBase(t, o) {
524
524
  for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
525
525
  return t;
526
526
  }
527
- function _superPropGet(t, e, o, r) {
528
- var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), e, o);
527
+ function _superPropGet(t, o, e, r) {
528
+ var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
529
529
  return 2 & r && "function" == typeof p ? function (t) {
530
- return p.apply(o, t);
530
+ return p.apply(e, t);
531
531
  } : p;
532
532
  }
533
533
  function _toConsumableArray(r) {
@@ -536,7 +536,7 @@ function _toConsumableArray(r) {
536
536
  function _toPrimitive(t, r) {
537
537
  if ("object" != typeof t || !t) return t;
538
538
  var e = t[Symbol.toPrimitive];
539
- if (void 0 !== e) {
539
+ if (undefined !== e) {
540
540
  var i = e.call(t, r || "default");
541
541
  if ("object" != typeof i) return i;
542
542
  throw new TypeError("@@toPrimitive must return a primitive value.");
@@ -560,7 +560,7 @@ function _unsupportedIterableToArray(r, a) {
560
560
  if (r) {
561
561
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
562
562
  var t = {}.toString.call(r).slice(8, -1);
563
- 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;
563
+ 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) : undefined;
564
564
  }
565
565
  }
566
566
 
@@ -649,7 +649,7 @@ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pa
649
649
  * @return {*} The copied value.
650
650
  */function _clone(value,deep,map){map||(map=new _ObjectMap());// this avoids the slower switch with a quick if decision removing some milliseconds in each run.
651
651
  if(_isPrimitive(value)){return value;}var copy=function copy(copiedValue){// Check for circular and same references on the object graph and return its corresponding clone.
652
- var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,copiedValue);for(var key in value){if(Object.prototype.hasOwnProperty.call(value,key)){copiedValue[key]=_clone(value[key],true,map);}}return copiedValue;};switch(type(value)){case'Object':return copy(Object.create(Object.getPrototypeOf(value)));case'Array':return copy(Array(value.length));case'Date':return new Date(value.valueOf());case'RegExp':return _cloneRegExp(value);case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'BigInt64Array':case'BigUint64Array':return value.slice();default:return value;}}function _isPrimitive(param){var type=_typeof(param);return param==null||type!='object'&&type!='function';}var _ObjectMap=/*#__PURE__*/function(){function _ObjectMap(){this.map={};this.length=0;}_ObjectMap.prototype.set=function(key,value){var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){this.map[hashedKey]=bucket=[];}bucket.push([key,value]);this.length+=1;};_ObjectMap.prototype.hash=function(key){var hashedKey=[];for(var value in key){hashedKey.push(Object.prototype.toString.call(key[value]));}return hashedKey.join();};_ObjectMap.prototype.get=function(key){/**
652
+ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,copiedValue);for(var key in value){if(Object.prototype.hasOwnProperty.call(value,key)){copiedValue[key]=_clone(value[key],true,map);}}return copiedValue;};switch(type(value)){case 'Object':return copy(Object.create(Object.getPrototypeOf(value)));case 'Array':return copy(Array(value.length));case 'Date':return new Date(value.valueOf());case 'RegExp':return _cloneRegExp(value);case 'Int8Array':case 'Uint8Array':case 'Uint8ClampedArray':case 'Int16Array':case 'Uint16Array':case 'Int32Array':case 'Uint32Array':case 'Float32Array':case 'Float64Array':case 'BigInt64Array':case 'BigUint64Array':return value.slice();default:return value;}}function _isPrimitive(param){var type=_typeof(param);return param==null||type!='object'&&type!='function';}var _ObjectMap=/*#__PURE__*/function(){function _ObjectMap(){this.map={};this.length=0;}_ObjectMap.prototype.set=function(key,value){var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){this.map[hashedKey]=bucket=[];}bucket.push([key,value]);this.length+=1;};_ObjectMap.prototype.hash=function(key){var hashedKey=[];for(var value in key){hashedKey.push(Object.prototype.toString.call(key[value]));}return hashedKey.join();};_ObjectMap.prototype.get=function(key){/**
653
653
  * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,
654
654
  * on my tests this number is 180, anything above that using the hash function is faster.
655
655
  */if(this.length<=180){for(var p in this.map){var bucket=this.map[p];for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}}return;}var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){return;}for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}};return _ObjectMap;}();
@@ -877,7 +877,22 @@ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};var merge
877
877
  * A utility to recursively remove undefined and null values from an object
878
878
  * @param obj input object
879
879
  * @returns a new object
880
- */var _removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy(isDefinedAndNotNull,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=_removeUndefinedAndNullValues(value);}});return result;};
880
+ */var _removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy(isDefinedAndNotNull,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=_removeUndefinedAndNullValues(value);}});return result;};/**
881
+ * Normalizes an object by removing undefined and null values.
882
+ * @param val - The value to normalize
883
+ * @returns The normalized object, or undefined if input is not a non-empty object
884
+ * @example
885
+ * getNormalizedObjectValue({ a: 1, b: null, c: undefined }) // returns { a: 1 }
886
+ * getNormalizedObjectValue({}) // returns undefined
887
+ * getNormalizedObjectValue(null) // returns undefined
888
+ */var getNormalizedObjectValue=function getNormalizedObjectValue(val){if(!isNonEmptyObject(val)){return undefined;}return _removeUndefinedAndNullValues(val);};/**
889
+ * Normalizes a value to a boolean, with support for a default value
890
+ * @param val Input value
891
+ * @param defVal Default value
892
+ * @returns Returns the normalized boolean value
893
+ * @example
894
+ * getNormalizedBooleanValue(true, false) // returns true
895
+ */var getNormalizedBooleanValue=function getNormalizedBooleanValue(val,defVal){if(isDefined(defVal)){return isDefined(val)?val===true:defVal;}return val===true;};
881
896
 
882
897
  var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeDoubleSpaces=function removeDoubleSpaces(value){return value.replace(/ {2,}/g,' ');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
883
898
  * A function to convert values to string
@@ -985,17 +1000,17 @@ var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_
985
1000
 
986
1001
  var JSON_STRINGIFY='JSONStringify';var BIG_INT_PLACEHOLDER='[BigInt]';var CIRCULAR_REFERENCE_PLACEHOLDER='[Circular Reference]';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
987
1002
  // eslint-disable-next-line func-names
988
- return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
1003
+ return function(key,value){if(excludeKeys!==null&&excludeKeys!==undefined&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
989
1004
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
990
1005
  // @ts-ignore-next-line
991
- while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return CIRCULAR_REFERENCE_PLACEHOLDER;}ancestors.push(value);return value;};};/**
1006
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===undefined||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return CIRCULAR_REFERENCE_PLACEHOLDER;}ancestors.push(value);return value;};};/**
992
1007
  * Utility method for JSON stringify object excluding null values & circular references
993
1008
  *
994
1009
  * @param {*} value input
995
1010
  * @param {boolean} excludeNull if it should exclude nul or not
996
1011
  * @param {function} logger optional logger methods for warning
997
1012
  * @returns string
998
- */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};var getReplacer=function getReplacer(logger){var ancestors=[];// Array to track ancestor objects
1013
+ */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===undefined||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};var getReplacer=function getReplacer(logger){var ancestors=[];// Array to track ancestor objects
999
1014
  // Using a regular function to use `this` for the parent context
1000
1015
  return function replacer(key,value){if(isBigInt(value)){return BIG_INT_PLACEHOLDER;// Replace BigInt values
1001
1016
  }// `this` is the object that value is contained in, i.e., its direct parent.
@@ -1023,9 +1038,9 @@ var MANUAL_ERROR_IDENTIFIER='[MANUAL ERROR]';/**
1023
1038
  * @param err Original error
1024
1039
  * @param issue Issue to prepend to error message
1025
1040
  * @returns Instance of Error with message prepended with issue
1026
- */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var _error$stack;error.stack="".concat((_error$stack=error.stack)!==null&&_error$stack!==void 0?_error$stack:'',"\n").concat(MANUAL_ERROR_IDENTIFIER);}globalThis.dispatchEvent(new ErrorEvent('error',{error:error}));};
1041
+ */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var _error$stack;error.stack="".concat((_error$stack=error.stack)!==null&&_error$stack!==undefined?_error$stack:'',"\n").concat(MANUAL_ERROR_IDENTIFIER);}globalThis.dispatchEvent(new ErrorEvent('error',{error:error}));};
1027
1042
 
1028
- var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.11.17';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';
1043
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.12.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';
1029
1044
 
1030
1045
  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';
1031
1046
 
@@ -1068,7 +1083,7 @@ preloadedEventsArray.splice.apply(preloadedEventsArray,[0,preloadedEventsArray.l
1068
1083
  * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
1069
1084
  */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
1070
1085
  retrieveEventsFromQueryString(preloadedEventsArray);// Enqueue the non load events in the buffer of the global rudder analytics singleton
1071
- if(preloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,[]);}};var consumePreloadBufferedEvent=function consumePreloadBufferedEvent(event,analyticsInstance){var _ref;var methodName=event.shift();var callOptions;if(isFunction(analyticsInstance[methodName])){switch(methodName){case'page':callOptions=pageArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'track':callOptions=trackArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'identify':callOptions=identifyArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'alias':callOptions=aliasArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'group':callOptions=groupArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;default:(_ref=analyticsInstance)[methodName].apply(_ref,_toConsumableArray(event));break;}if(callOptions){analyticsInstance[methodName](callOptions);}}};
1086
+ if(preloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,[]);}};var consumePreloadBufferedEvent=function consumePreloadBufferedEvent(event,analyticsInstance){var _ref;var methodName=event.shift();var callOptions;if(isFunction(analyticsInstance[methodName])){switch(methodName){case 'page':callOptions=pageArgumentsToCallOptions.apply(undefined,_toConsumableArray(event));break;case 'track':callOptions=trackArgumentsToCallOptions.apply(undefined,_toConsumableArray(event));break;case 'identify':callOptions=identifyArgumentsToCallOptions.apply(undefined,_toConsumableArray(event));break;case 'alias':callOptions=aliasArgumentsToCallOptions.apply(undefined,_toConsumableArray(event));break;case 'group':callOptions=groupArgumentsToCallOptions.apply(undefined,_toConsumableArray(event));break;default:(_ref=analyticsInstance)[methodName].apply(_ref,_toConsumableArray(event));break;}if(callOptions){analyticsInstance[methodName](callOptions);}}};
1072
1087
 
1073
1088
  var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
1074
1089
 
@@ -1092,9 +1107,9 @@ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
1092
1107
  *
1093
1108
  * @returns
1094
1109
  */var insertScript=function insertScript(newScriptElement){var _scriptElements$;// First try to add it to the head
1095
- var headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===void 0||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===void 0?void 0:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
1096
- var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==void 0&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===void 0||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
1097
- var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
1110
+ var headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===undefined||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===undefined?undefined:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
1111
+ var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==undefined&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===undefined||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
1112
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===undefined||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
1098
1113
  * Loads external js file as a script html tag
1099
1114
  *
1100
1115
  * @param {*} url The URL of the script to be loaded
@@ -1114,9 +1129,9 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
1114
1129
  * Load external resource of type javascript
1115
1130
  */return _createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var _this=this;var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!isFunction(callback);jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){_this.onError(err);if(!isFireAndForget){callback();}});}/**
1116
1131
  * Handle errors
1117
- */},{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,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);}();
1132
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);}();
1118
1133
 
1119
- var i$2=Symbol.for("preact-signals");function t$1(){if(!(s>1)){var i,t=!1;while(void 0!==h){var r=h;h=void 0;f++;while(void 0!==r){var o=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c();}catch(r){if(!t){i=r;t=!0;}}r=o;}}f=0;s--;if(t)throw i;}else s--;}function r(i){if(s>0)return i();s++;try{return i();}finally{t$1();}}var o=void 0;var h=void 0,s=0,f=0,v=0;function e(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t;}return t;}}}function u(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}u.prototype.brand=i$2;u.prototype.h=function(){return !0;};u.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i;}};u.prototype.U=function(i){if(void 0!==this.t){var t=i.e,r=i.x;if(void 0!==t){t.x=r;i.e=void 0;}if(void 0!==r){r.e=t;i.x=void 0;}if(i===this.t)this.t=r;}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=void 0;try{i(r);}finally{o=n;}});};u.prototype.valueOf=function(){return this.value;};u.prototype.toString=function(){return this.value+"";};u.prototype.toJSON=function(){return this.value;};u.prototype.peek=function(){var i=o;o=void 0;try{return this.value;}finally{o=i;}};Object.defineProperty(u.prototype,"value",{get:function get(){var i=e(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(i){if(i!==this.v){if(f>100)throw new Error("Cycle detected");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N();}finally{t$1();}}}});function d$1(i){return new u(i);}function c(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return !0;return !1;}function a(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function l(i){var t=i.s,r=void 0;while(void 0!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(void 0!==o)o.n=t.n;if(void 0!==t.n)t.n.p=o;}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=o;}i.s=r;}function y(i){u.call(this,void 0);this.x=i;this.s=void 0;this.g=v-1;this.f=4;}(y.prototype=new u()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===v)return !0;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return !0;}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;l(this);this.f&=-2;return !0;};y.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t);}u.prototype.S.call(this,i);};y.prototype.U=function(i){if(void 0!==this.t){u.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t);}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};Object.defineProperty(y.prototype,"value",{get:function get(){if(1&this.f)throw new Error("Cycle detected");var i=e(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v;}});function _(i){var r=i.u;i.u=void 0;if("function"==typeof r){s++;var n=o;o=void 0;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{o=n;t$1();}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;_(i);}function p(i){if(o!==this)throw new Error("Out-of-order effect");l(this);o=i;this.f&=-2;if(8&this.f)g(this);t$1();}function b(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}b.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};b.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return p.bind(this,i);};b.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this;}};b.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new b(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1134
+ var i$2=Symbol.for("preact-signals");function t$1(){if(!(s>1)){var i,t=false;while(undefined!==h){var r=h;h=undefined;f++;while(undefined!==r){var o=r.o;r.o=undefined;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c();}catch(r){if(!t){i=r;t=true;}}r=o;}}f=0;s--;if(t)throw i;}else s--;}function r(i){if(s>0)return i();s++;try{return i();}finally{t$1();}}var o=undefined;var h=undefined,s=0,f=0,v=0;function e(i){if(undefined!==o){var t=i.n;if(undefined===t||t.t!==o){t={i:0,S:i,p:o.s,n:undefined,t:o,e:undefined,x:undefined,r:t};if(undefined!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(undefined!==t.n){t.n.p=t.p;if(undefined!==t.p)t.p.n=t.n;t.p=o.s;t.n=undefined;o.s.n=t;o.s=t;}return t;}}}function u(i){this.v=i;this.i=0;this.n=undefined;this.t=undefined;}u.prototype.brand=i$2;u.prototype.h=function(){return true;};u.prototype.S=function(i){if(this.t!==i&&undefined===i.e){i.x=this.t;if(undefined!==this.t)this.t.e=i;this.t=i;}};u.prototype.U=function(i){if(undefined!==this.t){var t=i.e,r=i.x;if(undefined!==t){t.x=r;i.e=undefined;}if(undefined!==r){r.e=t;i.x=undefined;}if(i===this.t)this.t=r;}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=undefined;try{i(r);}finally{o=n;}});};u.prototype.valueOf=function(){return this.value;};u.prototype.toString=function(){return this.value+"";};u.prototype.toJSON=function(){return this.value;};u.prototype.peek=function(){var i=o;o=undefined;try{return this.value;}finally{o=i;}};Object.defineProperty(u.prototype,"value",{get:function get(){var i=e(this);if(undefined!==i)i.i=this.i;return this.v;},set:function set(i){if(i!==this.v){if(f>100)throw new Error("Cycle detected");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N();}finally{t$1();}}}});function d$1(i){return new u(i);}function c(i){for(var t=i.s;undefined!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return true;return false;}function a(i){for(var t=i.s;undefined!==t;t=t.n){var r=t.S.n;if(undefined!==r)t.r=r;t.S.n=t;t.i=-1;if(undefined===t.n){i.s=t;break;}}}function l(i){var t=i.s,r=undefined;while(undefined!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(undefined!==o)o.n=t.n;if(undefined!==t.n)t.n.p=o;}else r=t;t.S.n=t.r;if(undefined!==t.r)t.r=undefined;t=o;}i.s=r;}function y(i){u.call(this,undefined);this.x=i;this.s=undefined;this.g=v-1;this.f=4;}(y.prototype=new u()).h=function(){this.f&=-3;if(1&this.f)return false;if(32==(36&this.f))return true;this.f&=-5;if(this.g===v)return true;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return true;}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;l(this);this.f&=-2;return true;};y.prototype.S=function(i){if(undefined===this.t){this.f|=36;for(var t=this.s;undefined!==t;t=t.n)t.S.S(t);}u.prototype.S.call(this,i);};y.prototype.U=function(i){if(undefined!==this.t){u.prototype.U.call(this,i);if(undefined===this.t){this.f&=-33;for(var t=this.s;undefined!==t;t=t.n)t.S.U(t);}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;undefined!==i;i=i.x)i.t.N();}};Object.defineProperty(y.prototype,"value",{get:function get(){if(1&this.f)throw new Error("Cycle detected");var i=e(this);this.h();if(undefined!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v;}});function _(i){var r=i.u;i.u=undefined;if("function"==typeof r){s++;var n=o;o=undefined;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{o=n;t$1();}}}function g(i){for(var t=i.s;undefined!==t;t=t.n)t.S.U(t);i.x=undefined;i.s=undefined;_(i);}function p(i){if(o!==this)throw new Error("Out-of-order effect");l(this);o=i;this.f&=-2;if(8&this.f)g(this);t$1();}function b(i){this.x=i;this.u=undefined;this.s=undefined;this.o=undefined;this.f=32;}b.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};b.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return p.bind(this,i);};b.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this;}};b.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new b(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1120
1135
 
1121
1136
  /**
1122
1137
  * A buffer queue to serve as a store for any type of data
@@ -1124,7 +1139,7 @@ var i$2=Symbol.for("preact-signals");function t$1(){if(!(s>1)){var i,t=!1;while(
1124
1139
 
1125
1140
  var LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};var DEFAULT_LOG_LEVEL='LOG';var POST_LOAD_LOG_LEVEL='ERROR';var LOG_MSG_PREFIX='RS SDK';var LOG_MSG_PREFIX_STYLE='font-weight: bold; background: black; color: white;';var LOG_MSG_STYLE='font-weight: normal;';/**
1126
1141
  * Service to log messages/data to output provider, default is console
1127
- */var Logger=/*#__PURE__*/function(){function Logger(){var minLogLevel=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LOG_LEVEL;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var logProvider=arguments.length>2&&arguments[2]!==undefined?arguments[2]:console;_classCallCheck(this,Logger);this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}return _createClass(Logger,[{key:"log",value:function log(){for(var _len=arguments.length,data=new Array(_len),_key=0;_key<_len;_key++){data[_key]=arguments[_key];}this.outputLog('LOG',data);}},{key:"info",value:function info(){for(var _len2=arguments.length,data=new Array(_len2),_key2=0;_key2<_len2;_key2++){data[_key2]=arguments[_key2];}this.outputLog('INFO',data);}},{key:"debug",value:function debug(){for(var _len3=arguments.length,data=new Array(_len3),_key3=0;_key3<_len3;_key3++){data[_key3]=arguments[_key3];}this.outputLog('DEBUG',data);}},{key:"warn",value:function warn(){for(var _len4=arguments.length,data=new Array(_len4),_key4=0;_key4<_len4;_key4++){data[_key4]=arguments[_key4];}this.outputLog('WARN',data);}},{key:"error",value:function error(){for(var _len5=arguments.length,data=new Array(_len5),_key5=0;_key5<_len5;_key5++){data[_key5]=arguments[_key5];}this.outputLog('ERROR',data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
1142
+ */var Logger=/*#__PURE__*/function(){function Logger(){var minLogLevel=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LOG_LEVEL;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var logProvider=arguments.length>2&&arguments[2]!==undefined?arguments[2]:console;_classCallCheck(this,Logger);this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}return _createClass(Logger,[{key:"log",value:function log(){for(var _len=arguments.length,data=new Array(_len),_key=0;_key<_len;_key++){data[_key]=arguments[_key];}this.outputLog('LOG',data);}},{key:"info",value:function info(){for(var _len2=arguments.length,data=new Array(_len2),_key2=0;_key2<_len2;_key2++){data[_key2]=arguments[_key2];}this.outputLog('INFO',data);}},{key:"debug",value:function debug(){for(var _len3=arguments.length,data=new Array(_len3),_key3=0;_key3<_len3;_key3++){data[_key3]=arguments[_key3];}this.outputLog('DEBUG',data);}},{key:"warn",value:function warn(){for(var _len4=arguments.length,data=new Array(_len4),_key4=0;_key4<_len4;_key4++){data[_key4]=arguments[_key4];}this.outputLog('WARN',data);}},{key:"error",value:function error(){for(var _len5=arguments.length,data=new Array(_len5),_key5=0;_key5<_len5;_key5++){data[_key5]=arguments[_key5];}this.outputLog('ERROR',data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===undefined||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
1128
1143
  // to assist on the fly debugging?
1129
1144
  },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
1130
1145
  * Formats the console message using `scope` and styles
@@ -1143,7 +1158,7 @@ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="ha
1143
1158
  // default is v3
1144
1159
  var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
1145
1160
 
1146
- 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
1161
+ 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,url){return "Failed to load the SDK as the base URL \"".concat(url,"\" for ").concat(component," is not valid.");};// ERROR
1147
1162
  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(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"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(context,dataPlaneUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"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 provided 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
1148
1163
  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_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 SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};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 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 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.");};var BAD_COOKIES_WARNING=function BAD_COOKIES_WARNING(key){return "The cookie data for ".concat(key," seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.");};var PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=function PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Page Unloaded event can only be tracked when the Beacon transport is active. Please enable \"useBeacon\" load API option.");};
1149
1164
 
@@ -1160,11 +1175,11 @@ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=
1160
1175
  '(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
1161
1176
  ;
1162
1177
 
1163
- 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';
1178
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEFAULT_INTEGRATION_SDKS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var DEFAULT_PLUGINS_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';
1164
1179
 
1165
1180
  var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};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';var METRICS_SERVICE_ENDPOINT='rsaMetrics';
1166
1181
 
1167
- var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,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,cookie:{}},sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
1182
+ var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,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,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
1168
1183
 
1169
1184
  var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
1170
1185
 
@@ -1176,7 +1191,7 @@ var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled
1176
1191
 
1177
1192
  var sourceConfigState=d$1(undefined);
1178
1193
 
1179
- var lifecycleState={activeDataplaneUrl:d$1(undefined),integrationsCDNPath:d$1(DEST_SDK_BASE_URL),pluginsCDNPath:d$1(PLUGINS_BASE_URL),sourceConfigUrl:d$1(undefined),status:d$1(undefined),initialized:d$1(false),logLevel:d$1('ERROR'),loaded:d$1(false),readyCallbacks:d$1([]),writeKey:d$1(undefined),dataPlaneUrl:d$1(undefined)};
1194
+ var lifecycleState={activeDataplaneUrl:d$1(undefined),integrationsCDNPath:d$1(DEFAULT_INTEGRATION_SDKS_URL),pluginsCDNPath:d$1(DEFAULT_PLUGINS_URL),sourceConfigUrl:d$1(undefined),status:d$1(undefined),initialized:d$1(false),logLevel:d$1('ERROR'),loaded:d$1(false),readyCallbacks:d$1([]),writeKey:d$1(undefined),dataPlaneUrl:d$1(undefined)};
1180
1195
 
1181
1196
  var consentsState={enabled:d$1(false),initialized:d$1(false),data:d$1({}),activeConsentManagerPluginName:d$1(undefined),preConsent:d$1({enabled:false}),postConsent:d$1({}),resolutionStrategy:d$1('and'),provider:d$1(undefined),metadata:d$1(undefined)};
1182
1197
 
@@ -1204,12 +1219,12 @@ var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,co
1204
1219
  // to next or return the value if it is the last one instead of an array per
1205
1220
  // plugin that is the normal invoke
1206
1221
  // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1207
- var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(_errorMessage);}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==void 0&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(errorMessage);}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===void 0||_this$logger4.error(_errorMessage2);}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==void 0?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==void 0&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){var _this$logger5;// If deps not exist, then not load it.
1208
- var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0||_this$logger5.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1222
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(_errorMessage);}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==undefined&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.error(errorMessage);}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===undefined||_this$logger4.error(_errorMessage2);}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==undefined?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==undefined&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){var _this$logger5;// If deps not exist, then not load it.
1223
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===undefined||_this$logger5.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1209
1224
  // do some unified pre-process before application starts.
1210
- },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==void 0?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1225
+ },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==undefined?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1211
1226
  extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1212
- if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1227
+ if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===undefined||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1213
1228
 
1214
1229
  var LOAD_ORIGIN='RS_JS_SDK';
1215
1230
 
@@ -1224,11 +1239,11 @@ if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.d
1224
1239
  * A service to handle errors
1225
1240
  */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1226
1241
  function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;this.errorBuffer=new BufferQueue();this.attachEffect();}return _createClass(ErrorHandler,[{key:"attachEffect",value:function attachEffect(){if(state.reporting.isErrorReportingPluginLoaded.value===true){while(this.errorBuffer.size()>0){var errorToProcess=this.errorBuffer.dequeue();if(errorToProcess){// send it to the plugin
1227
- this.notifyError(errorToProcess.error,errorToProcess.errorState);}}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDREJECTION);});}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.debug("Failed to attach global error listeners.");}}},{key:"init",value:function init(httpClient,externalSrcLoader){var _this2=this;this.httpClient=httpClient;// Below lines are only kept for backward compatibility
1242
+ this.notifyError(errorToProcess.error,errorToProcess.errorState);}}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDREJECTION);});}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.debug("Failed to attach global error listeners.");}}},{key:"init",value:function init(httpClient,externalSrcLoader){var _this2=this;this.httpClient=httpClient;// Below lines are only kept for backward compatibility
1228
1243
  // TODO: Remove this in the next major release
1229
1244
  if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this2.errReportingClient=client;}).catch(function(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var _error;var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var errorType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ErrorType.HANDLEDEXCEPTION;var normalizedError;var errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
1230
1245
  if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}}else {normalizedError=getNormalizedErrorForUnhandledError(error);}var isErrorReportingEnabled=state.reporting.isErrorReportingEnabled.value;var isErrorReportingPluginLoaded=state.reporting.isErrorReportingPluginLoaded.value;try{if(isErrorReportingEnabled){var errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};if(!isErrorReportingPluginLoaded){// buffer the error
1231
- this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}else if((_error=error.error)!==null&&_error!==void 0&&(_error=_error.stack)!==null&&_error!==void 0&&_error.includes(MANUAL_ERROR_IDENTIFIER)){var _this$logger3,_error2;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error('An unknown error occurred:',(_error2=error.error)===null||_error2===void 0?void 0:_error2.message);}}/**
1246
+ this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}else if((_error=error.error)!==null&&_error!==undefined&&(_error=_error.stack)!==null&&_error!==undefined&&_error.includes(MANUAL_ERROR_IDENTIFIER)){var _this$logger3,_error2;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.error('An unknown error occurred:',(_error2=error.error)===null||_error2===undefined?undefined:_error2.message);}}/**
1232
1247
  * Add breadcrumbs to add insight of a user's journey before an error
1233
1248
  * occurred and send to external error monitoring service via a plugin
1234
1249
  *
@@ -1242,7 +1257,7 @@ breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorR
1242
1257
  */},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
1243
1258
  this.errReportingClient,// deprecated parameter
1244
1259
  error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$logger4;// Not calling onError here as we don't want to go into infinite loop
1245
- (_this$logger4=this.logger)===null||_this$logger4===void 0||_this$logger4.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1260
+ (_this$logger4=this.logger)===null||_this$logger4===undefined||_this$logger4.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1246
1261
 
1247
1262
  /**
1248
1263
  * A function to filter and return non cloud mode destinations
@@ -1273,12 +1288,12 @@ var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.repla
1273
1288
  if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
1274
1289
  new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
1275
1290
 
1276
- var isErrRetryable=function isErrRetryable(details){var isRetryableNWFailure=false;if(details!==null&&details!==void 0&&details.error&&details!==null&&details!==void 0&&details.xhr){var xhrStatus=details.xhr.status;// same as in v1.1
1291
+ var isErrRetryable=function isErrRetryable(details){var isRetryableNWFailure=false;if(details!==null&&details!==undefined&&details.error&&details!==null&&details!==undefined&&details.xhr){var xhrStatus=details.xhr.status;// same as in v1.1
1277
1292
  isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
1278
1293
 
1279
1294
  /**
1280
1295
  * Encode.
1281
- */var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
1296
+ */var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===undefined||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
1282
1297
  * Decode
1283
1298
  */var decode$1=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
1284
1299
  return undefined;}};/**
@@ -1297,7 +1312,7 @@ var cookie=function cookie(name,value,options,logger){switch(arguments.length){c
1297
1312
 
1298
1313
  var userIdKey='rl_user_id';var userTraitsKey='rl_trait';var anonymousUserIdKey='rl_anonymous_id';var groupIdKey='rl_group_id';var groupTraitsKey='rl_group_trait';var pageInitialReferrerKey='rl_page_init_referrer';var pageInitialReferringDomainKey='rl_page_init_referring_domain';var sessionInfoKey='rl_session';var authTokenKey='rl_auth_token';var COOKIE_KEYS={userId:userIdKey,userTraits:userTraitsKey,anonymousId:anonymousUserIdKey,groupId:groupIdKey,groupTraits:groupTraitsKey,initialReferrer:pageInitialReferrerKey,initialReferringDomain:pageInitialReferringDomainKey,sessionInfo:sessionInfoKey,authToken:authTokenKey};var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
1299
1314
 
1300
- var encryptBrowser=function encryptBrowser(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decryptBrowser=function decryptBrowser(value){if(value!==null&&value!==void 0&&value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1315
+ var encryptBrowser=function encryptBrowser(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decryptBrowser=function decryptBrowser(value){if(value!==null&&value!==undefined&&value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1301
1316
 
1302
1317
  var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1303
1318
 
@@ -1310,7 +1325,7 @@ var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL
1310
1325
  * Utility to validate final payload size before sending to server
1311
1326
  * @param event RudderEvent object
1312
1327
  * @param logger Logger instance
1313
- */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
1328
+ */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===undefined||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===undefined||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
1314
1329
  * Mutates the event and return final event for delivery
1315
1330
  * Updates certain parameters like sentAt timestamp, integrations config etc.
1316
1331
  * @param event RudderEvent object
@@ -1336,7 +1351,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
1336
1351
  * @param events RudderEvent object array
1337
1352
  * @param logger Logger instance
1338
1353
  * @returns stringified events payload as Blob, undefined if error occurs.
1339
- */var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,currentTime,logger){var data={batch:events,sentAt:currentTime};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===void 0||logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/','beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
1354
+ */var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,currentTime,logger){var data={batch:events,sentAt:currentTime};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===undefined||logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/','beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
1340
1355
 
1341
1356
  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={};}}]);}();
1342
1357
 
@@ -1354,22 +1369,22 @@ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='
1354
1369
  * @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1355
1370
  * @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
1356
1371
  */var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){var _options$timerScaleFa;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// Limit the timer scale factor to the minimum value
1357
- var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==void 0?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1372
+ var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==undefined?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1358
1373
  timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1359
1374
  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
1360
1375
  this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1361
1376
  this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);this.isPageAccessible=true;// Flush the queue on page leave
1362
1377
  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
1363
- 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
1378
+ this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==undefined?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==undefined?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==undefined?_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
1364
1379
  },{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
1365
1380
  * Stops processing the queue
1366
1381
  */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1367
1382
  * Starts processing the queue
1368
1383
  */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.scheduleFlushBatch();this.ack();this.checkReclaim();this.processHead();}/**
1369
1384
  * Configures the timeout handler for flushing the batch queue
1370
- */},{key:"scheduleFlushBatch",value:function scheduleFlushBatch(){var _this$batch;if(this.batch.enabled&&(_this$batch=this.batch)!==null&&_this$batch!==void 0&&_this$batch.flushInterval){if(this.flushBatchTaskId){this.schedule.cancel(this.flushBatchTaskId);}this.flushBatchTaskId=this.schedule.run(this.flushBatch,this.batch.flushInterval,ScheduleModes.ASAP);}}/**
1385
+ */},{key:"scheduleFlushBatch",value:function scheduleFlushBatch(){var _this$batch;if(this.batch.enabled&&(_this$batch=this.batch)!==null&&_this$batch!==undefined&&_this$batch.flushInterval){if(this.flushBatchTaskId){this.schedule.cancel(this.flushBatchTaskId);}this.flushBatchTaskId=this.schedule.run(this.flushBatch,this.batch.flushInterval,ScheduleModes.ASAP);}}/**
1371
1386
  * Flushes the batch queue
1372
- */},{key:"flushBatch",value:function flushBatch(){var isAccessible=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;if(!this.batchingInProgress){var _ref;this.isPageAccessible=isAccessible;this.batchingInProgress=true;var batchQueue=(_ref=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];if(batchQueue.length>0){batchQueue=batchQueue.slice(-batchQueue.length);var batchEntry=this.genQueueItem(batchQueue.map(function(queueItem){return queueItem.item;}),BATCH_QUEUE_ITEM_TYPE);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);this.pushToMainQueue(batchEntry);}this.batchingInProgress=false;// Re-schedule the flush task
1387
+ */},{key:"flushBatch",value:function flushBatch(){var isAccessible=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;if(!this.batchingInProgress){var _ref;this.isPageAccessible=isAccessible;this.batchingInProgress=true;var batchQueue=(_ref=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==undefined?_ref:[];if(batchQueue.length>0){batchQueue=batchQueue.slice(-batchQueue.length);var batchEntry=this.genQueueItem(batchQueue.map(function(queueItem){return queueItem.item;}),BATCH_QUEUE_ITEM_TYPE);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);this.pushToMainQueue(batchEntry);}this.batchingInProgress=false;// Re-schedule the flush task
1373
1388
  this.scheduleFlushBatch();}}/**
1374
1389
  * Decides whether to retry. Overridable.
1375
1390
  *
@@ -1386,11 +1401,11 @@ if(curEntry){this.pushToMainQueue(curEntry);}}/**
1386
1401
  * Handles a new item added to the retry queue when batching is enabled
1387
1402
  * @param entry New item added to the retry queue
1388
1403
  * @returns Undefined or batch entry object
1389
- */},{key:"handleNewItemForBatch",value:function handleNewItemForBatch(entry){var _ref2;var curEntry;var batchQueue=(_ref2=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref2!==void 0?_ref2:[];if(!this.batchingInProgress){this.batchingInProgress=true;batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);var batchDispatchInfo=this.getBatchDispatchInfo(batchQueue);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
1404
+ */},{key:"handleNewItemForBatch",value:function handleNewItemForBatch(entry){var _ref2;var curEntry;var batchQueue=(_ref2=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref2!==undefined?_ref2:[];if(!this.batchingInProgress){this.batchingInProgress=true;batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);var batchDispatchInfo=this.getBatchDispatchInfo(batchQueue);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
1390
1405
  if(batchDispatchInfo.criteriaMet||batchDispatchInfo.criteriaExceeded){var batchItems;if(batchDispatchInfo.criteriaExceeded){batchItems=batchQueue.slice(0,batchQueue.length-1).map(function(queueItem){return queueItem.item;});batchQueue=[entry];}else {batchItems=batchQueue.map(function(queueItem){return queueItem.item;});batchQueue=[];}// Don't make any batch request if there are no items
1391
1406
  if(batchItems.length>0){curEntry=this.genQueueItem(batchItems,BATCH_QUEUE_ITEM_TYPE);}// re-attach the timeout handler
1392
1407
  this.scheduleFlushBatch();}this.batchingInProgress=false;}else {batchQueue.push(entry);}// update the batch queue
1393
- this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{key:"pushToMainQueue",value:function pushToMainQueue(curEntry){var _ref3;var queue=(_ref3=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1408
+ this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{key:"pushToMainQueue",value:function pushToMainQueue(curEntry){var _ref3;var queue=(_ref3=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref3!==undefined?_ref3:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1394
1409
  * Adds an item to the queue
1395
1410
  *
1396
1411
  * @param {Object} itemData The item to process
@@ -1404,34 +1419,34 @@ this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{k
1404
1419
  * @param {Object} qItem The item to process
1405
1420
  * @param {Error} [error] The error that occurred during processing
1406
1421
  */},{key:"requeue",value:function requeue(qItem,error){var attemptNumber=qItem.attemptNumber,item=qItem.item,type=qItem.type,id=qItem.id;// Increment the attempt number as we're about to retry
1407
- var attemptNumberToUse=attemptNumber+1;if(this.shouldRetry(item,attemptNumberToUse)){this.enqueue({item:item,attemptNumber:attemptNumberToUse,time:this.schedule.now()+this.getDelay(attemptNumberToUse),id:id!==null&&id!==void 0?id:generateUUID(),type:type});}}/**
1422
+ var attemptNumberToUse=attemptNumber+1;if(this.shouldRetry(item,attemptNumberToUse)){this.enqueue({item:item,attemptNumber:attemptNumberToUse,time:this.schedule.now()+this.getDelay(attemptNumberToUse),id:id!==null&&id!==undefined?id:generateUUID(),type:type});}}/**
1408
1423
  * Returns the information about whether the batch criteria is met or exceeded
1409
1424
  * @param batchItems Prospective batch items
1410
1425
  * @returns Batch dispatch info
1411
- */},{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,_this=this,_ref6,_ref7;// cancel the scheduled task if it exists
1426
+ */},{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===undefined?undefined:_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===undefined?undefined:_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,_this=this,_ref6,_ref7;// cancel the scheduled task if it exists
1412
1427
  this.schedule.cancel(this.processId);// Pop the head off the queue
1413
- var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==void 0?_ref4:[];var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1414
- var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref5;var inProgress=(_ref5=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};delete inProgress[id];_this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this.requeue(el,err);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgress=(_ref6=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==void 0?_ref6:{};// If the page is unloading, clear the previous in progress queue also to avoid any stale data
1428
+ var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==undefined?_ref4:[];var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1429
+ var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref5;var inProgress=(_ref5=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==undefined?_ref5:{};delete inProgress[id];_this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this.requeue(el,err);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgress=(_ref6=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==undefined?_ref6:{};// If the page is unloading, clear the previous in progress queue also to avoid any stale data
1415
1430
  // Otherwise, the next page load will retry the items which were in progress previously
1416
1431
  if(!this.isPageAccessible){inProgress={};}var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
1417
1432
  while(queue.length>0&&queue[0].time<=now&&inProgressSize++<this.maxItems){var el=queue.shift();if(el){var id=generateUUID();// If the page is unloading, don't add items to the in progress queue
1418
1433
  if(this.isPageAccessible){// Save this to the in progress map
1419
1434
  inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now(),type:el.type};}enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1420
- 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
1421
- 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
1422
- },{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 {var _el$type;// Hack to determine the item type by the contents of the entry
1435
+ 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===undefined||_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
1436
+ queue=(_ref7=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref7!==undefined?_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
1437
+ },{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!==undefined?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==undefined?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==undefined?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==undefined?_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!==undefined?_el$id:generateUUID();if(trackMessageIds.includes(id));else {var _el$type;// Hack to determine the item type by the contents of the entry
1423
1438
  // After some point, we can remove this hack as most of the stale data will have been processed
1424
1439
  // and the new entries will have the type field set
1425
- var type=Array.isArray(el.item)?BATCH_QUEUE_ITEM_TYPE:SINGLE_QUEUE_ITEM_TYPE;our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id,type:(_el$type=el.type)!==null&&_el$type!==void 0?_el$type:type});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#
1440
+ var type=Array.isArray(el.item)?BATCH_QUEUE_ITEM_TYPE:SINGLE_QUEUE_ITEM_TYPE;our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id,type:(_el$type=el.type)!==null&&_el$type!==undefined?_el$type:type});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#
1426
1441
  addConcatQueue(their.queue,0);// Process batch queue items
1427
- if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2,_el$type2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();el.type=(_el$type2=el.type)!==null&&_el$type2!==void 0?_el$type2:SINGLE_QUEUE_ITEM_TYPE;el.time=_this2.schedule.now();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
1442
+ if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2,_el$type2;var id=(_el$id2=el.id)!==null&&_el$id2!==undefined?_el$id2:generateUUID();el.type=(_el$type2=el.type)!==null&&_el$type2!==undefined?_el$type2:SINGLE_QUEUE_ITEM_TYPE;el.time=_this2.schedule.now();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
1428
1443
  addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1429
1444
  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
1430
1445
  this.clearQueueEntries(other,1);// process the new items we claimed
1431
1446
  this.processHead();}// eslint-disable-next-line class-methods-use-this
1432
1447
  },{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
1433
1448
  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
1434
- _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
1449
+ _this3.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===undefined||_this3$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
1435
1450
  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
1436
1451
  // Hence, we need this backward compatibility check
1437
1452
  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();}}]);}();
@@ -1444,7 +1459,7 @@ var pluginName$f='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {na
1444
1459
  * @param errorHandler Error handler instance
1445
1460
  * @param logger Logger instance
1446
1461
  * @returns BeaconItemsQueue instance
1447
- */init:function init(state,httpClient,storeManager,errorHandler,logger){var _state$loadOptions$va;var writeKey=state.lifecycle.writeKey.value;var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl$1(dataplaneUrl,writeKey);var finalQOpts=getNormalizedBeaconQueueOptions((_state$loadOptions$va=state.loadOptions.value.beaconQueueOptions)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:{});var queueProcessCallback=function queueProcessCallback(itemData,done){logger===null||logger===void 0||logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var currentTime=getCurrentTimeFormatted();var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});var data=getBatchDeliveryPayload$1(finalEvents,currentTime,logger);if(data){try{var isEnqueuedInBeacon=navigator.sendBeacon(url,data);if(!isEnqueuedInBeacon){logger===null||logger===void 0||logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,BEACON_QUEUE_PLUGIN,BEACON_QUEUE_DELIVERY_ERROR(url));// Remove the item from queue
1462
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var _state$loadOptions$va;var writeKey=state.lifecycle.writeKey.value;var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl$1(dataplaneUrl,writeKey);var finalQOpts=getNormalizedBeaconQueueOptions((_state$loadOptions$va=state.loadOptions.value.beaconQueueOptions)!==null&&_state$loadOptions$va!==undefined?_state$loadOptions$va:{});var queueProcessCallback=function queueProcessCallback(itemData,done){logger===null||logger===undefined||logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var currentTime=getCurrentTimeFormatted();var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});var data=getBatchDeliveryPayload$1(finalEvents,currentTime,logger);if(data){try{var isEnqueuedInBeacon=navigator.sendBeacon(url,data);if(!isEnqueuedInBeacon){logger===null||logger===void 0||logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,BEACON_QUEUE_PLUGIN,BEACON_QUEUE_DELIVERY_ERROR(url));// Remove the item from queue
1448
1463
  done(null);}}else {// Mark the item as done so that it can be removed from the queue
1449
1464
  done(null);}};var eventsQueue=new RetryQueue("".concat(QUEUE_NAME$3,"_").concat(writeKey),{batch:{enabled:true,flushInterval:finalQOpts.flushQueueInterval,maxSize:MAX_BATCH_PAYLOAD_SIZE_BYTES,// set the hard limit
1450
1465
  maxItems:finalQOpts.maxItems}},queueProcessCallback,storeManager,LOCAL_STORAGE,logger,function(itemData){var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to Blob as we know that the event has already been validated prior to enqueue
@@ -1476,27 +1491,27 @@ var APP_STATE_EXCLUDE_KEYS$1=['userId','userTraits','groupId','groupTraits','ano
1476
1491
 
1477
1492
  var isValidVersion=function isValidVersion(globalLibInstance){var _globalLibInstance$_c;// For version 7
1478
1493
  // eslint-disable-next-line no-underscore-dangle
1479
- 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
1494
+ var version=globalLibInstance===null||globalLibInstance===undefined||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===undefined||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===undefined?undefined:_globalLibInstance$_c.version;// For versions older than 7
1480
1495
  if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
1481
- 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$1=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
1482
- var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES$1().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata$1=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS$1);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$1(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
1496
+ beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===undefined?undefined:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError$1=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===undefined||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===undefined?undefined:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}// Prefix folder for all the destination SDK scripts
1497
+ var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES$1().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata$1=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS$1);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$1(state))!==null&&_getAppStateForMetada!==undefined?_getAppStateForMetada:{});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
1483
1498
  event.context=errorMessage;// Hack for easily grouping the script load errors
1484
1499
  // on the dashboard
1485
1500
  if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
1486
1501
  event.context='Script load failures';}// eslint-disable-next-line no-param-reassign
1487
1502
  event.severity='error';};var onError=function onError(state,logger){return function(event){try{// Discard the event if it's not originated at the SDK
1488
- if(!isRudderSDKError$1(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
1503
+ if(!isRudderSDKError$1(event)){return false;}enhanceErrorEventMutator(state,event);return true;}catch(_unused){logger===null||logger===undefined||logger.error(FAILED_TO_FILTER_ERROR(BUGSNAG_PLUGIN));// Drop the error event if it couldn't be filtered as
1489
1504
  // it is most likely a non-SDK error
1490
1505
  return false;}};};var getReleaseStage$1=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS$1.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$i,_state$source$value,_state$session$sessio,_state$session$sessio2,_state$autoTrack$page,_state$autoTrack;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
1491
1506
  collectUserIp:false,// collecting user's IP is disabled
1492
1507
  // enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
1493
1508
  maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage$1(),user:{// Combination of source, session and visit ids
1494
- id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)!==null&&_state$source$value$i!==void 0?_state$source$value$i:state.lifecycle.writeKey.value,"..").concat((_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===void 0?void 0:_state$session$sessio2.id)!==null&&_state$session$sessio!==void 0?_state$session$sessio:'NA',"..").concat((_state$autoTrack$page=(_state$autoTrack=state.autoTrack)===null||_state$autoTrack===void 0||(_state$autoTrack=_state$autoTrack.pageLifecycle)===null||_state$autoTrack===void 0||(_state$autoTrack=_state$autoTrack.visitId)===null||_state$autoTrack===void 0?void 0:_state$autoTrack.value)!==null&&_state$autoTrack$page!==void 0?_state$autoTrack$page:'NA')},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
1509
+ id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===undefined?undefined:_state$source$value.id)!==null&&_state$source$value$i!==undefined?_state$source$value$i:state.lifecycle.writeKey.value,"..").concat((_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===undefined?undefined:_state$session$sessio2.id)!==null&&_state$session$sessio!==undefined?_state$session$sessio:'NA',"..").concat((_state$autoTrack$page=(_state$autoTrack=state.autoTrack)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.pageLifecycle)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.visitId)===null||_state$autoTrack===undefined?undefined:_state$autoTrack.value)!==null&&_state$autoTrack$page!==undefined?_state$autoTrack$page:'NA')},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===undefined||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
1495
1510
  globalThis.setTimeout(_initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};
1496
1511
 
1497
1512
  var pluginName$e='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},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
1498
1513
  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
1499
- 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);}}};};
1514
+ 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===undefined||client.leaveBreadcrumb(message);}}};};
1500
1515
 
1501
1516
  var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1502
1517
 
@@ -1509,7 +1524,7 @@ if(!consentManagement){return true;}// Get the corresponding consents for the de
1509
1524
  var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1510
1525
  if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1511
1526
  // the configured resolution strategy
1512
- var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};switch(resolutionStrategy){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,CUSTOM_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$3);return true;}}}};};
1527
+ var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};switch(resolutionStrategy){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,CUSTOM_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$3);return true;}}}};};
1513
1528
 
1514
1529
  var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
1515
1530
  var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
@@ -1523,7 +1538,7 @@ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){retur
1523
1538
  * @param intgOpts Integration options object
1524
1539
  * @param destinations Destinations array
1525
1540
  * @returns Destinations array filtered based on the integration options
1526
- */var filterDestinations=function filterDestinations(intgOpts,destinations){var _intgOpts$All;var allOptVal=(_intgOpts$All=intgOpts.All)!==null&&_intgOpts$All!==void 0?_intgOpts$All:true;return destinations.filter(function(dest){var destDisplayName=dest.displayName;var isDestEnabled;if(allOptVal){isDestEnabled=true;if(isDestIntgConfigFalsy(intgOpts[destDisplayName])){isDestEnabled=false;}}else {isDestEnabled=false;if(isDestIntgConfigTruthy(intgOpts[destDisplayName])){isDestEnabled=true;}}return isDestEnabled;});};
1541
+ */var filterDestinations=function filterDestinations(intgOpts,destinations){var _intgOpts$All;var allOptVal=(_intgOpts$All=intgOpts.All)!==null&&_intgOpts$All!==undefined?_intgOpts$All:true;return destinations.filter(function(dest){var destDisplayName=dest.displayName;var isDestEnabled;if(allOptVal){isDestEnabled=true;if(isDestIntgConfigFalsy(intgOpts[destDisplayName])){isDestEnabled=false;}}else {isDestEnabled=false;if(isDestIntgConfigTruthy(intgOpts[destDisplayName])){isDestEnabled=true;}}return isDestEnabled;});};
1527
1542
 
1528
1543
  /*
1529
1544
  GENERATED - DO NOT EDIT
@@ -1702,22 +1717,22 @@ var destDisplayNamesToFileNamesMap=(_destDisplayNamesToFi={},_defineProperty(_de
1702
1717
  * @param sdkTypeName The name of the destination SDK type
1703
1718
  * @param logger Logger instance
1704
1719
  * @returns true if the destination SDK code is evaluated, false otherwise
1705
- */var isDestinationSDKMounted=function isDestinationSDKMounted(destSDKIdentifier,sdkTypeName,logger){var _destSDKIdentifier;return Boolean(((_destSDKIdentifier=globalThis[destSDKIdentifier])===null||_destSDKIdentifier===void 0||(_destSDKIdentifier=_destSDKIdentifier[sdkTypeName])===null||_destSDKIdentifier===void 0?void 0:_destSDKIdentifier.prototype)&&typeof globalThis[destSDKIdentifier][sdkTypeName].prototype.constructor!=='undefined');};var wait=function wait(time){return new Promise(function(resolve){globalThis.setTimeout(resolve,time);});};var createDestinationInstance=function createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state){var _state$consents$postC,_state$consents$postC2;var rAnalytics=globalThis.rudderanalytics;var analytics=rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);var analyticsInstance={loadIntegration:state.nativeDestinations.loadIntegration.value,logLevel:state.lifecycle.logLevel.value,loadOnlyIntegrations:(_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===void 0?void 0:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,page:function page(category,name,properties,options,callback){return analytics.page(pageArgumentsToCallOptions(getSanitizedValue(category),getSanitizedValue(name),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));},track:function track(event,properties,options,callback){return analytics.track(trackArgumentsToCallOptions(getSanitizedValue(event),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));},identify:function identify(userId,traits,options,callback){return analytics.identify(identifyArgumentsToCallOptions(getSanitizedValue(userId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));},alias:function alias(to,from,options,callback){return analytics.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));},group:function group(groupId,traits,options,callback){return analytics.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));},getAnonymousId:function getAnonymousId(options){return analytics.getAnonymousId(getSanitizedValue(options));},getUserId:function getUserId(){return analytics.getUserId();},getUserTraits:function getUserTraits(){return analytics.getUserTraits();},getGroupId:function getGroupId(){return analytics.getGroupId();},getGroupTraits:function getGroupTraits(){return analytics.getGroupTraits();},getSessionId:function getSessionId(){return analytics.getSessionId();}};var deviceModeDestination=new globalThis[destSDKIdentifier][sdkTypeName](clone(dest.config),analyticsInstance,{shouldApplyDeviceModeTransformation:dest.shouldApplyDeviceModeTransformation,propagateEventsUntransformedOnError:dest.propagateEventsUntransformedOnError,destinationId:dest.id});return deviceModeDestination;};var _isDestinationReady=function isDestinationReady(dest){var time=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;return new Promise(function(resolve,reject){var instance=dest.instance;if(instance.isLoaded()&&(!instance.isReady||instance.isReady())){resolve(true);}else if(time>=READY_CHECK_TIMEOUT_MS){reject(new Error(DESTINATION_READY_TIMEOUT_ERROR(READY_CHECK_TIMEOUT_MS,dest.userFriendlyId)));}else {var curTime=Date.now();wait(READY_CHECK_INTERVAL_MS).then(function(){var elapsedTime=Date.now()-curTime;_isDestinationReady(dest,time+elapsedTime).then(resolve).catch(function(err){return reject(err);});}).catch(function(err){return reject(err);});}});};/**
1720
+ */var isDestinationSDKMounted=function isDestinationSDKMounted(destSDKIdentifier,sdkTypeName,logger){var _destSDKIdentifier;return Boolean(((_destSDKIdentifier=globalThis[destSDKIdentifier])===null||_destSDKIdentifier===undefined||(_destSDKIdentifier=_destSDKIdentifier[sdkTypeName])===null||_destSDKIdentifier===undefined?undefined:_destSDKIdentifier.prototype)&&typeof globalThis[destSDKIdentifier][sdkTypeName].prototype.constructor!=='undefined');};var wait=function wait(time){return new Promise(function(resolve){globalThis.setTimeout(resolve,time);});};var createDestinationInstance=function createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state){var _state$consents$postC,_state$consents$postC2;var rAnalytics=globalThis.rudderanalytics;var analytics=rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);var analyticsInstance={loadIntegration:state.nativeDestinations.loadIntegration.value,logLevel:state.lifecycle.logLevel.value,loadOnlyIntegrations:(_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===undefined?undefined:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==undefined?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,page:function page(category,name,properties,options,callback){return analytics.page(pageArgumentsToCallOptions(getSanitizedValue(category),getSanitizedValue(name),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));},track:function track(event,properties,options,callback){return analytics.track(trackArgumentsToCallOptions(getSanitizedValue(event),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));},identify:function identify(userId,traits,options,callback){return analytics.identify(identifyArgumentsToCallOptions(getSanitizedValue(userId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));},alias:function alias(to,from,options,callback){return analytics.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));},group:function group(groupId,traits,options,callback){return analytics.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));},getAnonymousId:function getAnonymousId(options){return analytics.getAnonymousId(getSanitizedValue(options));},getUserId:function getUserId(){return analytics.getUserId();},getUserTraits:function getUserTraits(){return analytics.getUserTraits();},getGroupId:function getGroupId(){return analytics.getGroupId();},getGroupTraits:function getGroupTraits(){return analytics.getGroupTraits();},getSessionId:function getSessionId(){return analytics.getSessionId();}};var deviceModeDestination=new globalThis[destSDKIdentifier][sdkTypeName](clone(dest.config),analyticsInstance,{shouldApplyDeviceModeTransformation:dest.shouldApplyDeviceModeTransformation,propagateEventsUntransformedOnError:dest.propagateEventsUntransformedOnError,destinationId:dest.id});return deviceModeDestination;};var _isDestinationReady=function isDestinationReady(dest){var time=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;return new Promise(function(resolve,reject){var instance=dest.instance;if(instance.isLoaded()&&(!instance.isReady||instance.isReady())){resolve(true);}else if(time>=READY_CHECK_TIMEOUT_MS){reject(new Error(DESTINATION_READY_TIMEOUT_ERROR(READY_CHECK_TIMEOUT_MS,dest.userFriendlyId)));}else {var curTime=Date.now();wait(READY_CHECK_INTERVAL_MS).then(function(){var elapsedTime=Date.now()-curTime;_isDestinationReady(dest,time+elapsedTime).then(resolve).catch(function(err){return reject(err);});}).catch(function(err){return reject(err);});}});};/**
1706
1721
  * Extracts the integration config, if any, from the given destination
1707
1722
  * and merges it with the current integrations config
1708
1723
  * @param dest Destination object
1709
1724
  * @param curDestIntgConfig Current destinations integration config
1710
1725
  * @param logger Logger object
1711
1726
  * @returns Combined destinations integrations config
1712
- */var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){var _dest$instance;var integrationsConfig=curDestIntgConfig;if(isFunction((_dest$instance=dest.instance)===null||_dest$instance===void 0?void 0:_dest$instance.getDataForIntegrationsObject)){try{var _dest$instance2;integrationsConfig=mergeDeepRight(curDestIntgConfig,getSanitizedValue((_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject()));}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId));}}return integrationsConfig;};var initializeDestination=function initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger){try{var initializedDestination=clone(dest);var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state);initializedDestination.instance=destInstance;destInstance.init();_isDestinationReady(initializedDestination).then(function(){// Collect the integrations data for the hybrid mode destinations
1727
+ */var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){var _dest$instance;var integrationsConfig=curDestIntgConfig;if(isFunction((_dest$instance=dest.instance)===null||_dest$instance===undefined?undefined:_dest$instance.getDataForIntegrationsObject)){try{var _dest$instance2;integrationsConfig=mergeDeepRight(curDestIntgConfig,getSanitizedValue((_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject()));}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId));}}return integrationsConfig;};var initializeDestination=function initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger){try{var initializedDestination=clone(dest);var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state);initializedDestination.instance=destInstance;destInstance.init();_isDestinationReady(initializedDestination).then(function(){// Collect the integrations data for the hybrid mode destinations
1713
1728
  if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);// The error message is already formatted in the isDestinationReady function
1714
- logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
1729
+ logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===undefined||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
1715
1730
 
1716
1731
  var pluginName$c='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$c,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,errorHandler,logger){var _state$consents$postC,_state$consents$postC2;state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
1717
- var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load or consent API options
1718
- var destinationsToLoad=filterDestinations((_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===void 0?void 0:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1719
- (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==void 0?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1720
- var sdkTypeName=sdkName;if(sdkTypeName&&!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==void 0?externalScriptOnLoad:function(id){if(!id){logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else if(sdkTypeName){initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}else {logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.displayName));}});}}};};
1732
+ var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===undefined||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load or consent API options
1733
+ var destinationsToLoad=filterDestinations((_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===undefined?undefined:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==undefined?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1734
+ (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==undefined?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1735
+ var sdkTypeName=sdkName;if(sdkTypeName&&!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==undefined?externalScriptOnLoad:function(id){if(!id){logger===null||logger===undefined||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else if(sdkTypeName){initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}else {logger===null||logger===undefined||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.displayName));}});}}};};
1721
1736
 
1722
1737
  var DEFAULT_TRANSFORMATION_QUEUE_OPTIONS={minRetryDelay:500,backoffFactor:2,maxAttempts:3};var REQUEST_TIMEOUT_MS$2=10*1000;// 10 seconds
1723
1738
  var QUEUE_NAME$2='rudder';var DMT_PLUGIN='DeviceModeTransformationPlugin';
@@ -1729,11 +1744,11 @@ var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSF
1729
1744
  * a batch payload that will be sent to transformation server
1730
1745
  *
1731
1746
  */var createPayload=function createPayload(event,destinationIds,token){var orderNo=Date.now();var payload={metadata:{'Custom-Authorization':token},batch:[{orderNo:orderNo,destinationIds:destinationIds,event:event}]};return payload;};var sendTransformedEventToDestinations=function sendTransformedEventToDestinations(state,pluginsManager,destinationIds,result,status,event,errorHandler,logger){var NATIVE_DEST_EXT_POINT='destinationsEventsQueue.enqueueEventToDestination';var ACTION_TO_SEND_UNTRANSFORMED_EVENT='Sending untransformed event';var ACTION_TO_DROP_EVENT='Dropping the event';var destinations=state.nativeDestinations.initializedDestinations.value.filter(function(d){return d&&destinationIds.includes(d.id);});destinations.forEach(function(dest){try{var eventsToSend=[];switch(status){case 200:{var response=JSON.parse(result);var destTransformedResult=response.transformedBatch.find(function(e){return e.id===dest.id;});destTransformedResult===null||destTransformedResult===void 0||destTransformedResult.payload.forEach(function(tEvent){if(tEvent.status==='200'){eventsToSend.push(tEvent.event);}else {var reason='Unknown';if(tEvent.status==='410'){reason='Transformation is not available';}var action=ACTION_TO_DROP_EVENT;if(dest.propagateEventsUntransformedOnError===true){action=ACTION_TO_SEND_UNTRANSFORMED_EVENT;eventsToSend.push(event);logger===null||logger===void 0||logger.warn(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}else {logger===null||logger===void 0||logger.error(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}}});break;}// Transformation server access denied
1732
- case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
1747
+ case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===undefined||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
1733
1748
 
1734
1749
  var pluginName$b='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$b,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1735
1750
  "".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.activeDataplaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$2,callback:function callback(result,details){// null means item will not be requeued
1736
- var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
1751
+ var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===undefined||(_details$xhr=details.xhr)===null||_details$xhr===undefined?undefined:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
1737
1752
 
1738
1753
  // Errors from the below scripts are NOT allowed to reach Bugsnag
1739
1754
  var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
@@ -1744,10 +1759,10 @@ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anony
1744
1759
  'traits','authToken'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
1745
1760
  var NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';var SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';var SOURCE_NAME='js';var ERROR_REPORTING_PLUGIN='ErrorReportingPlugin';
1746
1761
 
1747
- var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==void 0?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getErrorContext=function getErrorContext(event){var message=event.message;var context=message;// Hack for easily grouping the script load errors
1762
+ var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==undefined?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getErrorContext=function getErrorContext(event){var message=event.message;var context=message;// Hack for easily grouping the script load errors
1748
1763
  // on the dashboard
1749
- if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};var getBugsnagErrorEvent=function getBugsnagErrorEvent(payload,errorState,state){var _state$context$locale,_state$context$userAg,_getAppStateForMetada,_state$source$value$i,_state$source$value,_state$session$sessio,_state$session$sessio2,_state$autoTrack$page,_state$autoTrack;return {notifier:{name:NOTIFIER_NAME,version:state.context.app.value.version,url:SDK_GITHUB_URL},events:[{payloadVersion:'5',exceptions:clone(payload.errors),severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:state.context.app.value.version,releaseStage:getReleaseStage()},device:{locale:(_state$context$locale=state.context.locale.value)!==null&&_state$context$locale!==void 0?_state$context$locale:undefined,userAgent:(_state$context$userAg=state.context.userAgent.value)!==null&&_state$context$userAg!==void 0?_state$context$userAg:undefined,time:new Date()},request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(state.reporting.breadcrumbs.value),context:getErrorContext(payload.errors[0]),metaData:{sdk:{name:'JS',installType:state.context.app.value.installType},state:(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{// Combination of source, session and visit ids
1750
- id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)!==null&&_state$source$value$i!==void 0?_state$source$value$i:state.lifecycle.writeKey.value,"..").concat((_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===void 0?void 0:_state$session$sessio2.id)!==null&&_state$session$sessio!==void 0?_state$session$sessio:'NA',"..").concat((_state$autoTrack$page=(_state$autoTrack=state.autoTrack)===null||_state$autoTrack===void 0||(_state$autoTrack=_state$autoTrack.pageLifecycle)===null||_state$autoTrack===void 0||(_state$autoTrack=_state$autoTrack.visitId)===null||_state$autoTrack===void 0?void 0:_state$autoTrack.value)!==null&&_state$autoTrack$page!==void 0?_state$autoTrack$page:'NA')}}]};};/**
1764
+ if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};var getBugsnagErrorEvent=function getBugsnagErrorEvent(payload,errorState,state){var _state$context$locale,_state$context$userAg,_getAppStateForMetada,_state$source$value$i,_state$source$value,_state$session$sessio,_state$session$sessio2,_state$autoTrack$page,_state$autoTrack;return {notifier:{name:NOTIFIER_NAME,version:state.context.app.value.version,url:SDK_GITHUB_URL},events:[{payloadVersion:'5',exceptions:clone(payload.errors),severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:state.context.app.value.version,releaseStage:getReleaseStage()},device:{locale:(_state$context$locale=state.context.locale.value)!==null&&_state$context$locale!==undefined?_state$context$locale:undefined,userAgent:(_state$context$userAg=state.context.userAgent.value)!==null&&_state$context$userAg!==undefined?_state$context$userAg:undefined,time:new Date()},request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(state.reporting.breadcrumbs.value),context:getErrorContext(payload.errors[0]),metaData:{sdk:{name:'JS',installType:state.context.app.value.installType},state:(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==undefined?_getAppStateForMetada:{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{// Combination of source, session and visit ids
1765
+ id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===undefined?undefined:_state$source$value.id)!==null&&_state$source$value$i!==undefined?_state$source$value$i:state.lifecycle.writeKey.value,"..").concat((_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===undefined?undefined:_state$session$sessio2.id)!==null&&_state$session$sessio!==undefined?_state$session$sessio:'NA',"..").concat((_state$autoTrack$page=(_state$autoTrack=state.autoTrack)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.pageLifecycle)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.visitId)===null||_state$autoTrack===undefined?undefined:_state$autoTrack.value)!==null&&_state$autoTrack$page!==undefined?_state$autoTrack$page:'NA')}}]};};/**
1751
1766
  * A function to determine whether the error should be promoted to notify or not
1752
1767
  * @param {Error} error
1753
1768
  * @returns
@@ -1755,7 +1770,7 @@ id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===n
1755
1770
  * A function to determine if the error is from Rudder SDK
1756
1771
  * @param {Error} event
1757
1772
  * @returns
1758
- */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;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
1773
+ */var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===undefined||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===undefined?undefined:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
1759
1774
  // Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
1760
1775
  var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return stringifyWithoutCircular(data);};
1761
1776
 
@@ -1790,7 +1805,7 @@ parseOpera11:function ErrorStackParser$$parseOpera11(error){var filtered=error.s
1790
1805
  var errorStackParserExports = requireErrorStackParser();
1791
1806
  var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1792
1807
 
1793
- var hasStack=function hasStack(err){return !!err&&(!!err.stack||!!err.stacktrace||!!err['opera#sourceloc'])&&typeof(err.stack||err.stacktrace||err['opera#sourceloc'])==='string'&&err.stack!=="".concat(err.name,": ").concat(err.message);};var isError=function isError(value){switch(Object.prototype.toString.call(value)){case'[object Error]':case'[object Exception]':case'[object DOMException]':return true;default:return value instanceof Error;}};
1808
+ var hasStack=function hasStack(err){return !!err&&(!!err.stack||!!err.stacktrace||!!err['opera#sourceloc'])&&typeof(err.stack||err.stacktrace||err['opera#sourceloc'])==='string'&&err.stack!=="".concat(err.name,": ").concat(err.message);};var isError=function isError(value){switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}};
1794
1809
 
1795
1810
  var normaliseFunctionName=function normaliseFunctionName(name){return /^global code$/i.test(name)?'global code':name;};// takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1796
1811
  // and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
@@ -1800,17 +1815,17 @@ var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName
1800
1815
  // This adds one.
1801
1816
  if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};var ensureString=function ensureString(str){return typeof str==='string'?str:'';};function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
1802
1817
  try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
1803
- var getStacktrace=function getStacktrace(error){if(hasStack(error))return ErrorStackParser.parse(error);return [];};var normaliseError=function normaliseError(maybeError,component,logger){var error;if(isError(maybeError)){error=maybeError;}else {logger===null||logger===void 0||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(stringifyWithoutCircular(error)));error=undefined;}if(error&&!hasStack(error)){error=undefined;}return error;};var ErrorFormat=/*#__PURE__*/function(){function ErrorFormat(errorClass,errorMessage,stacktrace){_classCallCheck(this,ErrorFormat);this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}return _createClass(ErrorFormat,null,[{key:"create",value:function create(maybeError,component,logger){var error=normaliseError(maybeError,component,logger);if(!error){return undefined;}var event;try{var stacktrace=getStacktrace(error);event=new ErrorFormat(error.name,error.message,stacktrace);}catch(e){event=new ErrorFormat(error.name,error.message,[]);}return event;}}]);}();
1818
+ var getStacktrace=function getStacktrace(error){if(hasStack(error))return ErrorStackParser.parse(error);return [];};var normaliseError=function normaliseError(maybeError,component,logger){var error;if(isError(maybeError)){error=maybeError;}else {logger===null||logger===undefined||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(stringifyWithoutCircular(error)));error=undefined;}if(error&&!hasStack(error)){error=undefined;}return error;};var ErrorFormat=/*#__PURE__*/function(){function ErrorFormat(errorClass,errorMessage,stacktrace){_classCallCheck(this,ErrorFormat);this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}return _createClass(ErrorFormat,null,[{key:"create",value:function create(maybeError,component,logger){var error=normaliseError(maybeError,component,logger);if(!error){return undefined;}var event;try{var stacktrace=getStacktrace(error);event=new ErrorFormat(error.name,error.message,stacktrace);}catch(e){event=new ErrorFormat(error.name,error.message,[]);}return event;}}]);}();
1804
1819
 
1805
1820
  var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
1806
1821
 
1807
- var pluginName$a='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$a,deps:[],initialize:function initialize(state){var _state$reporting$brea;state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);state.reporting.isErrorReportingPluginLoaded.value=true;if((_state$reporting$brea=state.reporting.breadcrumbs)!==null&&_state$reporting$brea!==void 0&&_state$reporting$brea.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
1822
+ var pluginName$a='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$a,deps:[],initialize:function initialize(state){var _state$reporting$brea;state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);state.reporting.isErrorReportingPluginLoaded.value=true;if((_state$reporting$brea=state.reporting.breadcrumbs)!==null&&_state$reporting$brea!==undefined&&_state$reporting$brea.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
1808
1823
  // TODO: Remove this in the next major release
1809
- init:function init(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore){var _state$source$value,_state$source$value2;if(isInvokedFromLatestCore){return undefined;}if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==void 0&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==void 0&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger,httpClient,errorState){if(httpClient){var _getConfigForPayloadC=getConfigForPayloadCreation(error,errorState===null||errorState===void 0?void 0:errorState.severityReason.type),component=_getConfigForPayloadC.component,normalizedError=_getConfigForPayloadC.normalizedError;// Generate the error payload
1824
+ init:function init(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore){var _state$source$value,_state$source$value2;if(isInvokedFromLatestCore){return undefined;}if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==undefined&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==undefined&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger,httpClient,errorState){if(httpClient){var _getConfigForPayloadC=getConfigForPayloadCreation(error,errorState===null||errorState===undefined?undefined:errorState.severityReason.type),component=_getConfigForPayloadC.component,normalizedError=_getConfigForPayloadC.normalizedError;// Generate the error payload
1810
1825
  var errorPayload=ErrorFormat.create(normalizedError,component,logger);if(!errorPayload||!isAllowedToBeNotified(errorPayload.errors[0])){return;}// filter errors
1811
1826
  if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
1812
1827
  var bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
1813
- httpClient===null||httpClient===void 0||httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// do nothing
1828
+ httpClient===null||httpClient===undefined||httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// do nothing
1814
1829
  }});}else {pluginEngine.invokeSingle('errorReportingProvider.notify',client,error,state,logger);}},breadcrumb:function breadcrumb(pluginEngine,client,message,logger,state,metaData){if(state){state.reporting.breadcrumbs.value=[].concat(_toConsumableArray(state.reporting.breadcrumbs.value),[createNewBreadcrumb(message,metaData)]);}else {pluginEngine.invokeSingle('errorReportingProvider.breadcrumb',client,message,logger);}}}};};
1815
1830
 
1816
1831
  var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
@@ -1818,11 +1833,11 @@ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1818
1833
  var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1819
1834
  * First check the local storage for anonymousId
1820
1835
  * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1821
- */var lsEngine=getStorageEngine(LOCAL_STORAGE);if(lsEngine!==null&&lsEngine!==void 0&&lsEngine.isEnabled){anonymousId=lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);}// If anonymousId is not present in local storage and find it in cookies
1822
- var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1836
+ */var lsEngine=getStorageEngine(LOCAL_STORAGE);if(lsEngine!==null&&lsEngine!==undefined&&lsEngine.isEnabled){anonymousId=lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);}// If anonymousId is not present in local storage and find it in cookies
1837
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==undefined&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1823
1838
 
1824
- var pluginName$9='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$9,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);},storage:{getAnonymousId:function getAnonymousId(getStorageEngine,options){var _options$autoCapture;var anonymousId;if(options!==null&&options!==void 0&&(_options$autoCapture=options.autoCapture)!==null&&_options$autoCapture!==void 0&&_options$autoCapture.enabled&&options.autoCapture.source){var source=options.autoCapture.source.toLowerCase();if(!Object.keys(externallyLoadedSessionStorageKeys).includes(source)){return anonymousId;}// eslint-disable-next-line sonarjs/no-small-switch
1825
- switch(source){case'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1839
+ var pluginName$9='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$9,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);},storage:{getAnonymousId:function getAnonymousId(getStorageEngine,options){var _options$autoCapture;var anonymousId;if(options!==null&&options!==undefined&&(_options$autoCapture=options.autoCapture)!==null&&_options$autoCapture!==undefined&&_options$autoCapture.enabled&&options.autoCapture.source){var source=options.autoCapture.source.toLowerCase();if(!Object.keys(externallyLoadedSessionStorageKeys).includes(source)){return anonymousId;}// eslint-disable-next-line sonarjs/no-small-switch
1840
+ switch(source){case 'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1826
1841
 
1827
1842
  var AMP_LINKER_ANONYMOUS_ID_KEY='rs_amp_id';
1828
1843
 
@@ -1844,9 +1859,9 @@ crc=crc>>>8^crcTable[(crc^str.charCodeAt(i))&0xff];}return (crc^-1)>>>0;};
1844
1859
  * An interface to fetch user device details.
1845
1860
  */var USER_INTERFACE={/**
1846
1861
  * @returns {string} user language
1847
- */getUserLanguage:function getUserLanguage(){var _navigator;return (_navigator=navigator)===null||_navigator===void 0?void 0:_navigator.language;},/**
1862
+ */getUserLanguage:function getUserLanguage(){var _navigator;return (_navigator=navigator)===null||_navigator===undefined?undefined:_navigator.language;},/**
1848
1863
  * @returns {string} userAgent
1849
- */getUserAgent:function getUserAgent(){var _navigator2;return (_navigator2=navigator)===null||_navigator2===void 0?void 0:_navigator2.userAgent;}};
1864
+ */getUserAgent:function getUserAgent(){var _navigator2;return (_navigator2=navigator)===null||_navigator2===undefined?undefined:_navigator2.userAgent;}};
1850
1865
 
1851
1866
  /**
1852
1867
  * This is utility function for decoding from base 64 to utf8
@@ -1872,7 +1887,7 @@ var KEY_VALIDATOR=/^[\w.-]+$/;var CHECKSUM_OFFSET_MAX_MIN=1;var VALID_VERSION=1;
1872
1887
  */var parseLinkerParamValue=function parseLinkerParamValue(value){var parts=value.split(DELIMITER);var isEven=parts.length%2===0;if(parts.length<4||!isEven){// Format <version>*<checksum>*<key1>*<value1>
1873
1888
  // Note: linker makes sure there's at least one pair of non empty key value
1874
1889
  // Make sure there is at least three delimiters.
1875
- return null;}var version=Number(parts.shift());if(version!==VALID_VERSION){return null;}var checksum=parts.shift();var serializedIds=parts.join(DELIMITER);return {checksum:checksum!==null&&checksum!==void 0?checksum:'',serializedIds:serializedIds};};/**
1890
+ return null;}var version=Number(parts.shift());if(version!==VALID_VERSION){return null;}var checksum=parts.shift();var serializedIds=parts.join(DELIMITER);return {checksum:checksum!==null&&checksum!==undefined?checksum:'',serializedIds:serializedIds};};/**
1876
1891
  * Deserialize the serializedIds and return keyValue pairs.
1877
1892
  *
1878
1893
  * @param {string} serializedIds
@@ -1921,13 +1936,13 @@ var IUBENDA_CONSENT_MANAGER_PLUGIN='IubendaConsentManagerPlugin';var IUBENDA_CON
1921
1936
  var getIubendaCookieName=function getIubendaCookieName(logger){try{// Retrieve cookies as a string and split them into an array
1922
1937
  var cookies=document.cookie.split('; ');// Find the cookie that matches the iubenda cookie pattern
1923
1938
  var matchedCookie=cookies.find(function(cookie){var _cookie$split=cookie.split('='),_cookie$split2=_slicedToArray(_cookie$split,1),name=_cookie$split2[0];return IUBENDA_CONSENT_COOKIE_NAME_PATTERN.test((name||'').trim());});if(!matchedCookie){throw new Error('Iubenda Cookie not found with the specified pattern.');}// Extract and return the cookie name
1924
- var _matchedCookie$split=matchedCookie.split('='),_matchedCookie$split2=_slicedToArray(_matchedCookie$split,1),name=_matchedCookie$split2[0];return name||'';}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return '';}};/**
1939
+ var _matchedCookie$split=matchedCookie.split('='),_matchedCookie$split2=_slicedToArray(_matchedCookie$split,1),name=_matchedCookie$split2[0];return name||'';}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return '';}};/**
1925
1940
  * Gets the consent data from the Iubenda's consent cookie
1926
1941
  * @param storeManager Store manager instance
1927
1942
  * @param logger Logger instance
1928
1943
  * @returns Consent data from the consent cookie
1929
- */var getIubendaConsentData=function getIubendaConsentData(storeManager,logger){var rawConsentCookieData=null;try{var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:IUBENDA_CONSENT_MANAGER_PLUGIN,name:IUBENDA_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(getIubendaCookieName(logger));}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1930
- var consentCookieData;try{consentCookieData=JSON.parse(decodeURIComponent(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_PARSE_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1944
+ */var getIubendaConsentData=function getIubendaConsentData(storeManager,logger){var rawConsentCookieData=null;try{var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:IUBENDA_CONSENT_MANAGER_PLUGIN,name:IUBENDA_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(getIubendaCookieName(logger));}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1945
+ var consentCookieData;try{consentCookieData=JSON.parse(decodeURIComponent(rawConsentCookieData));}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_PARSE_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1931
1946
  var consentPurposes=consentCookieData.purposes;return consentPurposes;};/**
1932
1947
  * Gets the consent data in the format expected by the application state
1933
1948
  * @param iubendaConsentData Consent data derived from the consent cookie
@@ -1936,9 +1951,9 @@ var consentPurposes=consentCookieData.purposes;return consentPurposes;};/**
1936
1951
 
1937
1952
  var pluginName$7='IubendaConsentManager';var IubendaConsentManager=function IubendaConsentManager(){return {name:pluginName$7,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$7]);},consentManager:{init:function init(state,logger){// getIubendaUserConsentedPurposes returns current iubenda opted-in purposes
1938
1953
  // This will be helpful for debugging
1939
- globalThis.getIubendaUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getIubendaUserDeniedPurposes returns current Iubenda opted-out purposes
1954
+ globalThis.getIubendaUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===undefined?undefined:_state$consents$data$.slice();};// getIubendaUserDeniedPurposes returns current Iubenda opted-out purposes
1940
1955
  // This will be helpful for debugging
1941
- globalThis.getIubendaUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateIubendaConsent callback function to update current consent purpose state
1956
+ globalThis.getIubendaUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===undefined?undefined:_state$consents$data$2.slice();};// updateIubendaConsent callback function to update current consent purpose state
1942
1957
  globalThis.updateIubendaConsent=function(iubendaConsentData){updateConsentStateFromData$1(state,iubendaConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1943
1958
  var iubendaConsentData;// From window
1944
1959
  if(!isUndefined(globalThis._iub.cs.consent.purposes)){iubendaConsentData=globalThis._iub.cs.consent.purposes;// From cookie
@@ -1947,7 +1962,7 @@ if(consentManagement){var _cmpConfig$resolution;// Get the corresponding consent
1947
1962
  var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1948
1963
  if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1949
1964
  // the configured resolution strategy
1950
- switch(resolutionStrategy){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}}return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,IUBENDA_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$2);return true;}}}};};
1965
+ switch(resolutionStrategy){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}}return true;}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,IUBENDA_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$2);return true;}}}};};
1951
1966
 
1952
1967
  var KETCH_CONSENT_COOKIE_READ_ERROR=function KETCH_CONSENT_COOKIE_READ_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to read the consent cookie.");};var KETCH_CONSENT_COOKIE_PARSE_ERROR=function KETCH_CONSENT_COOKIE_PARSE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to parse the consent cookie.");};var DESTINATION_CONSENT_STATUS_ERROR$1="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1953
1968
 
@@ -1959,9 +1974,9 @@ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_C
1959
1974
  * @param logger Logger instance
1960
1975
  * @returns Consent data from the consent cookie
1961
1976
  */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1962
- var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1963
- var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1964
- var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===void 0?void 0:purposeValue.status)==='granted';});return consentPurposes;};/**
1977
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===undefined||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1978
+ var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===undefined||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1979
+ var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===undefined?undefined:purposeValue.status)==='granted';});return consentPurposes;};/**
1965
1980
  * Gets the consent data in the format expected by the application state
1966
1981
  * @param ketchConsentData Consent data derived from the consent cookie
1967
1982
  * @returns Consent data
@@ -1969,9 +1984,9 @@ var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry
1969
1984
 
1970
1985
  var pluginName$6='KetchConsentManager';var KetchConsentManager=function KetchConsentManager(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},consentManager:{init:function init(state,logger){// getKetchUserConsentedPurposes returns current ketch opted-in purposes
1971
1986
  // This will be helpful for debugging
1972
- globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1987
+ globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===undefined?undefined:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1973
1988
  // This will be helpful for debugging
1974
- globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateKetchConsent callback function to update current consent purpose state
1989
+ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===undefined?undefined:_state$consents$data$2.slice();};// updateKetchConsent callback function to update current consent purpose state
1975
1990
  // this will be called from ketch rudderstack plugin
1976
1991
  globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1977
1992
  var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
@@ -1979,21 +1994,21 @@ if(consentManagement){var _consentManagement$fi;// Get the corresponding consent
1979
1994
  var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1980
1995
  if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1981
1996
  // the configured resolution strategy
1982
- switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1997
+ switch(state.consents.resolutionStrategy.value){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1983
1998
  // TODO: To be removed once the source config API is updated to support generic consent management
1984
1999
  }else if(ketchConsentPurposes){var _configuredConsents=ketchConsentPurposes.map(function(p){return p.purpose.trim();}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
1985
2000
  return _configuredConsents.some(matchPredicate)||_configuredConsents.length===0;}// If there are no consents configured for the destination for the current provider, events should be sent.
1986
- return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$1);return true;}}}};};
2001
+ return true;}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$1);return true;}}}};};
1987
2002
 
1988
2003
  var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
1989
2004
 
1990
2005
  var DESTINATION_EVENT_FILTERING_WARNING=function DESTINATION_EVENT_FILTERING_WARNING(context,eventName,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(eventName,"\" track event has been filtered for the \"").concat(destUserFriendlyId,"\" destination.");};var DESTINATION_EVENT_FORWARDING_ERROR=function DESTINATION_EVENT_FORWARDING_ERROR(destUserFriendlyId){return "Failed to forward event to destination \"".concat(destUserFriendlyId,"\".");};
1991
2006
 
1992
2007
  var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_QUEUE_OPTIONS,queueOpts);};var isValidEventName=function isValidEventName(eventName){return eventName&&typeof eventName==='string';};var isEventDenyListed=function isEventDenyListed(eventType,eventName,dest){if(eventType!=='track'){return false;}var _dest$config=dest.config,blacklistedEvents=_dest$config.blacklistedEvents,whitelistedEvents=_dest$config.whitelistedEvents,eventFilteringOption=_dest$config.eventFilteringOption;switch(eventFilteringOption){// Blacklist is chosen for filtering events
1993
- case'blacklistedEvents':{if(!isValidEventName(eventName)){return false;}var trimmedEventName=eventName.trim();if(Array.isArray(blacklistedEvents)){return blacklistedEvents.some(function(eventObj){return eventObj.eventName.trim()===trimmedEventName;});}return false;}// Whitelist is chosen for filtering events
1994
- case'whitelistedEvents':{if(!isValidEventName(eventName)){return true;}var _trimmedEventName=eventName.trim();if(Array.isArray(whitelistedEvents)){return !whitelistedEvents.some(function(eventObj){return eventObj.eventName.trim()===_trimmedEventName;});}return true;}case'disable':default:return false;}};var sendEventToDestination=function sendEventToDestination(item,dest,errorHandler,logger){var methodName=item.type.toString();try{var _dest$instance,_dest$instance$method;// Destinations expect the event to be wrapped under the `message` key
2008
+ case 'blacklistedEvents':{if(!isValidEventName(eventName)){return false;}var trimmedEventName=eventName.trim();if(Array.isArray(blacklistedEvents)){return blacklistedEvents.some(function(eventObj){return eventObj.eventName.trim()===trimmedEventName;});}return false;}// Whitelist is chosen for filtering events
2009
+ case 'whitelistedEvents':{if(!isValidEventName(eventName)){return true;}var _trimmedEventName=eventName.trim();if(Array.isArray(whitelistedEvents)){return !whitelistedEvents.some(function(eventObj){return eventObj.eventName.trim()===_trimmedEventName;});}return true;}case 'disable':default:return false;}};var sendEventToDestination=function sendEventToDestination(item,dest,errorHandler,logger){var methodName=item.type.toString();try{var _dest$instance,_dest$instance$method;// Destinations expect the event to be wrapped under the `message` key
1995
2010
  // This will remain until we update the destinations to accept the event directly
1996
- (_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0||_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,NATIVE_DESTINATION_QUEUE_PLUGIN,DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
2011
+ (_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0||_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,NATIVE_DESTINATION_QUEUE_PLUGIN,DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
1997
2012
 
1998
2013
  var pluginName$5='NativeDestinationQueue';var NativeDestinationQueue=function NativeDestinationQueue(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},destinationsEventsQueue:{/**
1999
2014
  * Initialize the queue for delivery to destinations
@@ -2005,7 +2020,7 @@ var pluginName$5='NativeDestinationQueue';var NativeDestinationQueue=function Na
2005
2020
  * @returns IQueue instance
2006
2021
  */init:function init(state,pluginsManager,storeManager,dmtQueue,errorHandler,logger){var finalQOpts=getNormalizedQueueOptions$1(state.loadOptions.value.destinationsQueueOptions);var writeKey=state.lifecycle.writeKey.value;var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
2007
2022
  "".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);// list of destinations which are enable for DMT
2008
- var destWithTransformationEnabled=[];var clonedRudderEvent=clone(rudderEvent);destinationsToSend.forEach(function(dest){try{var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0||logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,clonedRudderEvent.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){destWithTransformationEnabled.push(dest);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler,logger);}}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,NATIVE_DESTINATION_QUEUE_PLUGIN);}});if(destWithTransformationEnabled.length>0){pluginsManager.invokeSingle('transformEvent.enqueue',state,dmtQueue,clonedRudderEvent,destWithTransformationEnabled,errorHandler,logger);}// Mark success always
2023
+ var destWithTransformationEnabled=[];var clonedRudderEvent=clone(rudderEvent);destinationsToSend.forEach(function(dest){try{var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0||logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,clonedRudderEvent.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){destWithTransformationEnabled.push(dest);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler,logger);}}catch(e){errorHandler===null||errorHandler===undefined||errorHandler.onError(e,NATIVE_DESTINATION_QUEUE_PLUGIN);}});if(destWithTransformationEnabled.length>0){pluginsManager.invokeSingle('transformEvent.enqueue',state,dmtQueue,clonedRudderEvent,destWithTransformationEnabled,errorHandler,logger);}// Mark success always
2009
2024
  done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
2010
2025
  // effect(() => {
2011
2026
  // if (state.nativeDestinations.clientDestinationsReady.value === true) {
@@ -2034,7 +2049,7 @@ var ONETRUST_ACCESS_ERROR=function ONETRUST_ACCESS_ERROR(context){return "".conc
2034
2049
  var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
2035
2050
 
2036
2051
  var pluginName$4='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$4,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$4]);},consentManager:{init:function init(state,logger){// Nothing to initialize
2037
- },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.initialized.value=false;return;}// Get the groups (cookie categorization), user has created in OneTrust account.
2052
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===undefined||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.initialized.value=false;return;}// Get the groups (cookie categorization), user has created in OneTrust account.
2038
2053
  var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
2039
2054
  // the cookie categories Ids that the user has consented to.
2040
2055
  // Eg: ',C0001,C0003,'
@@ -2045,18 +2060,18 @@ if(consentManagement){var _consentManagement$fi;// Get the corresponding consent
2045
2060
  var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
2046
2061
  if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
2047
2062
  // the configured resolution strategy
2048
- switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
2063
+ switch(state.consents.resolutionStrategy.value){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
2049
2064
  // TODO: To be removed once the source config API is updated to support generic consent management
2050
2065
  }else if(oneTrustCookieCategories){// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
2051
2066
  // Eg:
2052
2067
  // ["Performance Cookies", "Functional Cookies"]
2053
2068
  var _configuredConsents=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory.trim();}).filter(function(n){return n;});// Check if all the destination's mapped cookie categories are consented by the user in the browser.
2054
2069
  return _configuredConsents.every(matchPredicate);}// If there are no consents configured for the destination for the current provider, events should be sent.
2055
- return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
2070
+ return true;}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
2056
2071
 
2057
2072
  var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$3,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$3]);},storage:{encrypt:function encrypt(value){return encryptBrowser(value);},decrypt:function decrypt(value){return decryptBrowser(value);}}};};
2058
2073
 
2059
- var _ref,_ref2,_ref3,_ref4,_ref5;/* eslint-disable no-use-before-define */var crypto$1=((_ref=typeof globalThis!='undefined'?globalThis:void 0)===null||_ref===void 0?void 0:_ref.crypto)||((_ref2=typeof global!='undefined'?global:void 0)===null||_ref2===void 0?void 0:_ref2.crypto)||((_ref3=typeof window!='undefined'?window:void 0)===null||_ref3===void 0?void 0:_ref3.crypto)||((_ref4=typeof self!='undefined'?self:void 0)===null||_ref4===void 0?void 0:_ref4.crypto)||((_ref5=typeof frames!='undefined'?frames:void 0)===null||_ref5===void 0||(_ref5=_ref5[0])===null||_ref5===void 0?void 0:_ref5.crypto);var randomWordArray;if(crypto$1){randomWordArray=function randomWordArray(nBytes){var words=[];for(var i=0,rcache;i<nBytes;i+=4){words.push(crypto$1.getRandomValues(new Uint32Array(1))[0]);}return new WordArray(words,nBytes);};}else {// Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used.
2074
+ var _ref,_ref2,_ref3,_ref4,_ref5;/* eslint-disable no-use-before-define */var crypto$1=((_ref=typeof globalThis!='undefined'?globalThis:undefined)===null||_ref===undefined?undefined:_ref.crypto)||((_ref2=typeof global!='undefined'?global:undefined)===null||_ref2===undefined?undefined:_ref2.crypto)||((_ref3=typeof window!='undefined'?window:undefined)===null||_ref3===undefined?undefined:_ref3.crypto)||((_ref4=typeof self!='undefined'?self:undefined)===null||_ref4===undefined?undefined:_ref4.crypto)||((_ref5=typeof frames!='undefined'?frames:undefined)===null||_ref5===undefined||(_ref5=_ref5[0])===null||_ref5===undefined?undefined:_ref5.crypto);var randomWordArray;if(crypto$1){randomWordArray=function randomWordArray(nBytes){var words=[];for(var i=0,rcache;i<nBytes;i+=4){words.push(crypto$1.getRandomValues(new Uint32Array(1))[0]);}return new WordArray(words,nBytes);};}else {// Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used.
2060
2075
  randomWordArray=function randomWordArray(nBytes){var words=[];var r=function r(m_w){var _m_w=m_w;var _m_z=0x3ade68b1;var mask=0xffffffff;return function(){_m_z=0x9069*(_m_z&0xFFFF)+(_m_z>>0x10)&mask;_m_w=0x4650*(_m_w&0xFFFF)+(_m_w>>0x10)&mask;var result=(_m_z<<0x10)+_m_w&mask;result/=0x100000000;result+=0.5;return result*(Math.random()>0.5?1:-1);};};for(var i=0,rcache;i<nBytes;i+=4){var _r=r((rcache||Math.random())*0x100000000);rcache=_r()*0x3ade67b7;words.push(_r()*0x100000000|0);}return new WordArray(words,nBytes);};}/**
2061
2076
  * Base class for inheritance.
2062
2077
  */var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}return _createClass(Base,[{key:"mixIn",value:/**
@@ -2774,8 +2789,8 @@ this._minBufferSize=1;}this._mode=modeCreator.call(mode,this,iv&&iv.words);this.
2774
2789
  var padding=this.cfg.padding;// Finalize
2775
2790
  if(this._xformMode===this.constructor._ENC_XFORM_MODE){// Pad data
2776
2791
  padding.pad(this._data,this.blockSize);// Process final blocks
2777
- finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
2778
- finalProcessedBlocks=this._process(!!'flush');// Unpad data
2792
+ finalProcessedBlocks=this._process(true);}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
2793
+ finalProcessedBlocks=this._process(true);// Unpad data
2779
2794
  padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);}(Cipher);/**
2780
2795
  * A collection of cipher parameters.
2781
2796
  *
@@ -3060,14 +3075,14 @@ var STORAGE_MIGRATOR_PLUGIN='StorageMigratorPlugin';
3060
3075
  var pluginName$1='StorageMigrator';var StorageMigrator=function StorageMigrator(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{migrate:function migrate(key,storageEngine,errorHandler,logger){try{var storedVal=storageEngine.getItem(key);if(isNullOrUndefined(storedVal)){return null;}var decryptedVal=decrypt(storedVal);// The value is not encrypted using legacy encryption
3061
3076
  // Try latest
3062
3077
  if(decryptedVal===storedVal){decryptedVal=decryptBrowser(storedVal);}if(isNullOrUndefined(decryptedVal)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3063
- return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
3078
+ return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===undefined||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
3064
3079
 
3065
3080
  var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
3066
3081
  var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
3067
3082
 
3068
3083
  var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s) to ").concat(url,".");};
3069
3084
 
3070
- var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime,logger){var batchPayload={batch:events,sentAt:currentTime};return stringifyWithoutCircular(batchPayload,true,undefined,logger);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===void 0?void 0:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===void 0||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state,logger){var data;var headers;var url;var currentTime=getCurrentTimeFormatted();if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});data=getBatchDeliveryPayload(finalEvents,currentTime,logger);headers=itemData[0]?clone(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,currentTime);data=getDeliveryPayload(finalEvent,logger);headers=clone(eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
3085
+ var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime,logger){var batchPayload={batch:events,sentAt:currentTime};return stringifyWithoutCircular(batchPayload,true,undefined,logger);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===undefined?undefined:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===undefined||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state,logger){var data;var headers;var url;var currentTime=getCurrentTimeFormatted();if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});data=getBatchDeliveryPayload(finalEvents,currentTime,logger);headers=itemData[0]?clone(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,currentTime);data=getDeliveryPayload(finalEvent,logger);headers=clone(eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
3071
3086
 
3072
3087
  var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginName,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName]);},dataplaneEventsQueue:{/**
3073
3088
  * Initialize the queue for delivery
@@ -3080,7 +3095,7 @@ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginNa
3080
3095
  */init:function init(state,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var finalQOpts=getNormalizedQueueOptions(state.loadOptions.value.queueOptions);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
3081
3096
  "".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state,logger),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
3082
3097
  var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});},storeManager,LOCAL_STORAGE,logger,function(itemData){var _getBatchDeliveryPayl;var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to string as we know that the event has already been validated prior to enqueue
3083
- return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
3098
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime,logger))===null||_getBatchDeliveryPayl===undefined?undefined:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
3084
3099
  * Add event to the queue for delivery
3085
3100
  * @param state Application state
3086
3101
  * @param eventsQueue RetryQueue instance
@@ -3133,7 +3148,7 @@ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!plug
3133
3148
  // });
3134
3149
  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 state.reporting.isErrorReportingEnabled.value;},configurationStatusStr:'Error reporting is enabled',supportedPlugins:['ErrorReporting','Bugsnag']// TODO: Remove deprecated plugin- Bugsnag
3135
3150
  },{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
3136
- );_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));}}/**
3151
+ );_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===undefined||_this$logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
3137
3152
  * Determine the list of plugins that should be activated
3138
3153
  */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
3139
3154
  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;});}/**
@@ -3141,7 +3156,7 @@ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory))
3141
3156
  */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this2=this;Object.values(pluginsInventory).forEach(function(localPlugin){if(isFunction(localPlugin)&&state.plugins.activePlugins.value.includes(localPlugin().name)){_this2.register([localPlugin()]);}});}/**
3142
3157
  * Register plugins that are dynamic imports to PluginEngine
3143
3158
  */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this3=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(remotePluginKey){return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this3.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
3144
- state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this3.onError(err,remotePluginKey);});case 2:case"end":return _context.stop();}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}())).catch(function(err){_this3.onError(err);});}/**
3159
+ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this3.onError(err,remotePluginKey);});case 2:case "end":return _context.stop();}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}())).catch(function(err){_this3.onError(err);});}/**
3145
3160
  * Extension point invoke that allows multiple plugins to be registered to it with error handling
3146
3161
  */},{key:"invokeMultiple",value:function invokeMultiple(extPoint){try{var _this$engine;for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return (_this$engine=this.engine).invokeMultiple.apply(_this$engine,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return [];}}/**
3147
3162
  * Extension point invoke that allows a single plugin to be registered to it with error handling
@@ -3172,11 +3187,11 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
3172
3187
  * Service to handle data communication with APIs
3173
3188
  */var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
3174
3189
  * Implement requests in a blocking way
3175
- */return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==void 0?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case"end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
3190
+ */return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==undefined?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case "end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
3176
3191
  * Implement requests in a non-blocking way
3177
- */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==void 0?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
3192
+ */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==undefined?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
3178
3193
  * Handle errors
3179
- */},{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,HTTP_CLIENT);}else {throw error;}}/**
3194
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
3180
3195
  * Set basic authentication header (eg writekey)
3181
3196
  */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
3182
3197
  * Clear basic authentication header
@@ -3194,12 +3209,12 @@ var detectAdBlockers=function detectAdBlockers(errorHandler,logger){// Apparentl
3194
3209
  var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");var httpClient=new HttpClient(errorHandler,logger);httpClient.setAuthHeader(state.lifecycle.writeKey.value);httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
3195
3210
  method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;// not ad blocked if the request is successful or it is not internally redirected on the client side
3196
3211
  // Often adblockers instead of blocking the request, they redirect it to an internal URL
3197
- state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});};
3212
+ state.capabilities.isAdBlocked.value=(details===null||details===undefined?undefined:details.error)!==undefined||(details===null||details===undefined||(_details$xhr=details.xhr)===null||_details$xhr===undefined?undefined:_details$xhr.responseURL)!==url;}});};
3198
3213
 
3199
3214
  var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
3200
3215
  var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};var isIE11=function isIE11(){return Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));};
3201
3216
 
3202
- var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
3217
+ var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===undefined||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
3203
3218
 
3204
3219
  var isDatasetAvailable=function isDatasetAvailable(){var testElement=globalThis.document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={// Ideally, we should separate the checks for URL and URLSearchParams but
3205
3220
  // the polyfill service serves them under the same feature name, "URL".
@@ -3215,7 +3230,7 @@ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
3215
3230
  var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
3216
3231
  // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
3217
3232
  var isStorageAvailable=function isStorageAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:LOCAL_STORAGE;var storageInstance=arguments.length>1?arguments[1]:undefined;var logger=arguments.length>2?arguments[2]:undefined;var storage;var testData;var msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);var reason='unavailable';var isAccessible=true;var errObj;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.localStorage;testData=STORAGE_TEST_LOCAL_STORAGE;// was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one
3218
- break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(storage){storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}}isAccessible=false;}catch(err){isAccessible=false;errObj=err;if(isStorageQuotaExceeded(err)){reason='full';}}if(!isAccessible){logger===null||logger===void 0||logger.warn("".concat(msgPrefix).concat(reason,"."),errObj);}// if we've have reached here, it means the storage is not available
3233
+ break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(storage){storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}}isAccessible=false;}catch(err){isAccessible=false;errObj=err;if(isStorageQuotaExceeded(err)){reason='full';}}if(!isAccessible){logger===null||logger===undefined||logger.warn("".concat(msgPrefix).concat(reason,"."),errObj);}// if we've have reached here, it means the storage is not available
3219
3234
  return false;};
3220
3235
 
3221
3236
  var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
@@ -3223,7 +3238,7 @@ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElem
3223
3238
  *
3224
3239
  * The method returns an empty array when the hostname is an ip.
3225
3240
  */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
3226
- var host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;var parts=(_host$split=host===null||host===void 0?void 0:host.split('.'))!==null&&_host$split!==void 0?_host$split:[];var last=parts[parts.length-1];var levels=[];// Ip address.
3241
+ var host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;var parts=(_host$split=host===null||host===undefined?undefined:host.split('.'))!==null&&_host$split!==undefined?_host$split:[];var last=parts[parts.length-1];var levels=[];// Ip address.
3227
3242
  if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
3228
3243
  if(parts.length<=1){// Fix to support localhost
3229
3244
  if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
@@ -3246,18 +3261,18 @@ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain="."
3246
3261
  /**
3247
3262
  * A storage utility to persist values in cookies via Storage interface
3248
3263
  */var CookieStorage=/*#__PURE__*/function(){function CookieStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,CookieStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);if(CookieStorage.globalSingleton){// eslint-disable-next-line no-constructor-return
3249
- return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}return _createClass(CookieStorage,[{key:"configure",value:function configure(options){var _this$options;this.options=mergeDeepRight((_this$options=this.options)!==null&&_this$options!==void 0?_this$options:{},options);if(options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
3264
+ return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}return _createClass(CookieStorage,[{key:"configure",value:function configure(options){var _this$options;this.options=mergeDeepRight((_this$options=this.options)!==null&&_this$options!==undefined?_this$options:{},options);if(options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
3250
3265
  },{key:"getItem",value:function getItem(key){var value=cookie(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){var result=this.setItem(key,null);this.length=Object.keys(cookie()).length;return result;}// eslint-disable-next-line class-methods-use-this
3251
3266
  },{key:"clear",value:function clear(){// Not implemented
3252
3267
  // getting a list of all cookie storage keys and remove all values
3253
3268
  // sounds risky to do as it will take on all top domain cookies
3254
3269
  // better to explicitly clear specific ones if needed
3255
- }},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3270
+ }},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==undefined?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3256
3271
  },{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();_defineProperty(CookieStorage,"globalSingleton",null);
3257
3272
 
3258
3273
  /**
3259
3274
  * A storage utility to retain values in memory via Storage interface
3260
- */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(options,logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;this.configure(options!==null&&options!==void 0?options:{});}return _createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isEnabled=Boolean(this.options.enabled);return this.options;}},{key:"setItem",value:function setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}},{key:"getItem",value:function getItem(key){if(key in this.data){return this.data[key];}return null;}},{key:"removeItem",value:function removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}},{key:"clear",value:function clear(){this.data={};this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}},{key:"keys",value:function keys(){return Object.keys(this.data);}}]);}();var defaultInMemoryStorage=new InMemoryStorage({},defaultLogger);
3275
+ */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(options,logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;this.configure(options!==null&&options!==undefined?options:{});}return _createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isEnabled=Boolean(this.options.enabled);return this.options;}},{key:"setItem",value:function setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}},{key:"getItem",value:function getItem(key){if(key in this.data){return this.data[key];}return null;}},{key:"removeItem",value:function removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}},{key:"clear",value:function clear(){this.data={};this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==undefined?_curKeys$index:null;}},{key:"keys",value:function keys(){return Object.keys(this.data);}}]);}();var defaultInMemoryStorage=new InMemoryStorage({},defaultLogger);
3261
3276
 
3262
3277
  var store$2 = {exports: {}};
3263
3278
 
@@ -3277,13 +3292,13 @@ var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
3277
3292
  /**
3278
3293
  * A storage utility to persist values in localstorage via Storage interface
3279
3294
  */var LocalStorage=/*#__PURE__*/function(){function LocalStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,LocalStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;this.configure(options);}return _createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){store.set(key,value);this.length=store.len();}// eslint-disable-next-line class-methods-use-this
3280
- },{key:"getItem",value:function getItem(key){var value=store.get(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){store.remove(key);this.length=store.len();}},{key:"clear",value:function clear(){store.clear();this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3295
+ },{key:"getItem",value:function getItem(key){var value=store.get(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){store.remove(key);this.length=store.len();}},{key:"clear",value:function clear(){store.clear();this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==undefined?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3281
3296
  },{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
3282
3297
 
3283
3298
  /**
3284
3299
  * A storage utility to persist values in SessionStorage via Storage interface
3285
3300
  */var SessionStorage=/*#__PURE__*/function(){function SessionStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,SessionStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultSessionStorageOptions();this.logger=logger;this.configure(options);}return _createClass(SessionStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE);// when storage is blocked by the user, even accessing the property throws an error
3286
- if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){if(!this.store){return;}this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){if(!this.store){return null;}var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){if(!this.store){return;}this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){var _this$store;(_this$store=this.store)===null||_this$store===void 0||_this$store.clear();this.length=0;}},{key:"key",value:function key(index){var _this$store$key,_this$store2;return (_this$store$key=(_this$store2=this.store)===null||_this$store2===void 0?void 0:_this$store2.key(index))!==null&&_this$store$key!==void 0?_this$store$key:null;}},{key:"keys",value:function keys(){var keys=[];if(!this.store){return keys;}for(var i=0;i<this.store.length;i+=1){var key=this.store.key(i);if(key!==null){keys.push(key);}}return keys;}}]);}();var defaultSessionStorage=new SessionStorage({},defaultLogger);
3301
+ if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){if(!this.store){return;}this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){if(!this.store){return null;}var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){if(!this.store){return;}this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){var _this$store;(_this$store=this.store)===null||_this$store===undefined||_this$store.clear();this.length=0;}},{key:"key",value:function key(index){var _this$store$key,_this$store2;return (_this$store$key=(_this$store2=this.store)===null||_this$store2===undefined?undefined:_this$store2.key(index))!==null&&_this$store$key!==undefined?_this$store$key:null;}},{key:"keys",value:function keys(){var keys=[];if(!this.store){return keys;}for(var i=0;i<this.store.length;i+=1){var key=this.store.key(i);if(key!==null){keys.push(key);}}return keys;}}]);}();var defaultSessionStorage=new SessionStorage({},defaultLogger);
3287
3302
 
3288
3303
  /**
3289
3304
  * A utility to retrieve the storage singleton instance by type
@@ -3301,7 +3316,7 @@ if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled
3301
3316
 
3302
3317
  /**
3303
3318
  * Store Implementation with dedicated storage
3304
- */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==void 0?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==void 0?_config$validKeys:{};this.engine=engine!==null&&engine!==void 0?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==void 0?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==void 0?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3319
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==undefined?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==undefined?_config$validKeys:{};this.engine=engine!==null&&engine!==undefined?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==undefined?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==undefined?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3305
3320
  * Ensure the key is valid and with correct format
3306
3321
  */return _createClass(Store,[{key:"createValidKey",value:function createValidKey(key){var name=this.name,id=this.id,validKeys=this.validKeys,noKeyValidation=this.noKeyValidation,noCompoundKey=this.noCompoundKey;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
3307
3322
  var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
@@ -3314,13 +3329,13 @@ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key])
3314
3329
  _this.remove(key);});this.engine=inMemoryStorage;}/**
3315
3330
  * Set value by key.
3316
3331
  */},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
3317
- this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3332
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3318
3333
  this.swapQueueStoreToInMemoryEngine();// and save it there
3319
3334
  this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
3320
3335
  * Get by Key.
3321
3336
  */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);var decryptedValue;try{if(!validKey){return null;}decryptedValue=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(decryptedValue)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3322
3337
  return JSON.parse(decryptedValue);}catch(err){this.onError(new Error("".concat(STORE_DATA_FETCH_ERROR(key),": ").concat(err.message)));// A hack for warning the users of potential partial SDK version migrations
3323
- if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.warn(BAD_COOKIES_WARNING(key));}return null;}}/**
3338
+ if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.warn(BAD_COOKIES_WARNING(key));}return null;}}/**
3324
3339
  * Remove by Key.
3325
3340
  */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
3326
3341
  * Get original engine
@@ -3330,32 +3345,32 @@ if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){var _t
3330
3345
  * Encrypt value
3331
3346
  */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
3332
3347
  * Extension point to use with encryption plugins
3333
- */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
3348
+ */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==undefined?formattedValue:'';}/**
3334
3349
  * Handle errors
3335
- */},{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 ".concat(this.id));}else {throw error;}}}]);}();
3350
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);}();
3336
3351
 
3337
- var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.strategy){case'none':overriddenStorageType=NO_STORAGE;break;case'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
3352
+ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===undefined?undefined:_state$consents$preCo.strategy){case 'none':overriddenStorageType=NO_STORAGE;break;case 'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case 'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
3338
3353
 
3339
3354
  /**
3340
3355
  * A service to manage stores & available storage client configurations
3341
3356
  */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
3342
3357
  * Configure available storage client instances
3343
- */return _createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true},sessionStorageOptions:{enabled:true}};configureStorageEngines(_removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==void 0?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==void 0?_state$storage$cookie:{})),_removeUndefinedValues(config.localStorageOptions),_removeUndefinedValues(config.inMemoryStorageOptions),_removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
3358
+ */return _createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true},sessionStorageOptions:{enabled:true}};configureStorageEngines(_removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==undefined?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===undefined?undefined:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==undefined?_state$storage$cookie:{})),_removeUndefinedValues(config.localStorageOptions),_removeUndefinedValues(config.inMemoryStorageOptions),_removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
3344
3359
  * Create store to persist data used by the SDK like session, used details etc
3345
3360
  */},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
3346
3361
  // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
3347
3362
  // Initializing all the enabled store because previous user data might be in different storage
3348
3363
  // that needs auto migration
3349
- var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3350
- var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===void 0||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===void 0?void 0:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
3351
- var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==void 0?preConsentStorageType:configuredStorageType)!==null&&_ref2!==void 0?_ref2:globalStorageType)!==null&&_ref!==void 0?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:COOKIE_KEYS[storageKey]}));});r(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
3352
- if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==void 0&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==void 0&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==void 0&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3364
+ var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==undefined&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===undefined?undefined:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3365
+ var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===undefined||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===undefined?undefined:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
3366
+ var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==undefined?preConsentStorageType:configuredStorageType)!==null&&_ref2!==undefined?_ref2:globalStorageType)!==null&&_ref!==undefined?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:COOKIE_KEYS[storageKey]}));});r(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==undefined&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==undefined&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
3367
+ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==undefined&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==undefined&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==undefined&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3353
3368
  * Create a new store
3354
3369
  */},{key:"setStore",value:function setStore(storeConfig){var storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
3355
3370
  * Retrieve a store
3356
3371
  */},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
3357
3372
  * Handle errors
3358
- */},{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;}}}]);}();
3373
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);}();
3359
3374
 
3360
3375
  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 getTopDomain=function getTopDomain(url){// Create a URL object
3361
3376
  var urlObj=new URL(url);// Extract the host and protocol
@@ -3376,11 +3391,11 @@ topDomain=host;}return {topDomain:topDomain,protocol:protocol};};var getTopDomai
3376
3391
  * Removes trailing slash from url
3377
3392
  * @param url
3378
3393
  * @returns url
3379
- */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;}};/**
3394
+ */var _removeTrailingSlashes=function removeTrailingSlashes(url){return url!==null&&url!==undefined&&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;}};/**
3380
3395
  * Get the referring domain from the referrer URL
3381
3396
  * @param referrer Page referrer
3382
3397
  * @returns Page referring domain
3383
- */var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
3398
+ */var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==undefined?_getDomain:'';};/**
3384
3399
  * Extracts UTM parameters from the URL
3385
3400
  * @param url Page URL
3386
3401
  * @returns UTM parameters
@@ -3396,11 +3411,11 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
3396
3411
  /**
3397
3412
  * Determines if the SDK is running inside a chrome extension
3398
3413
  * @returns boolean
3399
- */var isSDKRunningInChromeExtension=function isSDKRunningInChromeExtension(){var _chrome;return !!((_chrome=window.chrome)!==null&&_chrome!==void 0&&(_chrome=_chrome.runtime)!==null&&_chrome!==void 0&&_chrome.id);};
3414
+ */var isSDKRunningInChromeExtension=function isSDKRunningInChromeExtension(){var _chrome;return !!((_chrome=window.chrome)!==null&&_chrome!==undefined&&(_chrome=_chrome.runtime)!==null&&_chrome!==undefined&&_chrome.id);};
3400
3415
 
3401
3416
  var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
3402
3417
 
3403
- var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
3418
+ var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===undefined||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===undefined||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===undefined?undefined:_sourceConfig$statsCo.enabled)===true;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===undefined||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===undefined||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===undefined?undefined:_sourceConfig$statsCo2.enabled)===true;};
3404
3419
 
3405
3420
  /**
3406
3421
  * Validates and normalizes the consent options provided by the user
@@ -3416,29 +3431,34 @@ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{e
3416
3431
  * @param consentManagementOpts consent management options
3417
3432
  * @param logger logger instance
3418
3433
  * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
3419
- */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger===null||logger===void 0||logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3434
+ */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger===null||logger===undefined||logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3420
3435
  provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
3421
3436
  * Validates and converts the consent management options into a normalized format
3422
3437
  * @param consentManagementOpts Consent management options provided by the user
3423
3438
  * @param logger logger instance
3424
3439
  * @returns An object containing the consent manager plugin name, initialized, enabled and consents data
3425
- */var getConsentManagementData=function getConsentManagementData(consentManagementOpts,logger){var consentManagerPluginName;var allowedConsentIds=[];var deniedConsentIds=[];var initialized=false;var provider;var enabled=(consentManagementOpts===null||consentManagementOpts===void 0?void 0:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
3440
+ */var getConsentManagementData=function getConsentManagementData(consentManagementOpts,logger){var consentManagerPluginName;var allowedConsentIds=[];var deniedConsentIds=[];var initialized=false;var provider;var enabled=(consentManagementOpts===null||consentManagementOpts===undefined?undefined:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
3426
3441
  var _getConsentManagerInf=getConsentManagerInfo(consentManagementOpts,logger);provider=_getConsentManagerInf.provider;consentManagerPluginName=_getConsentManagerInf.consentManagerPluginName;if(isValidConsentsData(consentManagementOpts.allowedConsentIds)){allowedConsentIds=consentManagementOpts.allowedConsentIds;initialized=true;}if(isValidConsentsData(consentManagementOpts.deniedConsentIds)){deniedConsentIds=consentManagementOpts.deniedConsentIds;initialized=true;}}var consentsData={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};// Enable consent management only if consent manager is supported
3427
3442
  enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
3428
3443
 
3429
3444
  /**
3430
3445
  * Determines the SDK URL
3431
3446
  * @returns sdkURL
3432
- */var getSDKUrl=function getSDKUrl(){var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
3447
+ */var getSDKUrl=function getSDKUrl(){// First try the new method of getting the SDK URL
3448
+ // from the script tag
3449
+ var scriptTag=document.querySelector('script[data-rsa-write-key]');if(scriptTag&&scriptTag.dataset.rsaWriteKey===state.lifecycle.writeKey.value){return scriptTag.src;}// If the new method fails, try the old method
3450
+ // TODO: We need to remove this once all the customers upgrade to the
3451
+ // latest SDK loading snippet
3452
+ var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
3433
3453
  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;};/**
3434
3454
  * Updates the reporting state variables from the source config data
3435
3455
  * @param res Source config
3436
3456
  * @param logger Logger instance
3437
- */var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var getServerSideCookiesStateData=function getServerSideCookiesStateData(logger){var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var cookieOptions=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie;var sscEnabled=false;var finalDataServiceUrl;if(useServerSideCookies){var _cookieOptions$domain;sscEnabled=useServerSideCookies;var providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==void 0?_cookieOptions$domain:setCookieDomain;/**
3457
+ */var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var getServerSideCookiesStateData=function getServerSideCookiesStateData(logger){var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var cookieOptions=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.cookie;var sscEnabled=false;var finalDataServiceUrl;if(useServerSideCookies){var _cookieOptions$domain;sscEnabled=useServerSideCookies;var providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==undefined?_cookieOptions$domain:setCookieDomain;/**
3438
3458
  * Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
3439
3459
  * 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
3440
3460
  * 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
3441
- */var useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT,useExactDomain);if(isValidURL(dataServiceUrl)){finalDataServiceUrl=_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
3461
+ */var useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==undefined?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT,useExactDomain);if(isValidURL(dataServiceUrl)){finalDataServiceUrl=_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
3442
3462
  // For server-side cookies to work, we need to set the SameSite=None and Secure attributes
3443
3463
  // One round of cookie options manipulation is taking place here
3444
3464
  // Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
@@ -3447,34 +3467,49 @@ if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},coo
3447
3467
  * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),
3448
3468
  * and the data service host is different from the provided cookie domain, then we disable server-side cookies
3449
3469
  * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'
3450
- */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){sscEnabled=false;logger===null||logger===void 0||logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {sscEnabled=false;}}return {sscEnabled:sscEnabled,cookieOptions:cookieOptions,finalDataServiceUrl:finalDataServiceUrl};};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.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
3451
- 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
3452
- 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));}var _getServerSideCookies=getServerSideCookiesStateData(logger),sscEnabled=_getServerSideCookies.sscEnabled,finalDataServiceUrl=_getServerSideCookies.finalDataServiceUrl,cookieOptions=_getServerSideCookies.cookieOptions;r(function(){state.storage.type.value=storageType;state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;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
3453
- 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
3470
+ */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){sscEnabled=false;logger===null||logger===undefined||logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {sscEnabled=false;}}return {sscEnabled:sscEnabled,cookieOptions:cookieOptions,finalDataServiceUrl:finalDataServiceUrl};};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===undefined||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===undefined||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===undefined?undefined:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3471
+ logger===null||logger===undefined||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
3472
+ var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===undefined||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}var _getServerSideCookies=getServerSideCookiesStateData(logger),sscEnabled=_getServerSideCookies.sscEnabled,finalDataServiceUrl=_getServerSideCookies.finalDataServiceUrl,cookieOptions=_getServerSideCookies.cookieOptions;r(function(){state.storage.type.value=storageType;state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;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
3473
+ var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===undefined?undefined:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==undefined?_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===undefined||logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===undefined?undefined:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===undefined?undefined:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==undefined?_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===undefined||logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===undefined?undefined:_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
3454
3474
  // if it is not already initialized and
3455
3475
  // if consent management is enabled
3456
3476
  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}};});};/**
3457
3477
  * Determines the consent management state variables from the source config data
3458
3478
  * @param resp Source config response
3459
3479
  * @param logger Logger instance
3460
- */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
3461
- 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);};
3480
+ */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===undefined?undefined:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==undefined?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
3481
+ 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===undefined||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===undefined||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
3462
3482
 
3463
- 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;};/**
3483
+ /**
3484
+ * A function that determines the base URL for the integrations or plugins SDK
3485
+ * @param componentType The type of the component (integrations or plugins)
3486
+ * @param pathSuffix The path suffix to be appended to the base URL (js-integrations or plugins)
3487
+ * @param defaultComponentUrl The default URL to be used if the user has not provided a custom URL
3488
+ * @param currentSdkVersion The current version of the SDK
3489
+ * @param lockVersion Flag to lock the version of the component
3490
+ * @param urlFromLoadOptions The URL provided by the user in the load options
3491
+ * @returns The base URL for the integrations or plugins SDK
3492
+ */var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,defaultComponentUrl,currentSdkVersion,lockVersion,urlFromLoadOptions){var sdkComponentBaseURL;// If the user has provided a custom URL, then validate, clean up and use it
3493
+ if(urlFromLoadOptions){if(!isValidURL(urlFromLoadOptions)){throw new Error(COMPONENT_BASE_URL_ERROR(componentType,urlFromLoadOptions));}sdkComponentBaseURL=_removeTrailingSlashes(urlFromLoadOptions);}else {sdkComponentBaseURL=defaultComponentUrl;// We can automatically determine the base URL only for CDN installations
3494
+ if(state.context.app.value.installType==='cdn'){var sdkURL=getSDKUrl();if(sdkURL){// Extract the base URL from the core SDK file URL
3495
+ // and append the path suffix to it
3496
+ sdkComponentBaseURL=sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/');}}}// If the version needs to be locked, then replace the major version in the URL
3497
+ // with the current version of the SDK
3498
+ if(lockVersion){sdkComponentBaseURL=sdkComponentBaseURL.replace(new RegExp("/".concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(pathSuffix,"$")),"/".concat(currentSdkVersion,"/").concat(BUILD_TYPE,"/").concat(pathSuffix));}return sdkComponentBaseURL;};/**
3464
3499
  * A function that determines integration SDK loading path
3465
- * @param currentVersion
3466
- * @param lockIntegrationsVersion
3467
- * @param customIntegrationsCDNPath
3500
+ * @param currentSdkVersion Current SDK version
3501
+ * @param lockIntegrationsVersion Flag to lock the integrations version
3502
+ * @param integrationsUrlFromLoadOptions URL to load the integrations from as provided by the user
3468
3503
  * @returns
3469
- */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEST_SDK_BASE_URL,currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath);};/**
3504
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEFAULT_INTEGRATION_SDKS_URL,currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions);};/**
3470
3505
  * A function that determines plugins SDK loading path
3471
- * @param currentVersion Current SDK version
3506
+ * @param currentSdkVersion Current SDK version
3472
3507
  * @param lockPluginsVersion Flag to lock the plugins version
3473
- * @param customPluginsCDNPath URL to load the plugins from
3508
+ * @param pluginsUrlFromLoadOptions URL to load the plugins from as provided by the user
3474
3509
  * @returns Final plugins CDN path
3475
- */var getPluginsCDNPath=function getPluginsCDNPath(currentVersion,lockPluginsVersion,customPluginsCDNPath){return getSDKComponentBaseURL('plugins',CDN_PLUGINS_DIR,PLUGINS_BASE_URL,currentVersion,lockPluginsVersion,customPluginsCDNPath);};
3510
+ */var getPluginsCDNPath=function getPluginsCDNPath(currentSdkVersion,lockPluginsVersion,pluginsUrlFromLoadOptions){return getSDKComponentBaseURL('plugins',CDN_PLUGINS_DIR,DEFAULT_PLUGINS_URL,currentSdkVersion,lockPluginsVersion,pluginsUrlFromLoadOptions);};
3476
3511
 
3477
- 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);});}/**
3512
+ 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===undefined||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3478
3513
  * A function to validate, construct and store loadOption, lifecycle, source and destination
3479
3514
  * config related information in global state
3480
3515
  */},{key:"init",value:function init(){var _this2=this;this.attachEffects();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,integrations=_state$loadOptions$va.integrations;state.lifecycle.activeDataplaneUrl.value=_removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
@@ -3483,13 +3518,13 @@ var pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBa
3483
3518
  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);state.metrics.metricsServiceUrl.value="".concat(state.lifecycle.activeDataplaneUrl.value,"/").concat(METRICS_SERVICE_ENDPOINT);// Data in the loadOptions state is already normalized
3484
3519
  state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConfig();}/**
3485
3520
  * Handle errors
3486
- */},{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;}}/**
3521
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
3487
3522
  * A callback function that is executed once we fetch the source config response.
3488
3523
  * Use to construct and store information that are dependent on the sourceConfig.
3489
3524
  */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
3490
3525
  // We can use isErrRetryable utility method
3491
- 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
3492
- 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
3526
+ if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===undefined?undefined: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
3527
+ if(res.source.enabled===false){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
3493
3528
  updateReportingState(res);var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
3494
3529
  r(function(){var _state$loadOptions$va2;// set source related information in state
3495
3530
  state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
@@ -3509,19 +3544,19 @@ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:
3509
3544
  * @returns string
3510
3545
  */var getTimezone=function getTimezone(){// Not susceptible to super-linear backtracking
3511
3546
  // eslint-disable-next-line sonarjs/slow-regex
3512
- var timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone!==null&&timezone!==void 0&&timezone[1]?timezone[1]:'NA';};
3547
+ var timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone!==null&&timezone!==undefined&&timezone[1]?timezone[1]:'NA';};
3513
3548
 
3514
3549
  /**
3515
3550
  * Get the referrer URL
3516
3551
  * @returns The referrer URL
3517
- */var getReferrer=function getReferrer(){var _document;return ((_document=document)===null||_document===void 0?void 0:_document.referrer)||'$direct';};/**
3552
+ */var getReferrer=function getReferrer(){var _document;return ((_document=document)===null||_document===undefined?undefined:_document.referrer)||'$direct';};/**
3518
3553
  * To get the canonical URL of the page
3519
3554
  * @returns canonical URL
3520
- */var getCanonicalUrl=function getCanonicalUrl(){var tags=document.getElementsByTagName('link');var canonicalUrl='';for(var i=0;tags[i];i+=1){var tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==void 0?_tag$getAttribute:'';break;}}return canonicalUrl;};var getUserAgent=function getUserAgent(){if(isUndefined(globalThis.navigator)){return null;}var userAgent=globalThis.navigator.userAgent;var _ref=globalThis.navigator,brave=_ref.brave;// For supporting Brave browser detection,
3555
+ */var getCanonicalUrl=function getCanonicalUrl(){var tags=document.getElementsByTagName('link');var canonicalUrl='';for(var i=0;tags[i];i+=1){var tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==undefined?_tag$getAttribute:'';break;}}return canonicalUrl;};var getUserAgent=function getUserAgent(){if(isUndefined(globalThis.navigator)){return null;}var userAgent=globalThis.navigator.userAgent;var _ref=globalThis.navigator,brave=_ref.brave;// For supporting Brave browser detection,
3521
3556
  // add "Brave/<version>" to the user agent with the version value from the Chrome component
3522
3557
  if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
3523
3558
  // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36
3524
- 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;};/**
3559
+ 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!==undefined?_globalThis$navigator:globalThis.navigator.browserLanguage;};/**
3525
3560
  * Default page properties
3526
3561
  * @returns Default page properties
3527
3562
  */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.
@@ -3543,7 +3578,7 @@ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCH
3543
3578
  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
3544
3579
  E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
3545
3580
  * Detect if polyfills are required and then load script from polyfill URL
3546
- */},{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
3581
+ */},{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===undefined||_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
3547
3582
  // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
3548
3583
  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
3549
3584
  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();}}/**
@@ -3588,7 +3623,7 @@ var MIN_SESSION_ID_LENGTH=10;/**
3588
3623
  * @param {number} sessionId
3589
3624
  * @param logger logger
3590
3625
  * @returns
3591
- */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3626
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===undefined||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3592
3627
  * A function to generate new auto tracking session
3593
3628
  * @param sessionTimeout current timestamp
3594
3629
  * @returns SessionInfo
@@ -3609,17 +3644,17 @@ timeout:timeout,sessionStart:undefined,autoTrack:true};};/**
3609
3644
  * @param pageProps Page properties
3610
3645
  * @returns page properties object for context
3611
3646
  */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
3612
- 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;};/**
3647
+ var curPageProps=getDefaultPageProperties();var ctxPageProps={};Object.keys(curPageProps).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===undefined?undefined:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===undefined?undefined:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===undefined?undefined:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
3613
3648
  * Add any missing default page properties using values from options and defaults
3614
3649
  * @param properties Input page properties
3615
3650
  * @param options API options
3616
- */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
3651
+ */var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===undefined?undefined: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
3617
3652
  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;};/**
3618
3653
  * Utility to check for reserved keys in the input object
3619
3654
  * @param obj Generic object
3620
3655
  * @param parentKeyPath Object's parent key path
3621
3656
  * @param logger Logger instance
3622
- */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger===null||logger===void 0||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3657
+ */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger===null||logger===undefined||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3623
3658
  * Checks for reserved keys in traits, properties, and contextual traits
3624
3659
  * @param rudderEvent Generated rudder event
3625
3660
  * @param logger Logger instance
@@ -3647,17 +3682,17 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
3647
3682
  * @param integrationsConfig Event's integrations config
3648
3683
  * @returns Final integrations config
3649
3684
  */var getEventIntegrationsConfig=function getEventIntegrationsConfig(integrationsConfig){var finalIntgConfig;if(state.loadOptions.value.useGlobalIntegrationsConfigInEvents){var _state$consents$postC;// Prefer the integrations object from the consent API response over the load API integrations object
3650
- finalIntgConfig=(_state$consents$postC=state.consents.postConsent.value.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value;}else if(integrationsConfig){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return clone(finalIntgConfig);};/**
3685
+ finalIntgConfig=(_state$consents$postC=state.consents.postConsent.value.integrations)!==null&&_state$consents$postC!==undefined?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value;}else if(integrationsConfig){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return clone(finalIntgConfig);};/**
3651
3686
  * Enrich the base event object with data from state and the API options
3652
3687
  * @param rudderEvent RudderEvent object
3653
3688
  * @param options API options
3654
3689
  * @param pageProps Page properties
3655
3690
  * @param logger logger
3656
3691
  * @returns Enriched RudderEvent object
3657
- */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var _state$storage$entrie;var commonEventData={channel:CHANNEL,context:_objectSpread2(_objectSpread2({traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined},state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),{},{'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value},state.autoTrack.enabled.value&&{autoTrack:_objectSpread2({},state.autoTrack.pageLifecycle.enabled.value&&{page:{visitId:state.autoTrack.pageLifecycle.visitId.value}})}),originalTimestamp:getCurrentTimeFormatted(),messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type)){// Generate new anonymous id for each request
3692
+ */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var _state$storage$entrie;var commonEventData={channel:CHANNEL,context:_objectSpread2(_objectSpread2({traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined},state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),{},{'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value},state.autoTrack.enabled.value&&{autoTrack:_objectSpread2({},state.autoTrack.pageLifecycle.enabled.value&&{page:{visitId:state.autoTrack.pageLifecycle.visitId.value}})}),originalTimestamp:getCurrentTimeFormatted(),messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===undefined?undefined:_state$storage$entrie.type)){// Generate new anonymous id for each request
3658
3693
  commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
3659
3694
  commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
3660
- if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===void 0?void 0:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3695
+ if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===undefined?undefined:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===undefined?undefined:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3661
3696
  // matching with v1.1 payload
3662
3697
  if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3663
3698
  processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
@@ -3668,7 +3703,7 @@ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logge
3668
3703
  * @param name Page name
3669
3704
  * @param properties Page properties
3670
3705
  * @param options API options
3671
- */return _createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
3706
+ */return _createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==undefined?properties:{};props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
3672
3707
  * Generate a 'track' event based on the user-input fields
3673
3708
  * @param event The event name
3674
3709
  * @param properties Event properties
@@ -3684,7 +3719,7 @@ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logge
3684
3719
  * @param from Old user ID
3685
3720
  * @param options API options
3686
3721
  */},{key:"generateAliasEvent",value:function generateAliasEvent(to,from,options){var aliasEvent={previousId:from,type:'alias'};var enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger);// override the User ID from the API inputs
3687
- enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
3722
+ enrichedEvent.userId=to!==null&&to!==undefined?to:enrichedEvent.userId;return enrichedEvent;}/**
3688
3723
  * Generate a 'group' event based on the user-input fields
3689
3724
  * @param groupId New group ID
3690
3725
  * @param traits new group traits
@@ -3693,7 +3728,7 @@ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enric
3693
3728
  * Generates a new RudderEvent object based on the user-input fields
3694
3729
  * @param event API event parameters object
3695
3730
  * @returns A RudderEvent object
3696
- */},{key:"create",value:function create(event){var eventObj;switch(event.type){case'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case'group':eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
3731
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case 'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case 'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case 'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case 'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case 'group':eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
3697
3732
 
3698
3733
  /**
3699
3734
  * A service to generate valid event payloads and queue them for processing
@@ -3717,16 +3752,16 @@ var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(error
3717
3752
  * Initialize User session with values from storage
3718
3753
  */return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
3719
3754
  this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
3720
- this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());var _state$loadOptions$va=state.loadOptions.value,externalAnonymousIdCookieName=_state$loadOptions$va.externalAnonymousIdCookieName,anonymousIdOptions=_state$loadOptions$va.anonymousIdOptions;var externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId((_externalAnonymousId=externalAnonymousId)!==null&&_externalAnonymousId!==void 0?_externalAnonymousId:this.getAnonymousId(anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}},{key:"configureSessionTracking",value:function configureSessionTracking(){var sessionInfo=this.getSessionInfo();if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _sessionInfo;var configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();var initialSessionInfo=(_sessionInfo=sessionInfo)!==null&&_sessionInfo!==void 0?_sessionInfo:defaultSessionConfiguration;sessionInfo=_objectSpread2(_objectSpread2(_objectSpread2({},initialSessionInfo),configuredSessionTrackingInfo),{},{// If manualTrack is set to true in the storage, then autoTrack should be false
3755
+ this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());var _state$loadOptions$va=state.loadOptions.value,externalAnonymousIdCookieName=_state$loadOptions$va.externalAnonymousIdCookieName,anonymousIdOptions=_state$loadOptions$va.anonymousIdOptions;var externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId((_externalAnonymousId=externalAnonymousId)!==null&&_externalAnonymousId!==undefined?_externalAnonymousId:this.getAnonymousId(anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}},{key:"configureSessionTracking",value:function configureSessionTracking(){var sessionInfo=this.getSessionInfo();if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _sessionInfo;var configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();var initialSessionInfo=(_sessionInfo=sessionInfo)!==null&&_sessionInfo!==undefined?_sessionInfo:defaultSessionConfiguration;sessionInfo=_objectSpread2(_objectSpread2(_objectSpread2({},initialSessionInfo),configuredSessionTrackingInfo),{},{// If manualTrack is set to true in the storage, then autoTrack should be false
3721
3756
  autoTrack:configuredSessionTrackingInfo.autoTrack&&initialSessionInfo.manualTrack!==true});// If both autoTrack and manualTrack are disabled, reset the session info to default values
3722
3757
  if(!sessionInfo.autoTrack&&sessionInfo.manualTrack!==true){sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}}else {sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}state.session.sessionInfo.value=sessionInfo;// If auto session tracking is enabled start the session tracking
3723
- if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}},{key:"setInitialReferrerInfo",value:function setInitialReferrerInfo(){var persistedInitialReferrer=this.getInitialReferrer();var persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {var initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}},{key:"isPersistenceEnabledForStorageEntry",value:function isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type);}},{key:"migrateDataFromPreviousStorage",value:function migrateDataFromPreviousStorage(){var _this=this;var entries=state.storage.entries.value;var storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(function(entry){var _entries$key,_this$storeManager;var key=entry;var currentStorage=(_entries$key=entries[key])===null||_entries$key===void 0?void 0:_entries$key.type;var curStore=(_this$storeManager=_this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(function(storage){var _this$storeManager2;var store=(_this$storeManager2=_this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){var value=store.get(COOKIE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(COOKIE_KEYS[key],value);}store.remove(COOKIE_KEYS[key]);}});}});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this2=this;if(!state.storage.migrate.value){return;}var persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];var stores=[];persistentStoreNames.forEach(function(storeName){var _this2$storeManager;var store=(_this2$storeManager=_this2.storeManager)===null||_this2$storeManager===void 0?void 0:_this2$storeManager.getStore(storeName);if(store){stores.push(store);}});Object.keys(COOKIE_KEYS).forEach(function(storageKey){var storageEntry=COOKIE_KEYS[storageKey];stores.forEach(function(store){var _this2$pluginsManager;var migratedVal=(_this2$pluginsManager=_this2.pluginsManager)===null||_this2$pluginsManager===void 0?void 0:_this2$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,_this2.errorHandler,_this2.logger);// Skip setting the value if it is null or undefined
3758
+ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}},{key:"setInitialReferrerInfo",value:function setInitialReferrerInfo(){var persistedInitialReferrer=this.getInitialReferrer();var persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {var initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}},{key:"isPersistenceEnabledForStorageEntry",value:function isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===undefined?undefined:_state$storage$entrie.type);}},{key:"migrateDataFromPreviousStorage",value:function migrateDataFromPreviousStorage(){var _this=this;var entries=state.storage.entries.value;var storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(function(entry){var _entries$key,_this$storeManager;var key=entry;var currentStorage=(_entries$key=entries[key])===null||_entries$key===undefined?undefined:_entries$key.type;var curStore=(_this$storeManager=_this.storeManager)===null||_this$storeManager===undefined?undefined:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(function(storage){var _this$storeManager2;var store=(_this$storeManager2=_this.storeManager)===null||_this$storeManager2===undefined?undefined:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){var value=store.get(COOKIE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(COOKIE_KEYS[key],value);}store.remove(COOKIE_KEYS[key]);}});}});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this2=this;if(!state.storage.migrate.value){return;}var persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];var stores=[];persistentStoreNames.forEach(function(storeName){var _this2$storeManager;var store=(_this2$storeManager=_this2.storeManager)===null||_this2$storeManager===undefined?undefined:_this2$storeManager.getStore(storeName);if(store){stores.push(store);}});Object.keys(COOKIE_KEYS).forEach(function(storageKey){var storageEntry=COOKIE_KEYS[storageKey];stores.forEach(function(store){var _this2$pluginsManager;var migratedVal=(_this2$pluginsManager=_this2.pluginsManager)===null||_this2$pluginsManager===undefined?undefined:_this2$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,_this2.errorHandler,_this2.logger);// Skip setting the value if it is null or undefined
3724
3759
  // as those values indicate there is no need for migration or
3725
3760
  // migration failed
3726
- if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va2,_state$loadOptions$va3;var autoTrack=((_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.autoTrack)!==false;// Do not validate any further if autoTrack is disabled
3727
- if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va3=state.loadOptions.value.sessions)===null||_state$loadOptions$va3===void 0?void 0:_state$loadOptions$va3.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3761
+ if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va2,_state$loadOptions$va3;var autoTrack=((_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===undefined?undefined:_state$loadOptions$va2.autoTrack)!==false;// Do not validate any further if autoTrack is disabled
3762
+ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va3=state.loadOptions.value.sessions)===null||_state$loadOptions$va3===undefined?undefined:_state$loadOptions$va3.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3728
3763
  // and will proceed with it
3729
- if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3764
+ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3730
3765
  * Handles error
3731
3766
  * @param error The error object
3732
3767
  */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
@@ -3734,11 +3769,11 @@ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=t
3734
3769
  * @param cookiesData
3735
3770
  * @param store
3736
3771
  * @returns
3737
- */},{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;}/**
3772
+ */},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var _this3=this;var encryptedCookieData=[];cookiesData.forEach(function(cData){var encryptedValue=store===null||store===undefined?undefined:store.encrypt(stringifyWithoutCircular(cData.value,false,[],_this3.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
3738
3773
  * A function that makes request to data service to set the cookie
3739
3774
  * @param encryptedCookieData
3740
3775
  * @param callback
3741
- */},{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});}/**
3776
+ */},{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===undefined||_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===undefined?undefined:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===undefined?undefined:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===undefined?undefined:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===undefined?undefined:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===undefined?undefined:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===undefined?undefined:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===undefined?undefined:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true,withCredentials:true},isRawResponse:true,callback:callback});}/**
3742
3777
  * A function to make an external request to set the cookie from server side
3743
3778
  * @param key cookie name
3744
3779
  * @param value encrypted cookie value
@@ -3748,9 +3783,9 @@ this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _detai
3748
3783
  * A function to sync values in storage
3749
3784
  * @param sessionKey
3750
3785
  * @param value
3751
- */},{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
3786
+ */},{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===undefined?undefined:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===undefined?undefined:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===undefined?undefined:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
3752
3787
  // set the cookie from server side
3753
- 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);}}}/**
3788
+ 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===undefined||curStore.set(cookieName,cookieValue);},curStore);},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===undefined||curStore.set(key,value);}}else {curStore===null||curStore===undefined||curStore.remove(key);}}}/**
3754
3789
  * Function to update storage whenever state value changes
3755
3790
  */},{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
3756
3791
  USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this6.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
@@ -3760,13 +3795,13 @@ USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this6.syncValueToSt
3760
3795
  * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
3761
3796
  * using parseLinker util.
3762
3797
  * 3. generateUUID: A new unique id is generated and assigned.
3763
- */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
3798
+ */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===undefined?undefined:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
3764
3799
  * Fetches anonymousId
3765
3800
  * @param options option to fetch it from external source
3766
3801
  * @returns anonymousId
3767
- */},{key:"getAnonymousId",value:function getAnonymousId(options){var _state$storage$entrie2;var storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type;// fetch the anonymousId from storage
3802
+ */},{key:"getAnonymousId",value:function getAnonymousId(options){var _state$storage$entrie2;var storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===undefined?undefined:_state$storage$entrie2.type;// fetch the anonymousId from storage
3768
3803
  if(isStorageTypeValidForStoringData(storage)){var persistedAnonymousId=this.getEntryValue('anonymousId');if(!persistedAnonymousId&&options){var _this$pluginsManager2;// fetch anonymousId from external source
3769
- var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}},{key:"getEntryValue",value:function getEntryValue(sessionKey){var _entries$sessionKey3;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===void 0?void 0:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager4,_entries$sessionKey4,_store$get;var store=(_this$storeManager4=this.storeManager)===null||_this$storeManager4===void 0?void 0:_this$storeManager4.getStore(storageClientDataStoreNameMap[storageType]);var storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===void 0?void 0:_entries$sessionKey4.key;return (_store$get=store===null||store===void 0?void 0:store.get(storageKey))!==null&&_store$get!==void 0?_store$get:null;}return null;}},{key:"getExternalAnonymousIdByCookieName",value:function getExternalAnonymousIdByCookieName(key){var storageEngine=getStorageEngine(COOKIE_STORAGE);if(storageEngine!==null&&storageEngine!==void 0&&storageEngine.isEnabled){var _storageEngine$getIte;return (_storageEngine$getIte=storageEngine.getItem(key))!==null&&_storageEngine$getIte!==void 0?_storageEngine$getIte:null;}return null;}/**
3804
+ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===undefined?undefined:_this$pluginsManager2.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}},{key:"getEntryValue",value:function getEntryValue(sessionKey){var _entries$sessionKey3;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===undefined?undefined:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager4,_entries$sessionKey4,_store$get;var store=(_this$storeManager4=this.storeManager)===null||_this$storeManager4===undefined?undefined:_this$storeManager4.getStore(storageClientDataStoreNameMap[storageType]);var storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===undefined?undefined:_entries$sessionKey4.key;return (_store$get=store===null||store===undefined?undefined:store.get(storageKey))!==null&&_store$get!==undefined?_store$get:null;}return null;}},{key:"getExternalAnonymousIdByCookieName",value:function getExternalAnonymousIdByCookieName(key){var storageEngine=getStorageEngine(COOKIE_STORAGE);if(storageEngine!==null&&storageEngine!==undefined&&storageEngine.isEnabled){var _storageEngine$getIte;return (_storageEngine$getIte=storageEngine.getItem(key))!==null&&_storageEngine$getIte!==undefined?_storageEngine$getIte:null;}return null;}/**
3770
3805
  * Fetches User Id
3771
3806
  * @returns
3772
3807
  */},{key:"getUserId",value:function getUserId(){return this.getEntryValue('userId');}/**
@@ -3793,10 +3828,10 @@ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||
3793
3828
  */},{key:"getAuthToken",value:function getAuthToken(){return this.getEntryValue('authToken');}/**
3794
3829
  * If session is active it returns the sessionId
3795
3830
  * @returns
3796
- */},{key:"getSessionId",value:function getSessionId(){var _this$getSessionInfo;var sessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==void 0?_this$getSessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo.expiresAt)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==void 0?_sessionInfo$id:null;}return null;}/**
3831
+ */},{key:"getSessionId",value:function getSessionId(){var _this$getSessionInfo;var sessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==undefined?_this$getSessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo.expiresAt)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==undefined?_sessionInfo$id:null;}return null;}/**
3797
3832
  * A function to keep the session information up to date in the state
3798
3833
  * before using it for building event payloads.
3799
- */},{key:"refreshSession",value:function refreshSession(){var _this$getSessionInfo2;var sessionInfo=(_this$getSessionInfo2=this.getSessionInfo())!==null&&_this$getSessionInfo2!==void 0?_this$getSessionInfo2:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking(sessionInfo);sessionInfo=state.session.sessionInfo.value;}// Note that if sessionStart is false, then it's an active session.
3834
+ */},{key:"refreshSession",value:function refreshSession(){var _this$getSessionInfo2;var sessionInfo=(_this$getSessionInfo2=this.getSessionInfo())!==null&&_this$getSessionInfo2!==undefined?_this$getSessionInfo2:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking(sessionInfo);sessionInfo=state.session.sessionInfo.value;}// Note that if sessionStart is false, then it's an active session.
3800
3835
  // So, we needn't update the session info.
3801
3836
  //
3802
3837
  // For other scenarios,
@@ -3818,13 +3853,13 @@ _this7.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.ses
3818
3853
  */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
3819
3854
  * Set user traits
3820
3855
  * @param traits
3821
- */},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:DEFAULT_USER_SESSION_VALUES.userTraits,traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
3856
+ */},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==undefined?_state$session$userTr:DEFAULT_USER_SESSION_VALUES.userTraits,traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
3822
3857
  * Set group Id
3823
3858
  * @param groupId
3824
3859
  */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
3825
3860
  * Set group traits
3826
3861
  * @param traits
3827
- */},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:DEFAULT_USER_SESSION_VALUES.groupTraits,traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
3862
+ */},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==undefined?_state$session$groupT:DEFAULT_USER_SESSION_VALUES.groupTraits,traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
3828
3863
  * Set initial referrer
3829
3864
  * @param referrer
3830
3865
  */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
@@ -3850,8 +3885,8 @@ _this7.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.ses
3850
3885
  * Plugins to be loaded in the plugins loadOption is not defined
3851
3886
  */var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
3852
3887
 
3853
- var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
3854
- 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;normalizedLoadOpts.sameDomainCookiesOnly=normalizedLoadOpts.sameDomainCookiesOnly===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isNonEmptyObject(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;};
3888
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){// TODO: Maybe add warnings for invalid values
3889
+ var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){normalizedLoadOpts.setCookieDomain=undefined;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){normalizedLoadOpts.sameSiteCookie=undefined;}normalizedLoadOpts.secureCookie=getNormalizedBooleanValue(normalizedLoadOpts.secureCookie,loadOptionsFromState.secureCookie);normalizedLoadOpts.sameDomainCookiesOnly=getNormalizedBooleanValue(normalizedLoadOpts.sameDomainCookiesOnly,loadOptionsFromState.sameDomainCookiesOnly);var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){normalizedLoadOpts.uaChTrackLevel=undefined;}normalizedLoadOpts.integrations=getNormalizedObjectValue(normalizedLoadOpts.integrations);if(!Array.isArray(normalizedLoadOpts.plugins)){normalizedLoadOpts.plugins=defaultOptionalPluginsList;}normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=getNormalizedBooleanValue(normalizedLoadOpts.useGlobalIntegrationsConfigInEvents,loadOptionsFromState.useGlobalIntegrationsConfigInEvents);normalizedLoadOpts.bufferDataPlaneEventsUntilReady=getNormalizedBooleanValue(normalizedLoadOpts.bufferDataPlaneEventsUntilReady,loadOptionsFromState.bufferDataPlaneEventsUntilReady);normalizedLoadOpts.sendAdblockPage=getNormalizedBooleanValue(normalizedLoadOpts.sendAdblockPage,loadOptionsFromState.sendAdblockPage);normalizedLoadOpts.useServerSideCookies=getNormalizedBooleanValue(normalizedLoadOpts.useServerSideCookies,loadOptionsFromState.useServerSideCookies);if(!isString(normalizedLoadOpts.dataServiceEndpoint)){normalizedLoadOpts.dataServiceEndpoint=undefined;}normalizedLoadOpts.sendAdblockPageOptions=getNormalizedObjectValue(normalizedLoadOpts.sendAdblockPageOptions);normalizedLoadOpts.loadIntegration=getNormalizedBooleanValue(normalizedLoadOpts.loadIntegration,loadOptionsFromState.loadIntegration);if(!isNonEmptyObject(normalizedLoadOpts.storage)){normalizedLoadOpts.storage=undefined;}else {var _loadOptionsFromState;normalizedLoadOpts.storage.migrate=getNormalizedBooleanValue(normalizedLoadOpts.storage.migrate,(_loadOptionsFromState=loadOptionsFromState.storage)===null||_loadOptionsFromState===undefined?undefined:_loadOptionsFromState.migrate);normalizedLoadOpts.storage.cookie=getNormalizedObjectValue(normalizedLoadOpts.storage.cookie);normalizedLoadOpts.storage.encryption=getNormalizedObjectValue(normalizedLoadOpts.storage.encryption);normalizedLoadOpts.storage=_removeUndefinedAndNullValues(normalizedLoadOpts.storage);}normalizedLoadOpts.destinationsQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.destinationsQueueOptions);normalizedLoadOpts.queueOptions=getNormalizedObjectValue(normalizedLoadOpts.queueOptions);normalizedLoadOpts.lockIntegrationsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockIntegrationsVersion,loadOptionsFromState.lockIntegrationsVersion);normalizedLoadOpts.lockPluginsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockPluginsVersion,loadOptionsFromState.lockPluginsVersion);if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){normalizedLoadOpts.dataPlaneEventsBufferTimeout=undefined;}normalizedLoadOpts.beaconQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.beaconQueueOptions);normalizedLoadOpts.preConsent=getNormalizedObjectValue(normalizedLoadOpts.preConsent);var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,_removeUndefinedAndNullValues(normalizedLoadOpts));return mergedLoadOptions;};
3855
3890
 
3856
3891
  var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
3857
3892
 
@@ -3867,7 +3902,7 @@ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QU
3867
3902
  * @returns Mutated event with final integrations config
3868
3903
  */var getFinalEvent=function getFinalEvent(event,state){var finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
3869
3904
  // In general, the preference is given to the event's integrations config
3870
- var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo,_state$consents$preCo2,_state$consents$preCo3;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.delivery)==='buffer'&&(((_state$consents$preCo2=state.consents.preConsent.value.storage)===null||_state$consents$preCo2===void 0?void 0:_state$consents$preCo2.strategy)==='session'||((_state$consents$preCo3=state.consents.preConsent.value.storage)===null||_state$consents$preCo3===void 0?void 0:_state$consents$preCo3.strategy)==='none');};
3905
+ var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo,_state$consents$preCo2,_state$consents$preCo3;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===undefined?undefined:_state$consents$preCo.delivery)==='buffer'&&(((_state$consents$preCo2=state.consents.preConsent.value.storage)===null||_state$consents$preCo2===undefined?undefined:_state$consents$preCo2.strategy)==='session'||((_state$consents$preCo3=state.consents.preConsent.value.storage)===null||_state$consents$preCo3===undefined?undefined:_state$consents$preCo3.strategy)==='none');};
3871
3906
 
3872
3907
  /**
3873
3908
  * Event repository class responsible for queuing events for further processing and delivery
@@ -3880,12 +3915,12 @@ var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var
3880
3915
  */function EventRepository(pluginsManager,storeManager,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
3881
3916
  * Initializes the event repository
3882
3917
  */return _createClass(EventRepository,[{key:"init",value:function init(){var _this=this;try{this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DATAPLANE_PLUGIN_INITIALIZE_ERROR);}try{this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DMT_PLUGIN_INITIALIZE_ERROR);}try{this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);}catch(e){this.onError(e,NATIVE_DEST_PLUGIN_INITIALIZE_ERROR);}// Start the queue once the client destinations are ready
3883
- E(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===void 0||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3918
+ E(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===undefined||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===undefined||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3884
3919
  // However, events will be enqueued for now.
3885
3920
  // At the time of processing the events, the integrations config data from destinations
3886
3921
  // is merged into the event object
3887
- var timeoutId;E(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
3888
- if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}},{key:"resume",value:function resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===void 0?void 0:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===void 0||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===void 0||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===void 0||_this$dataplaneEvents7.start();}}/**
3922
+ var timeoutId;E(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===undefined?undefined:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===undefined||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
3923
+ if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===undefined?undefined:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===undefined||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}},{key:"resume",value:function resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===undefined?undefined:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===undefined||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===undefined||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===undefined||_this$dataplaneEvents7.start();}}/**
3889
3924
  * Enqueues the event for processing
3890
3925
  * @param event RudderEvent object
3891
3926
  * @param callback API callback function
@@ -3909,13 +3944,13 @@ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new Custom
3909
3944
  * Start application lifecycle if not already started
3910
3945
  */return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _this$logger,_state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}// Set initial state values
3911
3946
  r(function(){state.lifecycle.writeKey.value=clone(writeKey);state.lifecycle.dataPlaneUrl.value=clone(dataPlaneUrl);state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,loadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
3912
- (_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
3947
+ (_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==undefined?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
3913
3948
  setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
3914
3949
  // State application lifecycle
3915
3950
  this.startLifecycle();}// Start lifecycle methods
3916
3951
  /**
3917
3952
  * Orchestrate the lifecycle of the application phases/status
3918
- */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;E(function(){try{switch(state.lifecycle.status.value){case'mounted':_this.onMounted();break;case'browserCapabilitiesReady':_this.onBrowserCapabilitiesReady();break;case'configured':_this.onConfigured();break;case'pluginsLoading':break;case'pluginsReady':_this.onPluginsReady();break;case'initialized':_this.onInitialized();break;case'loaded':_this.onLoaded();break;case'destinationsLoading':break;case'destinationsReady':_this.onDestinationsReady();break;case'ready':_this.onReady();break;case'readyExecuted':default:break;}}catch(err){var issue='Failed to load the SDK';_this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}},{key:"onBrowserCapabilitiesReady",value:function onBrowserCapabilitiesReady(){// initialize the preloaded events enqueuing
3953
+ */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;E(function(){try{switch(state.lifecycle.status.value){case 'mounted':_this.onMounted();break;case 'browserCapabilitiesReady':_this.onBrowserCapabilitiesReady();break;case 'configured':_this.onConfigured();break;case 'pluginsLoading':break;case 'pluginsReady':_this.onPluginsReady();break;case 'initialized':_this.onInitialized();break;case 'loaded':_this.onLoaded();break;case 'destinationsLoading':break;case 'destinationsReady':_this.onDestinationsReady();break;case 'ready':_this.onReady();break;case 'readyExecuted':default:break;}}catch(err){var issue='Failed to load the SDK';_this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}},{key:"onBrowserCapabilitiesReady",value:function onBrowserCapabilitiesReady(){// initialize the preloaded events enqueuing
3919
3954
  retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();}},{key:"onLoaded",value:function onLoaded(){this.processBufferedEvents();// Short-circuit the life cycle and move to the ready state if pre-consent behavior is enabled
3920
3955
  if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
3921
3956
  * Load browser polyfill if required
@@ -3925,15 +3960,15 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
3925
3960
  * Process the buffer preloaded events by passing their arguments to the respective facade methods
3926
3961
  */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.errorHandler,this.logger,this.pluginsManager,this.storeManager,this.httpClient);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3927
3962
  * Load configuration
3928
- */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
3963
+ */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===undefined||_this$configManager.init();}/**
3929
3964
  * Initialize the storage and event queue
3930
3965
  */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.httpClient,this.externalSrcLoader);// Initialize storage
3931
- (_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
3932
- if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
3933
- (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
3966
+ (_this$storeManager=this.storeManager)===null||_this$storeManager===undefined||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===undefined||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
3967
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===undefined||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===undefined||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
3968
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===undefined||_this$eventManager.init();// Mark the SDK as initialized
3934
3969
  state.lifecycle.status.value='initialized';}/**
3935
3970
  * Load plugins
3936
- */},{key:"onConfigured",value:function onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
3971
+ */},{key:"onConfigured",value:function onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===undefined||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
3937
3972
  // registerCustomPlugins(state.loadOptions.value.customPlugins);
3938
3973
  }/**
3939
3974
  * Trigger onLoaded callback if any is provided in config & emit initialised event
@@ -3956,8 +3991,8 @@ var bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEven
3956
3991
  (_ref=this)[methodName].apply(_ref,_toConsumableArray(bufferedEvent.slice(1)).concat([true]));}}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}/**
3957
3992
  * Load device mode destinations
3958
3993
  */},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;if(state.nativeDestinations.clientDestinationsReady.value){return;}// Set in state the desired activeDestinations to inject in DOM
3959
- (_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value='destinationsReady';return;}// Start loading native integration scripts and create instances
3960
- state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===void 0||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
3994
+ (_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===undefined||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value='destinationsReady';return;}// Start loading native integration scripts and create instances
3995
+ state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===undefined||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
3961
3996
  E(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){r(function(){state.lifecycle.status.value='destinationsReady';state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
3962
3997
  * Move to the ready state
3963
3998
  */// eslint-disable-next-line class-methods-use-this
@@ -3969,26 +4004,26 @@ if(state.lifecycle.status.value!=='ready'){state.lifecycle.status.value='ready';
3969
4004
  * If destinations are loaded or no integration is available for loading
3970
4005
  * execute the callback immediately else push the callbacks to a queue that
3971
4006
  * will be executed after loading completes
3972
- */if(state.lifecycle.status.value==='readyExecuted'){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
4007
+ */if(state.lifecycle.status.value==='readyExecuted'){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===undefined||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
3973
4008
  // Send automatic ad blocked page event if ad-blockers are detected on the page
3974
4009
  // Check page category to avoid infinite loop
3975
4010
  if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
3976
4011
  // in v3 implementation
3977
- path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event - ").concat(payload.name));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
3978
- if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getUserId())!==null&&_ref2!==void 0?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0?void 0:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana7,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
3979
- if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,resetAnonymousId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0||_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0?void 0:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
3980
- if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,anonymousId,rudderAmpLinkerParam]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
4012
+ path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event - ").concat(payload.name));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===undefined||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
4013
+ if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===undefined||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===undefined||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===undefined||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==undefined?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===undefined?undefined:_this$userSessionMana4.getUserId())!==null&&_ref2!==undefined?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===undefined?undefined:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===undefined||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana7,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
4014
+ if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===undefined||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===undefined||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===undefined||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,resetAnonymousId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===undefined||_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===undefined?undefined:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
4015
+ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,anonymousId,rudderAmpLinkerParam]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===undefined||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
3981
4016
  },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
3982
4017
  },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
3983
4018
  },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
3984
- },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,sessionId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
3985
- },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13;var sessionId=(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0?void 0:_this$userSessionMana13.getSessionId();return sessionId!==null&&sessionId!==void 0?sessionId:null;}},{key:"consent",value:function consent(options){var _this4=this,_this$storeManager2,_this$userSessionMana14,_this$eventManager7;var isBufferedInvocation=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var type='consent';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,options]]);return;}this.errorHandler.leaveBreadcrumb("New consent invocation");r(function(){state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options);var _getConsentManagement=getConsentManagementData(state.consents.postConsent.value.consentManagement,_this4.logger),initialized=_getConsentManagement.initialized,consentsData=_getConsentManagement.consentsData;state.consents.initialized.value=initialized||state.consents.initialized.value;state.consents.data.value=consentsData;});// Update consents data in state
3986
- if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===void 0||_this$pluginsManager6.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}// Re-init store manager
3987
- (_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
3988
- (_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===void 0||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
3989
- (_this$eventManager7=this.eventManager)===null||_this$eventManager7===void 0||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents(isBufferedInvocation);}},{key:"sendTrackingEvents",value:function sendTrackingEvents(isBufferedInvocation){// If isBufferedInvocation is true, then the tracking events will be added to the end of the
4019
+ },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,sessionId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===undefined||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===undefined||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
4020
+ },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13;var sessionId=(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===undefined?undefined:_this$userSessionMana13.getSessionId();return sessionId!==null&&sessionId!==undefined?sessionId:null;}},{key:"consent",value:function consent(options){var _this4=this,_this$storeManager2,_this$userSessionMana14,_this$eventManager7;var isBufferedInvocation=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var type='consent';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,options]]);return;}this.errorHandler.leaveBreadcrumb("New consent invocation");r(function(){state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options);var _getConsentManagement=getConsentManagementData(state.consents.postConsent.value.consentManagement,_this4.logger),initialized=_getConsentManagement.initialized,consentsData=_getConsentManagement.consentsData;state.consents.initialized.value=initialized||state.consents.initialized.value;state.consents.data.value=consentsData;});// Update consents data in state
4021
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===undefined||_this$pluginsManager6.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}// Re-init store manager
4022
+ (_this$storeManager2=this.storeManager)===null||_this$storeManager2===undefined||_this$storeManager2.initializeStorageState();// Re-init user session manager
4023
+ (_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===undefined||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
4024
+ (_this$eventManager7=this.eventManager)===null||_this$eventManager7===undefined||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents(isBufferedInvocation);}},{key:"sendTrackingEvents",value:function sendTrackingEvents(isBufferedInvocation){// If isBufferedInvocation is true, then the tracking events will be added to the end of the
3990
4025
  // events buffer array so that any other preload events (mainly from query string API) will be processed first.
3991
- if(state.consents.postConsent.value.trackConsent){var trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['track',trackOptions]]);}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){var pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['page',pageOptions]]);}else {this.page(pageOptions);}}}},{key:"setAuthToken",value:function setAuthToken(token){var _this$userSessionMana15;(_this$userSessionMana15=this.userSessionManager)===null||_this$userSessionMana15===void 0||_this$userSessionMana15.setAuthToken(token);}// End consumer exposed methods
4026
+ if(state.consents.postConsent.value.trackConsent){var trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['track',trackOptions]]);}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){var pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['page',pageOptions]]);}else {this.page(pageOptions);}}}},{key:"setAuthToken",value:function setAuthToken(token){var _this$userSessionMana15;(_this$userSessionMana15=this.userSessionManager)===null||_this$userSessionMana15===undefined||_this$userSessionMana15.setAuthToken(token);}// End consumer exposed methods
3992
4027
  }]);}();
3993
4028
 
3994
4029
  /*
@@ -4029,7 +4064,7 @@ promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL
4029
4064
  * @param preloadedEventsArray
4030
4065
  * @param loadOptions
4031
4066
  * @returns
4032
- */},{key:"trackPageLifecycleEvents",value:function trackPageLifecycleEvents(preloadedEventsArray,loadOptions){var _ref=loadOptions!==null&&loadOptions!==void 0?loadOptions:{},autoTrack=_ref.autoTrack,useBeacon=_ref.useBeacon;var _ref2=autoTrack!==null&&autoTrack!==void 0?autoTrack:{},_ref2$enabled=_ref2.enabled,autoTrackEnabled=_ref2$enabled===void 0?false:_ref2$enabled,_ref2$options=_ref2.options,autoTrackOptions=_ref2$options===void 0?{}:_ref2$options,pageLifecycle=_ref2.pageLifecycle;var _ref3=pageLifecycle!==null&&pageLifecycle!==void 0?pageLifecycle:{},_ref3$events=_ref3.events,events=_ref3$events===void 0?[PageLifecycleEvents.LOADED,PageLifecycleEvents.UNLOADED]:_ref3$events,_ref3$enabled=_ref3.enabled,pageLifecycleEnabled=_ref3$enabled===void 0?autoTrackEnabled:_ref3$enabled,_ref3$options=_ref3.options,options=_ref3$options===void 0?autoTrackOptions:_ref3$options;state.autoTrack.pageLifecycle.enabled.value=pageLifecycleEnabled;// Set the autoTrack enabled state
4067
+ */},{key:"trackPageLifecycleEvents",value:function trackPageLifecycleEvents(preloadedEventsArray,loadOptions){var _ref=loadOptions!==null&&loadOptions!==undefined?loadOptions:{},autoTrack=_ref.autoTrack,useBeacon=_ref.useBeacon;var _ref2=autoTrack!==null&&autoTrack!==undefined?autoTrack:{},_ref2$enabled=_ref2.enabled,autoTrackEnabled=_ref2$enabled===undefined?false:_ref2$enabled,_ref2$options=_ref2.options,autoTrackOptions=_ref2$options===undefined?{}:_ref2$options,pageLifecycle=_ref2.pageLifecycle;var _ref3=pageLifecycle!==null&&pageLifecycle!==undefined?pageLifecycle:{},_ref3$events=_ref3.events,events=_ref3$events===undefined?[PageLifecycleEvents.LOADED,PageLifecycleEvents.UNLOADED]:_ref3$events,_ref3$enabled=_ref3.enabled,pageLifecycleEnabled=_ref3$enabled===undefined?autoTrackEnabled:_ref3$enabled,_ref3$options=_ref3.options,options=_ref3$options===undefined?autoTrackOptions:_ref3$options;state.autoTrack.pageLifecycle.enabled.value=pageLifecycleEnabled;// Set the autoTrack enabled state
4033
4068
  // if at least one of the autoTrack options is enabled
4034
4069
  // IMPORTANT: make sure this is done at the end as it depends on the above states
4035
4070
  state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLifecycleEnabled){return;}this.trackPageLoadedEvent(events,options,preloadedEventsArray);this.setupPageUnloadTracking(events,useBeacon,options);}/**