@rudderstack/analytics-js 3.1.0 → 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 +21 -0
- package/dist/npm/index.d.ts +4 -1
- package/dist/npm/legacy/cjs/index.js +225 -229
- package/dist/npm/legacy/esm/index.js +225 -229
- package/dist/npm/legacy/umd/index.js +225 -229
- package/dist/npm/modern/bundled/cjs/index.js +136 -140
- package/dist/npm/modern/bundled/esm/index.js +136 -140
- package/dist/npm/modern/bundled/umd/index.js +136 -140
- package/dist/npm/modern/cjs/index.js +135 -139
- package/dist/npm/modern/content-script/cjs/index.js +135 -139
- package/dist/npm/modern/content-script/esm/index.js +135 -139
- package/dist/npm/modern/content-script/umd/index.js +135 -139
- package/dist/npm/modern/esm/index.js +135 -139
- package/dist/npm/modern/umd/index.js +135 -139
- package/package.json +7 -5
@@ -6,7 +6,7 @@ function _construct(t, e, r) {
|
|
6
6
|
var o = [null];
|
7
7
|
o.push.apply(o, e);
|
8
8
|
var p = new (t.bind.apply(t, o))();
|
9
|
-
return
|
9
|
+
return p;
|
10
10
|
}
|
11
11
|
function _isNativeReflectConstruct() {
|
12
12
|
try {
|
@@ -145,7 +145,7 @@ function _regeneratorRuntime() {
|
|
145
145
|
function makeInvokeMethod(e, r, n) {
|
146
146
|
var o = h;
|
147
147
|
return function (i, a) {
|
148
|
-
if (o === f) throw
|
148
|
+
if (o === f) throw Error("Generator is already running");
|
149
149
|
if (o === s) {
|
150
150
|
if ("throw" === i) throw a;
|
151
151
|
return {
|
@@ -287,7 +287,7 @@ function _regeneratorRuntime() {
|
|
287
287
|
} else if (c) {
|
288
288
|
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
289
289
|
} else {
|
290
|
-
if (!u) throw
|
290
|
+
if (!u) throw Error("try statement without catch or finally");
|
291
291
|
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
292
292
|
}
|
293
293
|
}
|
@@ -327,7 +327,7 @@ function _regeneratorRuntime() {
|
|
327
327
|
return o;
|
328
328
|
}
|
329
329
|
}
|
330
|
-
throw
|
330
|
+
throw Error("illegal catch attempt");
|
331
331
|
},
|
332
332
|
delegateYield: function (e, r, n) {
|
333
333
|
return this.delegate = {
|
@@ -350,7 +350,7 @@ function _toPrimitive(t, r) {
|
|
350
350
|
}
|
351
351
|
function _toPropertyKey(t) {
|
352
352
|
var i = _toPrimitive(t, "string");
|
353
|
-
return "symbol" == typeof i ? i :
|
353
|
+
return "symbol" == typeof i ? i : i + "";
|
354
354
|
}
|
355
355
|
function _typeof(o) {
|
356
356
|
"@babel/helpers - typeof";
|
@@ -519,7 +519,9 @@ function _nonIterableSpread() {
|
|
519
519
|
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
520
520
|
}
|
521
521
|
|
522
|
-
|
522
|
+
var _placeholder = {'@@functional/placeholder':true};
|
523
|
+
|
524
|
+
function _isPlaceholder(a){return a===_placeholder;}
|
523
525
|
|
524
526
|
/**
|
525
527
|
* Optimized internal one-arity curry function.
|
@@ -575,6 +577,7 @@ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
|
|
575
577
|
* R.type(() => {}); //=> "Function"
|
576
578
|
* R.type(async () => {}); //=> "AsyncFunction"
|
577
579
|
* R.type(undefined); //=> "Undefined"
|
580
|
+
* R.type(BigInt(123)); //=> "BigInt"
|
578
581
|
*/var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
|
579
582
|
|
580
583
|
function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
|
@@ -590,32 +593,7 @@ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object
|
|
590
593
|
|
591
594
|
function _isString(x){return Object.prototype.toString.call(x)==='[object String]';}
|
592
595
|
|
593
|
-
|
594
|
-
* Returns the nth element of the given list or string. If n is negative the
|
595
|
-
* element at index length + n is returned.
|
596
|
-
*
|
597
|
-
* @func
|
598
|
-
* @memberOf R
|
599
|
-
* @since v0.1.0
|
600
|
-
* @category List
|
601
|
-
* @sig Number -> [a] -> a | Undefined
|
602
|
-
* @sig Number -> String -> String
|
603
|
-
* @param {Number} offset
|
604
|
-
* @param {*} list
|
605
|
-
* @return {*}
|
606
|
-
* @example
|
607
|
-
*
|
608
|
-
* const list = ['foo', 'bar', 'baz', 'quux'];
|
609
|
-
* R.nth(1, list); //=> 'bar'
|
610
|
-
* R.nth(-1, list); //=> 'quux'
|
611
|
-
* R.nth(-99, list); //=> undefined
|
612
|
-
*
|
613
|
-
* R.nth(2, 'abc'); //=> 'c'
|
614
|
-
* R.nth(3, 'abc'); //=> ''
|
615
|
-
* @symb R.nth(-1, [a, b, c]) = c
|
616
|
-
* @symb R.nth(0, [a, b, c]) = a
|
617
|
-
* @symb R.nth(1, [a, b, c]) = b
|
618
|
-
*/var nth=/*#__PURE__*/_curry2(function nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];});
|
596
|
+
function _nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];}
|
619
597
|
|
620
598
|
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':''));}
|
621
599
|
|
@@ -628,10 +606,10 @@ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pa
|
|
628
606
|
* @return {*} The copied value.
|
629
607
|
*/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.
|
630
608
|
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.
|
631
|
-
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]=
|
609
|
+
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){/**
|
632
610
|
* 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,
|
633
611
|
* on my tests this number is 180, anything above that using the hash function is faster.
|
634
|
-
*/if(this.length<=180){for(var p in this.map){var
|
612
|
+
*/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;}();
|
635
613
|
|
636
614
|
/**
|
637
615
|
* Creates a deep copy of the source that can be used in place of the source
|
@@ -659,51 +637,9 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
659
637
|
* const objectsClone = R.clone(objects);
|
660
638
|
* objects === objectsClone; //=> false
|
661
639
|
* objects[0] === objectsClone[0]; //=> false
|
662
|
-
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value
|
663
|
-
|
664
|
-
/**
|
665
|
-
* Retrieves the values at given paths of an object.
|
666
|
-
*
|
667
|
-
* @func
|
668
|
-
* @memberOf R
|
669
|
-
* @since v0.27.1
|
670
|
-
* @category Object
|
671
|
-
* @typedefn Idx = [String | Int | Symbol]
|
672
|
-
* @sig [Idx] -> {a} -> [a | Undefined]
|
673
|
-
* @param {Array} pathsArray The array of paths to be fetched.
|
674
|
-
* @param {Object} obj The object to retrieve the nested properties from.
|
675
|
-
* @return {Array} A list consisting of values at paths specified by "pathsArray".
|
676
|
-
* @see R.path
|
677
|
-
* @example
|
678
|
-
*
|
679
|
-
* R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]
|
680
|
-
* R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]
|
681
|
-
*/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;});});
|
640
|
+
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value);});
|
682
641
|
|
683
|
-
|
684
|
-
* Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
|
685
|
-
* For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
|
686
|
-
*
|
687
|
-
* @func
|
688
|
-
* @memberOf R
|
689
|
-
* @since v0.2.0
|
690
|
-
* @category Object
|
691
|
-
* @typedefn Idx = String | Int | Symbol
|
692
|
-
* @sig [Idx] -> {a} -> a | Undefined
|
693
|
-
* @sig Idx = String | NonNegativeInt
|
694
|
-
* @param {Array} path The path to use.
|
695
|
-
* @param {Object} obj The object or array to retrieve the nested property from.
|
696
|
-
* @return {*} The data at `path`.
|
697
|
-
* @see R.prop, R.nth, R.assocPath, R.dissocPath
|
698
|
-
* @example
|
699
|
-
*
|
700
|
-
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
|
701
|
-
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
|
702
|
-
* R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
|
703
|
-
* R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
|
704
|
-
* R.path([2], {'2': 2}); //=> 2
|
705
|
-
* R.path([-2], {'-2': 'a'}); //=> undefined
|
706
|
-
*/var path=/*#__PURE__*/_curry2(function path(pathAr,obj){return paths([pathAr],obj)[0];});
|
642
|
+
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;}
|
707
643
|
|
708
644
|
/**
|
709
645
|
* Creates a new object with the own properties of the two provided objects. If
|
@@ -788,6 +724,31 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
788
724
|
* //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
|
789
725
|
*/var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});
|
790
726
|
|
727
|
+
/**
|
728
|
+
* Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
|
729
|
+
* For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
|
730
|
+
*
|
731
|
+
* @func
|
732
|
+
* @memberOf R
|
733
|
+
* @since v0.2.0
|
734
|
+
* @category Object
|
735
|
+
* @typedefn Idx = String | Int | Symbol
|
736
|
+
* @sig [Idx] -> {a} -> a | Undefined
|
737
|
+
* @sig Idx = String | NonNegativeInt
|
738
|
+
* @param {Array} path The path to use.
|
739
|
+
* @param {Object} obj The object or array to retrieve the nested property from.
|
740
|
+
* @return {*} The data at `path`.
|
741
|
+
* @see R.prop, R.nth, R.assocPath, R.dissocPath
|
742
|
+
* @example
|
743
|
+
*
|
744
|
+
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
|
745
|
+
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
|
746
|
+
* R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
|
747
|
+
* R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
|
748
|
+
* R.path([2], {'2': 2}); //=> 2
|
749
|
+
* R.path([-2], {'-2': 'a'}); //=> undefined
|
750
|
+
*/var path=/*#__PURE__*/_curry2(_path);
|
751
|
+
|
791
752
|
/**
|
792
753
|
* Returns a partial copy of an object containing only the keys that satisfy
|
793
754
|
* the supplied predicate.
|
@@ -934,7 +895,7 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
934
895
|
|
935
896
|
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';
|
936
897
|
|
937
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.
|
898
|
+
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';
|
938
899
|
|
939
900
|
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';
|
940
901
|
|
@@ -1044,19 +1005,19 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
|
|
1044
1005
|
* Service to load external resources/files
|
1045
1006
|
*/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);}/**
|
1046
1007
|
* Load external resource of type javascript
|
1047
|
-
*/_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();}});}/**
|
1008
|
+
*/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();}});}/**
|
1048
1009
|
* Handle errors
|
1049
|
-
*/},{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;}}}]);
|
1010
|
+
*/},{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;}}}]);}();
|
1050
1011
|
|
1051
|
-
|
1012
|
+
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);}
|
1052
1013
|
|
1053
1014
|
/**
|
1054
1015
|
* A buffer queue to serve as a store for any type of data
|
1055
|
-
*/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=[];}}]);
|
1016
|
+
*/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=[];}}]);}();
|
1056
1017
|
|
1057
1018
|
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;';/**
|
1058
1019
|
* Service to log messages/data to output provider, default is console
|
1059
|
-
*/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
|
1020
|
+
*/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
|
1060
1021
|
// to assist on the fly debugging?
|
1061
1022
|
},{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
1062
1023
|
* Formats the console message using `scope` and styles
|
@@ -1068,63 +1029,65 @@ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PRE
|
|
1068
1029
|
LOG_MSG_STYLE// reset the style for the actual message
|
1069
1030
|
];// add first it if it was not a string msg
|
1070
1031
|
if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
|
1071
|
-
styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);
|
1032
|
+
styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);}();var defaultLogger=new Logger();
|
1072
1033
|
|
1073
1034
|
// default is v3
|
1074
1035
|
var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
|
1075
1036
|
|
1076
1037
|
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
|
1077
|
-
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
|
1078
|
-
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
|
1038
|
+
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
|
1039
|
+
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
|
1079
1040
|
|
1080
1041
|
var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';
|
1081
1042
|
|
1082
1043
|
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';
|
1083
1044
|
|
1084
|
-
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');
|
1045
|
+
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';
|
1085
1046
|
|
1086
|
-
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=
|
1047
|
+
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));
|
1087
1048
|
|
1088
1049
|
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};
|
1089
1050
|
|
1090
|
-
var
|
1051
|
+
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)};
|
1091
1052
|
|
1092
|
-
var capabilitiesState={isOnline:
|
1053
|
+
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)};
|
1093
1054
|
|
1094
|
-
var reportingState={isErrorReportingEnabled:
|
1055
|
+
var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled:d$1(false),errorReportingProviderPluginName:d$1(undefined),isErrorReportingPluginLoaded:d$1(false)};
|
1095
1056
|
|
1096
|
-
var sourceConfigState=
|
1057
|
+
var sourceConfigState=d$1(undefined);
|
1097
1058
|
|
1098
|
-
var lifecycleState={activeDataplaneUrl:
|
1059
|
+
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)};
|
1099
1060
|
|
1100
|
-
var consentsState={enabled:
|
1061
|
+
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)};
|
1101
1062
|
|
1102
|
-
var metricsState={retries:
|
1063
|
+
var metricsState={retries:d$1(0),dropped:d$1(0),sent:d$1(0),queued:d$1(0),triggered:d$1(0)};
|
1103
1064
|
|
1104
|
-
var contextState={app:
|
1065
|
+
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)};
|
1105
1066
|
|
1106
|
-
var nativeDestinationsState={configuredDestinations:
|
1067
|
+
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({})};
|
1107
1068
|
|
1108
|
-
var eventBufferState={toBeProcessedArray:
|
1069
|
+
var eventBufferState={toBeProcessedArray:d$1([]),readyCallbacksArray:d$1([])};
|
1109
1070
|
|
1110
|
-
var pluginsState={ready:
|
1071
|
+
var pluginsState={ready:d$1(false),loadedPlugins:d$1([]),failedPlugins:d$1([]),pluginsToLoadFromConfig:d$1([]),activePlugins:d$1([]),totalPluginsToLoad:d$1(0)};
|
1111
1072
|
|
1112
|
-
var storageState={encryptionPluginName:
|
1073
|
+
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)};
|
1113
1074
|
|
1114
|
-
var
|
1075
|
+
var serverSideCookiesState={isEnabledServerSideCookies:d$1(false),dataServiceUrl:d$1(undefined)};
|
1076
|
+
|
1077
|
+
var dataPlaneEventsState={eventsQueuePluginName:d$1(undefined),deliveryEnabled:d$1(true)// Delivery should always happen
|
1115
1078
|
};
|
1116
1079
|
|
1117
|
-
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));
|
1080
|
+
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));
|
1118
1081
|
|
1119
1082
|
// to next or return the value if it is the last one instead of an array per
|
1120
1083
|
// plugin that is the normal invoke
|
1121
1084
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
1122
|
-
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.
|
1085
|
+
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.
|
1123
1086
|
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
|
1124
1087
|
// do some unified pre-process before application starts.
|
1125
1088
|
},{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
|
1126
1089
|
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
|
1127
|
-
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));}}]);
|
1090
|
+
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);
|
1128
1091
|
|
1129
1092
|
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1130
1093
|
|
@@ -1144,7 +1107,7 @@ if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.d
|
|
1144
1107
|
/**
|
1145
1108
|
* A service to handle errors
|
1146
1109
|
*/var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
|
1147
|
-
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
|
1110
|
+
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
|
1148
1111
|
var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1149
1112
|
if(!errorMessage){return;}// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1150
1113
|
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
|
@@ -1159,7 +1122,7 @@ if(state.reporting.isErrorReportingEnabled.value&&!state.reporting.isErrorReport
|
|
1159
1122
|
*
|
1160
1123
|
* @param {Error} error Error instance from handled error
|
1161
1124
|
*/},{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
|
1162
|
-
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);
|
1125
|
+
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1163
1126
|
|
1164
1127
|
/**
|
1165
1128
|
* A function to filter and return non cloud mode destinations
|
@@ -1239,7 +1202,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
|
|
1239
1202
|
|
1240
1203
|
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1241
1204
|
|
1242
|
-
var ScheduleModes=/*#__PURE__*/function(ScheduleModes){ScheduleModes[ScheduleModes["ASAP"]=1]="ASAP";ScheduleModes[ScheduleModes["RESCHEDULE"]=2]="RESCHEDULE";ScheduleModes[ScheduleModes["ABANDON"]=3]="ABANDON";return ScheduleModes;}({});var DEFAULT_CLOCK_LATE_FACTOR=2;var DEFAULT_CLOCK={setTimeout:function setTimeout(fn,ms){return globalThis.setTimeout(fn,ms);},clearTimeout:function clearTimeout(id){return globalThis.clearTimeout(id);},Date:globalThis.Date,clockLateFactor:DEFAULT_CLOCK_LATE_FACTOR};var Schedule=/*#__PURE__*/function(){function Schedule(){_classCallCheck(this,Schedule);this.tasks={};this.nextId=1;this.clock=DEFAULT_CLOCK;}_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={};}}]);
|
1205
|
+
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={};}}]);}();
|
1243
1206
|
|
1244
1207
|
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,".");};
|
1245
1208
|
|
@@ -1259,7 +1222,7 @@ timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakin
|
|
1259
1222
|
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
|
1260
1223
|
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
|
1261
1224
|
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
|
1262
|
-
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
|
1225
|
+
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
|
1263
1226
|
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
|
1264
1227
|
},{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
|
1265
1228
|
* Stops processing the queue
|
@@ -1329,7 +1292,7 @@ if(entryIdx+1<queueEntryKeys.length){_this4.removeStorageEntry(store,entryIdx+1,
|
|
1329
1292
|
_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
|
1330
1293
|
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
|
1331
1294
|
// Hence, we need this backward compatibility check
|
1332
|
-
if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_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();}}]);
|
1295
|
+
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();}}]);}();
|
1333
1296
|
|
1334
1297
|
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:{/**
|
1335
1298
|
* Initialize the queue for delivery
|
@@ -1382,7 +1345,7 @@ event.context='Script load failures';}// eslint-disable-next-line no-param-reass
|
|
1382
1345
|
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
|
1383
1346
|
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
|
1384
1347
|
// it is most likely a non-SDK error
|
1385
|
-
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.
|
1348
|
+
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
|
1386
1349
|
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1387
1350
|
collectUserIp:false,// collecting user's IP is disabled
|
1388
1351
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
@@ -1617,7 +1580,7 @@ var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSF
|
|
1617
1580
|
case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
|
1618
1581
|
|
1619
1582
|
var pluginName$a='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$a,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
|
1620
|
-
"".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.
|
1583
|
+
"".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.activeDataplaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// null means item will not be requeued
|
1621
1584
|
var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
|
1622
1585
|
|
1623
1586
|
var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
|
@@ -1835,7 +1798,7 @@ var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncry
|
|
1835
1798
|
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.
|
1836
1799
|
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);};}/**
|
1837
1800
|
* Base class for inheritance.
|
1838
|
-
*/var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}_createClass(Base,[{key:"mixIn",value:/**
|
1801
|
+
*/var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}return _createClass(Base,[{key:"mixIn",value:/**
|
1839
1802
|
* Copies properties into this object.
|
1840
1803
|
*
|
1841
1804
|
* @param {Object} properties The properties to mix in.
|
@@ -1864,12 +1827,12 @@ randomWordArray=function randomWordArray(nBytes){var words=[];var r=function r(m
|
|
1864
1827
|
* @example
|
1865
1828
|
*
|
1866
1829
|
* var instance = MyType.create();
|
1867
|
-
*/function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);
|
1830
|
+
*/function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);}();/**
|
1868
1831
|
* An array of 32-bit words.
|
1869
1832
|
*
|
1870
1833
|
* @property {Array} words The array of 32-bit words.
|
1871
1834
|
* @property {number} sigBytes The number of significant bytes in this word array.
|
1872
|
-
*/var WordArray=/*#__PURE__*/function(_Base){
|
1835
|
+
*/var WordArray=/*#__PURE__*/function(_Base){/**
|
1873
1836
|
* Initializes a newly created word array.
|
1874
1837
|
*
|
1875
1838
|
* @param {Array} words (Optional) An array of 32-bit words.
|
@@ -1899,7 +1862,7 @@ _this.words=words;_this.sigBytes=sigBytes;}return _this;}/**
|
|
1899
1862
|
* @example
|
1900
1863
|
*
|
1901
1864
|
* var wordArray = CryptoJS.lib.WordArray.random(16);
|
1902
|
-
*/_createClass(WordArray,[{key:"toString",value:/**
|
1865
|
+
*/_inherits(WordArray,_Base);return _createClass(WordArray,[{key:"toString",value:/**
|
1903
1866
|
* Converts this word array to a string.
|
1904
1867
|
*
|
1905
1868
|
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
|
@@ -1943,7 +1906,7 @@ words[sigBytes>>>2]&=0xffffffff<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes
|
|
1943
1906
|
* @example
|
1944
1907
|
*
|
1945
1908
|
* var clone = wordArray.clone();
|
1946
|
-
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);
|
1909
|
+
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);}(Base);/**
|
1947
1910
|
* Hex encoding strategy.
|
1948
1911
|
*/_defineProperty(WordArray,"random",randomWordArray);var Hex={/**
|
1949
1912
|
* Converts a word array to a hex string.
|
@@ -2037,13 +2000,13 @@ var words=[];for(var i=0;i<latin1StrLength;i+=1){words[i>>>2]|=(latin1Str.charCo
|
|
2037
2000
|
* @property {number} _minBufferSize
|
2038
2001
|
*
|
2039
2002
|
* The number of blocks that should be kept unprocessed in the buffer. Default: 0
|
2040
|
-
*/var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){
|
2003
|
+
*/var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){function BufferedBlockAlgorithm(){var _this2;_classCallCheck(this,BufferedBlockAlgorithm);_this2=_callSuper(this,BufferedBlockAlgorithm);_this2._minBufferSize=0;return _this2;}/**
|
2041
2004
|
* Resets this block algorithm's data buffer to its initial state.
|
2042
2005
|
*
|
2043
2006
|
* @example
|
2044
2007
|
*
|
2045
2008
|
* bufferedBlockAlgorithm.reset();
|
2046
|
-
*/_createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
|
2009
|
+
*/_inherits(BufferedBlockAlgorithm,_Base2);return _createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
|
2047
2010
|
this._data=new WordArray();this._nDataBytes=0;}/**
|
2048
2011
|
* Adds new data to this block algorithm's buffer.
|
2049
2012
|
*
|
@@ -2089,13 +2052,13 @@ return new WordArray(processedWords,nBytesReady);}/**
|
|
2089
2052
|
* @example
|
2090
2053
|
*
|
2091
2054
|
* var clone = bufferedBlockAlgorithm.clone();
|
2092
|
-
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);
|
2055
|
+
*/},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);}(Base);/**
|
2093
2056
|
* Abstract hasher template.
|
2094
2057
|
*
|
2095
2058
|
* @property {number} blockSize
|
2096
2059
|
*
|
2097
2060
|
* The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
|
2098
|
-
*/var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){
|
2061
|
+
*/var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){function Hasher(cfg){var _this3;_classCallCheck(this,Hasher);_this3=_callSuper(this,Hasher);_this3.blockSize=512/32;/**
|
2099
2062
|
* Configuration options.
|
2100
2063
|
*/_this3.cfg=Object.assign(new Base(),cfg);// Set initial values
|
2101
2064
|
_this3.reset();return _this3;}/**
|
@@ -2110,7 +2073,7 @@ _this3.reset();return _this3;}/**
|
|
2110
2073
|
* @example
|
2111
2074
|
*
|
2112
2075
|
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
|
2113
|
-
*/_createClass(Hasher,[{key:"reset",value:/**
|
2076
|
+
*/_inherits(Hasher,_BufferedBlockAlgorit);return _createClass(Hasher,[{key:"reset",value:/**
|
2114
2077
|
* Resets this hasher to its initial state.
|
2115
2078
|
*
|
2116
2079
|
* @example
|
@@ -2159,9 +2122,9 @@ var hash=this._doFinalize();return hash;}}],[{key:"_createHelper",value:function
|
|
2159
2122
|
* @example
|
2160
2123
|
*
|
2161
2124
|
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
|
2162
|
-
*/},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);
|
2125
|
+
*/},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);}(BufferedBlockAlgorithm);/**
|
2163
2126
|
* HMAC algorithm.
|
2164
|
-
*/var HMAC=/*#__PURE__*/function(_Base3){
|
2127
|
+
*/var HMAC=/*#__PURE__*/function(_Base3){/**
|
2165
2128
|
* Initializes a newly created HMAC.
|
2166
2129
|
*
|
2167
2130
|
* @param {Hasher} SubHasher The hash algorithm to use.
|
@@ -2184,7 +2147,7 @@ _this4.reset();return _this4;}/**
|
|
2184
2147
|
* @example
|
2185
2148
|
*
|
2186
2149
|
* hmacHasher.reset();
|
2187
|
-
*/_createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
|
2150
|
+
*/_inherits(HMAC,_Base3);return _createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
|
2188
2151
|
var hasher=this._hasher;// Reset
|
2189
2152
|
hasher.reset();hasher.update(this._iKey);}/**
|
2190
2153
|
* Updates this HMAC with a message.
|
@@ -2213,7 +2176,7 @@ return this;}/**
|
|
2213
2176
|
* var hmac = hmacHasher.finalize(wordArray);
|
2214
2177
|
*/},{key:"finalize",value:function finalize(messageUpdate){// Shortcut
|
2215
2178
|
var hasher=this._hasher;// Compute HMAC
|
2216
|
-
var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);
|
2179
|
+
var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);}(Base);
|
2217
2180
|
|
2218
2181
|
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);};/**
|
2219
2182
|
* Base64 encoding strategy.
|
@@ -2253,7 +2216,7 @@ return parseLoop(base64Str,base64StrLength,reverseMap);},_map:'ABCDEFGHIJKLMNOPQ
|
|
2253
2216
|
var T=[];// Compute constants
|
2254
2217
|
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;};/**
|
2255
2218
|
* MD5 hash algorithm.
|
2256
|
-
*/var MD5Algo=/*#__PURE__*/function(_Hasher){
|
2219
|
+
*/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
|
2257
2220
|
for(var _i=0;_i<16;_i+=1){// Shortcuts
|
2258
2221
|
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
|
2259
2222
|
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
|
@@ -2266,7 +2229,7 @@ this._process();// Shortcuts
|
|
2266
2229
|
var hash=this._hash;var H=hash.words;// Swap endian
|
2267
2230
|
for(var _i2=0;_i2<4;_i2+=1){// Shortcut
|
2268
2231
|
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
|
2269
|
-
return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(MD5Algo.prototype),"clone",this).call(this);clone._hash=this._hash.clone();return clone;}}]);
|
2232
|
+
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);/**
|
2270
2233
|
* Shortcut function to the hasher's object interface.
|
2271
2234
|
*
|
2272
2235
|
* @param {WordArray|string} message The message to hash.
|
@@ -2297,7 +2260,7 @@ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeO
|
|
2297
2260
|
/**
|
2298
2261
|
* This key derivation function is meant to conform with EVP_BytesToKey.
|
2299
2262
|
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
|
2300
|
-
*/var EvpKDFAlgo=/*#__PURE__*/function(_Base){
|
2263
|
+
*/var EvpKDFAlgo=/*#__PURE__*/function(_Base){/**
|
2301
2264
|
* Initializes a newly created key derivation function.
|
2302
2265
|
*
|
2303
2266
|
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
|
@@ -2324,13 +2287,13 @@ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeO
|
|
2324
2287
|
* @example
|
2325
2288
|
*
|
2326
2289
|
* const key = kdf.compute(password, salt);
|
2327
|
-
*/_createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
|
2290
|
+
*/_inherits(EvpKDFAlgo,_Base);return _createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
|
2328
2291
|
var cfg=this.cfg;// Init hasher
|
2329
2292
|
var hasher=cfg.hasher.create();// Initial values
|
2330
2293
|
var derivedKey=WordArray.create();// Shortcuts
|
2331
2294
|
var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize,iterations=cfg.iterations;// Generate key
|
2332
2295
|
while(derivedKeyWords.length<keySize){if(block){hasher.update(block);}block=hasher.update(password).finalize(salt);hasher.reset();// Iterations
|
2333
|
-
for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);
|
2296
|
+
for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);}(Base);
|
2334
2297
|
|
2335
2298
|
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;/**
|
2336
2299
|
* Abstract base cipher template.
|
@@ -2339,7 +2302,7 @@ var ObjectAssign=typeof Object.assign!=="function"?function(target){if(target==n
|
|
2339
2302
|
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
|
2340
2303
|
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
|
2341
2304
|
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
|
2342
|
-
*/var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){
|
2305
|
+
*/var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){/**
|
2343
2306
|
* Initializes a newly created cipher.
|
2344
2307
|
*
|
2345
2308
|
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
|
@@ -2370,7 +2333,7 @@ _this.reset();return _this;}/**
|
|
2370
2333
|
* @example
|
2371
2334
|
*
|
2372
2335
|
* const cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
|
2373
|
-
*/_createClass(Cipher,[{key:"reset",value:/**
|
2336
|
+
*/_inherits(Cipher,_BufferedBlockAlgorit);return _createClass(Cipher,[{key:"reset",value:/**
|
2374
2337
|
* Resets this cipher to its initial state.
|
2375
2338
|
*
|
2376
2339
|
* @example
|
@@ -2431,9 +2394,9 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2431
2394
|
* @example
|
2432
2395
|
*
|
2433
2396
|
* const AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
|
2434
|
-
*/},{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);}};}}]);
|
2397
|
+
*/},{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;/**
|
2435
2398
|
* Abstract base block cipher mode template.
|
2436
|
-
*/var BlockCipherMode=/*#__PURE__*/function(_Base){
|
2399
|
+
*/var BlockCipherMode=/*#__PURE__*/function(_Base){/**
|
2437
2400
|
* Initializes a newly created mode.
|
2438
2401
|
*
|
2439
2402
|
* @param {Cipher} cipher A block cipher instance.
|
@@ -2453,7 +2416,7 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2453
2416
|
* @example
|
2454
2417
|
*
|
2455
2418
|
* const mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
|
2456
|
-
*/_createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
|
2419
|
+
*/_inherits(BlockCipherMode,_Base);return _createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
|
2457
2420
|
* Creates this mode for decryption.
|
2458
2421
|
*
|
2459
2422
|
* @param {Cipher} cipher A block cipher instance.
|
@@ -2464,7 +2427,7 @@ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"c
|
|
2464
2427
|
* @example
|
2465
2428
|
*
|
2466
2429
|
* const mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
|
2467
|
-
*/},{key:"createDecryptor",value:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);}}]);
|
2430
|
+
*/},{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
|
2468
2431
|
var iv=this._iv;// Choose mixing block
|
2469
2432
|
if(iv){block=iv;// Remove IV for subsequent blocks
|
2470
2433
|
this._iv=undefined;}else {block=this._prevBlock;}// XOR blocks
|
@@ -2472,9 +2435,9 @@ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
|
|
2472
2435
|
* Cipher Block Chaining mode.
|
2473
2436
|
*/ /**
|
2474
2437
|
* Abstract base CBC mode.
|
2475
|
-
*/var CBC=/*#__PURE__*/function(_BlockCipherMode){
|
2438
|
+
*/var CBC=/*#__PURE__*/function(_BlockCipherMode){function CBC(){_classCallCheck(this,CBC);return _callSuper(this,CBC,arguments);}_inherits(CBC,_BlockCipherMode);return _createClass(CBC);}(BlockCipherMode);/**
|
2476
2439
|
* CBC encryptor.
|
2477
|
-
*/CBC.Encryptor=/*#__PURE__*/function(_CBC){
|
2440
|
+
*/CBC.Encryptor=/*#__PURE__*/function(_CBC){function _class(){_classCallCheck(this,_class);return _callSuper(this,_class,arguments);}_inherits(_class,_CBC);return _createClass(_class,[{key:"processBlock",value:/**
|
2478
2441
|
* Processes the data block at offset.
|
2479
2442
|
*
|
2480
2443
|
* @param {Array} words The data words to operate on.
|
@@ -2486,9 +2449,9 @@ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
|
|
2486
2449
|
*/function processBlock(words,offset){// Shortcuts
|
2487
2450
|
var cipher=this._cipher;var blockSize=cipher.blockSize;// XOR and encrypt
|
2488
2451
|
xorBlock.call(this,words,offset,blockSize);cipher.encryptBlock(words,offset);// Remember this block to use with next block
|
2489
|
-
this._prevBlock=words.slice(offset,offset+blockSize);}}]);
|
2452
|
+
this._prevBlock=words.slice(offset,offset+blockSize);}}]);}(CBC);/**
|
2490
2453
|
* CBC decryptor.
|
2491
|
-
*/CBC.Decryptor=/*#__PURE__*/function(_CBC2){
|
2454
|
+
*/CBC.Decryptor=/*#__PURE__*/function(_CBC2){function _class2(){_classCallCheck(this,_class2);return _callSuper(this,_class2,arguments);}_inherits(_class2,_CBC2);return _createClass(_class2,[{key:"processBlock",value:/**
|
2492
2455
|
* Processes the data block at offset.
|
2493
2456
|
*
|
2494
2457
|
* @param {Array} words The data words to operate on.
|
@@ -2501,7 +2464,7 @@ this._prevBlock=words.slice(offset,offset+blockSize);}}]);return _class;}(CBC);/
|
|
2501
2464
|
var cipher=this._cipher;var blockSize=cipher.blockSize;// Remember this block to use with next block
|
2502
2465
|
var thisBlock=words.slice(offset,offset+blockSize);// Decrypt and XOR
|
2503
2466
|
cipher.decryptBlock(words,offset);xorBlock.call(this,words,offset,blockSize);// This block becomes the previous block
|
2504
|
-
this._prevBlock=thisBlock;}}]);
|
2467
|
+
this._prevBlock=thisBlock;}}]);}(CBC);/**
|
2505
2468
|
* PKCS #5/7 padding strategy.
|
2506
2469
|
*/var Pkcs7={/**
|
2507
2470
|
* Pads data using the algorithm defined in PKCS #5/7.
|
@@ -2537,12 +2500,12 @@ _data.sigBytes-=nPaddingBytes;}};/**
|
|
2537
2500
|
* @property {number} blockSize
|
2538
2501
|
*
|
2539
2502
|
* The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
|
2540
|
-
*/var BlockCipher=/*#__PURE__*/function(_Cipher2){
|
2503
|
+
*/var BlockCipher=/*#__PURE__*/function(_Cipher2){function BlockCipher(xformMode,key,cfg){var _this4;_classCallCheck(this,BlockCipher);/**
|
2541
2504
|
* Configuration options.
|
2542
2505
|
*
|
2543
2506
|
* @property {Mode} mode The block mode to use. Default: CBC
|
2544
2507
|
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
|
2545
|
-
*/_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
|
2508
|
+
*/_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
|
2546
2509
|
_get(_getPrototypeOf(BlockCipher.prototype),"reset",this).call(this);// Shortcuts
|
2547
2510
|
var cfg=this.cfg;var iv=cfg.iv,mode=cfg.mode;// Reset block mode
|
2548
2511
|
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
|
@@ -2552,7 +2515,7 @@ if(this._xformMode===this.constructor._ENC_XFORM_MODE){// Pad data
|
|
2552
2515
|
padding.pad(this._data,this.blockSize);// Process final blocks
|
2553
2516
|
finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
|
2554
2517
|
finalProcessedBlocks=this._process(!!'flush');// Unpad data
|
2555
|
-
padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);
|
2518
|
+
padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);}(Cipher);/**
|
2556
2519
|
* A collection of cipher parameters.
|
2557
2520
|
*
|
2558
2521
|
* @property {WordArray} ciphertext The raw ciphertext.
|
@@ -2565,7 +2528,7 @@ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);return Blo
|
|
2565
2528
|
* @property {number} blockSize The block size of the cipher.
|
2566
2529
|
* @property {Format} formatter
|
2567
2530
|
* The default formatting strategy to convert this cipher params object to a string.
|
2568
|
-
*/var CipherParams=/*#__PURE__*/function(_Base2){
|
2531
|
+
*/var CipherParams=/*#__PURE__*/function(_Base2){/**
|
2569
2532
|
* Initializes a newly created cipher params object.
|
2570
2533
|
*
|
2571
2534
|
* @param {Object} cipherParams An object with any of the possible cipher parameters.
|
@@ -2597,7 +2560,7 @@ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);return Blo
|
|
2597
2560
|
* var string = cipherParams + '';
|
2598
2561
|
* var string = cipherParams.toString();
|
2599
2562
|
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
|
2600
|
-
*/_createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);
|
2563
|
+
*/_inherits(CipherParams,_Base2);return _createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);}(Base);/**
|
2601
2564
|
* OpenSSL formatting strategy.
|
2602
2565
|
*/var OpenSSLFormatter={/**
|
2603
2566
|
* Converts a cipher params object to an OpenSSL-compatible string.
|
@@ -2632,7 +2595,7 @@ if(ciphertextWords[0]===0x53616c74&&ciphertextWords[1]===0x65645f5f){// Extract
|
|
2632
2595
|
salt=WordArray.create(ciphertextWords.slice(2,4));// Remove salt from ciphertext
|
2633
2596
|
ciphertextWords.splice(0,4);ciphertext.sigBytes-=16;}return CipherParams.create({ciphertext:ciphertext,salt:salt});}};/**
|
2634
2597
|
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
|
2635
|
-
*/var SerializableCipher=/*#__PURE__*/function(_Base3){
|
2598
|
+
*/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:/**
|
2636
2599
|
* Encrypts a message.
|
2637
2600
|
*
|
2638
2601
|
* @param {Cipher} cipher The cipher algorithm to use.
|
@@ -2694,7 +2657,7 @@ var plaintext=cipher.createDecryptor(key,_cfg).finalize(_ciphertext.ciphertext);
|
|
2694
2657
|
*
|
2695
2658
|
* var ciphertextParams = CryptoJS.lib.SerializableCipher
|
2696
2659
|
* ._parse(ciphertextStringOrParams, format);
|
2697
|
-
*/},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);
|
2660
|
+
*/},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);}(Base);/**
|
2698
2661
|
* Configuration options.
|
2699
2662
|
*
|
2700
2663
|
* @property {Formatter} format
|
@@ -2727,7 +2690,7 @@ var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*
|
|
2727
2690
|
return CipherParams.create({key:key,iv:iv,salt:_salt});}};/**
|
2728
2691
|
* A serializable cipher wrapper that derives the key from a password,
|
2729
2692
|
* and returns ciphertext as a serializable cipher params object.
|
2730
|
-
*/var PasswordBasedCipher=/*#__PURE__*/function(_SerializableCipher){
|
2693
|
+
*/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:/**
|
2731
2694
|
* Encrypts a message using a password.
|
2732
2695
|
*
|
2733
2696
|
* @param {Cipher} cipher The cipher algorithm to use.
|
@@ -2775,7 +2738,7 @@ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
|
|
2775
2738
|
_ciphertext=this._parse(_ciphertext,_cfg.format);// Derive key and other params
|
2776
2739
|
var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_ciphertext.salt,_cfg.hasher);// Add IV to config
|
2777
2740
|
_cfg.iv=derivedParams.iv;// Decrypt
|
2778
|
-
var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);
|
2741
|
+
var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);}(SerializableCipher);/**
|
2779
2742
|
* Configuration options.
|
2780
2743
|
*
|
2781
2744
|
* @property {KDF} kdf
|
@@ -2794,7 +2757,7 @@ t=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV
|
|
2794
2757
|
if(!x){xi=1;x=xi;}else {x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]];}}// Precomputed Rcon lookup
|
2795
2758
|
var RCON=[0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36];/**
|
2796
2759
|
* AES block cipher algorithm.
|
2797
|
-
*/var AESAlgo=/*#__PURE__*/function(_BlockCipher){
|
2760
|
+
*/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
|
2798
2761
|
if(this._nRounds&&this._keyPriorReset===this._key){return;}// Shortcuts
|
2799
2762
|
this._keyPriorReset=this._key;var key=this._keyPriorReset;var keyWords=key.words;var keySize=key.sigBytes/4;// Compute number of rounds
|
2800
2763
|
this._nRounds=keySize+6;var nRounds=this._nRounds;// Compute number of key schedule rows
|
@@ -2814,7 +2777,7 @@ for(var round=1;round<nRounds;round+=1){// Shift rows, sub bytes, mix columns, a
|
|
2814
2777
|
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
|
2815
2778
|
s0=_t;s1=_t2;s2=_t3;s3=_t4;}// Shift rows, sub bytes, add round key
|
2816
2779
|
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
|
2817
|
-
_M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);
|
2780
|
+
_M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);}(BlockCipher);AESAlgo.keySize=256/32;/**
|
2818
2781
|
* Shortcut functions to the cipher's object interface.
|
2819
2782
|
*
|
2820
2783
|
* @example
|
@@ -2888,11 +2851,11 @@ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:he
|
|
2888
2851
|
// TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
|
2889
2852
|
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);}/**
|
2890
2853
|
* Orchestrate the plugin loading and registering
|
2891
|
-
*/_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
|
2854
|
+
*/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
|
2892
2855
|
this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
|
2893
2856
|
* Update state based on plugin loaded status
|
2894
2857
|
*/ // eslint-disable-next-line class-methods-use-this
|
2895
|
-
},{key:"attachEffects",value:function attachEffects(){
|
2858
|
+
},{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.
|
2896
2859
|
// Should we stop here or should we progress?
|
2897
2860
|
state.lifecycle.status.value='pluginsReady';});}});}/**
|
2898
2861
|
* Determine the list of plugins that should be loaded based on sourceConfig & load options
|
@@ -2902,7 +2865,7 @@ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!plug
|
|
2902
2865
|
);_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));}}/**
|
2903
2866
|
* Determine the list of plugins that should be activated
|
2904
2867
|
*/},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
2905
|
-
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(','))));}
|
2868
|
+
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;});}/**
|
2906
2869
|
* Register plugins that are direct imports to PluginEngine
|
2907
2870
|
*/},{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()]);}});}/**
|
2908
2871
|
* Register plugins that are dynamic imports to PluginEngine
|
@@ -2916,7 +2879,7 @@ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.fai
|
|
2916
2879
|
*/},{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
|
2917
2880
|
},{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);}});}/**
|
2918
2881
|
* Handle errors
|
2919
|
-
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);
|
2882
|
+
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);}();
|
2920
2883
|
|
2921
2884
|
/**
|
2922
2885
|
* Utility to parse XHR JSON response
|
@@ -2938,7 +2901,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
2938
2901
|
* Service to handle data communication with APIs
|
2939
2902
|
*/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);}/**
|
2940
2903
|
* Implement requests in a blocking way
|
2941
|
-
*/_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;}()/**
|
2904
|
+
*/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;}()/**
|
2942
2905
|
* Implement requests in a non-blocking way
|
2943
2906
|
*/)},{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);}});}/**
|
2944
2907
|
* Handle errors
|
@@ -2946,7 +2909,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
2946
2909
|
* Set basic authentication header (eg writekey)
|
2947
2910
|
*/},{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);}/**
|
2948
2911
|
* Clear basic authentication header
|
2949
|
-
*/},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);
|
2912
|
+
*/},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
|
2950
2913
|
|
2951
2914
|
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'];
|
2952
2915
|
|
@@ -2962,16 +2925,17 @@ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:fu
|
|
2962
2925
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
2963
2926
|
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;}});};
|
2964
2927
|
|
2965
|
-
var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);}
|
2928
|
+
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
|
2929
|
+
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\./));};
|
2966
2930
|
|
2967
2931
|
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();});}};
|
2968
2932
|
|
2969
2933
|
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
|
2970
2934
|
// the polyfill service serves them under the same feature name, "URL".
|
2971
|
-
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
|
2935
|
+
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
|
2972
2936
|
// the polyfill service serves them under the same feature name, "TextEncoder".
|
2973
2937
|
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".
|
2974
|
-
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;};
|
2938
|
+
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;};
|
2975
2939
|
|
2976
2940
|
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;};
|
2977
2941
|
|
@@ -3029,18 +2993,18 @@ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=dom
|
|
3029
2993
|
/**
|
3030
2994
|
* A storage utility to persist values in cookies via Storage interface
|
3031
2995
|
*/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
|
3032
|
-
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
|
2996
|
+
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
|
3033
2997
|
},{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
|
3034
2998
|
},{key:"clear",value:function clear(){// Not implemented
|
3035
2999
|
// getting a list of all cookie storage keys and remove all values
|
3036
3000
|
// sounds risky to do as it will take on all top domain cookies
|
3037
3001
|
// better to explicitly clear specific ones if needed
|
3038
3002
|
}},{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
|
3039
|
-
},{key:"keys",value:function keys(){return Object.keys(cookie());}}]);
|
3003
|
+
},{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();_defineProperty(CookieStorage,"globalSingleton",null);
|
3040
3004
|
|
3041
3005
|
/**
|
3042
3006
|
* A storage utility to retain values in memory via Storage interface
|
3043
|
-
*/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);}}]);
|
3007
|
+
*/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);
|
3044
3008
|
|
3045
3009
|
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
3046
3010
|
|
@@ -3062,19 +3026,19 @@ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=va
|
|
3062
3026
|
// https://www.npmjs.com/package/storejs
|
3063
3027
|
/**
|
3064
3028
|
* A storage utility to persist values in localstorage via Storage interface
|
3065
|
-
*/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
|
3029
|
+
*/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
|
3066
3030
|
},{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
|
3067
|
-
},{key:"keys",value:function keys(){return store.keys();}}]);
|
3031
|
+
},{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
|
3068
3032
|
|
3069
3033
|
/**
|
3070
3034
|
* A storage utility to persist values in SessionStorage via Storage interface
|
3071
|
-
*/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;}}]);
|
3035
|
+
*/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);
|
3072
3036
|
|
3073
3037
|
/**
|
3074
3038
|
* A utility to retrieve the storage singleton instance by type
|
3075
3039
|
*/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;}};/**
|
3076
3040
|
* Configure cookie storage singleton
|
3077
|
-
*/var configureCookieStorageEngine=function configureCookieStorageEngine(options){new CookieStorage({},defaultLogger).configure(options);};/**
|
3041
|
+
*/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};};/**
|
3078
3042
|
* Configure local storage singleton
|
3079
3043
|
*/var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
|
3080
3044
|
* Configure in memory storage singleton
|
@@ -3088,7 +3052,7 @@ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=va
|
|
3088
3052
|
* Store Implementation with dedicated storage
|
3089
3053
|
*/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;}/**
|
3090
3054
|
* Ensure the key is valid and with correct format
|
3091
|
-
*/_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
|
3055
|
+
*/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
|
3092
3056
|
var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
|
3093
3057
|
* Switch to inMemoryEngine, bringing any existing data with.
|
3094
3058
|
*/},{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
|
@@ -3116,7 +3080,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3116
3080
|
* Extension point to use with encryption plugins
|
3117
3081
|
*/},{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:'';}/**
|
3118
3082
|
* Handle errors
|
3119
|
-
*/},{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;}}}]);
|
3083
|
+
*/},{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;}}}]);}();
|
3120
3084
|
|
3121
3085
|
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;};
|
3122
3086
|
|
@@ -3124,7 +3088,7 @@ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConse
|
|
3124
3088
|
* A service to manage stores & available storage client configurations
|
3125
3089
|
*/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);}/**
|
3126
3090
|
* Configure available storage client instances
|
3127
|
-
*/_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;}/**
|
3091
|
+
*/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;}/**
|
3128
3092
|
* Create store to persist data used by the SDK like session, used details etc
|
3129
3093
|
*/},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
3130
3094
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
@@ -3132,14 +3096,14 @@ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConse
|
|
3132
3096
|
// that needs auto migration
|
3133
3097
|
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
|
3134
3098
|
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
|
3135
|
-
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]}));});
|
3099
|
+
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
|
3136
3100
|
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;}/**
|
3137
3101
|
* Create a new store
|
3138
3102
|
*/},{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];}/**
|
3139
3103
|
* Retrieve a store
|
3140
3104
|
*/},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
|
3141
3105
|
* Handle errors
|
3142
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);
|
3106
|
+
*/},{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;}}}]);}();
|
3143
3107
|
|
3144
3108
|
/**
|
3145
3109
|
* Removes trailing slash from url
|
@@ -3167,7 +3131,13 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
|
|
3167
3131
|
*/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
|
3168
3132
|
}return urlWithoutHash;};
|
3169
3133
|
|
3170
|
-
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);};
|
3134
|
+
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
|
3135
|
+
var urlObj=new URL(url);// Extract the hostname and protocol
|
3136
|
+
var hostname=urlObj.hostname,protocol=urlObj.protocol;// Split the hostname into parts
|
3137
|
+
var parts=hostname.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
3138
|
+
if(parts.length>2){// Join the last two parts for the top-level domain
|
3139
|
+
topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
|
3140
|
+
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);};
|
3171
3141
|
|
3172
3142
|
/**
|
3173
3143
|
* Plugins to be loaded in the plugins loadOption is not defined
|
@@ -3189,7 +3159,7 @@ var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)|
|
|
3189
3159
|
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3190
3160
|
|
3191
3161
|
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
|
3192
|
-
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
|
3162
|
+
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
|
3193
3163
|
// doesn't seem to throw errors for empty URLs
|
3194
3164
|
// TODO: Need to improve this check to find out if the URL is valid or not
|
3195
3165
|
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);};
|
@@ -3261,8 +3231,8 @@ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,con
|
|
3261
3231
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3262
3232
|
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
|
3263
3233
|
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
|
3264
|
-
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));}
|
3265
|
-
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));}
|
3234
|
+
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
|
3235
|
+
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
|
3266
3236
|
// if it is not already initialized and
|
3267
3237
|
// if consent management is enabled
|
3268
3238
|
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}};});};/**
|
@@ -3270,7 +3240,7 @@ enabled:((_state$loadOptions$va=state.loadOptions.value.preConsent)===null||_sta
|
|
3270
3240
|
* @param resp Source config response
|
3271
3241
|
* @param logger Logger instance
|
3272
3242
|
*/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
|
3273
|
-
if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}
|
3243
|
+
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;});}};
|
3274
3244
|
|
3275
3245
|
/**
|
3276
3246
|
* A function that determines integration SDK loading path
|
@@ -3289,13 +3259,13 @@ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_
|
|
3289
3259
|
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
|
3290
3260
|
var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
|
3291
3261
|
|
3292
|
-
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;
|
3262
|
+
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);});}/**
|
3293
3263
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3294
3264
|
* config related information in global state
|
3295
3265
|
*/},{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
|
3296
3266
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
3297
|
-
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
|
3298
|
-
|
3267
|
+
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
|
3268
|
+
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();}/**
|
3299
3269
|
* Handle errors
|
3300
3270
|
*/},{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;}}/**
|
3301
3271
|
* A callback function that is executed once we fetch the source config response.
|
@@ -3305,10 +3275,10 @@ n(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycl
|
|
3305
3275
|
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
|
3306
3276
|
updateReportingState(res,this.logger);// determine the dataPlane url
|
3307
3277
|
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
|
3308
|
-
|
3309
|
-
state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
|
3278
|
+
r(function(){var _state$loadOptions$va2;// set source related information in state
|
3279
|
+
state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
|
3310
3280
|
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
3311
|
-
state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$
|
3281
|
+
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
|
3312
3282
|
// Cast to string as we are sure that the value is not undefined
|
3313
3283
|
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value='configured';});}/**
|
3314
3284
|
* A function to fetch source config either from /sourceConfig endpoint
|
@@ -3316,7 +3286,7 @@ state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);sta
|
|
3316
3286
|
* @returns
|
3317
3287
|
*/},{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
|
3318
3288
|
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
|
3319
|
-
this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);
|
3289
|
+
this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
|
3320
3290
|
|
3321
3291
|
/**
|
3322
3292
|
* To get the timezone of the user
|
@@ -3345,14 +3315,14 @@ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}
|
|
3345
3315
|
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
|
3346
3316
|
var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
|
3347
3317
|
|
3348
|
-
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);}}/**
|
3318
|
+
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);}}/**
|
3349
3319
|
* Detect supported capabilities and set values in state
|
3350
3320
|
*/ // eslint-disable-next-line class-methods-use-this
|
3351
|
-
},{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;
|
3321
|
+
},{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;r(function(){// Storage related details
|
3352
3322
|
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
|
3353
3323
|
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
|
3354
3324
|
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
|
3355
|
-
|
3325
|
+
E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3356
3326
|
* Detect if polyfills are required and then load script from polyfill URL
|
3357
3327
|
*/},{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
|
3358
3328
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
@@ -3365,7 +3335,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
|
|
3365
3335
|
},{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
|
3366
3336
|
* Handles error
|
3367
3337
|
* @param error The error object
|
3368
|
-
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);
|
3338
|
+
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);}();
|
3369
3339
|
|
3370
3340
|
var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
3371
3341
|
var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
@@ -3432,7 +3402,7 @@ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
|
|
3432
3402
|
* @param rudderContext Generated rudder event
|
3433
3403
|
* @param options API options
|
3434
3404
|
* @param logger Logger instance
|
3435
|
-
*/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
|
3405
|
+
*/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;};/**
|
3436
3406
|
* A function to determine whether SDK should use the integration option provided in load call
|
3437
3407
|
* @returns boolean
|
3438
3408
|
*/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));};/**
|
@@ -3466,7 +3436,7 @@ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logge
|
|
3466
3436
|
* @param name Page name
|
3467
3437
|
* @param properties Page properties
|
3468
3438
|
* @param options API options
|
3469
|
-
*/_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);}/**
|
3439
|
+
*/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);}/**
|
3470
3440
|
* Generate a 'track' event based on the user-input fields
|
3471
3441
|
* @param event The event name
|
3472
3442
|
* @param properties Event properties
|
@@ -3491,7 +3461,7 @@ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enric
|
|
3491
3461
|
* Generates a new RudderEvent object based on the user-input fields
|
3492
3462
|
* @param event API event parameters object
|
3493
3463
|
* @returns A RudderEvent object
|
3494
|
-
*/},{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;}}]);
|
3464
|
+
*/},{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;}}]);}();
|
3495
3465
|
|
3496
3466
|
/**
|
3497
3467
|
* A service to generate valid event payloads and queue them for processing
|
@@ -3503,19 +3473,20 @@ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enric
|
|
3503
3473
|
* @param logger Logger object
|
3504
3474
|
*/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);}/**
|
3505
3475
|
* Initializes the event manager
|
3506
|
-
*/_createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
|
3476
|
+
*/return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
|
3507
3477
|
* Consumes a new incoming event
|
3508
3478
|
* @param event Incoming event data
|
3509
3479
|
*/},{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));}}/**
|
3510
3480
|
* Handles error
|
3511
3481
|
* @param error The error object
|
3512
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);
|
3482
|
+
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3513
3483
|
|
3514
|
-
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);}/**
|
3484
|
+
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);}/**
|
3515
3485
|
* Initialize User session with values from storage
|
3516
|
-
*/_createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
3486
|
+
*/return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
3517
3487
|
this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
3518
|
-
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
|
3488
|
+
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
|
3489
|
+
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
|
3519
3490
|
// as those values indicate there is no need for migration or
|
3520
3491
|
// migration failed
|
3521
3492
|
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
|
@@ -3524,14 +3495,34 @@ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTi
|
|
3524
3495
|
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};}/**
|
3525
3496
|
* Handles error
|
3526
3497
|
* @param error The error object
|
3527
|
-
*/},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER);}else {throw error;}}/**
|
3498
|
+
*/},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
|
3499
|
+
* A function to encrypt the cookie value and return the encrypted data
|
3500
|
+
* @param cookieData
|
3501
|
+
* @param store
|
3502
|
+
* @returns
|
3503
|
+
*/},{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;}/**
|
3504
|
+
* A function that makes request to data service to set the cookie
|
3505
|
+
* @param encryptedCookieData
|
3506
|
+
* @param callback
|
3507
|
+
*/},{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});}/**
|
3508
|
+
* A function to make an external request to set the cookie from server side
|
3509
|
+
* @param key cookie name
|
3510
|
+
* @param value encrypted cookie value
|
3511
|
+
*/},{key:"setServerSideCookie",value:function setServerSideCookie(cookieData,cb,store){var _this4=this;try{// encrypt cookies values
|
3512
|
+
var encryptedCookieData=this.getEncryptedCookieData(cookieData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
3513
|
+
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);}});}}/**
|
3528
3514
|
* A function to sync values in storage
|
3529
3515
|
* @param sessionKey
|
3530
3516
|
* @param value
|
3531
|
-
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey
|
3517
|
+
*/},{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
|
3518
|
+
// set the cookie from server side
|
3519
|
+
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
|
3520
|
+
// TODO: Test cookies set from server side can be cleared from client side
|
3521
|
+
// and make appropriate changes.
|
3522
|
+
this.setServerSideCookie([{name:key,value:''}],undefined,curStore);}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
|
3532
3523
|
* Function to update storage whenever state value changes
|
3533
|
-
*/},{key:"registerEffects",value:function registerEffects(){var
|
3534
|
-
USER_SESSION_KEYS.forEach(function(sessionKey){
|
3524
|
+
*/},{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
|
3525
|
+
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this5.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
|
3535
3526
|
* Sets anonymous id in the following precedence:
|
3536
3527
|
*
|
3537
3528
|
* 1. anonymousId: Id directly provided to the function.
|
@@ -3571,30 +3562,35 @@ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||
|
|
3571
3562
|
*/},{key:"getAuthToken",value:function getAuthToken(){return this.getEntryValue('authToken');}/**
|
3572
3563
|
* If session is active it returns the sessionId
|
3573
3564
|
* @returns
|
3574
|
-
*/},{key:"getSessionId",value:function getSessionId(){var sessionInfo=
|
3575
|
-
* A function to
|
3576
|
-
|
3577
|
-
|
3578
|
-
|
3565
|
+
*/},{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;}/**
|
3566
|
+
* A function to keep the session information up to date in the state
|
3567
|
+
* before using it for building event payloads.
|
3568
|
+
*/},{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.
|
3569
|
+
// So, we needn't update the session info.
|
3570
|
+
//
|
3571
|
+
// For other scenarios,
|
3572
|
+
// 1. If sessionStart is undefined, then it's a new session.
|
3573
|
+
// Mark it as sessionStart.
|
3574
|
+
// 2. If sessionStart is true, then need to flip it for the future events.
|
3575
|
+
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});}}}/**
|
3579
3576
|
* Reset state values
|
3580
3577
|
* @param resetAnonymousId
|
3581
3578
|
* @param noNewSessionStart
|
3582
3579
|
* @returns
|
3583
|
-
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var
|
3584
|
-
|
3585
|
-
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
|
3580
|
+
*/},{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
|
3581
|
+
_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();}});}/**
|
3586
3582
|
* Set user Id
|
3587
3583
|
* @param userId
|
3588
3584
|
*/},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
3589
3585
|
* Set user traits
|
3590
3586
|
* @param traits
|
3591
|
-
*/},{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:
|
3587
|
+
*/},{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;}/**
|
3592
3588
|
* Set group Id
|
3593
3589
|
* @param groupId
|
3594
3590
|
*/},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
|
3595
3591
|
* Set group traits
|
3596
3592
|
* @param traits
|
3597
|
-
*/},{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:
|
3593
|
+
*/},{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;}/**
|
3598
3594
|
* Set initial referrer
|
3599
3595
|
* @param referrer
|
3600
3596
|
*/},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
|
@@ -3602,7 +3598,7 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3602
3598
|
* @param {String} referringDomain
|
3603
3599
|
*/},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
|
3604
3600
|
* A function to check for existing session details and depending on that create a new session
|
3605
|
-
*/},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(){
|
3601
|
+
*/},{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
|
3606
3602
|
});}}/**
|
3607
3603
|
* A function method to start a manual session
|
3608
3604
|
* @param {number} id session identifier
|
@@ -3611,10 +3607,10 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3611
3607
|
* An internal function to start manual session
|
3612
3608
|
*/},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
|
3613
3609
|
* A public method to end an ongoing session.
|
3614
|
-
*/},{key:"end",value:function end(){state.session.sessionInfo.value=
|
3610
|
+
*/},{key:"end",value:function end(){state.session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;}/**
|
3615
3611
|
* Set auth token
|
3616
3612
|
* @param userId
|
3617
|
-
*/},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);
|
3613
|
+
*/},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
|
3618
3614
|
|
3619
3615
|
var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
|
3620
3616
|
|
@@ -3642,12 +3638,12 @@ var eventIntgConfig=(_event$integrations=event.integrations)!==null&&_event$inte
|
|
3642
3638
|
* @param logger Logger object
|
3643
3639
|
*/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);}/**
|
3644
3640
|
* Initializes the event repository
|
3645
|
-
*/_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
|
3646
|
-
|
3641
|
+
*/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
|
3642
|
+
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
|
3647
3643
|
// However, events will be enqueued for now.
|
3648
3644
|
// At the time of processing the events, the integrations config data from destinations
|
3649
3645
|
// is merged into the event object
|
3650
|
-
var timeoutId;
|
3646
|
+
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
|
3651
3647
|
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();}}/**
|
3652
3648
|
* Enqueues the event for processing
|
3653
3649
|
* @param event RudderEvent object
|
@@ -3660,7 +3656,7 @@ callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onErro
|
|
3660
3656
|
* @param error The error object
|
3661
3657
|
* @param customMessage a message
|
3662
3658
|
* @param shouldAlwaysThrow if it should throw or use logger
|
3663
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);
|
3659
|
+
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3664
3660
|
|
3665
3661
|
var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
|
3666
3662
|
|
@@ -3670,16 +3666,16 @@ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new Custom
|
|
3670
3666
|
* Initialize services and components or use default ones if singletons
|
3671
3667
|
*/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;}/**
|
3672
3668
|
* Start application lifecycle if not already started
|
3673
|
-
*/_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
|
3669
|
+
*/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
|
3674
3670
|
if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
|
3675
|
-
|
3671
|
+
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
|
3676
3672
|
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
|
3677
3673
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
3678
3674
|
// State application lifecycle
|
3679
3675
|
this.startLifecycle();}// Start lifecycle methods
|
3680
3676
|
/**
|
3681
3677
|
* Orchestrate the lifecycle of the application phases/status
|
3682
|
-
*/},{key:"startLifecycle",value:function startLifecycle(){var _this=this;
|
3678
|
+
*/},{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
|
3683
3679
|
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
|
3684
3680
|
if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
|
3685
3681
|
* Load browser polyfill if required
|
@@ -3687,7 +3683,7 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
|
|
3687
3683
|
* Enqueue in SDK preload buffer events, used from preloadBuffer component
|
3688
3684
|
*/},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
|
3689
3685
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
3690
|
-
*/},{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);}/**
|
3686
|
+
*/},{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);}/**
|
3691
3687
|
* Load configuration
|
3692
3688
|
*/},{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();}/**
|
3693
3689
|
* Initialize the storage and event queue
|
@@ -3706,7 +3702,7 @@ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window o
|
|
3706
3702
|
// as this will prevent us from supporting multiple SDK instances in the same page
|
3707
3703
|
// Execute onLoaded callback if provided in load options
|
3708
3704
|
if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
|
3709
|
-
|
3705
|
+
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
|
3710
3706
|
dispatchSDKEvent('RSA_Initialised');}/**
|
3711
3707
|
* Emit ready event
|
3712
3708
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -3722,7 +3718,7 @@ var bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEven
|
|
3722
3718
|
*/},{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
|
3723
3719
|
(_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
|
3724
3720
|
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
|
3725
|
-
|
3721
|
+
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;});}});}/**
|
3726
3722
|
* Move to the ready state
|
3727
3723
|
*/ // eslint-disable-next-line class-methods-use-this
|
3728
3724
|
},{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
|
@@ -3746,14 +3742,14 @@ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].
|
|
3746
3742
|
},{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
3747
3743
|
},{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
3748
3744
|
},{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
|
3749
|
-
},{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");
|
3745
|
+
},{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
|
3750
3746
|
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
|
3751
3747
|
(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
|
3752
3748
|
(_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===void 0||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
|
3753
3749
|
(_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
|
3754
3750
|
// events buffer array so that any other preload events (mainly from query string API) will be processed first.
|
3755
3751
|
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
|
3756
|
-
}]);
|
3752
|
+
}]);}();
|
3757
3753
|
|
3758
3754
|
/*
|
3759
3755
|
* RudderAnalytics facade singleton that is exposed as global object and will:
|
@@ -3771,7 +3767,7 @@ globalThis.rudderanalytics=this;}/**
|
|
3771
3767
|
* Set instance to use if no specific writeKey is provided in methods
|
3772
3768
|
* automatically for the first created instance
|
3773
3769
|
* TODO: to support multiple analytics instances in the near future
|
3774
|
-
*/_createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
3770
|
+
*/return _createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
3775
3771
|
* Retrieve an existing analytics instance
|
3776
3772
|
*/},{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];}/**
|
3777
3773
|
* Create new analytics instance and trigger application lifecycle start
|
@@ -3799,6 +3795,6 @@ this.load.apply(null,loadEvent);}}/**
|
|
3799
3795
|
* Process alias arguments and forward to page call
|
3800
3796
|
*/},{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
|
3801
3797
|
* Process group arguments and forward to page call
|
3802
|
-
*/},{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);}}]);
|
3798
|
+
*/},{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);
|
3803
3799
|
|
3804
3800
|
export { RudderAnalytics };
|