@rudderstack/analytics-js 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/npm/index.d.ts +4 -1
- package/dist/npm/legacy/cjs/index.js +224 -228
- package/dist/npm/legacy/esm/index.js +224 -228
- package/dist/npm/legacy/umd/index.js +224 -228
- package/dist/npm/modern/bundled/cjs/index.js +135 -139
- package/dist/npm/modern/bundled/esm/index.js +135 -139
- package/dist/npm/modern/bundled/umd/index.js +135 -139
- package/dist/npm/modern/cjs/index.js +135 -139
- package/dist/npm/modern/content-script/cjs/index.js +134 -138
- package/dist/npm/modern/content-script/esm/index.js +134 -138
- package/dist/npm/modern/content-script/umd/index.js +134 -138
- package/dist/npm/modern/esm/index.js +135 -139
- package/dist/npm/modern/umd/index.js +135 -139
- package/package.json +7 -5
@@ -8,7 +8,7 @@ function _construct(t, e, r) {
|
|
8
8
|
var o = [null];
|
9
9
|
o.push.apply(o, e);
|
10
10
|
var p = new (t.bind.apply(t, o))();
|
11
|
-
return
|
11
|
+
return p;
|
12
12
|
}
|
13
13
|
function _isNativeReflectConstruct() {
|
14
14
|
try {
|
@@ -147,7 +147,7 @@ function _regeneratorRuntime() {
|
|
147
147
|
function makeInvokeMethod(e, r, n) {
|
148
148
|
var o = h;
|
149
149
|
return function (i, a) {
|
150
|
-
if (o === f) throw
|
150
|
+
if (o === f) throw Error("Generator is already running");
|
151
151
|
if (o === s) {
|
152
152
|
if ("throw" === i) throw a;
|
153
153
|
return {
|
@@ -289,7 +289,7 @@ function _regeneratorRuntime() {
|
|
289
289
|
} else if (c) {
|
290
290
|
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
291
291
|
} else {
|
292
|
-
if (!u) throw
|
292
|
+
if (!u) throw Error("try statement without catch or finally");
|
293
293
|
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
294
294
|
}
|
295
295
|
}
|
@@ -329,7 +329,7 @@ function _regeneratorRuntime() {
|
|
329
329
|
return o;
|
330
330
|
}
|
331
331
|
}
|
332
|
-
throw
|
332
|
+
throw Error("illegal catch attempt");
|
333
333
|
},
|
334
334
|
delegateYield: function (e, r, n) {
|
335
335
|
return this.delegate = {
|
@@ -352,7 +352,7 @@ function _toPrimitive(t, r) {
|
|
352
352
|
}
|
353
353
|
function _toPropertyKey(t) {
|
354
354
|
var i = _toPrimitive(t, "string");
|
355
|
-
return "symbol" == typeof i ? i :
|
355
|
+
return "symbol" == typeof i ? i : i + "";
|
356
356
|
}
|
357
357
|
function _typeof(o) {
|
358
358
|
"@babel/helpers - typeof";
|
@@ -521,7 +521,9 @@ function _nonIterableSpread() {
|
|
521
521
|
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
522
522
|
}
|
523
523
|
|
524
|
-
|
524
|
+
var _placeholder = {'@@functional/placeholder':true};
|
525
|
+
|
526
|
+
function _isPlaceholder(a){return a===_placeholder;}
|
525
527
|
|
526
528
|
/**
|
527
529
|
* Optimized internal one-arity curry function.
|
@@ -577,6 +579,7 @@ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
|
|
577
579
|
* R.type(() => {}); //=> "Function"
|
578
580
|
* R.type(async () => {}); //=> "AsyncFunction"
|
579
581
|
* R.type(undefined); //=> "Undefined"
|
582
|
+
* R.type(BigInt(123)); //=> "BigInt"
|
580
583
|
*/var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
|
581
584
|
|
582
585
|
function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
|
@@ -592,32 +595,7 @@ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object
|
|
592
595
|
|
593
596
|
function _isString(x){return Object.prototype.toString.call(x)==='[object String]';}
|
594
597
|
|
595
|
-
|
596
|
-
* Returns the nth element of the given list or string. If n is negative the
|
597
|
-
* element at index length + n is returned.
|
598
|
-
*
|
599
|
-
* @func
|
600
|
-
* @memberOf R
|
601
|
-
* @since v0.1.0
|
602
|
-
* @category List
|
603
|
-
* @sig Number -> [a] -> a | Undefined
|
604
|
-
* @sig Number -> String -> String
|
605
|
-
* @param {Number} offset
|
606
|
-
* @param {*} list
|
607
|
-
* @return {*}
|
608
|
-
* @example
|
609
|
-
*
|
610
|
-
* const list = ['foo', 'bar', 'baz', 'quux'];
|
611
|
-
* R.nth(1, list); //=> 'bar'
|
612
|
-
* R.nth(-1, list); //=> 'quux'
|
613
|
-
* R.nth(-99, list); //=> undefined
|
614
|
-
*
|
615
|
-
* R.nth(2, 'abc'); //=> 'c'
|
616
|
-
* R.nth(3, 'abc'); //=> ''
|
617
|
-
* @symb R.nth(-1, [a, b, c]) = c
|
618
|
-
* @symb R.nth(0, [a, b, c]) = a
|
619
|
-
* @symb R.nth(1, [a, b, c]) = b
|
620
|
-
*/var nth=/*#__PURE__*/_curry2(function nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];});
|
598
|
+
function _nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];}
|
621
599
|
|
622
600
|
function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pattern.flags:(pattern.global?'g':'')+(pattern.ignoreCase?'i':'')+(pattern.multiline?'m':'')+(pattern.sticky?'y':'')+(pattern.unicode?'u':'')+(pattern.dotAll?'s':''));}
|
623
601
|
|
@@ -630,10 +608,10 @@ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pa
|
|
630
608
|
* @return {*} The copied value.
|
631
609
|
*/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.
|
632
610
|
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.
|
633
|
-
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]=
|
611
|
+
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){/**
|
634
612
|
* 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,
|
635
613
|
* on my tests this number is 180, anything above that using the hash function is faster.
|
636
|
-
*/if(this.length<=180){for(var p in this.map){var
|
614
|
+
*/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;}();
|
637
615
|
|
638
616
|
/**
|
639
617
|
* Creates a deep copy of the source that can be used in place of the source
|
@@ -661,51 +639,9 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
661
639
|
* const objectsClone = R.clone(objects);
|
662
640
|
* objects === objectsClone; //=> false
|
663
641
|
* objects[0] === objectsClone[0]; //=> false
|
664
|
-
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value
|
665
|
-
|
666
|
-
/**
|
667
|
-
* Retrieves the values at given paths of an object.
|
668
|
-
*
|
669
|
-
* @func
|
670
|
-
* @memberOf R
|
671
|
-
* @since v0.27.1
|
672
|
-
* @category Object
|
673
|
-
* @typedefn Idx = [String | Int | Symbol]
|
674
|
-
* @sig [Idx] -> {a} -> [a | Undefined]
|
675
|
-
* @param {Array} pathsArray The array of paths to be fetched.
|
676
|
-
* @param {Object} obj The object to retrieve the nested properties from.
|
677
|
-
* @return {Array} A list consisting of values at paths specified by "pathsArray".
|
678
|
-
* @see R.path
|
679
|
-
* @example
|
680
|
-
*
|
681
|
-
* R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]
|
682
|
-
* R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]
|
683
|
-
*/var paths=/*#__PURE__*/_curry2(function paths(pathsArray,obj){return pathsArray.map(function(paths){var val=obj;var idx=0;var p;while(idx<paths.length){if(val==null){return;}p=paths[idx];val=_isInteger(p)?nth(p,val):val[p];idx+=1;}return val;});});
|
642
|
+
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value);});
|
684
643
|
|
685
|
-
|
686
|
-
* Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
|
687
|
-
* For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
|
688
|
-
*
|
689
|
-
* @func
|
690
|
-
* @memberOf R
|
691
|
-
* @since v0.2.0
|
692
|
-
* @category Object
|
693
|
-
* @typedefn Idx = String | Int | Symbol
|
694
|
-
* @sig [Idx] -> {a} -> a | Undefined
|
695
|
-
* @sig Idx = String | NonNegativeInt
|
696
|
-
* @param {Array} path The path to use.
|
697
|
-
* @param {Object} obj The object or array to retrieve the nested property from.
|
698
|
-
* @return {*} The data at `path`.
|
699
|
-
* @see R.prop, R.nth, R.assocPath, R.dissocPath
|
700
|
-
* @example
|
701
|
-
*
|
702
|
-
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
|
703
|
-
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
|
704
|
-
* R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
|
705
|
-
* R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
|
706
|
-
* R.path([2], {'2': 2}); //=> 2
|
707
|
-
* R.path([-2], {'-2': 'a'}); //=> undefined
|
708
|
-
*/var path=/*#__PURE__*/_curry2(function path(pathAr,obj){return paths([pathAr],obj)[0];});
|
644
|
+
function _path(pathAr,obj){var val=obj;for(var i=0;i<pathAr.length;i+=1){if(val==null){return undefined;}var p=pathAr[i];if(_isInteger(p)){val=_nth(p,val);}else {val=val[p];}}return val;}
|
709
645
|
|
710
646
|
/**
|
711
647
|
* Creates a new object with the own properties of the two provided objects. If
|
@@ -790,6 +726,31 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
790
726
|
* //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
|
791
727
|
*/var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});
|
792
728
|
|
729
|
+
/**
|
730
|
+
* Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
|
731
|
+
* For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
|
732
|
+
*
|
733
|
+
* @func
|
734
|
+
* @memberOf R
|
735
|
+
* @since v0.2.0
|
736
|
+
* @category Object
|
737
|
+
* @typedefn Idx = String | Int | Symbol
|
738
|
+
* @sig [Idx] -> {a} -> a | Undefined
|
739
|
+
* @sig Idx = String | NonNegativeInt
|
740
|
+
* @param {Array} path The path to use.
|
741
|
+
* @param {Object} obj The object or array to retrieve the nested property from.
|
742
|
+
* @return {*} The data at `path`.
|
743
|
+
* @see R.prop, R.nth, R.assocPath, R.dissocPath
|
744
|
+
* @example
|
745
|
+
*
|
746
|
+
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
|
747
|
+
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
|
748
|
+
* R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
|
749
|
+
* R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
|
750
|
+
* R.path([2], {'2': 2}); //=> 2
|
751
|
+
* R.path([-2], {'-2': 'a'}); //=> undefined
|
752
|
+
*/var path=/*#__PURE__*/_curry2(_path);
|
753
|
+
|
793
754
|
/**
|
794
755
|
* Returns a partial copy of an object containing only the keys that satisfy
|
795
756
|
* the supplied predicate.
|
@@ -936,7 +897,7 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
936
897
|
|
937
898
|
var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
|
938
899
|
|
939
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.
|
900
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.2.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';
|
940
901
|
|
941
902
|
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';
|
942
903
|
|
@@ -1046,19 +1007,19 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
|
|
1046
1007
|
* Service to load external resources/files
|
1047
1008
|
*/var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
|
1048
1009
|
* Load external resource of type javascript
|
1049
|
-
*/_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();}});}/**
|
1010
|
+
*/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();}});}/**
|
1050
1011
|
* Handle errors
|
1051
|
-
*/},{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;}}}]);
|
1012
|
+
*/},{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;}}}]);}();
|
1052
1013
|
|
1053
|
-
|
1014
|
+
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);}
|
1054
1015
|
|
1055
1016
|
/**
|
1056
1017
|
* A buffer queue to serve as a store for any type of data
|
1057
|
-
*/var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}_createClass(BufferQueue,[{key:"enqueue",value:function enqueue(item){this.items.push(item);}},{key:"dequeue",value:function dequeue(){if(this.items.length===0){return null;}return this.items.shift();}},{key:"isEmpty",value:function isEmpty(){return this.items.length===0;}},{key:"size",value:function size(){return this.items.length;}},{key:"clear",value:function clear(){this.items=[];}}]);
|
1018
|
+
*/var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}return _createClass(BufferQueue,[{key:"enqueue",value:function enqueue(item){this.items.push(item);}},{key:"dequeue",value:function dequeue(){if(this.items.length===0){return null;}return this.items.shift();}},{key:"isEmpty",value:function isEmpty(){return this.items.length===0;}},{key:"size",value:function size(){return this.items.length;}},{key:"clear",value:function clear(){this.items=[];}}]);}();
|
1058
1019
|
|
1059
1020
|
var LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};var DEFAULT_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;';/**
|
1060
1021
|
* Service to log messages/data to output provider, default is console
|
1061
|
-
*/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;}_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
|
1022
|
+
*/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
|
1062
1023
|
// to assist on the fly debugging?
|
1063
1024
|
},{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
1064
1025
|
* Formats the console message using `scope` and styles
|
@@ -1070,63 +1031,65 @@ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PRE
|
|
1070
1031
|
LOG_MSG_STYLE// reset the style for the actual message
|
1071
1032
|
];// add first it if it was not a string msg
|
1072
1033
|
if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
|
1073
|
-
styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);
|
1034
|
+
styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);}();var defaultLogger=new Logger();
|
1074
1035
|
|
1075
1036
|
// default is v3
|
1076
1037
|
var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
|
1077
1038
|
|
1078
1039
|
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 INTG_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for integrations is not valid.";var PLUGINS_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for plugins is not valid.";var DATA_PLANE_URL_ERROR="Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";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.";// ERROR
|
1079
|
-
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};// WARNING
|
1080
|
-
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"US, EU\". The default region \"").concat(defaultRegion,"\" will be used instead.");};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
|
1040
|
+
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_TO_REMOVE_COOKIE_FROM_SERVER_ERROR=function FAILED_TO_REMOVE_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to remove the ".concat(key," cookie.");};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
|
1041
|
+
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"US, EU\". The default region \"").concat(defaultRegion,"\" will be used instead.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var NATIVE_DEST_PLUGIN_INITIALIZE_ERROR="NativeDestinationQueuePlugin initialization failed";var DATAPLANE_PLUGIN_INITIALIZE_ERROR="XhrQueuePlugin initialization failed";var DMT_PLUGIN_INITIALIZE_ERROR="DeviceModeTransformationPlugin initialization failed";var NATIVE_DEST_PLUGIN_ENQUEUE_ERROR="NativeDestinationQueuePlugin event enqueue failed";var DATAPLANE_PLUGIN_ENQUEUE_ERROR="XhrQueuePlugin event enqueue failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var MISCONFIGURED_PLUGINS_WARNING=function MISCONFIGURED_PLUGINS_WARNING(context,configurationStatusStr,missingPlugins,shouldAddMissingPlugins){var pluginsString=missingPlugins.length===1?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatusStr,", but").concat(pluginsString," not configured to load.");var warningStr;if(shouldAddMissingPlugins){warningStr="".concat(baseWarning," So, ").concat(missingPlugins.length===1?'the plugin':'those plugins'," will be loaded automatically.");}else {warningStr="".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(missingPlugins.length===1?'it':'them'," to the 'plugins' load API option.");}return warningStr;};// DEBUG
|
1081
1042
|
|
1082
1043
|
var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';
|
1083
1044
|
|
1084
1045
|
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';
|
1085
1046
|
|
1086
|
-
var DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var ErrorReportingProvidersToPluginNameMap=_defineProperty({},DEFAULT_ERROR_REPORTING_PROVIDER,'Bugsnag');var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');
|
1047
|
+
var DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var ErrorReportingProvidersToPluginNameMap=_defineProperty({},DEFAULT_ERROR_REPORTING_PROVIDER,'Bugsnag');var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');var DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';
|
1087
1048
|
|
1088
|
-
var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true},sendAdblockPageOptions:{}};var loadOptionsState=
|
1049
|
+
var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true},sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
|
1089
1050
|
|
1090
1051
|
var USER_SESSION_STORAGE_KEYS={userId:'rl_user_id',userTraits:'rl_trait',anonymousId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session',authToken:'rl_auth_token'};var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};
|
1091
1052
|
|
1092
|
-
var
|
1053
|
+
var defaultSessionConfiguration={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};var sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
|
1093
1054
|
|
1094
|
-
var capabilitiesState={isOnline:
|
1055
|
+
var capabilitiesState={isOnline:d$1(true),storage:{isLocalStorageAvailable:d$1(false),isCookieStorageAvailable:d$1(false),isSessionStorageAvailable:d$1(false)},isBeaconAvailable:d$1(false),isLegacyDOM:d$1(false),isUaCHAvailable:d$1(false),isCryptoAvailable:d$1(false),isIE11:d$1(false),isAdBlocked:d$1(false)};
|
1095
1056
|
|
1096
|
-
var reportingState={isErrorReportingEnabled:
|
1057
|
+
var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled:d$1(false),errorReportingProviderPluginName:d$1(undefined),isErrorReportingPluginLoaded:d$1(false)};
|
1097
1058
|
|
1098
|
-
var sourceConfigState=
|
1059
|
+
var sourceConfigState=d$1(undefined);
|
1099
1060
|
|
1100
|
-
var lifecycleState={activeDataplaneUrl:
|
1061
|
+
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)};
|
1101
1062
|
|
1102
|
-
var consentsState={enabled:
|
1063
|
+
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)};
|
1103
1064
|
|
1104
|
-
var metricsState={retries:
|
1065
|
+
var metricsState={retries:d$1(0),dropped:d$1(0),sent:d$1(0),queued:d$1(0),triggered:d$1(0)};
|
1105
1066
|
|
1106
|
-
var contextState={app:
|
1067
|
+
var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(''),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
|
1107
1068
|
|
1108
|
-
var nativeDestinationsState={configuredDestinations:
|
1069
|
+
var nativeDestinationsState={configuredDestinations:d$1([]),activeDestinations:d$1([]),loadOnlyIntegrations:d$1({}),failedDestinations:d$1([]),loadIntegration:d$1(true),initializedDestinations:d$1([]),clientDestinationsReady:d$1(false),integrationsConfig:d$1({})};
|
1109
1070
|
|
1110
|
-
var eventBufferState={toBeProcessedArray:
|
1071
|
+
var eventBufferState={toBeProcessedArray:d$1([]),readyCallbacksArray:d$1([])};
|
1111
1072
|
|
1112
|
-
var pluginsState={ready:
|
1073
|
+
var pluginsState={ready:d$1(false),loadedPlugins:d$1([]),failedPlugins:d$1([]),pluginsToLoadFromConfig:d$1([]),activePlugins:d$1([]),totalPluginsToLoad:d$1(0)};
|
1113
1074
|
|
1114
|
-
var storageState={encryptionPluginName:
|
1075
|
+
var storageState={encryptionPluginName:d$1(undefined),migrate:d$1(false),type:d$1(undefined),cookie:d$1(undefined),entries:d$1({}),trulyAnonymousTracking:d$1(false)};
|
1115
1076
|
|
1116
|
-
var
|
1077
|
+
var serverSideCookiesState={isEnabledServerSideCookies:d$1(false),dataServiceUrl:d$1(undefined)};
|
1078
|
+
|
1079
|
+
var dataPlaneEventsState={eventsQueuePluginName:d$1(undefined),deliveryEnabled:d$1(true)// Delivery should always happen
|
1117
1080
|
};
|
1118
1081
|
|
1119
|
-
var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState,dataPlaneEvents:dataPlaneEventsState};var state=_objectSpread2({},clone(defaultStateValues));
|
1082
|
+
var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState,serverCookies:serverSideCookiesState,dataPlaneEvents:dataPlaneEventsState};var state=_objectSpread2({},clone(defaultStateValues));
|
1120
1083
|
|
1121
1084
|
// to next or return the value if it is the last one instead of an array per
|
1122
1085
|
// plugin that is the normal invoke
|
1123
1086
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
1124
|
-
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;}_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.
|
1087
|
+
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.
|
1125
1088
|
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
|
1126
1089
|
// do some unified pre-process before application starts.
|
1127
1090
|
},{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
|
1128
1091
|
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
|
1129
|
-
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));}}]);
|
1092
|
+
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);
|
1130
1093
|
|
1131
1094
|
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1132
1095
|
|
@@ -1146,7 +1109,7 @@ if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.d
|
|
1146
1109
|
/**
|
1147
1110
|
* A service to handle errors
|
1148
1111
|
*/var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
|
1149
|
-
function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;this.errorBuffer=new BufferQueue();this.attachEffect();}_createClass(ErrorHandler,[{key:"attachEffect",value:function attachEffect(){if(state.reporting.isErrorReportingPluginLoaded.value===true){while(this.errorBuffer.size()>0){this.errorBuffer.dequeue();}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,'unhandledException');});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,'unhandledPromiseRejection');});}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(externalSrcLoader){var _this2=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);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 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]:'handled';// Error handling is already implemented in processError method
|
1112
|
+
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){this.errorBuffer.dequeue();}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,'unhandledException');});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,'unhandledPromiseRejection');});}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(externalSrcLoader){var _this2=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);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 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]:'handled';// Error handling is already implemented in processError method
|
1150
1113
|
var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1151
1114
|
if(!errorMessage){return;}// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1152
1115
|
errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}if(errorType==='handled'){// TODO: Remove the below line once the new Reporting plugin is ready
|
@@ -1161,7 +1124,7 @@ if(state.reporting.isErrorReportingEnabled.value&&!state.reporting.isErrorReport
|
|
1161
1124
|
*
|
1162
1125
|
* @param {Error} error Error instance from handled error
|
1163
1126
|
*/},{key:"notifyError",value:function notifyError(error){if(this.pluginEngine&&isAllowedToBeNotified(error)){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,this.errReportingClient,error,state,this.logger);}catch(err){var _this$logger2;// Not calling onError here as we don't want to go into infinite loop
|
1164
|
-
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);
|
1127
|
+
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1165
1128
|
|
1166
1129
|
/**
|
1167
1130
|
* A function to filter and return non cloud mode destinations
|
@@ -1241,7 +1204,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
|
|
1241
1204
|
|
1242
1205
|
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1243
1206
|
|
1244
|
-
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;}_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={};}}]);
|
1207
|
+
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={};}}]);}();
|
1245
1208
|
|
1246
1209
|
var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};var RETRY_QUEUE_ENTRY_REMOVE_ERROR=function RETRY_QUEUE_ENTRY_REMOVE_ERROR(context,entry,attempt){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to remove local storage entry \"").concat(entry,"\" (attempt: ").concat(attempt,".");};
|
1247
1210
|
|
@@ -1261,7 +1224,7 @@ timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakin
|
|
1261
1224
|
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
|
1262
1225
|
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
|
1263
1226
|
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);// Attach visibility change listener to flush the queue
|
1264
|
-
this.attachListeners();this.scheduleTimeoutActive=false;}_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
|
1227
|
+
this.attachListeners();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
|
1265
1228
|
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:"attachListeners",value:function attachListeners(){var _this=this;if(this.batch.enabled){globalThis.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden'){_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
|
1266
1229
|
},{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
|
1267
1230
|
* Stops processing the queue
|
@@ -1331,7 +1294,7 @@ if(entryIdx+1<queueEntryKeys.length){_this4.removeStorageEntry(store,entryIdx+1,
|
|
1331
1294
|
_this4.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
|
1332
1295
|
if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this4.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this5=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this5.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this5.id){return;}_this5.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this5.id){return;}store.set(QueueStatuses.RECLAIM_END,_this5.id);_this5.schedule.run(createReclaimStartTask(store),_this5.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this5.id);store.set(QueueStatuses.ACK,_this5.schedule.now());_this5.schedule.run(createReclaimEndTask(store),_this5.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storageEngine=_this5.store.getOriginalEngine();var storageKeys=[];// 'keys' API is not supported by all the core SDK versions
|
1333
1296
|
// Hence, we need this backward compatibility check
|
1334
|
-
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]!==_this5.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this5.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this5.schedule.now()-store.get(QueueStatuses.ACK)<_this5.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();}}]);
|
1297
|
+
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]!==_this5.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this5.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this5.schedule.now()-store.get(QueueStatuses.ACK)<_this5.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();}}]);}();
|
1335
1298
|
|
1336
1299
|
var pluginName$e='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},dataplaneEventsQueue:{/**
|
1337
1300
|
* Initialize the queue for delivery
|
@@ -1384,7 +1347,7 @@ event.context='Script load failures';}// eslint-disable-next-line no-param-reass
|
|
1384
1347
|
event.severity='error';};var onError=function onError(state){var _state$source$value;var metadataSource=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id;return function(event){try{// Discard the event if it's not originated at the SDK
|
1385
1348
|
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
|
1386
1349
|
// it is most likely a non-SDK error
|
1387
|
-
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.
|
1350
|
+
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.2.0',// Set SDK version as the app version from build config
|
1388
1351
|
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1389
1352
|
collectUserIp:false,// collecting user's IP is disabled
|
1390
1353
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
@@ -1837,7 +1800,7 @@ var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncry
|
|
1837
1800
|
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.
|
1838
1801
|
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);};}/**
|
1839
1802
|
* Base class for inheritance.
|
1840
|
-
*/var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}_createClass(Base,[{key:"mixIn",value:/**
|
1803
|
+
*/var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}return _createClass(Base,[{key:"mixIn",value:/**
|
1841
1804
|
* Copies properties into this object.
|
1842
1805
|
*
|
1843
1806
|
* @param {Object} properties The properties to mix in.
|
@@ -1866,12 +1829,12 @@ randomWordArray=function randomWordArray(nBytes){var words=[];var r=function r(m
|
|
1866
1829
|
* @example
|
1867
1830
|
*
|
1868
1831
|
* var instance = MyType.create();
|
1869
|
-
*/function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);
|
1832
|
+
*/function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);}();/**
|
1870
1833
|
* An array of 32-bit words.
|
1871
1834
|
*
|
1872
1835
|
* @property {Array} words The array of 32-bit words.
|
1873
1836
|
* @property {number} sigBytes The number of significant bytes in this word array.
|
1874
|
-
*/var WordArray=/*#__PURE__*/function(_Base){
|
1837
|
+
*/var WordArray=/*#__PURE__*/function(_Base){/**
|
1875
1838
|
* Initializes a newly created word array.
|
1876
1839
|
*
|
1877
1840
|
* @param {Array} words (Optional) An array of 32-bit words.
|
@@ -1901,7 +1864,7 @@ _this.words=words;_this.sigBytes=sigBytes;}return _this;}/**
|
|
1901
1864
|
* @example
|
1902
1865
|
*
|
1903
1866
|
* var wordArray = CryptoJS.lib.WordArray.random(16);
|
1904
|
-
*/_createClass(WordArray,[{key:"toString",value:/**
|
1867
|
+
*/_inherits(WordArray,_Base);return _createClass(WordArray,[{key:"toString",value:/**
|
1905
1868
|
* Converts this word array to a string.
|
1906
1869
|
*
|
1907
1870
|
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
|
@@ -1945,7 +1908,7 @@ words[sigBytes>>>2]&=0xffffffff<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes
|
|
1945
1908
|
* @example
|
1946
1909
|
*
|
1947
1910
|
* var clone = wordArray.clone();
|
1948
|
-
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);
|
1911
|
+
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);}(Base);/**
|
1949
1912
|
* Hex encoding strategy.
|
1950
1913
|
*/_defineProperty(WordArray,"random",randomWordArray);var Hex={/**
|
1951
1914
|
* Converts a word array to a hex string.
|
@@ -2039,13 +2002,13 @@ var words=[];for(var i=0;i<latin1StrLength;i+=1){words[i>>>2]|=(latin1Str.charCo
|
|
2039
2002
|
* @property {number} _minBufferSize
|
2040
2003
|
*
|
2041
2004
|
* The number of blocks that should be kept unprocessed in the buffer. Default: 0
|
2042
|
-
*/var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){
|
2005
|
+
*/var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){function BufferedBlockAlgorithm(){var _this2;_classCallCheck(this,BufferedBlockAlgorithm);_this2=_callSuper(this,BufferedBlockAlgorithm);_this2._minBufferSize=0;return _this2;}/**
|
2043
2006
|
* Resets this block algorithm's data buffer to its initial state.
|
2044
2007
|
*
|
2045
2008
|
* @example
|
2046
2009
|
*
|
2047
2010
|
* bufferedBlockAlgorithm.reset();
|
2048
|
-
*/_createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
|
2011
|
+
*/_inherits(BufferedBlockAlgorithm,_Base2);return _createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
|
2049
2012
|
this._data=new WordArray();this._nDataBytes=0;}/**
|
2050
2013
|
* Adds new data to this block algorithm's buffer.
|
2051
2014
|
*
|
@@ -2091,13 +2054,13 @@ return new WordArray(processedWords,nBytesReady);}/**
|
|
2091
2054
|
* @example
|
2092
2055
|
*
|
2093
2056
|
* var clone = bufferedBlockAlgorithm.clone();
|
2094
|
-
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);
|
2057
|
+
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);}(Base);/**
|
2095
2058
|
* Abstract hasher template.
|
2096
2059
|
*
|
2097
2060
|
* @property {number} blockSize
|
2098
2061
|
*
|
2099
2062
|
* The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
|
2100
|
-
*/var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){
|
2063
|
+
*/var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){function Hasher(cfg){var _this3;_classCallCheck(this,Hasher);_this3=_callSuper(this,Hasher);_this3.blockSize=512/32;/**
|
2101
2064
|
* Configuration options.
|
2102
2065
|
*/_this3.cfg=Object.assign(new Base(),cfg);// Set initial values
|
2103
2066
|
_this3.reset();return _this3;}/**
|
@@ -2112,7 +2075,7 @@ _this3.reset();return _this3;}/**
|
|
2112
2075
|
* @example
|
2113
2076
|
*
|
2114
2077
|
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
|
2115
|
-
*/_createClass(Hasher,[{key:"reset",value:/**
|
2078
|
+
*/_inherits(Hasher,_BufferedBlockAlgorit);return _createClass(Hasher,[{key:"reset",value:/**
|
2116
2079
|
* Resets this hasher to its initial state.
|
2117
2080
|
*
|
2118
2081
|
* @example
|
@@ -2161,9 +2124,9 @@ var hash=this._doFinalize();return hash;}}],[{key:"_createHelper",value:function
|
|
2161
2124
|
* @example
|
2162
2125
|
*
|
2163
2126
|
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
|
2164
|
-
*/},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);
|
2127
|
+
*/},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);}(BufferedBlockAlgorithm);/**
|
2165
2128
|
* HMAC algorithm.
|
2166
|
-
*/var HMAC=/*#__PURE__*/function(_Base3){
|
2129
|
+
*/var HMAC=/*#__PURE__*/function(_Base3){/**
|
2167
2130
|
* Initializes a newly created HMAC.
|
2168
2131
|
*
|
2169
2132
|
* @param {Hasher} SubHasher The hash algorithm to use.
|
@@ -2186,7 +2149,7 @@ _this4.reset();return _this4;}/**
|
|
2186
2149
|
* @example
|
2187
2150
|
*
|
2188
2151
|
* hmacHasher.reset();
|
2189
|
-
*/_createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
|
2152
|
+
*/_inherits(HMAC,_Base3);return _createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
|
2190
2153
|
var hasher=this._hasher;// Reset
|
2191
2154
|
hasher.reset();hasher.update(this._iKey);}/**
|
2192
2155
|
* Updates this HMAC with a message.
|
@@ -2215,7 +2178,7 @@ return this;}/**
|
|
2215
2178
|
* var hmac = hmacHasher.finalize(wordArray);
|
2216
2179
|
*/},{key:"finalize",value:function finalize(messageUpdate){// Shortcut
|
2217
2180
|
var hasher=this._hasher;// Compute HMAC
|
2218
|
-
var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);
|
2181
|
+
var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);}(Base);
|
2219
2182
|
|
2220
2183
|
var parseLoop=function parseLoop(base64Str,base64StrLength,reverseMap){var words=[];var nBytes=0;for(var i=0;i<base64StrLength;i+=1){if(i%4){var bits1=reverseMap[base64Str.charCodeAt(i-1)]<<i%4*2;var bits2=reverseMap[base64Str.charCodeAt(i)]>>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes+=1;}}return WordArray.create(words,nBytes);};/**
|
2221
2184
|
* Base64 encoding strategy.
|
@@ -2255,7 +2218,7 @@ return parseLoop(base64Str,base64StrLength,reverseMap);},_map:'ABCDEFGHIJKLMNOPQ
|
|
2255
2218
|
var T=[];// Compute constants
|
2256
2219
|
for(var i$1=0;i$1<64;i$1+=1){T[i$1]=Math.abs(Math.sin(i$1+1))*0x100000000|0;}var FF=function FF(a,b,c,d,x,s,t){var n=a+(b&c|~b&d)+x+t;return (n<<s|n>>>32-s)+b;};var GG=function GG(a,b,c,d,x,s,t){var n=a+(b&d|c&~d)+x+t;return (n<<s|n>>>32-s)+b;};var HH=function HH(a,b,c,d,x,s,t){var n=a+(b^c^d)+x+t;return (n<<s|n>>>32-s)+b;};var II=function II(a,b,c,d,x,s,t){var n=a+(c^(b|~d))+x+t;return (n<<s|n>>>32-s)+b;};/**
|
2257
2220
|
* MD5 hash algorithm.
|
2258
|
-
*/var MD5Algo=/*#__PURE__*/function(_Hasher){
|
2221
|
+
*/var MD5Algo=/*#__PURE__*/function(_Hasher){function MD5Algo(){_classCallCheck(this,MD5Algo);return _callSuper(this,MD5Algo,arguments);}_inherits(MD5Algo,_Hasher);return _createClass(MD5Algo,[{key:"_doReset",value:function _doReset(){this._hash=new WordArray([0x67452301,0xefcdab89,0x98badcfe,0x10325476]);}},{key:"_doProcessBlock",value:function _doProcessBlock(M,offset){var _M=M;// Swap endian
|
2259
2222
|
for(var _i=0;_i<16;_i+=1){// Shortcuts
|
2260
2223
|
var offset_i=offset+_i;var M_offset_i=M[offset_i];_M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&0x00ff00ff|(M_offset_i<<24|M_offset_i>>>8)&0xff00ff00;}// Shortcuts
|
2261
2224
|
var H=this._hash.words;var M_offset_0=_M[offset+0];var M_offset_1=_M[offset+1];var M_offset_2=_M[offset+2];var M_offset_3=_M[offset+3];var M_offset_4=_M[offset+4];var M_offset_5=_M[offset+5];var M_offset_6=_M[offset+6];var M_offset_7=_M[offset+7];var M_offset_8=_M[offset+8];var M_offset_9=_M[offset+9];var M_offset_10=_M[offset+10];var M_offset_11=_M[offset+11];var M_offset_12=_M[offset+12];var M_offset_13=_M[offset+13];var M_offset_14=_M[offset+14];var M_offset_15=_M[offset+15];// Working varialbes
|
@@ -2268,7 +2231,7 @@ this._process();// Shortcuts
|
|
2268
2231
|
var hash=this._hash;var H=hash.words;// Swap endian
|
2269
2232
|
for(var _i2=0;_i2<4;_i2+=1){// Shortcut
|
2270
2233
|
var H_i=H[_i2];H[_i2]=(H_i<<8|H_i>>>24)&0x00ff00ff|(H_i<<24|H_i>>>8)&0xff00ff00;}// Return final computed hash
|
2271
|
-
return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(MD5Algo.prototype),"clone",this).call(this);clone._hash=this._hash.clone();return clone;}}]);
|
2234
|
+
return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(MD5Algo.prototype),"clone",this).call(this);clone._hash=this._hash.clone();return clone;}}]);}(Hasher);/**
|
2272
2235
|
* Shortcut function to the hasher's object interface.
|
2273
2236
|
*
|
2274
2237
|
* @param {WordArray|string} message The message to hash.
|
@@ -2299,7 +2262,7 @@ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeO
|
|
2299
2262
|
/**
|
2300
2263
|
* This key derivation function is meant to conform with EVP_BytesToKey.
|
2301
2264
|
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
|
2302
|
-
*/var EvpKDFAlgo=/*#__PURE__*/function(_Base){
|
2265
|
+
*/var EvpKDFAlgo=/*#__PURE__*/function(_Base){/**
|
2303
2266
|
* Initializes a newly created key derivation function.
|
2304
2267
|
*
|
2305
2268
|
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
|
@@ -2326,13 +2289,13 @@ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeO
|
|
2326
2289
|
* @example
|
2327
2290
|
*
|
2328
2291
|
* const key = kdf.compute(password, salt);
|
2329
|
-
*/_createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
|
2292
|
+
*/_inherits(EvpKDFAlgo,_Base);return _createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
|
2330
2293
|
var cfg=this.cfg;// Init hasher
|
2331
2294
|
var hasher=cfg.hasher.create();// Initial values
|
2332
2295
|
var derivedKey=WordArray.create();// Shortcuts
|
2333
2296
|
var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize,iterations=cfg.iterations;// Generate key
|
2334
2297
|
while(derivedKeyWords.length<keySize){if(block){hasher.update(block);}block=hasher.update(password).finalize(salt);hasher.reset();// Iterations
|
2335
|
-
for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);
|
2298
|
+
for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);}(Base);
|
2336
2299
|
|
2337
2300
|
var ObjectAssign=typeof Object.assign!=="function"?function(target){if(target==null){throw new TypeError('Cannot convert undefined or null to object');}target=Object(target);for(var index=1;index<arguments.length;index++){var source=arguments[index];if(source!=null){for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}}return target;}:Object.assign;/**
|
2338
2301
|
* Abstract base cipher template.
|
@@ -2341,7 +2304,7 @@ var ObjectAssign=typeof Object.assign!=="function"?function(target){if(target==n
|
|
2341
2304
|
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
|
2342
2305
|
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
|
2343
2306
|
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
|
2344
|
-
*/var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){
|
2307
|
+
*/var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){/**
|
2345
2308
|
* Initializes a newly created cipher.
|
2346
2309
|
*
|
2347
2310
|
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
|
@@ -2372,7 +2335,7 @@ _this.reset();return _this;}/**
|
|
2372
2335
|
* @example
|
2373
2336
|
*
|
2374
2337
|
* const cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
|
2375
|
-
*/_createClass(Cipher,[{key:"reset",value:/**
|
2338
|
+
*/_inherits(Cipher,_BufferedBlockAlgorit);return _createClass(Cipher,[{key:"reset",value:/**
|
2376
2339
|
* Resets this cipher to its initial state.
|
2377
2340
|
*
|
2378
2341
|
* @example
|
@@ -2433,9 +2396,9 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2433
2396
|
* @example
|
2434
2397
|
*
|
2435
2398
|
* const AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
|
2436
|
-
*/},{key:"_createHelper",value:function _createHelper(SubCipher){var selectCipherStrategy=function selectCipherStrategy(key){if(typeof key==='string'){return PasswordBasedCipher;}return SerializableCipher;};return {encrypt:function encrypt(message,key,cfg){return selectCipherStrategy(key).encrypt(SubCipher,message,key,cfg);},decrypt:function decrypt(ciphertext,key,cfg){return selectCipherStrategy(key).decrypt(SubCipher,ciphertext,key,cfg);}};}}]);
|
2399
|
+
*/},{key:"_createHelper",value:function _createHelper(SubCipher){var selectCipherStrategy=function selectCipherStrategy(key){if(typeof key==='string'){return PasswordBasedCipher;}return SerializableCipher;};return {encrypt:function encrypt(message,key,cfg){return selectCipherStrategy(key).encrypt(SubCipher,message,key,cfg);},decrypt:function decrypt(ciphertext,key,cfg){return selectCipherStrategy(key).decrypt(SubCipher,ciphertext,key,cfg);}};}}]);}(BufferedBlockAlgorithm);Cipher._ENC_XFORM_MODE=1;Cipher._DEC_XFORM_MODE=2;Cipher.keySize=128/32;Cipher.ivSize=128/32;/**
|
2437
2400
|
* Abstract base block cipher mode template.
|
2438
|
-
*/var BlockCipherMode=/*#__PURE__*/function(_Base){
|
2401
|
+
*/var BlockCipherMode=/*#__PURE__*/function(_Base){/**
|
2439
2402
|
* Initializes a newly created mode.
|
2440
2403
|
*
|
2441
2404
|
* @param {Cipher} cipher A block cipher instance.
|
@@ -2455,7 +2418,7 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2455
2418
|
* @example
|
2456
2419
|
*
|
2457
2420
|
* const mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
|
2458
|
-
*/_createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
|
2421
|
+
*/_inherits(BlockCipherMode,_Base);return _createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
|
2459
2422
|
* Creates this mode for decryption.
|
2460
2423
|
*
|
2461
2424
|
* @param {Cipher} cipher A block cipher instance.
|
@@ -2466,7 +2429,7 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2466
2429
|
* @example
|
2467
2430
|
*
|
2468
2431
|
* const mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
|
2469
|
-
*/},{key:"createDecryptor",value:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);}}]);
|
2432
|
+
*/},{key:"createDecryptor",value:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);}}]);}(Base);function xorBlock(words,offset,blockSize){var _words=words;var block;// Shortcut
|
2470
2433
|
var iv=this._iv;// Choose mixing block
|
2471
2434
|
if(iv){block=iv;// Remove IV for subsequent blocks
|
2472
2435
|
this._iv=undefined;}else {block=this._prevBlock;}// XOR blocks
|
@@ -2474,9 +2437,9 @@ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
|
|
2474
2437
|
* Cipher Block Chaining mode.
|
2475
2438
|
*/ /**
|
2476
2439
|
* Abstract base CBC mode.
|
2477
|
-
*/var CBC=/*#__PURE__*/function(_BlockCipherMode){
|
2440
|
+
*/var CBC=/*#__PURE__*/function(_BlockCipherMode){function CBC(){_classCallCheck(this,CBC);return _callSuper(this,CBC,arguments);}_inherits(CBC,_BlockCipherMode);return _createClass(CBC);}(BlockCipherMode);/**
|
2478
2441
|
* CBC encryptor.
|
2479
|
-
*/CBC.Encryptor=/*#__PURE__*/function(_CBC){
|
2442
|
+
*/CBC.Encryptor=/*#__PURE__*/function(_CBC){function _class(){_classCallCheck(this,_class);return _callSuper(this,_class,arguments);}_inherits(_class,_CBC);return _createClass(_class,[{key:"processBlock",value:/**
|
2480
2443
|
* Processes the data block at offset.
|
2481
2444
|
*
|
2482
2445
|
* @param {Array} words The data words to operate on.
|
@@ -2488,9 +2451,9 @@ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
|
|
2488
2451
|
*/function processBlock(words,offset){// Shortcuts
|
2489
2452
|
var cipher=this._cipher;var blockSize=cipher.blockSize;// XOR and encrypt
|
2490
2453
|
xorBlock.call(this,words,offset,blockSize);cipher.encryptBlock(words,offset);// Remember this block to use with next block
|
2491
|
-
this._prevBlock=words.slice(offset,offset+blockSize);}}]);
|
2454
|
+
this._prevBlock=words.slice(offset,offset+blockSize);}}]);}(CBC);/**
|
2492
2455
|
* CBC decryptor.
|
2493
|
-
*/CBC.Decryptor=/*#__PURE__*/function(_CBC2){
|
2456
|
+
*/CBC.Decryptor=/*#__PURE__*/function(_CBC2){function _class2(){_classCallCheck(this,_class2);return _callSuper(this,_class2,arguments);}_inherits(_class2,_CBC2);return _createClass(_class2,[{key:"processBlock",value:/**
|
2494
2457
|
* Processes the data block at offset.
|
2495
2458
|
*
|
2496
2459
|
* @param {Array} words The data words to operate on.
|
@@ -2503,7 +2466,7 @@ this._prevBlock=words.slice(offset,offset+blockSize);}}]);return _class;}(CBC);/
|
|
2503
2466
|
var cipher=this._cipher;var blockSize=cipher.blockSize;// Remember this block to use with next block
|
2504
2467
|
var thisBlock=words.slice(offset,offset+blockSize);// Decrypt and XOR
|
2505
2468
|
cipher.decryptBlock(words,offset);xorBlock.call(this,words,offset,blockSize);// This block becomes the previous block
|
2506
|
-
this._prevBlock=thisBlock;}}]);
|
2469
|
+
this._prevBlock=thisBlock;}}]);}(CBC);/**
|
2507
2470
|
* PKCS #5/7 padding strategy.
|
2508
2471
|
*/var Pkcs7={/**
|
2509
2472
|
* Pads data using the algorithm defined in PKCS #5/7.
|
@@ -2539,12 +2502,12 @@ _data.sigBytes-=nPaddingBytes;}};/**
|
|
2539
2502
|
* @property {number} blockSize
|
2540
2503
|
*
|
2541
2504
|
* The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
|
2542
|
-
*/var BlockCipher=/*#__PURE__*/function(_Cipher2){
|
2505
|
+
*/var BlockCipher=/*#__PURE__*/function(_Cipher2){function BlockCipher(xformMode,key,cfg){var _this4;_classCallCheck(this,BlockCipher);/**
|
2543
2506
|
* Configuration options.
|
2544
2507
|
*
|
2545
2508
|
* @property {Mode} mode The block mode to use. Default: CBC
|
2546
2509
|
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
|
2547
|
-
*/_this4=_callSuper(this,BlockCipher,[xformMode,key,ObjectAssign({mode:CBC,padding:Pkcs7},cfg)]);_this4.blockSize=128/32;return _this4;}_createClass(BlockCipher,[{key:"reset",value:function reset(){var modeCreator;// Reset cipher
|
2510
|
+
*/_this4=_callSuper(this,BlockCipher,[xformMode,key,ObjectAssign({mode:CBC,padding:Pkcs7},cfg)]);_this4.blockSize=128/32;return _this4;}_inherits(BlockCipher,_Cipher2);return _createClass(BlockCipher,[{key:"reset",value:function reset(){var modeCreator;// Reset cipher
|
2548
2511
|
_get(_getPrototypeOf(BlockCipher.prototype),"reset",this).call(this);// Shortcuts
|
2549
2512
|
var cfg=this.cfg;var iv=cfg.iv,mode=cfg.mode;// Reset block mode
|
2550
2513
|
if(this._xformMode===this.constructor._ENC_XFORM_MODE){modeCreator=mode.createEncryptor;}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{modeCreator=mode.createDecryptor;// Keep at least one block in the buffer for unpadding
|
@@ -2554,7 +2517,7 @@ if(this._xformMode===this.constructor._ENC_XFORM_MODE){// Pad data
|
|
2554
2517
|
padding.pad(this._data,this.blockSize);// Process final blocks
|
2555
2518
|
finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
|
2556
2519
|
finalProcessedBlocks=this._process(!!'flush');// Unpad data
|
2557
|
-
padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);
|
2520
|
+
padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);}(Cipher);/**
|
2558
2521
|
* A collection of cipher parameters.
|
2559
2522
|
*
|
2560
2523
|
* @property {WordArray} ciphertext The raw ciphertext.
|
@@ -2567,7 +2530,7 @@ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);return Blo
|
|
2567
2530
|
* @property {number} blockSize The block size of the cipher.
|
2568
2531
|
* @property {Format} formatter
|
2569
2532
|
* The default formatting strategy to convert this cipher params object to a string.
|
2570
|
-
*/var CipherParams=/*#__PURE__*/function(_Base2){
|
2533
|
+
*/var CipherParams=/*#__PURE__*/function(_Base2){/**
|
2571
2534
|
* Initializes a newly created cipher params object.
|
2572
2535
|
*
|
2573
2536
|
* @param {Object} cipherParams An object with any of the possible cipher parameters.
|
@@ -2599,7 +2562,7 @@ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);return Blo
|
|
2599
2562
|
* var string = cipherParams + '';
|
2600
2563
|
* var string = cipherParams.toString();
|
2601
2564
|
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
|
2602
|
-
*/_createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);
|
2565
|
+
*/_inherits(CipherParams,_Base2);return _createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);}(Base);/**
|
2603
2566
|
* OpenSSL formatting strategy.
|
2604
2567
|
*/var OpenSSLFormatter={/**
|
2605
2568
|
* Converts a cipher params object to an OpenSSL-compatible string.
|
@@ -2634,7 +2597,7 @@ if(ciphertextWords[0]===0x53616c74&&ciphertextWords[1]===0x65645f5f){// Extract
|
|
2634
2597
|
salt=WordArray.create(ciphertextWords.slice(2,4));// Remove salt from ciphertext
|
2635
2598
|
ciphertextWords.splice(0,4);ciphertext.sigBytes-=16;}return CipherParams.create({ciphertext:ciphertext,salt:salt});}};/**
|
2636
2599
|
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
|
2637
|
-
*/var SerializableCipher=/*#__PURE__*/function(_Base3){
|
2600
|
+
*/var SerializableCipher=/*#__PURE__*/function(_Base3){function SerializableCipher(){_classCallCheck(this,SerializableCipher);return _callSuper(this,SerializableCipher,arguments);}_inherits(SerializableCipher,_Base3);return _createClass(SerializableCipher,null,[{key:"encrypt",value:/**
|
2638
2601
|
* Encrypts a message.
|
2639
2602
|
*
|
2640
2603
|
* @param {Cipher} cipher The cipher algorithm to use.
|
@@ -2696,7 +2659,7 @@ var plaintext=cipher.createDecryptor(key,_cfg).finalize(_ciphertext.ciphertext);
|
|
2696
2659
|
*
|
2697
2660
|
* var ciphertextParams = CryptoJS.lib.SerializableCipher
|
2698
2661
|
* ._parse(ciphertextStringOrParams, format);
|
2699
|
-
*/},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);
|
2662
|
+
*/},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);}(Base);/**
|
2700
2663
|
* Configuration options.
|
2701
2664
|
*
|
2702
2665
|
* @property {Formatter} format
|
@@ -2729,7 +2692,7 @@ var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*
|
|
2729
2692
|
return CipherParams.create({key:key,iv:iv,salt:_salt});}};/**
|
2730
2693
|
* A serializable cipher wrapper that derives the key from a password,
|
2731
2694
|
* and returns ciphertext as a serializable cipher params object.
|
2732
|
-
*/var PasswordBasedCipher=/*#__PURE__*/function(_SerializableCipher){
|
2695
|
+
*/var PasswordBasedCipher=/*#__PURE__*/function(_SerializableCipher){function PasswordBasedCipher(){_classCallCheck(this,PasswordBasedCipher);return _callSuper(this,PasswordBasedCipher,arguments);}_inherits(PasswordBasedCipher,_SerializableCipher);return _createClass(PasswordBasedCipher,null,[{key:"encrypt",value:/**
|
2733
2696
|
* Encrypts a message using a password.
|
2734
2697
|
*
|
2735
2698
|
* @param {Cipher} cipher The cipher algorithm to use.
|
@@ -2777,7 +2740,7 @@ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
|
|
2777
2740
|
_ciphertext=this._parse(_ciphertext,_cfg.format);// Derive key and other params
|
2778
2741
|
var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_ciphertext.salt,_cfg.hasher);// Add IV to config
|
2779
2742
|
_cfg.iv=derivedParams.iv;// Decrypt
|
2780
|
-
var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);
|
2743
|
+
var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);}(SerializableCipher);/**
|
2781
2744
|
* Configuration options.
|
2782
2745
|
*
|
2783
2746
|
* @property {KDF} kdf
|
@@ -2796,7 +2759,7 @@ t=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV
|
|
2796
2759
|
if(!x){xi=1;x=xi;}else {x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]];}}// Precomputed Rcon lookup
|
2797
2760
|
var RCON=[0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36];/**
|
2798
2761
|
* AES block cipher algorithm.
|
2799
|
-
*/var AESAlgo=/*#__PURE__*/function(_BlockCipher){
|
2762
|
+
*/var AESAlgo=/*#__PURE__*/function(_BlockCipher){function AESAlgo(){_classCallCheck(this,AESAlgo);return _callSuper(this,AESAlgo,arguments);}_inherits(AESAlgo,_BlockCipher);return _createClass(AESAlgo,[{key:"_doReset",value:function _doReset(){var t;// Skip reset of nRounds has been set before and key did not change
|
2800
2763
|
if(this._nRounds&&this._keyPriorReset===this._key){return;}// Shortcuts
|
2801
2764
|
this._keyPriorReset=this._key;var key=this._keyPriorReset;var keyWords=key.words;var keySize=key.sigBytes/4;// Compute number of rounds
|
2802
2765
|
this._nRounds=keySize+6;var nRounds=this._nRounds;// Compute number of key schedule rows
|
@@ -2816,7 +2779,7 @@ for(var round=1;round<nRounds;round+=1){// Shift rows, sub bytes, mix columns, a
|
|
2816
2779
|
var _t=SUB_MIX_0[s0>>>24]^SUB_MIX_1[s1>>>16&0xff]^SUB_MIX_2[s2>>>8&0xff]^SUB_MIX_3[s3&0xff]^keySchedule[ksRow];ksRow+=1;var _t2=SUB_MIX_0[s1>>>24]^SUB_MIX_1[s2>>>16&0xff]^SUB_MIX_2[s3>>>8&0xff]^SUB_MIX_3[s0&0xff]^keySchedule[ksRow];ksRow+=1;var _t3=SUB_MIX_0[s2>>>24]^SUB_MIX_1[s3>>>16&0xff]^SUB_MIX_2[s0>>>8&0xff]^SUB_MIX_3[s1&0xff]^keySchedule[ksRow];ksRow+=1;var _t4=SUB_MIX_0[s3>>>24]^SUB_MIX_1[s0>>>16&0xff]^SUB_MIX_2[s1>>>8&0xff]^SUB_MIX_3[s2&0xff]^keySchedule[ksRow];ksRow+=1;// Update state
|
2817
2780
|
s0=_t;s1=_t2;s2=_t3;s3=_t4;}// Shift rows, sub bytes, add round key
|
2818
2781
|
var t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&0xff]<<16|SBOX[s2>>>8&0xff]<<8|SBOX[s3&0xff])^keySchedule[ksRow];ksRow+=1;var t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&0xff]<<16|SBOX[s3>>>8&0xff]<<8|SBOX[s0&0xff])^keySchedule[ksRow];ksRow+=1;var t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&0xff]<<16|SBOX[s0>>>8&0xff]<<8|SBOX[s1&0xff])^keySchedule[ksRow];ksRow+=1;var t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&0xff]<<16|SBOX[s1>>>8&0xff]<<8|SBOX[s2&0xff])^keySchedule[ksRow];ksRow+=1;// Set output
|
2819
|
-
_M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);
|
2782
|
+
_M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);}(BlockCipher);AESAlgo.keySize=256/32;/**
|
2820
2783
|
* Shortcut functions to the cipher's object interface.
|
2821
2784
|
*
|
2822
2785
|
* @example
|
@@ -2890,11 +2853,11 @@ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:he
|
|
2890
2853
|
// TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
|
2891
2854
|
var PluginsManager=/*#__PURE__*/function(){function PluginsManager(engine,errorHandler,logger){_classCallCheck(this,PluginsManager);this.engine=engine;this.errorHandler=errorHandler;this.logger=logger;this.onError=this.onError.bind(this);}/**
|
2892
2855
|
* Orchestrate the plugin loading and registering
|
2893
|
-
*/_createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value='pluginsLoading';// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
|
2856
|
+
*/return _createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value='pluginsLoading';// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
|
2894
2857
|
this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
|
2895
2858
|
* Update state based on plugin loaded status
|
2896
2859
|
*/ // eslint-disable-next-line class-methods-use-this
|
2897
|
-
},{key:"attachEffects",value:function attachEffects(){
|
2860
|
+
},{key:"attachEffects",value:function attachEffects(){E(function(){var isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){r(function(){state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
|
2898
2861
|
// Should we stop here or should we progress?
|
2899
2862
|
state.lifecycle.status.value='pluginsReady';});}});}/**
|
2900
2863
|
* Determine the list of plugins that should be loaded based on sourceConfig & load options
|
@@ -2904,7 +2867,7 @@ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!plug
|
|
2904
2867
|
);_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(MISCONFIGURED_PLUGINS_WARNING(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
|
2905
2868
|
* Determine the list of plugins that should be activated
|
2906
2869
|
*/},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
2907
|
-
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(','))));}
|
2870
|
+
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;});}/**
|
2908
2871
|
* Register plugins that are direct imports to PluginEngine
|
2909
2872
|
*/},{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()]);}});}/**
|
2910
2873
|
* Register plugins that are dynamic imports to PluginEngine
|
@@ -2918,7 +2881,7 @@ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.fai
|
|
2918
2881
|
*/},{key:"register",value:function register(plugins){var _this4=this;plugins.forEach(function(plugin){try{_this4.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this4.onError(e);}});}// TODO: Implement reset API instead
|
2919
2882
|
},{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this5=this;Object.values(pluginsInventory).forEach(function(localPlugin){try{_this5.engine.unregister(localPlugin().name);}catch(e){_this5.onError(e);}});}/**
|
2920
2883
|
* Handle errors
|
2921
|
-
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);
|
2884
|
+
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);}();
|
2922
2885
|
|
2923
2886
|
/**
|
2924
2887
|
* Utility to parse XHR JSON response
|
@@ -2940,7 +2903,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
2940
2903
|
* Service to handle data communication with APIs
|
2941
2904
|
*/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);}/**
|
2942
2905
|
* Implement requests in a blocking way
|
2943
|
-
*/_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;}()/**
|
2906
|
+
*/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;}()/**
|
2944
2907
|
* Implement requests in a non-blocking way
|
2945
2908
|
*/)},{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);}});}/**
|
2946
2909
|
* Handle errors
|
@@ -2948,7 +2911,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
2948
2911
|
* Set basic authentication header (eg writekey)
|
2949
2912
|
*/},{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);}/**
|
2950
2913
|
* Clear basic authentication header
|
2951
|
-
*/},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);
|
2914
|
+
*/},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
|
2952
2915
|
|
2953
2916
|
var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_COOKIE='clientDataInCookie';var CLIENT_DATA_STORE_LS='clientDataInLocalStorage';var CLIENT_DATA_STORE_MEMORY='clientDataInMemory';var CLIENT_DATA_STORE_SESSION='clientDataInSessionStorage';var USER_SESSION_KEYS=['userId','userTraits','anonymousId','groupId','groupTraits','initialReferrer','initialReferringDomain','sessionInfo','authToken'];
|
2954
2917
|
|
@@ -2964,16 +2927,17 @@ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:fu
|
|
2964
2927
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
2965
2928
|
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;}});};
|
2966
2929
|
|
2967
|
-
var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);}
|
2930
|
+
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
|
2931
|
+
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\./));};
|
2968
2932
|
|
2969
2933
|
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();});}};
|
2970
2934
|
|
2971
2935
|
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
|
2972
2936
|
// the polyfill service serves them under the same feature name, "URL".
|
2973
|
-
URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
|
2937
|
+
URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Object.fromEntries':function ObjectFromEntries(){return !isFunction(globalThis.Object.fromEntries);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
|
2974
2938
|
// the polyfill service serves them under the same feature name, "TextEncoder".
|
2975
2939
|
TextEncoder:function TextEncoder(){return !isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder);},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame)||!isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},'navigator.sendBeacon':function navigatorSendBeacon(){return !isFunction(globalThis.navigator.sendBeacon);},// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
|
2976
|
-
ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
|
2940
|
+
ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);},Set:function Set(){return !isFunction(globalThis.Set);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
|
2977
2941
|
|
2978
2942
|
var getScreenDetails=function getScreenDetails(){var screenDetails={density:0,width:0,height:0,innerWidth:0,innerHeight:0};screenDetails={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};return screenDetails;};
|
2979
2943
|
|
@@ -3031,18 +2995,18 @@ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=dom
|
|
3031
2995
|
/**
|
3032
2996
|
* A storage utility to persist values in cookies via Storage interface
|
3033
2997
|
*/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
|
3034
|
-
return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}_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.logger);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
|
2998
|
+
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.logger);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
|
3035
2999
|
},{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
|
3036
3000
|
},{key:"clear",value:function clear(){// Not implemented
|
3037
3001
|
// getting a list of all cookie storage keys and remove all values
|
3038
3002
|
// sounds risky to do as it will take on all top domain cookies
|
3039
3003
|
// better to explicitly clear specific ones if needed
|
3040
3004
|
}},{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
|
3041
|
-
},{key:"keys",value:function keys(){return Object.keys(cookie());}}]);
|
3005
|
+
},{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();_defineProperty(CookieStorage,"globalSingleton",null);
|
3042
3006
|
|
3043
3007
|
/**
|
3044
3008
|
* A storage utility to retain values in memory via Storage interface
|
3045
|
-
*/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:{});}_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);}}]);
|
3009
|
+
*/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);
|
3046
3010
|
|
3047
3011
|
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
3048
3012
|
|
@@ -3064,19 +3028,19 @@ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=va
|
|
3064
3028
|
// https://www.npmjs.com/package/storejs
|
3065
3029
|
/**
|
3066
3030
|
* A storage utility to persist values in localstorage via Storage interface
|
3067
|
-
*/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);}_createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE,this,this.logger);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
|
3031
|
+
*/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,this.logger);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
|
3068
3032
|
},{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
|
3069
|
-
},{key:"keys",value:function keys(){return store.keys();}}]);
|
3033
|
+
},{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
|
3070
3034
|
|
3071
3035
|
/**
|
3072
3036
|
* A storage utility to persist values in SessionStorage via Storage interface
|
3073
|
-
*/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);_defineProperty(this,"store",globalThis.sessionStorage);this.options=getDefaultSessionStorageOptions();this.logger=logger;this.configure(options);}_createClass(SessionStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){this.store.clear();this.length=0;}},{key:"key",value:function key(index){return this.store.key(index);}},{key:"keys",value:function keys(){var 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;}}]);
|
3037
|
+
*/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);_defineProperty(this,"store",globalThis.sessionStorage);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,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){this.store.clear();this.length=0;}},{key:"key",value:function key(index){return this.store.key(index);}},{key:"keys",value:function keys(){var 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);
|
3074
3038
|
|
3075
3039
|
/**
|
3076
3040
|
* A utility to retrieve the storage singleton instance by type
|
3077
3041
|
*/var getStorageEngine=function getStorageEngine(type){switch(type){case LOCAL_STORAGE:return defaultLocalStorage;case SESSION_STORAGE:return defaultSessionStorage;case MEMORY_STORAGE:return defaultInMemoryStorage;case COOKIE_STORAGE:return new CookieStorage({},defaultLogger);default:return defaultInMemoryStorage;}};/**
|
3078
3042
|
* Configure cookie storage singleton
|
3079
|
-
*/var configureCookieStorageEngine=function configureCookieStorageEngine(options){new CookieStorage({},defaultLogger).configure(options);};/**
|
3043
|
+
*/var configureCookieStorageEngine=function configureCookieStorageEngine(options){var cookieStorageOptions=new CookieStorage({},defaultLogger).configure(options);state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorageOptions.path,domain:cookieStorageOptions.domain,samesite:cookieStorageOptions.samesite,expires:cookieStorageOptions.expires,secure:cookieStorageOptions.secure};};/**
|
3080
3044
|
* Configure local storage singleton
|
3081
3045
|
*/var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
|
3082
3046
|
* Configure in memory storage singleton
|
@@ -3090,7 +3054,7 @@ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=va
|
|
3090
3054
|
* Store Implementation with dedicated storage
|
3091
3055
|
*/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;}/**
|
3092
3056
|
* Ensure the key is valid and with correct format
|
3093
|
-
*/_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
|
3057
|
+
*/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
|
3094
3058
|
var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
|
3095
3059
|
* Switch to inMemoryEngine, bringing any existing data with.
|
3096
3060
|
*/},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var name=this.name,id=this.id,validKeys=this.validKeys,noCompoundKey=this.noCompoundKey;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
|
@@ -3118,7 +3082,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3118
3082
|
* Extension point to use with encryption plugins
|
3119
3083
|
*/},{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:'';}/**
|
3120
3084
|
* Handle errors
|
3121
|
-
*/},{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;}}}]);
|
3085
|
+
*/},{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;}}}]);}();
|
3122
3086
|
|
3123
3087
|
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;};
|
3124
3088
|
|
@@ -3126,7 +3090,7 @@ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConse
|
|
3126
3090
|
* A service to manage stores & available storage client configurations
|
3127
3091
|
*/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);}/**
|
3128
3092
|
* Configure available storage client instances
|
3129
|
-
*/_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;}/**
|
3093
|
+
*/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;}/**
|
3130
3094
|
* Create store to persist data used by the SDK like session, used details etc
|
3131
3095
|
*/},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
3132
3096
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
@@ -3134,14 +3098,14 @@ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConse
|
|
3134
3098
|
// that needs auto migration
|
3135
3099
|
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
|
3136
3100
|
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
|
3137
|
-
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:USER_SESSION_STORAGE_KEYS[storageKey]}));});
|
3101
|
+
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:USER_SESSION_STORAGE_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
|
3138
3102
|
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;}/**
|
3139
3103
|
* Create a new store
|
3140
3104
|
*/},{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];}/**
|
3141
3105
|
* Retrieve a store
|
3142
3106
|
*/},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
|
3143
3107
|
* Handle errors
|
3144
|
-
*/},{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;}}}]);
|
3108
|
+
*/},{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;}}}]);}();
|
3145
3109
|
|
3146
3110
|
/**
|
3147
3111
|
* Removes trailing slash from url
|
@@ -3169,7 +3133,13 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
|
|
3169
3133
|
*/var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
3170
3134
|
}return urlWithoutHash;};
|
3171
3135
|
|
3172
|
-
var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(dataPlaneUrl&&!isValidUrl(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};
|
3136
|
+
var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(dataPlaneUrl&&!isValidUrl(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomainUrl=function getTopDomainUrl(url){// Create a URL object
|
3137
|
+
var urlObj=new URL(url);// Extract the hostname and protocol
|
3138
|
+
var hostname=urlObj.hostname,protocol=urlObj.protocol;// Split the hostname into parts
|
3139
|
+
var parts=hostname.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
3140
|
+
if(parts.length>2){// Join the last two parts for the top-level domain
|
3141
|
+
topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
|
3142
|
+
topDomain=hostname;}return "".concat(protocol,"//").concat(topDomain);};var getDataServiceUrl=function getDataServiceUrl(endpoint){var url=getTopDomainUrl(window.location.href);var formattedEndpoint=endpoint.startsWith('/')?endpoint.substring(1):endpoint;return "".concat(url,"/").concat(formattedEndpoint);};
|
3173
3143
|
|
3174
3144
|
/**
|
3175
3145
|
* Plugins to be loaded in the plugins loadOption is not defined
|
@@ -3191,7 +3161,7 @@ var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)|
|
|
3191
3161
|
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3192
3162
|
|
3193
3163
|
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
|
3194
|
-
var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
|
3164
|
+
var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;normalizedLoadOpts.useServerSideCookies=normalizedLoadOpts.useServerSideCookies===true;if(normalizedLoadOpts.dataServiceEndpoint&&typeof normalizedLoadOpts.dataServiceEndpoint!=='string'){delete normalizedLoadOpts.dataServiceEndpoint;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
|
3195
3165
|
// doesn't seem to throw errors for empty URLs
|
3196
3166
|
// TODO: Need to improve this check to find out if the URL is valid or not
|
3197
3167
|
if(configUrl){try{var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}catch(err){logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
|
@@ -3263,8 +3233,8 @@ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,con
|
|
3263
3233
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3264
3234
|
logger===null||logger===void 0||logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var 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
|
3265
3235
|
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
|
3266
|
-
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));}
|
3267
|
-
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));}
|
3236
|
+
var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(function(){state.storage.type.value=storageType;state.storage.cookie.value=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie;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
|
3237
|
+
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$va;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
|
3268
3238
|
// if it is not already initialized and
|
3269
3239
|
// if consent management is enabled
|
3270
3240
|
enabled:((_state$loadOptions$va=state.loadOptions.value.preConsent)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
|
@@ -3272,7 +3242,7 @@ enabled:((_state$loadOptions$va=state.loadOptions.value.preConsent)===null||_sta
|
|
3272
3242
|
* @param resp Source config response
|
3273
3243
|
* @param logger Logger instance
|
3274
3244
|
*/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
|
3275
|
-
if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}
|
3245
|
+
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;});}};
|
3276
3246
|
|
3277
3247
|
/**
|
3278
3248
|
* A function that determines integration SDK loading path
|
@@ -3291,13 +3261,13 @@ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_
|
|
3291
3261
|
if(customPluginsCDNPath){pluginsCDNPath=removeTrailingSlashes(customPluginsCDNPath);if(!pluginsCDNPath||pluginsCDNPath&&!isValidUrl(pluginsCDNPath)){throw new Error(PLUGINS_CDN_BASE_URL_ERROR);}return pluginsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
|
3292
3262
|
var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
|
3293
3263
|
|
3294
|
-
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);}_createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;
|
3264
|
+
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);});}/**
|
3295
3265
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3296
3266
|
* config related information in global state
|
3297
3267
|
*/},{key:"init",value:function init(){var _this2=this;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;// determine the path to fetch integration SDK from
|
3298
3268
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
3299
|
-
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
|
3300
|
-
|
3269
|
+
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl;// set application lifecycle state in global state
|
3270
|
+
r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,_this2.logger);if(useServerSideCookies){state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT);if(isValidUrl(dataServiceUrl)){state.serverCookies.dataServiceUrl.value=removeTrailingSlashes(dataServiceUrl);}else {state.serverCookies.isEnabledServerSideCookies.value=false;}}});this.getConfig();}/**
|
3301
3271
|
* Handle errors
|
3302
3272
|
*/},{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;}}/**
|
3303
3273
|
* A callback function that is executed once we fetch the source config response.
|
@@ -3307,10 +3277,10 @@ n(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycl
|
|
3307
3277
|
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;}// set the values in state for reporting slice
|
3308
3278
|
updateReportingState(res,this.logger);// determine the dataPlane url
|
3309
3279
|
var dataPlaneUrl=resolveDataPlaneUrl(res.source.dataplanes,state.lifecycle.dataPlaneUrl.value,state.loadOptions.value.residencyServer,this.logger);if(!dataPlaneUrl){this.onError(new Error(DATA_PLANE_URL_ERROR),undefined,true);return;}var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
3310
|
-
|
3311
|
-
state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
|
3280
|
+
r(function(){var _state$loadOptions$va2;// set source related information in state
|
3281
|
+
state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
|
3312
3282
|
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
3313
|
-
state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$
|
3283
|
+
state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va2=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:[];updateConsentsState(res);// set application lifecycle state
|
3314
3284
|
// Cast to string as we are sure that the value is not undefined
|
3315
3285
|
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value='configured';});}/**
|
3316
3286
|
* A function to fetch source config either from /sourceConfig endpoint
|
@@ -3318,7 +3288,7 @@ state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);sta
|
|
3318
3288
|
* @returns
|
3319
3289
|
*/},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// fetch source config from the function
|
3320
3290
|
var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// fetch source config from config url API
|
3321
|
-
this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);
|
3291
|
+
this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
|
3322
3292
|
|
3323
3293
|
/**
|
3324
3294
|
* To get the timezone of the user
|
@@ -3347,14 +3317,14 @@ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}
|
|
3347
3317
|
var POLYFILL_URL="https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=".concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
|
3348
3318
|
var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
|
3349
3319
|
|
3350
|
-
var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}_createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
|
3320
|
+
var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}return _createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
|
3351
3321
|
* Detect supported capabilities and set values in state
|
3352
3322
|
*/ // eslint-disable-next-line class-methods-use-this
|
3353
|
-
},{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;
|
3323
|
+
},{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;r(function(){// Storage related details
|
3354
3324
|
state.capabilities.storage.isCookieStorageAvailable.value=isStorageAvailable(COOKIE_STORAGE,getStorageEngine(COOKIE_STORAGE),_this.logger);state.capabilities.storage.isLocalStorageAvailable.value=isStorageAvailable(LOCAL_STORAGE,undefined,_this.logger);state.capabilities.storage.isSessionStorageAvailable.value=isStorageAvailable(SESSION_STORAGE,undefined,_this.logger);// Browser feature detection details
|
3355
3325
|
state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
|
3356
3326
|
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
|
3357
|
-
|
3327
|
+
E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3358
3328
|
* Detect if polyfills are required and then load script from polyfill URL
|
3359
3329
|
*/},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _state$loadOptions$va,_this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var polyfillUrl=(_state$loadOptions$va=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POLYFILL_URL;var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){var _this$externalSrcLoad;var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
|
3360
3330
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
@@ -3367,7 +3337,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
|
|
3367
3337
|
},{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
|
3368
3338
|
* Handles error
|
3369
3339
|
* @param error The error object
|
3370
|
-
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);
|
3340
|
+
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);}();
|
3371
3341
|
|
3372
3342
|
var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
3373
3343
|
var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
@@ -3434,7 +3404,7 @@ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
|
|
3434
3404
|
* @param rudderContext Generated rudder event
|
3435
3405
|
* @param options API options
|
3436
3406
|
* @param logger Logger instance
|
3437
|
-
*/var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else
|
3407
|
+
*/var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else;}});return context;};/**
|
3438
3408
|
* A function to determine whether SDK should use the integration option provided in load call
|
3439
3409
|
* @returns boolean
|
3440
3410
|
*/var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){var _state$consents$postC;return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&(isObjectLiteralAndNotNull((_state$consents$postC=state.consents.postConsent.value)===null||_state$consents$postC===void 0?void 0:_state$consents$postC.integrations)||isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value));};/**
|
@@ -3468,7 +3438,7 @@ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logge
|
|
3468
3438
|
* @param name Page name
|
3469
3439
|
* @param properties Page properties
|
3470
3440
|
* @param options API options
|
3471
|
-
*/_createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props.name=name;props.category=category;props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
|
3441
|
+
*/return _createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props.name=name;props.category=category;props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
|
3472
3442
|
* Generate a 'track' event based on the user-input fields
|
3473
3443
|
* @param event The event name
|
3474
3444
|
* @param properties Event properties
|
@@ -3493,7 +3463,7 @@ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enric
|
|
3493
3463
|
* Generates a new RudderEvent object based on the user-input fields
|
3494
3464
|
* @param event API event parameters object
|
3495
3465
|
* @returns A RudderEvent object
|
3496
|
-
*/},{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;}}]);
|
3466
|
+
*/},{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;}}]);}();
|
3497
3467
|
|
3498
3468
|
/**
|
3499
3469
|
* A service to generate valid event payloads and queue them for processing
|
@@ -3505,19 +3475,20 @@ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enric
|
|
3505
3475
|
* @param logger Logger object
|
3506
3476
|
*/function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);this.onError=this.onError.bind(this);}/**
|
3507
3477
|
* Initializes the event manager
|
3508
|
-
*/_createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
|
3478
|
+
*/return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
|
3509
3479
|
* Consumes a new incoming event
|
3510
3480
|
* @param event Incoming event data
|
3511
3481
|
*/},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);if(rudderEvent){this.eventRepository.enqueue(rudderEvent,event.callback);}else {this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));}}/**
|
3512
3482
|
* Handles error
|
3513
3483
|
* @param error The error object
|
3514
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);
|
3484
|
+
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3515
3485
|
|
3516
|
-
var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
|
3486
|
+
var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager,httpClient){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);}/**
|
3517
3487
|
* Initialize User session with values from storage
|
3518
|
-
*/_createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
3488
|
+
*/return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
3519
3489
|
this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
3520
|
-
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
|
3490
|
+
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),{},{autoTrack:configuredSessionTrackingInfo.autoTrack&&initialSessionInfo.manualTrack!==true});}state.session.sessionInfo.value=this.isPersistenceEnabledForStorageEntry('sessionInfo')?sessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;// If auto session tracking is enabled start the session tracking
|
3491
|
+
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(USER_SESSION_STORAGE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(USER_SESSION_STORAGE_KEYS[key],value);}store.remove(USER_SESSION_STORAGE_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(USER_SESSION_STORAGE_KEYS).forEach(function(storageKey){var storageEntry=USER_SESSION_STORAGE_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
|
3521
3492
|
// as those values indicate there is no need for migration or
|
3522
3493
|
// migration failed
|
3523
3494
|
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
|
@@ -3526,14 +3497,34 @@ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTi
|
|
3526
3497
|
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};}/**
|
3527
3498
|
* Handles error
|
3528
3499
|
* @param error The error object
|
3529
|
-
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER);}else {throw error;}}/**
|
3500
|
+
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
|
3501
|
+
* A function to encrypt the cookie value and return the encrypted data
|
3502
|
+
* @param cookieData
|
3503
|
+
* @param store
|
3504
|
+
* @returns
|
3505
|
+
*/},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookieData,store){var _this3=this;var encryptedCookieData=[];cookieData.forEach(function(e){var encryptedValue=e.value===''?e.value:store===null||store===void 0?void 0:store.encrypt(stringifyWithoutCircular(e.value,false,[],_this3.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:e.name,value:encryptedValue});}});return encryptedCookieData;}/**
|
3506
|
+
* A function that makes request to data service to set the cookie
|
3507
|
+
* @param encryptedCookieData
|
3508
|
+
* @param callback
|
3509
|
+
*/},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true},isRawResponse:true,callback:callback});}/**
|
3510
|
+
* A function to make an external request to set the cookie from server side
|
3511
|
+
* @param key cookie name
|
3512
|
+
* @param value encrypted cookie value
|
3513
|
+
*/},{key:"setServerSideCookie",value:function setServerSideCookie(cookieData,cb,store){var _this4=this;try{// encrypt cookies values
|
3514
|
+
var encryptedCookieData=this.getEncryptedCookieData(cookieData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
3515
|
+
this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookieData.forEach(function(each){var cookieValue=store===null||store===void 0?void 0:store.get(each.name);if(each.value){if(cookieValue!==each.value){var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(each.name));if(cb){cb(each.name,each.value);}}}else if(cookieValue){var _this4$logger2;(_this4$logger2=_this4.logger)===null||_this4$logger2===void 0||_this4$logger2.error(FAILED_TO_REMOVE_COOKIE_FROM_SERVER_ERROR(each.name));}});}else {var _this4$logger3,_details$xhr2;(_this4$logger3=_this4.logger)===null||_this4$logger3===void 0||_this4$logger3.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookieData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookieData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
|
3530
3516
|
* A function to sync values in storage
|
3531
3517
|
* @param sessionKey
|
3532
3518
|
* @param value
|
3533
|
-
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey
|
3519
|
+
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
|
3520
|
+
// set the cookie from server side
|
3521
|
+
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){this.setServerSideCookie([{name:key,value:value}],function(cookieName,cookieValue){curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);}else {curStore===null||curStore===void 0||curStore.set(key,value);}}else if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){// remove cookie that is set from server side
|
3522
|
+
// TODO: Test cookies set from server side can be cleared from client side
|
3523
|
+
// and make appropriate changes.
|
3524
|
+
this.setServerSideCookie([{name:key,value:''}],undefined,curStore);}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
|
3534
3525
|
* Function to update storage whenever state value changes
|
3535
|
-
*/},{key:"registerEffects",value:function registerEffects(){var
|
3536
|
-
USER_SESSION_KEYS.forEach(function(sessionKey){
|
3526
|
+
*/},{key:"registerEffects",value:function registerEffects(){var _this5=this;// This will work as long as the user session entry key names are same as the state keys
|
3527
|
+
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this5.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
|
3537
3528
|
* Sets anonymous id in the following precedence:
|
3538
3529
|
*
|
3539
3530
|
* 1. anonymousId: Id directly provided to the function.
|
@@ -3573,30 +3564,35 @@ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||
|
|
3573
3564
|
*/},{key:"getAuthToken",value:function getAuthToken(){return this.getEntryValue('authToken');}/**
|
3574
3565
|
* If session is active it returns the sessionId
|
3575
3566
|
* @returns
|
3576
|
-
*/},{key:"getSessionId",value:function getSessionId(){var sessionInfo=
|
3577
|
-
* A function to
|
3578
|
-
|
3579
|
-
|
3580
|
-
|
3567
|
+
*/},{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;}/**
|
3568
|
+
* A function to keep the session information up to date in the state
|
3569
|
+
* before using it for building event payloads.
|
3570
|
+
*/},{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.
|
3571
|
+
// So, we needn't update the session info.
|
3572
|
+
//
|
3573
|
+
// For other scenarios,
|
3574
|
+
// 1. If sessionStart is undefined, then it's a new session.
|
3575
|
+
// Mark it as sessionStart.
|
3576
|
+
// 2. If sessionStart is true, then need to flip it for the future events.
|
3577
|
+
if(sessionInfo.sessionStart===undefined){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:true});}else if(sessionInfo.sessionStart){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:false});}}}/**
|
3581
3578
|
* Reset state values
|
3582
3579
|
* @param resetAnonymousId
|
3583
3580
|
* @param noNewSessionStart
|
3584
3581
|
* @returns
|
3585
|
-
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var
|
3586
|
-
|
3587
|
-
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
|
3582
|
+
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this6=this;var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack;r(function(){session.userId.value=DEFAULT_USER_SESSION_VALUES.userId;session.userTraits.value=DEFAULT_USER_SESSION_VALUES.userTraits;session.groupId.value=DEFAULT_USER_SESSION_VALUES.groupId;session.groupTraits.value=DEFAULT_USER_SESSION_VALUES.groupTraits;session.authToken.value=DEFAULT_USER_SESSION_VALUES.authToken;if(resetAnonymousId){// This will generate a new anonymous ID
|
3583
|
+
_this6.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;_this6.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){_this6.startManualTrackingInternal();}});}/**
|
3588
3584
|
* Set user Id
|
3589
3585
|
* @param userId
|
3590
3586
|
*/},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
3591
3587
|
* Set user traits
|
3592
3588
|
* @param traits
|
3593
|
-
*/},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&traits?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:
|
3589
|
+
*/},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&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;}/**
|
3594
3590
|
* Set group Id
|
3595
3591
|
* @param groupId
|
3596
3592
|
*/},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
|
3597
3593
|
* Set group traits
|
3598
3594
|
* @param traits
|
3599
|
-
*/},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&traits?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:
|
3595
|
+
*/},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&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;}/**
|
3600
3596
|
* Set initial referrer
|
3601
3597
|
* @param referrer
|
3602
3598
|
*/},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
|
@@ -3604,7 +3600,7 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3604
3600
|
* @param {String} referringDomain
|
3605
3601
|
*/},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
|
3606
3602
|
* A function to check for existing session details and depending on that create a new session
|
3607
|
-
*/},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(){
|
3603
|
+
*/},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(sessionInfo){if(hasSessionExpired(sessionInfo.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(sessionInfo.timeout);}else {var timestamp=Date.now();var timeout=sessionInfo.timeout;state.session.sessionInfo.value=mergeDeepRight(sessionInfo,{expiresAt:timestamp+timeout// set the expiry time of the session
|
3608
3604
|
});}}/**
|
3609
3605
|
* A function method to start a manual session
|
3610
3606
|
* @param {number} id session identifier
|
@@ -3613,10 +3609,10 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3613
3609
|
* An internal function to start manual session
|
3614
3610
|
*/},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
|
3615
3611
|
* A public method to end an ongoing session.
|
3616
|
-
*/},{key:"end",value:function end(){state.session.sessionInfo.value=
|
3612
|
+
*/},{key:"end",value:function end(){state.session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;}/**
|
3617
3613
|
* Set auth token
|
3618
3614
|
* @param userId
|
3619
|
-
*/},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);
|
3615
|
+
*/},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
|
3620
3616
|
|
3621
3617
|
var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
|
3622
3618
|
|
@@ -3644,12 +3640,12 @@ var eventIntgConfig=(_event$integrations=event.integrations)!==null&&_event$inte
|
|
3644
3640
|
* @param logger Logger object
|
3645
3641
|
*/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);}/**
|
3646
3642
|
* Initializes the event repository
|
3647
|
-
*/_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
|
3648
|
-
|
3643
|
+
*/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
|
3644
|
+
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
|
3649
3645
|
// However, events will be enqueued for now.
|
3650
3646
|
// At the time of processing the events, the integrations config data from destinations
|
3651
3647
|
// is merged into the event object
|
3652
|
-
var timeoutId;
|
3648
|
+
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
|
3653
3649
|
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();}}/**
|
3654
3650
|
* Enqueues the event for processing
|
3655
3651
|
* @param event RudderEvent object
|
@@ -3662,7 +3658,7 @@ callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onErro
|
|
3662
3658
|
* @param error The error object
|
3663
3659
|
* @param customMessage a message
|
3664
3660
|
* @param shouldAlwaysThrow if it should throw or use logger
|
3665
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);
|
3661
|
+
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3666
3662
|
|
3667
3663
|
var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
|
3668
3664
|
|
@@ -3672,16 +3668,16 @@ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new Custom
|
|
3672
3668
|
* Initialize services and components or use default ones if singletons
|
3673
3669
|
*/function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;}/**
|
3674
3670
|
* Start application lifecycle if not already started
|
3675
|
-
*/_createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}var clonedDataPlaneUrl=clone(dataPlaneUrl);var clonedLoadOptions=clone(loadOptions);// dataPlaneUrl is not provided
|
3671
|
+
*/return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}var clonedDataPlaneUrl=clone(dataPlaneUrl);var clonedLoadOptions=clone(loadOptions);// dataPlaneUrl is not provided
|
3676
3672
|
if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
|
3677
|
-
|
3673
|
+
r(function(){state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
|
3678
3674
|
if(state.loadOptions.value.logLevel){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.loadOptions.value.logLevel);}// Expose state to global objects
|
3679
3675
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
3680
3676
|
// State application lifecycle
|
3681
3677
|
this.startLifecycle();}// Start lifecycle methods
|
3682
3678
|
/**
|
3683
3679
|
* Orchestrate the lifecycle of the application phases/status
|
3684
|
-
*/},{key:"startLifecycle",value:function startLifecycle(){var _this=this;
|
3680
|
+
*/},{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
|
3685
3681
|
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
|
3686
3682
|
if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
|
3687
3683
|
* Load browser polyfill if required
|
@@ -3689,7 +3685,7 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
|
|
3689
3685
|
* Enqueue in SDK preload buffer events, used from preloadBuffer component
|
3690
3686
|
*/},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
|
3691
3687
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
3692
|
-
*/},{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.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
3688
|
+
*/},{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);}/**
|
3693
3689
|
* Load configuration
|
3694
3690
|
*/},{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();}/**
|
3695
3691
|
* Initialize the storage and event queue
|
@@ -3708,7 +3704,7 @@ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window o
|
|
3708
3704
|
// as this will prevent us from supporting multiple SDK instances in the same page
|
3709
3705
|
// Execute onLoaded callback if provided in load options
|
3710
3706
|
if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
|
3711
|
-
|
3707
|
+
r(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
|
3712
3708
|
dispatchSDKEvent('RSA_Initialised');}/**
|
3713
3709
|
* Emit ready event
|
3714
3710
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -3724,7 +3720,7 @@ var bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEven
|
|
3724
3720
|
*/},{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
|
3725
3721
|
(_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
|
3726
3722
|
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
|
3727
|
-
|
3723
|
+
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;});}});}/**
|
3728
3724
|
* Move to the ready state
|
3729
3725
|
*/ // eslint-disable-next-line class-methods-use-this
|
3730
3726
|
},{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
|
@@ -3748,14 +3744,14 @@ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].
|
|
3748
3744
|
},{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
3749
3745
|
},{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
3750
3746
|
},{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
|
3751
|
-
},{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");
|
3747
|
+
},{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
|
3752
3748
|
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
|
3753
3749
|
(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
|
3754
3750
|
(_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===void 0||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
|
3755
3751
|
(_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
|
3756
3752
|
// events buffer array so that any other preload events (mainly from query string API) will be processed first.
|
3757
3753
|
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
|
3758
|
-
}]);
|
3754
|
+
}]);}();
|
3759
3755
|
|
3760
3756
|
/*
|
3761
3757
|
* RudderAnalytics facade singleton that is exposed as global object and will:
|
@@ -3773,7 +3769,7 @@ globalThis.rudderanalytics=this;}/**
|
|
3773
3769
|
* Set instance to use if no specific writeKey is provided in methods
|
3774
3770
|
* automatically for the first created instance
|
3775
3771
|
* TODO: to support multiple analytics instances in the near future
|
3776
|
-
*/_createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
3772
|
+
*/return _createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
3777
3773
|
* Retrieve an existing analytics instance
|
3778
3774
|
*/},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){var instanceId=writeKey!==null&&writeKey!==void 0?writeKey:this.defaultAnalyticsKey;var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
|
3779
3775
|
* Create new analytics instance and trigger application lifecycle start
|
@@ -3801,6 +3797,6 @@ this.load.apply(null,loadEvent);}}/**
|
|
3801
3797
|
* Process alias arguments and forward to page call
|
3802
3798
|
*/},{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
|
3803
3799
|
* Process group arguments and forward to page call
|
3804
|
-
*/},{key:"group",value:function group(groupId,traits,options,callback){if(arguments.length===0){this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP));return;}this.getAnalyticsInstance().group(groupArgumentsToCallOptions(groupId,traits,options,callback));}},{key:"reset",value:function reset(resetAnonymousId){this.getAnalyticsInstance().reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){return this.getAnalyticsInstance().getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){this.getAnalyticsInstance().setAnonymousId(anonymousId,rudderAmpLinkerParam);}},{key:"getUserId",value:function getUserId(){return this.getAnalyticsInstance().getUserId();}},{key:"getUserTraits",value:function getUserTraits(){return this.getAnalyticsInstance().getUserTraits();}},{key:"getGroupId",value:function getGroupId(){return this.getAnalyticsInstance().getGroupId();}},{key:"getGroupTraits",value:function getGroupTraits(){return this.getAnalyticsInstance().getGroupTraits();}},{key:"startSession",value:function startSession(sessionId){return this.getAnalyticsInstance().startSession(sessionId);}},{key:"endSession",value:function endSession(){return this.getAnalyticsInstance().endSession();}},{key:"getSessionId",value:function getSessionId(){return this.getAnalyticsInstance().getSessionId();}},{key:"setAuthToken",value:function setAuthToken(token){return this.getAnalyticsInstance().setAuthToken(token);}},{key:"consent",value:function consent(options){return this.getAnalyticsInstance().consent(options);}}]);
|
3800
|
+
*/},{key:"group",value:function group(groupId,traits,options,callback){if(arguments.length===0){this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP));return;}this.getAnalyticsInstance().group(groupArgumentsToCallOptions(groupId,traits,options,callback));}},{key:"reset",value:function reset(resetAnonymousId){this.getAnalyticsInstance().reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){return this.getAnalyticsInstance().getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){this.getAnalyticsInstance().setAnonymousId(anonymousId,rudderAmpLinkerParam);}},{key:"getUserId",value:function getUserId(){return this.getAnalyticsInstance().getUserId();}},{key:"getUserTraits",value:function getUserTraits(){return this.getAnalyticsInstance().getUserTraits();}},{key:"getGroupId",value:function getGroupId(){return this.getAnalyticsInstance().getGroupId();}},{key:"getGroupTraits",value:function getGroupTraits(){return this.getAnalyticsInstance().getGroupTraits();}},{key:"startSession",value:function startSession(sessionId){return this.getAnalyticsInstance().startSession(sessionId);}},{key:"endSession",value:function endSession(){return this.getAnalyticsInstance().endSession();}},{key:"getSessionId",value:function getSessionId(){return this.getAnalyticsInstance().getSessionId();}},{key:"setAuthToken",value:function setAuthToken(token){return this.getAnalyticsInstance().setAuthToken(token);}},{key:"consent",value:function consent(options){return this.getAnalyticsInstance().consent(options);}}]);}();_defineProperty(RudderAnalytics,"globalSingleton",null);
|
3805
3801
|
|
3806
3802
|
exports.RudderAnalytics = RudderAnalytics;
|