@rudderstack/analytics-js 3.0.0-beta.6 → 3.0.0-beta.8
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +22 -3
- package/dist/npm/index.d.ts +1229 -0
- package/{legacy → dist/npm/legacy}/cjs/index.js +369 -508
- package/{legacy → dist/npm/legacy}/esm/index.js +369 -508
- package/{legacy → dist/npm/legacy}/umd/index.js +369 -508
- package/{modern → dist/npm/modern}/cjs/index.js +164 -289
- package/{modern → dist/npm/modern}/esm/index.js +164 -289
- package/{modern → dist/npm/modern}/umd/index.js +164 -289
- package/package.json +28 -107
- package/index.d.ts +0 -387
@@ -6,21 +6,24 @@ let UaChTrackLevel=/*#__PURE__*/function(UaChTrackLevel){UaChTrackLevel["None"]=
|
|
6
6
|
* Represents the options parameter for anonymousId
|
7
7
|
*/ /**
|
8
8
|
* Represents the beacon queue options parameter in loadOptions type
|
9
|
-
*/
|
9
|
+
*/ /**
|
10
10
|
* Represents the queue options parameter in loadOptions type
|
11
11
|
*/ /**
|
12
12
|
* Represents the destinations queue options parameter in loadOptions type
|
13
|
-
*/
|
13
|
+
*/let DeliveryType=/*#__PURE__*/function(DeliveryType){DeliveryType["Immediate"]="immediate";DeliveryType["Buffer"]="buffer";return DeliveryType;}({});let StorageStrategy=/*#__PURE__*/function(StorageStrategy){StorageStrategy["None"]="none";StorageStrategy["Session"]="session";StorageStrategy["AnonymousId"]="anonymousId";return StorageStrategy;}({});/**
|
14
14
|
* Represents the options parameter in the load API
|
15
15
|
*/
|
16
16
|
|
17
|
+
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
18
|
+
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';let CookieSameSite=/*#__PURE__*/function(CookieSameSite){CookieSameSite["Strict"]="Strict";CookieSameSite["Lax"]="Lax";CookieSameSite["None"]="None";return CookieSameSite;}({});
|
19
|
+
|
17
20
|
/**
|
18
21
|
* Represents residency server input the options
|
19
22
|
*/let ResidencyServerRegion=/*#__PURE__*/function(ResidencyServerRegion){ResidencyServerRegion["US"]="US";ResidencyServerRegion["EU"]="EU";return ResidencyServerRegion;}({});
|
20
23
|
|
21
24
|
let LogLevel=/*#__PURE__*/function(LogLevel){LogLevel["Log"]="LOG";LogLevel["Info"]="INFO";LogLevel["Debug"]="DEBUG";LogLevel["Warn"]="WARN";LogLevel["Error"]="ERROR";LogLevel["None"]="NONE";return LogLevel;}({});
|
22
25
|
|
23
|
-
let PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["
|
26
|
+
let PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["Bugsnag"]="Bugsnag";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["KetchConsentManager"]="KetchConsentManager";PluginName["NativeDestinationQueue"]="NativeDestinationQueue";PluginName["OneTrustConsentManager"]="OneTrustConsentManager";PluginName["StorageEncryption"]="StorageEncryption";PluginName["StorageEncryptionLegacy"]="StorageEncryptionLegacy";PluginName["StorageMigrator"]="StorageMigrator";PluginName["XhrQueue"]="XhrQueue";return PluginName;}({});
|
24
27
|
|
25
28
|
function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/placeholder']===true;}
|
26
29
|
|
@@ -51,57 +54,8 @@ function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/
|
|
51
54
|
* @return {Function} The curried function.
|
52
55
|
*/function _curry3(fn){return function f3(a,b,c){switch(arguments.length){case 0:return f3;case 1:return _isPlaceholder(a)?f3:_curry2(function(_b,_c){return fn(a,_b,_c);});case 2:return _isPlaceholder(a)&&_isPlaceholder(b)?f3:_isPlaceholder(a)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_curry1(function(_c){return fn(a,b,_c);});default:return _isPlaceholder(a)&&_isPlaceholder(b)&&_isPlaceholder(c)?f3:_isPlaceholder(a)&&_isPlaceholder(b)?_curry2(function(_a,_b){return fn(_a,_b,c);}):_isPlaceholder(a)&&_isPlaceholder(c)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)&&_isPlaceholder(c)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b,c);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b,c);}):_isPlaceholder(c)?_curry1(function(_c){return fn(a,b,_c);}):fn(a,b,c);}};}
|
53
56
|
|
54
|
-
/**
|
55
|
-
* Tests whether or not an object is an array.
|
56
|
-
*
|
57
|
-
* @private
|
58
|
-
* @param {*} val The object to test.
|
59
|
-
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
|
60
|
-
* @example
|
61
|
-
*
|
62
|
-
* _isArray([]); //=> true
|
63
|
-
* _isArray(null); //=> false
|
64
|
-
* _isArray({}); //=> false
|
65
|
-
*/const _isArray = Array.isArray||function _isArray(val){return val!=null&&val.length>=0&&Object.prototype.toString.call(val)==='[object Array]';};
|
66
|
-
|
67
|
-
function _arrayFromIterator(iter){var list=[];var next;while(!(next=iter.next()).done){list.push(next.value);}return list;}
|
68
|
-
|
69
|
-
function _includesWith(pred,x,list){var idx=0;var len=list.length;while(idx<len){if(pred(x,list[idx])){return true;}idx+=1;}return false;}
|
70
|
-
|
71
|
-
function _functionName(f){// String(x => x) evaluates to "x => x", so the pattern may not match.
|
72
|
-
var match=String(f).match(/^function (\w*)/);return match==null?'':match[1];}
|
73
|
-
|
74
57
|
function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
|
75
58
|
|
76
|
-
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
|
77
|
-
function _objectIs(a,b){// SameValue algorithm
|
78
|
-
if(a===b){// Steps 1-5, 7-10
|
79
|
-
// Steps 6.b-6.e: +0 != -0
|
80
|
-
return a!==0||1/a===1/b;}else {// Step 6.a: NaN == NaN
|
81
|
-
return a!==a&&b!==b;}}const _objectIs$1 = typeof Object.is==='function'?Object.is:_objectIs;
|
82
|
-
|
83
|
-
var toString=Object.prototype.toString;var _isArguments=/*#__PURE__*/function(){return toString.call(arguments)==='[object Arguments]'?function _isArguments(x){return toString.call(x)==='[object Arguments]';}:function _isArguments(x){return _has('callee',x);};}();
|
84
|
-
|
85
|
-
var hasEnumBug=!/*#__PURE__*/{toString:null}.propertyIsEnumerable('toString');var nonEnumerableProps=['constructor','valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];// Safari bug
|
86
|
-
var hasArgsEnumBug=/*#__PURE__*/function(){return arguments.propertyIsEnumerable('length');}();var contains=function contains(list,item){var idx=0;while(idx<list.length){if(list[idx]===item){return true;}idx+=1;}return false;};/**
|
87
|
-
* Returns a list containing the names of all the enumerable own properties of
|
88
|
-
* the supplied object.
|
89
|
-
* Note that the order of the output array is not guaranteed to be consistent
|
90
|
-
* across different JS platforms.
|
91
|
-
*
|
92
|
-
* @func
|
93
|
-
* @memberOf R
|
94
|
-
* @since v0.1.0
|
95
|
-
* @category Object
|
96
|
-
* @sig {k: v} -> [k]
|
97
|
-
* @param {Object} obj The object to extract properties from
|
98
|
-
* @return {Array} An array of the object's own properties.
|
99
|
-
* @see R.keysIn, R.values, R.toPairs
|
100
|
-
* @example
|
101
|
-
*
|
102
|
-
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
|
103
|
-
*/var keys=typeof Object.keys==='function'&&!hasArgsEnumBug?/*#__PURE__*/_curry1(function keys(obj){return Object(obj)!==obj?[]:Object.keys(obj);}):/*#__PURE__*/_curry1(function keys(obj){if(Object(obj)!==obj){return [];}var prop,nIdx;var ks=[];var checkArgsLength=hasArgsEnumBug&&_isArguments(obj);for(prop in obj){if(_has(prop,obj)&&(!checkArgsLength||prop!=='length')){ks[ks.length]=prop;}}if(hasEnumBug){nIdx=nonEnumerableProps.length-1;while(nIdx>=0){prop=nonEnumerableProps[nIdx];if(_has(prop,obj)&&!contains(ks,prop)){ks[ks.length]=prop;}nIdx-=1;}}return ks;});
|
104
|
-
|
105
59
|
/**
|
106
60
|
* Gives a single-word string description of the (native) type of a value,
|
107
61
|
* returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
|
@@ -128,45 +82,6 @@ var hasArgsEnumBug=/*#__PURE__*/function(){return arguments.propertyIsEnumerable
|
|
128
82
|
* R.type(undefined); //=> "Undefined"
|
129
83
|
*/var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
|
130
84
|
|
131
|
-
/**
|
132
|
-
* private _uniqContentEquals function.
|
133
|
-
* That function is checking equality of 2 iterator contents with 2 assumptions
|
134
|
-
* - iterators lengths are the same
|
135
|
-
* - iterators values are unique
|
136
|
-
*
|
137
|
-
* false-positive result will be returned for comparison of, e.g.
|
138
|
-
* - [1,2,3] and [1,2,3,4]
|
139
|
-
* - [1,1,1] and [1,2,3]
|
140
|
-
* */function _uniqContentEquals(aIterator,bIterator,stackA,stackB){var a=_arrayFromIterator(aIterator);var b=_arrayFromIterator(bIterator);function eq(_a,_b){return _equals(_a,_b,stackA.slice(),stackB.slice());}// if *a* array contains any element that is not included in *b*
|
141
|
-
return !_includesWith(function(b,aItem){return !_includesWith(eq,aItem,b);},b,a);}function _equals(a,b,stackA,stackB){if(_objectIs$1(a,b)){return true;}var typeA=type(a);if(typeA!==type(b)){return false;}if(typeof a['fantasy-land/equals']==='function'||typeof b['fantasy-land/equals']==='function'){return typeof a['fantasy-land/equals']==='function'&&a['fantasy-land/equals'](b)&&typeof b['fantasy-land/equals']==='function'&&b['fantasy-land/equals'](a);}if(typeof a.equals==='function'||typeof b.equals==='function'){return typeof a.equals==='function'&&a.equals(b)&&typeof b.equals==='function'&&b.equals(a);}switch(typeA){case'Arguments':case'Array':case'Object':if(typeof a.constructor==='function'&&_functionName(a.constructor)==='Promise'){return a===b;}break;case'Boolean':case'Number':case'String':if(!(typeof a===typeof b&&_objectIs$1(a.valueOf(),b.valueOf()))){return false;}break;case'Date':if(!_objectIs$1(a.valueOf(),b.valueOf())){return false;}break;case'Error':return a.name===b.name&&a.message===b.message;case'RegExp':if(!(a.source===b.source&&a.global===b.global&&a.ignoreCase===b.ignoreCase&&a.multiline===b.multiline&&a.sticky===b.sticky&&a.unicode===b.unicode)){return false;}break;}var idx=stackA.length-1;while(idx>=0){if(stackA[idx]===a){return stackB[idx]===b;}idx-=1;}switch(typeA){case'Map':if(a.size!==b.size){return false;}return _uniqContentEquals(a.entries(),b.entries(),stackA.concat([a]),stackB.concat([b]));case'Set':if(a.size!==b.size){return false;}return _uniqContentEquals(a.values(),b.values(),stackA.concat([a]),stackB.concat([b]));case'Arguments':case'Array':case'Object':case'Boolean':case'Number':case'String':case'Date':case'Error':case'RegExp':case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'ArrayBuffer':break;default:// Values of other types are only equal if identical.
|
142
|
-
return false;}var keysA=keys(a);if(keysA.length!==keys(b).length){return false;}var extendedStackA=stackA.concat([a]);var extendedStackB=stackB.concat([b]);idx=keysA.length-1;while(idx>=0){var key=keysA[idx];if(!(_has(key,b)&&_equals(b[key],a[key],extendedStackA,extendedStackB))){return false;}idx-=1;}return true;}
|
143
|
-
|
144
|
-
/**
|
145
|
-
* Returns `true` if its arguments are equivalent, `false` otherwise. Handles
|
146
|
-
* cyclical data structures.
|
147
|
-
*
|
148
|
-
* Dispatches symmetrically to the `equals` methods of both arguments, if
|
149
|
-
* present.
|
150
|
-
*
|
151
|
-
* @func
|
152
|
-
* @memberOf R
|
153
|
-
* @since v0.15.0
|
154
|
-
* @category Relation
|
155
|
-
* @sig a -> b -> Boolean
|
156
|
-
* @param {*} a
|
157
|
-
* @param {*} b
|
158
|
-
* @return {Boolean}
|
159
|
-
* @example
|
160
|
-
*
|
161
|
-
* R.equals(1, 1); //=> true
|
162
|
-
* R.equals(1, '1'); //=> false
|
163
|
-
* R.equals([1, 2, 3], [1, 2, 3]); //=> true
|
164
|
-
*
|
165
|
-
* const a = {}; a.v = a;
|
166
|
-
* const b = {}; b.v = b;
|
167
|
-
* R.equals(a, b); //=> true
|
168
|
-
*/var equals=/*#__PURE__*/_curry2(function equals(a,b){return _equals(a,b,[],[]);});
|
169
|
-
|
170
85
|
function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
|
171
86
|
|
172
87
|
/**
|
@@ -251,71 +166,6 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
251
166
|
* objects[0] === objectsClone[0]; //=> false
|
252
167
|
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value,true);});const clone$1 = clone;
|
253
168
|
|
254
|
-
/**
|
255
|
-
* Tests whether or not an object is a typed array.
|
256
|
-
*
|
257
|
-
* @private
|
258
|
-
* @param {*} val The object to test.
|
259
|
-
* @return {Boolean} `true` if `val` is a typed array, `false` otherwise.
|
260
|
-
* @example
|
261
|
-
*
|
262
|
-
* _isTypedArray(new Uint8Array([])); //=> true
|
263
|
-
* _isTypedArray(new Float32Array([])); //=> true
|
264
|
-
* _isTypedArray([]); //=> false
|
265
|
-
* _isTypedArray(null); //=> false
|
266
|
-
* _isTypedArray({}); //=> false
|
267
|
-
*/function _isTypedArray(val){var type=Object.prototype.toString.call(val);return type==='[object Uint8ClampedArray]'||type==='[object Int8Array]'||type==='[object Uint8Array]'||type==='[object Int16Array]'||type==='[object Uint16Array]'||type==='[object Int32Array]'||type==='[object Uint32Array]'||type==='[object Float32Array]'||type==='[object Float64Array]'||type==='[object BigInt64Array]'||type==='[object BigUint64Array]';}
|
268
|
-
|
269
|
-
/**
|
270
|
-
* Returns the empty value of its argument's type. Ramda defines the empty
|
271
|
-
* value of Array (`[]`), Object (`{}`), String (`''`),
|
272
|
-
* TypedArray (`Uint8Array []`, `Float32Array []`, etc), and Arguments. Other
|
273
|
-
* types are supported if they define `<Type>.empty`,
|
274
|
-
* `<Type>.prototype.empty` or implement the
|
275
|
-
* [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid).
|
276
|
-
*
|
277
|
-
* Dispatches to the `empty` method of the first argument, if present.
|
278
|
-
*
|
279
|
-
* @func
|
280
|
-
* @memberOf R
|
281
|
-
* @since v0.3.0
|
282
|
-
* @category Function
|
283
|
-
* @sig a -> a
|
284
|
-
* @param {*} x
|
285
|
-
* @return {*}
|
286
|
-
* @example
|
287
|
-
*
|
288
|
-
* R.empty(Just(42)); //=> Nothing()
|
289
|
-
* R.empty([1, 2, 3]); //=> []
|
290
|
-
* R.empty('unicorns'); //=> ''
|
291
|
-
* R.empty({x: 1, y: 2}); //=> {}
|
292
|
-
* R.empty(Uint8Array.from('123')); //=> Uint8Array []
|
293
|
-
*/var empty=/*#__PURE__*/_curry1(function empty(x){return x!=null&&typeof x['fantasy-land/empty']==='function'?x['fantasy-land/empty']():x!=null&&x.constructor!=null&&typeof x.constructor['fantasy-land/empty']==='function'?x.constructor['fantasy-land/empty']():x!=null&&typeof x.empty==='function'?x.empty():x!=null&&x.constructor!=null&&typeof x.constructor.empty==='function'?x.constructor.empty():_isArray(x)?[]:_isString(x)?'':_isObject(x)?{}:_isArguments(x)?function(){return arguments;}():_isTypedArray(x)?x.constructor.from(''):void 0// else
|
294
|
-
;});
|
295
|
-
|
296
|
-
/**
|
297
|
-
* Returns `true` if the given value is its type's empty value; `false`
|
298
|
-
* otherwise.
|
299
|
-
*
|
300
|
-
* @func
|
301
|
-
* @memberOf R
|
302
|
-
* @since v0.1.0
|
303
|
-
* @category Logic
|
304
|
-
* @sig a -> Boolean
|
305
|
-
* @param {*} x
|
306
|
-
* @return {Boolean}
|
307
|
-
* @see R.empty
|
308
|
-
* @example
|
309
|
-
*
|
310
|
-
* R.isEmpty([1, 2, 3]); //=> false
|
311
|
-
* R.isEmpty([]); //=> true
|
312
|
-
* R.isEmpty(''); //=> true
|
313
|
-
* R.isEmpty(null); //=> false
|
314
|
-
* R.isEmpty({}); //=> true
|
315
|
-
* R.isEmpty({length: 0}); //=> false
|
316
|
-
* R.isEmpty(Uint8Array.from('')); //=> true
|
317
|
-
*/var isEmpty=/*#__PURE__*/_curry1(function isEmpty(x){return x!=null&&equals(x,empty(x));});const isEmpty$1 = isEmpty;
|
318
|
-
|
319
169
|
/**
|
320
170
|
* Retrieves the values at given paths of an object.
|
321
171
|
*
|
@@ -493,6 +343,10 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
493
343
|
* @param value input value
|
494
344
|
* @returns boolean
|
495
345
|
*/const isDefinedAndNotNull=value=>!isNullOrUndefined(value);/**
|
346
|
+
* A function to check given value is defined and not null
|
347
|
+
* @param value input value
|
348
|
+
* @returns boolean
|
349
|
+
*/const isDefinedNotNullAndNotEmptyString=value=>isDefinedAndNotNull(value)&&value!=='';/**
|
496
350
|
* Determines if the input is an instance of Error
|
497
351
|
* @param obj input value
|
498
352
|
* @returns true if the input is an instance of Error and false otherwise
|
@@ -579,7 +433,7 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
579
433
|
|
580
434
|
const CAPABILITIES_MANAGER='CapabilitiesManager';const CONFIG_MANAGER='ConfigManager';const EVENT_MANAGER='EventManager';const PLUGINS_MANAGER='PluginsManager';const USER_SESSION_MANAGER='UserSessionManager';const ERROR_HANDLER='ErrorHandler';const PLUGIN_ENGINE='PluginEngine';const STORE_MANAGER='StoreManager';const READY_API='readyApi';const LOAD_CONFIGURATION='LoadConfiguration';const EVENT_REPOSITORY='EventRepository';const EXTERNAL_SRC_LOADER='ExternalSrcLoader';const HTTP_CLIENT='HttpClient';const RS_APP='RudderStackApplication';const ANALYTICS_CORE='AnalyticsCore';
|
581
435
|
|
582
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.0.0-beta.
|
436
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.0.0-beta.8';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';
|
583
437
|
|
584
438
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
585
439
|
|
@@ -687,7 +541,7 @@ timeoutID=globalThis.setTimeout(()=>{reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(
|
|
687
541
|
* Handle errors
|
688
542
|
*/onError(error){if(this.hasErrorHandler){this.errorHandler?.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}
|
689
543
|
|
690
|
-
function i(){throw new Error("Cycle detected");}function t(){if(!(
|
544
|
+
function i(){throw new Error("Cycle detected");}function t(){if(!(f>1)){var i,t=!1;while(void 0!==s){var r=s;s=void 0;v++;while(void 0!==r){var n=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&a(r))try{r.c();}catch(r){if(!t){i=r;t=!0;}}r=n;}}v=0;f--;if(t)throw i;}else f--;}function r(i){if(f>0)return i();f++;try{return i();}finally{t();}}var n=void 0;var s=void 0,f=0,v=0,e=0;function u(i){if(void 0!==n){var t=i.n;if(void 0===t||t.t!==n){t={i:0,S:i,p:n.s,n:void 0,t:n,e:void 0,x:void 0,r:t};if(void 0!==n.s)n.s.n=t;n.s=t;i.n=t;if(32&n.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=n.s;t.n=void 0;n.s.n=t;n.s=t;}return t;}}}function c(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}c.prototype.h=function(){return !0;};c.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;}};c.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;}};c.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=32&this.f;this.f&=-33;try{i(r);}finally{this.f|=n;}});};c.prototype.valueOf=function(){return this.value;};c.prototype.toString=function(){return this.value+"";};c.prototype.toJSON=function(){return this.value;};c.prototype.peek=function(){return this.v;};Object.defineProperty(c.prototype,"value",{get:function(){var i=u(this);if(void 0!==i)i.i=this.i;return this.v;},set:function(r){if(n instanceof y)!function(){throw new Error("Computed cannot have side-effects");}();if(r!==this.v){if(v>100)i();this.v=r;this.i++;e++;f++;try{for(var o=this.t;void 0!==o;o=o.x)o.t.N();}finally{t();}}}});function d(i){return new c(i);}function a(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 l(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 w(i){var t=i.s,r=void 0;while(void 0!==t){var n=t.p;if(-1===t.i){t.S.U(t);if(void 0!==n)n.n=t.n;if(void 0!==t.n)t.n.p=n;}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=n;}i.s=r;}function y(i){c.call(this,void 0);this.x=i;this.s=void 0;this.g=e-1;this.f=4;}(y.prototype=new c()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===e)return !0;this.g=e;this.f|=1;if(this.i>0&&!a(this)){this.f&=-2;return !0;}var i=n;try{l(this);n=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++;}n=i;w(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);}c.prototype.S.call(this,i);};y.prototype.U=function(i){if(void 0!==this.t){c.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();}};y.prototype.peek=function(){if(!this.h())i();if(16&this.f)throw this.v;return this.v;};Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)i();var t=u(this);this.h();if(void 0!==t)t.i=this.i;if(16&this.f)throw this.v;return this.v;}});function p(i){var r=i.u;i.u=void 0;if("function"==typeof r){f++;var o=n;n=void 0;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{n=o;t();}}}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;p(i);}function b(i){if(n!==this)throw new Error("Out-of-order effect");w(this);n=i;this.f&=-2;if(8&this.f)g(this);t();}function x(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}x.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();}};x.prototype.S=function(){if(1&this.f)i();this.f|=1;this.f&=-9;p(this);l(this);f++;var t=n;n=this;return b.bind(this,t);};x.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=s;s=this;}};x.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new x(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
|
691
545
|
|
692
546
|
let LifecycleStatus=/*#__PURE__*/function(LifecycleStatus){LifecycleStatus["Mounted"]="mounted";LifecycleStatus["BrowserCapabilitiesReady"]="browserCapabilitiesReady";LifecycleStatus["Configured"]="configured";LifecycleStatus["PluginsLoading"]="pluginsLoading";LifecycleStatus["PluginsReady"]="pluginsReady";LifecycleStatus["Initialized"]="initialized";LifecycleStatus["Loaded"]="loaded";LifecycleStatus["DestinationsLoading"]="destinationsLoading";LifecycleStatus["DestinationsReady"]="destinationsReady";LifecycleStatus["Ready"]="ready";return LifecycleStatus;}({});
|
693
547
|
|
@@ -713,45 +567,46 @@ LOG_MSG_STYLE// reset the style for the actual message
|
|
713
567
|
if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
|
714
568
|
styledLogArgs.push(...data.slice(1));return styledLogArgs;}return data;}}const defaultLogger=new Logger();
|
715
569
|
|
716
|
-
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
717
|
-
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';
|
718
|
-
|
719
570
|
const SOURCE_CONFIG_OPTION_ERROR=`"getSourceConfig" must be a function. Please make sure that it is defined and returns a valid source configuration object.`;const INTG_CDN_BASE_URL_ERROR=`Failed to load the SDK as the CDN base URL for integrations is not valid.`;const PLUGINS_CDN_BASE_URL_ERROR=`Failed to load the SDK as the CDN base URL for plugins is not valid.`;const 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.`;const XHR_PAYLOAD_PREP_ERROR=`Failed to prepare data for the request.`;const EVENT_OBJECT_GENERATION_ERROR=`Failed to generate the event object.`;const PLUGIN_EXT_POINT_MISSING_ERROR=`Failed to invoke plugin because the extension point name is missing.`;const PLUGIN_EXT_POINT_INVALID_ERROR=`Failed to invoke plugin because the extension point name is invalid.`;// ERROR
|
720
571
|
const UNSUPPORTED_CONSENT_MANAGER_ERROR=(context,selectedConsentManager,consentManagersToPluginNameMap)=>`${context}${LOG_CONTEXT_SEPARATOR}The consent manager "${selectedConsentManager}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(consentManagersToPluginNameMap)}".`;const REPORTING_PLUGIN_INIT_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to initialize the error reporting plugin.`;const NOTIFY_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to notify the error.`;const PLUGIN_NAME_MISSING_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin name is missing.`;const PLUGIN_ALREADY_EXISTS_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" already exists.`;const PLUGIN_NOT_FOUND_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found.`;const PLUGIN_ENGINE_BUG_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${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.`;const PLUGIN_DEPS_ERROR=(context,pluginName,notExistDeps)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" could not be loaded because some of its dependencies "${notExistDeps}" do not exist.`;const PLUGIN_INVOCATION_ERROR=(context,extPoint,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to invoke the "${extPoint}" extension point of plugin "${pluginName}".`;const STORAGE_UNAVAILABILITY_ERROR_PREFIX=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${storageType}" storage type is `;const SOURCE_CONFIG_FETCH_ERROR=reason=>`Failed to fetch the source config. Reason: ${reason}`;const WRITE_KEY_VALIDATION_ERROR=writeKey=>`The write key "${writeKey}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`;const DATA_PLANE_URL_VALIDATION_ERROR=dataPlaneUrl=>`The data plane URL "${dataPlaneUrl}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`;const READY_API_CALLBACK_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The callback is not a function.`;const XHR_DELIVERY_ERROR=(prefix,status,statusText,url)=>`${prefix} with status: ${status}, ${statusText} for URL: ${url}.`;const XHR_REQUEST_ERROR=(prefix,e,url)=>`${prefix} due to timeout or no connection (${e?e.type:''}) for URL: ${url}.`;const XHR_SEND_ERROR=(prefix,url)=>`${prefix} for URL: ${url}`;const STORE_DATA_SAVE_ERROR=key=>`Failed to save the value for "${key}" to storage`;const STORE_DATA_FETCH_ERROR=key=>`Failed to retrieve or parse data for "${key}" from storage`;// WARNING
|
721
|
-
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported
|
572
|
+
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default type "${defaultStorageType}" will be used instead.`;const UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider)=>`${context}${LOG_CONTEXT_SEPARATOR}The error reporting provider "${selectedErrorReportingProvider}" is not supported. Please choose one of the following supported providers: "${Object.keys(errorReportingProvidersToPluginNameMap)}". The default provider "${defaultProvider}" will be used instead.`;const UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version "${selectedStorageEncryptionVersion}" is not supported. Please choose one of the following supported versions: "${Object.keys(storageEncryptionVersionsToPluginNameMap)}". The default version "${defaultVersion}" will be used instead.`;const STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=(context,storageEncryptionVersion,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;const UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=(context,selectedResidencyServerRegion,defaultRegion)=>`${context}${LOG_CONTEXT_SEPARATOR}The residency server region "${selectedResidencyServerRegion}" is not supported. Please choose one of the following supported regions: "${Object.values(ResidencyServerRegion)}". The default region "${defaultRegion}" will be used instead.`;const RESERVED_KEYWORD_WARNING=(context,property,parentKeyPath,reservedElements)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${property}" property defined under "${parentKeyPath}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;const INVALID_CONTEXT_OBJECT_WARNING=logContext=>`${logContext}${LOG_CONTEXT_SEPARATOR}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`;const UNSUPPORTED_BEACON_API_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;const TIMEOUT_NOT_NUMBER_WARNING=(context,timeout,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value "${timeout}" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;const TIMEOUT_ZERO_WARNING=context=>`${context}${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.`;const TIMEOUT_NOT_RECOMMENDED_WARNING=(context,timeout,minTimeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;const INVALID_SESSION_ID_WARNING=(context,sessionId,minSessionIdLength)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least "${minSessionIdLength}" digits long. A new session ID will be auto-generated instead.`;const STORAGE_QUOTA_EXCEEDED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;const STORAGE_UNAVAILABLE_WARNING=(context,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available. The SDK will be initialized with "${finalStorageType}" instead.`;const WRITE_KEY_NOT_A_STRING_ERROR=(context,writeKey)=>`${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is not a string. Please check that the write key is correct and try again.`;const EMPTY_GROUP_CALL_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The group() method must be called with at least one argument.`;const READY_CALLBACK_INVOKE_ERROR=`Failed to invoke the ready callback`;const API_CALLBACK_INVOKE_ERROR=`API Callback Invocation Failed`;const INVALID_CONFIG_URL_WARNING=(context,configUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided config URL "${configUrl}" is invalid. Using the default value instead.`;const POLYFILL_SCRIPT_LOAD_ERROR=(scriptId,url)=>`Failed to load the polyfill script with ID "${scriptId}" from URL ${url}.`;const COOKIE_DATA_ENCODING_ERROR=`Failed to encode the cookie data.`;const UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=(context,selectedStrategy,defaultStrategy)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent storage strategy "${selectedStrategy}" is not supported. Please choose one of the following supported strategies: "${Object.values(StorageStrategy)}". The default strategy "${defaultStrategy}" will be used instead.`;const UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=(context,selectedDeliveryType,defaultDeliveryType)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent events delivery type "${selectedDeliveryType}" is not supported. Please choose one of the following supported types: "${Object.values(DeliveryType)}". The default type "${defaultDeliveryType}" will be used instead.`;// DEBUG
|
573
|
+
|
574
|
+
const CDN_INT_DIR='js-integrations';const CDN_PLUGINS_DIR='plugins';
|
722
575
|
|
723
|
-
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const
|
576
|
+
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const DEST_SDK_BASE_URL=`${SDK_CDN_BASE_URL}/beta/3.0.0-beta/${BUILD_TYPE}/${CDN_INT_DIR}`;const PLUGINS_BASE_URL=`${SDK_CDN_BASE_URL}/beta/3.0.0-beta/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;// TODO: change the above to production URLs when beta phase is done
|
724
577
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
725
578
|
// const PLUGINS_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;
|
726
579
|
const DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
|
727
580
|
|
728
581
|
const DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';const DEFAULT_STORAGE_ENCRYPTION_VERSION=StorageEncryptionVersion.V3;const ConsentManagersToPluginNameMap={oneTrust:PluginName.OneTrustConsentManager,ketch:PluginName.KetchConsentManager};const ErrorReportingProvidersToPluginNameMap={[DEFAULT_ERROR_REPORTING_PROVIDER]:PluginName.Bugsnag};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:PluginName.StorageEncryption,[StorageEncryptionVersion.Legacy]:PluginName.StorageEncryptionLegacy};
|
729
582
|
|
730
|
-
const defaultLoadOptions={logLevel:LogLevel.Error,configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:CookieSameSite.Lax,polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:UaChTrackLevel.None,plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false},sendAdblockPageOptions:{}};const loadOptionsState=
|
583
|
+
const defaultLoadOptions={logLevel:LogLevel.Error,configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:CookieSameSite.Lax,polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:UaChTrackLevel.None,plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false},sendAdblockPageOptions:{}};const loadOptionsState=d(clone$1(defaultLoadOptions));
|
731
584
|
|
732
|
-
const
|
585
|
+
const userSessionStorageKeys={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'};const defaultUserSessionValues={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{}};
|
733
586
|
|
734
|
-
const
|
587
|
+
const defaultSessionInfo={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};const sessionState={userId:d(defaultUserSessionValues.userId),userTraits:d(defaultUserSessionValues.userTraits),anonymousId:d(defaultUserSessionValues.anonymousId),groupId:d(defaultUserSessionValues.groupId),groupTraits:d(defaultUserSessionValues.groupTraits),initialReferrer:d(defaultUserSessionValues.initialReferrer),initialReferringDomain:d(defaultUserSessionValues.initialReferringDomain),sessionInfo:d(defaultUserSessionValues.sessionInfo)};
|
735
588
|
|
736
|
-
const
|
589
|
+
const capabilitiesState={isOnline:d(true),storage:{isLocalStorageAvailable:d(false),isCookieStorageAvailable:d(false),isSessionStorageAvailable:d(false)},isBeaconAvailable:d(false),isLegacyDOM:d(false),isUaCHAvailable:d(false),isCryptoAvailable:d(false),isIE11:d(false),isAdBlocked:d(false)};
|
737
590
|
|
738
|
-
const
|
591
|
+
const reportingState={isErrorReportingEnabled:d(false),isMetricsReportingEnabled:d(false),errorReportingProviderPluginName:d(undefined)};
|
739
592
|
|
740
|
-
const
|
593
|
+
const sourceConfigState=d(undefined);
|
741
594
|
|
742
|
-
const
|
595
|
+
const lifecycleState={activeDataplaneUrl:d(undefined),integrationsCDNPath:d(DEST_SDK_BASE_URL),pluginsCDNPath:d(PLUGINS_BASE_URL),sourceConfigUrl:d(undefined),status:d(undefined),initialized:d(false),logLevel:d(LogLevel.Error),loaded:d(false),readyCallbacks:d([]),writeKey:d(undefined),dataPlaneUrl:d(undefined)};
|
743
596
|
|
744
|
-
const
|
597
|
+
const consentsState={data:d({initialized:false}),activeConsentManagerPluginName:d(undefined),preConsentOptions:d({enabled:false})};
|
745
598
|
|
746
|
-
const
|
599
|
+
const metricsState={retries:d(0),dropped:d(0),sent:d(0),queued:d(0),triggered:d(0)};
|
747
600
|
|
748
|
-
const
|
601
|
+
const contextState={app:d({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:d(null),library:d({name:APP_NAME,version:APP_VERSION}),userAgent:d(''),device:d(null),network:d(null),os:d({name:'',version:''}),locale:d(null),screen:d({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d(undefined)};
|
749
602
|
|
750
|
-
const
|
603
|
+
const nativeDestinationsState={configuredDestinations:d([]),activeDestinations:d([]),loadOnlyIntegrations:d({}),failedDestinations:d([]),loadIntegration:d(true),initializedDestinations:d([]),clientDestinationsReady:d(false),integrationsConfig:d({})};
|
751
604
|
|
752
|
-
const
|
605
|
+
const eventBufferState={toBeProcessedArray:d([]),readyCallbacksArray:d([])};
|
753
606
|
|
754
|
-
const
|
607
|
+
const pluginsState={ready:d(false),loadedPlugins:d([]),failedPlugins:d([]),pluginsToLoadFromConfig:d([]),activePlugins:d([]),totalPluginsToLoad:d(0)};
|
608
|
+
|
609
|
+
const storageState={encryptionPluginName:d(undefined),migrate:d(false),type:d(undefined),cookie:d(undefined),entries:d({}),trulyAnonymousTracking:d(false)};
|
755
610
|
|
756
611
|
const 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};const state={...clone$1(defaultStateValues)};
|
757
612
|
|
@@ -813,7 +668,7 @@ destination.config.useNativeSDK===true);const isHybridModeDestination=destinatio
|
|
813
668
|
*/const remotePluginNames=[PluginName.BeaconQueue,PluginName.DeviceModeTransformation,PluginName.DeviceModeDestinations,PluginName.ErrorReporting,PluginName.ExternalAnonymousId,PluginName.GoogleLinker,PluginName.NativeDestinationQueue,PluginName.StorageEncryption,PluginName.StorageEncryptionLegacy,PluginName.StorageMigrator,PluginName.XhrQueue,PluginName.OneTrustConsentManager,PluginName.KetchConsentManager,PluginName.Bugsnag];
|
814
669
|
|
815
670
|
const remotesMap = {
|
816
|
-
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? "" + window.RudderStackGlobals.app.pluginsCDNPath + "/rsa-plugins.js" : "https://cdn.rudderlabs.com/3.0.0-beta.
|
671
|
+
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? "" + window.RudderStackGlobals.app.pluginsCDNPath + "/rsa-plugins.js" : "https://cdn.rudderlabs.com/3.0.0-beta.8/modern/plugins/rsa-plugins.js"),format:'esm',from:'vite'}
|
817
672
|
};
|
818
673
|
const loadJS = async (url, fn) => {
|
819
674
|
const resolvedUrl = typeof url === 'function' ? await url() : url;
|
@@ -885,7 +740,7 @@ const remotesMap = {
|
|
885
740
|
|
886
741
|
/**
|
887
742
|
* Get the lazy loaded dynamic import for a plugin name
|
888
|
-
*/const getFederatedModuleImport=pluginName=>{switch(pluginName){case PluginName.BeaconQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./BeaconQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.
|
743
|
+
*/const getFederatedModuleImport=pluginName=>{switch(pluginName){case PluginName.BeaconQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./BeaconQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.Bugsnag:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./Bugsnag").then(module=>__federation_method_wrapDefault(module, true));case PluginName.DeviceModeDestinations:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./DeviceModeDestinations").then(module=>__federation_method_wrapDefault(module, true));case PluginName.DeviceModeTransformation:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./DeviceModeTransformation").then(module=>__federation_method_wrapDefault(module, true));case PluginName.ErrorReporting:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./ErrorReporting").then(module=>__federation_method_wrapDefault(module, true));case PluginName.ExternalAnonymousId:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./ExternalAnonymousId").then(module=>__federation_method_wrapDefault(module, true));case PluginName.GoogleLinker:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./GoogleLinker").then(module=>__federation_method_wrapDefault(module, true));case PluginName.KetchConsentManager:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./KetchConsentManager").then(module=>__federation_method_wrapDefault(module, true));case PluginName.NativeDestinationQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./NativeDestinationQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.OneTrustConsentManager:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./OneTrustConsentManager").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageEncryption:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageEncryption").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageEncryptionLegacy:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageEncryptionLegacy").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageMigrator:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageMigrator").then(module=>__federation_method_wrapDefault(module, true));case PluginName.XhrQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./XhrQueue").then(module=>__federation_method_wrapDefault(module, true));default:return undefined;}};/**
|
889
744
|
* Map of active plugin names to their dynamic import
|
890
745
|
*/const modernBuildPluginImports=activePluginNames=>{const remotePlugins={};activePluginNames.forEach(pluginName=>{if(remotePluginNames.includes(pluginName)){const lazyLoadImport=getFederatedModuleImport(pluginName);if(lazyLoadImport){remotePlugins[pluginName]=lazyLoadImport;}}});return remotePlugins;};
|
891
746
|
|
@@ -906,7 +761,7 @@ class PluginsManager{constructor(engine,errorHandler,logger){this.engine=engine;
|
|
906
761
|
{setExposedGlobal('pluginsCDNPath',state.lifecycle.pluginsCDNPath.value);}this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
|
907
762
|
* Update state based on plugin loaded status
|
908
763
|
*/ // eslint-disable-next-line class-methods-use-this
|
909
|
-
attachEffects(){
|
764
|
+
attachEffects(){E(()=>{const isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){r(()=>{state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
|
910
765
|
// Should we stop here or should we progress?
|
911
766
|
state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
|
912
767
|
* Determine the list of plugins that should be loaded based on sourceConfig & load options
|
@@ -921,7 +776,7 @@ const supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsT
|
|
921
776
|
if(!state.storage.migrate.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(pluginName=>pluginName!==PluginName.StorageMigrator);}return [...Object.keys(getMandatoryPluginsMap()),...pluginsToLoadFromConfig];}/**
|
922
777
|
* Determine the list of plugins that should be activated
|
923
778
|
*/setActivePlugins(){const pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
924
|
-
const availablePlugins=[...Object.keys(pluginsInventory),...remotePluginNames];const activePlugins=[];const failedPlugins=[];pluginsToLoad.forEach(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: ${failedPlugins.join(',')}. Mandatory plugins: ${Object.keys(getMandatoryPluginsMap()).join(',')}. Load option plugins: ${state.plugins.pluginsToLoadFromConfig.value.join(',')}`));}
|
779
|
+
const availablePlugins=[...Object.keys(pluginsInventory),...remotePluginNames];const activePlugins=[];const failedPlugins=[];pluginsToLoad.forEach(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: ${failedPlugins.join(',')}. Mandatory plugins: ${Object.keys(getMandatoryPluginsMap()).join(',')}. Load option plugins: ${state.plugins.pluginsToLoadFromConfig.value.join(',')}`));}r(()=>{state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
|
925
780
|
* Register plugins that are direct imports to PluginEngine
|
926
781
|
*/registerLocalPlugins(){Object.values(pluginsInventory).forEach(localPlugin=>{if(state.plugins.activePlugins.value.includes(localPlugin().name)){this.register([localPlugin()]);}});}/**
|
927
782
|
* Register plugins that are dynamic imports to PluginEngine
|
@@ -969,22 +824,11 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(headerName=>{if(options
|
|
969
824
|
|
970
825
|
const COOKIE_STORAGE='cookieStorage';const LOCAL_STORAGE='localStorage';const SESSION_STORAGE='sessionStorage';const MEMORY_STORAGE='memoryStorage';const NO_STORAGE='none';
|
971
826
|
|
972
|
-
|
973
|
-
|
974
|
-
/**
|
975
|
-
* To get the current timestamp in ISO string format
|
976
|
-
* @returns ISO formatted timestamp string
|
977
|
-
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
978
|
-
|
979
|
-
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
980
|
-
|
981
|
-
var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
|
982
|
-
|
983
|
-
var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
|
827
|
+
let UserSessionKeys=/*#__PURE__*/function(UserSessionKeys){UserSessionKeys["userId"]="userId";UserSessionKeys["userTraits"]="userTraits";UserSessionKeys["anonymousId"]="anonymousId";UserSessionKeys["groupId"]="groupId";UserSessionKeys["groupTraits"]="groupTraits";UserSessionKeys["initialReferrer"]="initialReferrer";UserSessionKeys["initialReferringDomain"]="initialReferringDomain";UserSessionKeys["sessionInfo"]="sessionInfo";return UserSessionKeys;}({});
|
984
828
|
|
985
|
-
const
|
829
|
+
const STORAGE_TEST_COOKIE='test_rudder_cookie';const STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';const STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';const STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';const CLIENT_DATA_STORE_COOKIE='clientDataInCookie';const CLIENT_DATA_STORE_LS='clientDataInLocalStorage';const CLIENT_DATA_STORE_MEMORY='clientDataInMemory';
|
986
830
|
|
987
|
-
const
|
831
|
+
const storageClientDataStoreNameMap={[COOKIE_STORAGE]:CLIENT_DATA_STORE_COOKIE,[LOCAL_STORAGE]:CLIENT_DATA_STORE_LS,[MEMORY_STORAGE]:CLIENT_DATA_STORE_MEMORY};
|
988
832
|
|
989
833
|
const detectAdBlockers=(errorHandler,logger)=>{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
990
834
|
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
@@ -996,7 +840,7 @@ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:(r
|
|
996
840
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
997
841
|
state.capabilities.isAdBlocked.value=details?.error!==undefined||details?.xhr?.responseURL!==url;}});};
|
998
842
|
|
999
|
-
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);const isIE11=()=>Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));
|
843
|
+
const hasCrypto$1=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);const isIE11=()=>Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));
|
1000
844
|
|
1001
845
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
1002
846
|
|
@@ -1145,12 +989,14 @@ return JSON.parse(str);}catch(err){this.onError(new Error(`${STORE_DATA_FETCH_ER
|
|
1145
989
|
* A service to manage stores & available storage client configurations
|
1146
990
|
*/class StoreManager{stores={};isInitialized=false;hasErrorHandler=false;constructor(pluginsManager,errorHandler,logger){this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
|
1147
991
|
* Configure available storage client instances
|
1148
|
-
*/init(){if(this.isInitialized){return;}const config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(config.cookieOptions),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
|
992
|
+
*/init(){if(this.isInitialized){return;}const config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(mergeDeepRight(config.cookieOptions||{},state.storage.cookie?.value||{})),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
|
1149
993
|
* Create store to persist data used by the SDK like session, used details etc
|
1150
|
-
*/initClientDataStore(){const
|
1151
|
-
if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){finalStorageType=COOKIE_STORAGE;}else if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger?.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,storageType,finalStorageType));}
|
994
|
+
*/initClientDataStore(){const globalStorageType=state.storage.type.value;let trulyAnonymousTracking=true;const entries=state.loadOptions.value.storage?.entries;Object.keys(UserSessionKeys).forEach(sessionKey=>{const key=sessionKey;const storageKey=sessionKey;const providedStorageType=entries?.[key]?.type;const storageType=providedStorageType||globalStorageType||DEFAULT_STORAGE_TYPE;let finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!getStorageEngine(LOCAL_STORAGE)?.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
|
995
|
+
if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){finalStorageType=COOKIE_STORAGE;}else if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger?.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,storageType,finalStorageType));}if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}const storageState=state.storage.entries.value;state.storage.entries.value={...storageState,[sessionKey]:{type:finalStorageType,key:userSessionStorageKeys[storageKey]}};});state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
1152
996
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
1153
|
-
|
997
|
+
// Initializing all the enabled store because previous user data might be in different storage
|
998
|
+
// that needs auto migration
|
999
|
+
const storageTypesRequiringInitialization=[MEMORY_STORAGE];if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){storageTypesRequiringInitialization.push(LOCAL_STORAGE);}if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){storageTypesRequiringInitialization.push(COOKIE_STORAGE);}storageTypesRequiringInitialization.forEach(storageType=>{this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});});}/**
|
1154
1000
|
* Create a new store
|
1155
1001
|
*/setStore(storeConfig){const storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
|
1156
1002
|
* Retrieve a store
|
@@ -1206,7 +1052,7 @@ const defaultOptionalPluginsList=[PluginName.Bugsnag,PluginName.DeviceModeDestin
|
|
1206
1052
|
*/const isPositiveInteger=num=>isNumber(num)&&num>=0&&Number.isInteger(num);
|
1207
1053
|
|
1208
1054
|
const normalizeLoadOptions=(loadOptionsFromState,loadOptions)=>{// TODO: Maybe add warnings for invalid values
|
1209
|
-
const normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=normalizedLoadOpts.plugins??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 {normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=normalizedLoadOpts.storage?.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;}const mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};const getSourceConfigURL=(configUrl,writeKey,lockIntegrationsVersion,logger)=>{const defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});let origin=DEFAULT_CONFIG_BE_URL;let searchParams=defSearchParams;let pathname='/sourceConfig/';let hash='';// Ideally, this check is not required but URL polyfill
|
1055
|
+
const normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=normalizedLoadOpts.plugins??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 {normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=normalizedLoadOpts.storage?.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.storage?.cookie)){delete normalizedLoadOpts.storage?.cookie;}else {normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues(normalizedLoadOpts.storage?.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}const mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};const getSourceConfigURL=(configUrl,writeKey,lockIntegrationsVersion,logger)=>{const defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});let origin=DEFAULT_CONFIG_BE_URL;let searchParams=defSearchParams;let pathname='/sourceConfig/';let hash='';// Ideally, this check is not required but URL polyfill
|
1210
1056
|
// doesn't seem to throw errors for empty URLs
|
1211
1057
|
// TODO: Need to improve this check to find out if the URL is valid or not
|
1212
1058
|
if(configUrl){try{const configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname=`${removeTrailingSlashes(configUrlInstance.pathname)}/sourceConfig/`;}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach((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?.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return `${origin}${pathname}?${searchParams}${hash}`;};
|
@@ -1234,21 +1080,39 @@ if(dataplanes&&Object.keys(dataplanes).length>0){const region=validateResidencyS
|
|
1234
1080
|
if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
|
1235
1081
|
return undefined;};
|
1236
1082
|
|
1083
|
+
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY=StorageStrategy.None;const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE=DeliveryType.Immediate;
|
1084
|
+
|
1237
1085
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const getErrorReportingProviderNameFromConfig=sourceConfig=>sourceConfig?.statsCollection?.errors?.provider;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
1238
1086
|
|
1087
|
+
/**
|
1088
|
+
* A function to get the name of the consent manager with enabled true set in the load options
|
1089
|
+
* @param cookieConsentOptions Input provided as load option
|
1090
|
+
* @returns string|undefined
|
1091
|
+
*
|
1092
|
+
* Example input: {
|
1093
|
+
* oneTrust:{
|
1094
|
+
* enabled: true
|
1095
|
+
* }
|
1096
|
+
* }
|
1097
|
+
*
|
1098
|
+
* Output: 'oneTrust'
|
1099
|
+
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1100
|
+
|
1239
1101
|
/**
|
1240
1102
|
* Determines the SDK url
|
1241
1103
|
* @returns sdkURL
|
1242
|
-
*/const getSDKUrl=()=>{const scripts=document.getElementsByTagName('script');let sdkURL;const scriptList=Array.prototype.slice.call(scripts);scriptList.some(script=>{const curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){const urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;})
|
1243
|
-
return sdkURL;};/**
|
1104
|
+
*/const getSDKUrl=()=>{const scripts=document.getElementsByTagName('script');let sdkURL;const scriptList=Array.prototype.slice.call(scripts);scriptList.some(script=>{const curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){const urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;});return sdkURL;};/**
|
1244
1105
|
* Updates the reporting state variables from the source config data
|
1245
1106
|
* @param res Source config
|
1246
1107
|
* @param logger Logger instance
|
1247
1108
|
*/const updateReportingState=(res,logger)=>{state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config);state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){const errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
|
1248
1109
|
const errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
1249
|
-
logger?.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin??ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};const updateStorageState=logger=>{
|
1250
|
-
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;}
|
1251
|
-
const configuredMigrationValue=
|
1110
|
+
logger?.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin??ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};const updateStorageState=logger=>{const storageOptsFromLoad=state.loadOptions.value.storage;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
1111
|
+
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
|
1112
|
+
const configuredMigrationValue=storageOptsFromLoad?.migrate;const finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&state.storage.migrate.value!==configuredMigrationValue){logger?.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(()=>{state.storage.type.value=storageType;state.storage.cookie.value=storageOptsFromLoad?.cookie;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};const updateConsentsState=logger=>{// Get the consent manager if provided as load option
|
1113
|
+
const selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);let consentManagerPluginName;if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
1114
|
+
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){logger?.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}// Pre-consent
|
1115
|
+
const preConsentOpts=state.loadOptions.value.preConsent;let storageStrategy=preConsentOpts?.storage?.strategy??DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;if(isDefined(storageStrategy)&&!Object.values(StorageStrategy).includes(storageStrategy)){storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger?.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts?.storage?.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}let eventsDeliveryType=preConsentOpts?.events?.delivery??DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;if(isDefined(eventsDeliveryType)&&!Object.values(DeliveryType).includes(eventsDeliveryType)){eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger?.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts?.events?.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(()=>{state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.preConsentOptions.value={enabled:state.loadOptions.value.preConsent?.enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType},trackConsent:state.loadOptions.value.preConsent?.trackConsent===true};});};
|
1252
1116
|
|
1253
1117
|
/**
|
1254
1118
|
* A function that determines integration SDK loading path
|
@@ -1267,43 +1131,25 @@ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_
|
|
1267
1131
|
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
|
1268
1132
|
const sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
|
1269
1133
|
|
1270
|
-
/**
|
1271
|
-
* A function to get the name of the consent manager with enabled true set in the load options
|
1272
|
-
* @param cookieConsentOptions Input provided as load option
|
1273
|
-
* @returns string|undefined
|
1274
|
-
*
|
1275
|
-
* Example input: {
|
1276
|
-
* oneTrust:{
|
1277
|
-
* enabled: true
|
1278
|
-
* }
|
1279
|
-
* }
|
1280
|
-
*
|
1281
|
-
* Output: 'oneTrust'
|
1282
|
-
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1283
|
-
|
1284
|
-
class ConfigManager{hasErrorHandler=false;constructor(httpClient,errorHandler,logger){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);}attachEffects(){b(()=>{this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
1134
|
+
class ConfigManager{hasErrorHandler=false;constructor(httpClient,errorHandler,logger){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);}attachEffects(){E(()=>{this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
1285
1135
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
1286
1136
|
* config related information in global state
|
1287
|
-
*/init(){
|
1137
|
+
*/init(){this.attachEffects();const lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
1288
1138
|
const intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
1289
|
-
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);//
|
1290
|
-
|
1291
|
-
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){this.logger?.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}updateStorageState(this.logger);// set application lifecycle state in global state
|
1292
|
-
o(()=>{state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,this.logger);// Set consent manager plugin name in state
|
1293
|
-
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
1294
|
-
const storageType=state.loadOptions.value.storage?.type;if(!isValidStorageType(storageType)){this.logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));state.storage.type.value=DEFAULT_STORAGE_TYPE;}else {state.storage.type.value=storageType;}});this.getConfig();}/**
|
1139
|
+
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageState(this.logger);updateConsentsState(this.logger);// set application lifecycle state in global state
|
1140
|
+
r(()=>{state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,this.logger);});this.getConfig();}/**
|
1295
1141
|
* Handle errors
|
1296
1142
|
*/onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){this.errorHandler?.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
|
1297
1143
|
* A callback function that is executed once we fetch the source config response.
|
1298
1144
|
* Use to construct and store information that are dependent on the sourceConfig.
|
1299
1145
|
*/processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
1300
1146
|
// We can use isErrRetryable utility method
|
1301
|
-
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error));return;}let res;const errMessage='Unable to process/parse source config';try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(e){this.onError(e,errMessage,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(errMessage),undefined,true);return;}//
|
1147
|
+
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error));return;}let res;const errMessage='Unable to process/parse source config';try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(e){this.onError(e,errMessage,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(errMessage),undefined,true);return;}// set the values in state for reporting slice
|
1148
|
+
updateReportingState(res,this.logger);// determine the dataPlane url
|
1302
1149
|
const 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;}const nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
1303
|
-
|
1150
|
+
r(()=>{// set source related information in state
|
1304
1151
|
state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
|
1305
|
-
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the
|
1306
|
-
updateReportingState(res,this.logger);// set the desired optional plugins
|
1152
|
+
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
1307
1153
|
state.plugins.pluginsToLoadFromConfig.value=state.loadOptions.value.plugins??[];// set application lifecycle state
|
1308
1154
|
// Cast to string as we are sure that the value is not undefined
|
1309
1155
|
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value=LifecycleStatus.Configured;});}/**
|
@@ -1338,11 +1184,11 @@ const POLYFILL_SCRIPT_ID='rudderstackPolyfill';
|
|
1338
1184
|
class CapabilitiesManager{constructor(errorHandler,logger){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);}init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
|
1339
1185
|
* Detect supported capabilities and set values in state
|
1340
1186
|
*/ // eslint-disable-next-line class-methods-use-this
|
1341
|
-
detectBrowserCapabilities(){
|
1187
|
+
detectBrowserCapabilities(){r(()=>{// Storage related details
|
1342
1188
|
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
|
1343
|
-
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
|
1189
|
+
state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto$1();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
|
1344
1190
|
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();if(hasUAClientHints()){getUserAgentClientHint(uach=>{state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
1345
|
-
|
1191
|
+
E(()=>{if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(this.errorHandler,this.logger);}});}/**
|
1346
1192
|
* Detect if polyfills are required and then load script from polyfill URL
|
1347
1193
|
*/prepareBrowserCapabilities(){state.capabilities.isLegacyDOM.value=isLegacyJSEngine();let polyfillUrl=state.loadOptions.value.polyfillURL??POLYFILL_URL;const shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){const isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){const polyfillCallback=()=>this.onReady();// write key specific callback
|
1348
1194
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
@@ -1357,11 +1203,28 @@ onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=Lifecycl
|
|
1357
1203
|
* @param error The error object
|
1358
1204
|
*/onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}
|
1359
1205
|
|
1206
|
+
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
1207
|
+
|
1208
|
+
var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
|
1209
|
+
|
1210
|
+
var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
|
1211
|
+
|
1212
|
+
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);
|
1213
|
+
|
1214
|
+
const generateUUID=()=>{if(hasCrypto()){return v4$1();}return v4();};
|
1215
|
+
|
1216
|
+
/**
|
1217
|
+
* To get the current timestamp in ISO string format
|
1218
|
+
* @returns ISO formatted timestamp string
|
1219
|
+
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
1220
|
+
|
1221
|
+
const DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
1222
|
+
|
1360
1223
|
const CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
1361
1224
|
const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
1362
1225
|
// Typically, these elements are not allowed to be overridden by the user
|
1363
1226
|
const CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
1364
|
-
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1227
|
+
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1365
1228
|
|
1366
1229
|
/**
|
1367
1230
|
* To get the page properties for context object
|
@@ -1376,7 +1239,6 @@ const curPageProps=getDefaultPageProperties();const ctxPageProps={};Object.keys(
|
|
1376
1239
|
const curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(key=>{if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||curPageProps[key];}});if(isUndefined(pageProps.initial_referrer)){pageProps.initial_referrer=optionsPageProps.initial_referrer||state.session.initialReferrer.value;}if(isUndefined(pageProps.initial_referring_domain)){pageProps.initial_referring_domain=optionsPageProps.initial_referring_domain||state.session.initialReferringDomain.value;}return pageProps;};/**
|
1377
1240
|
* Utility to check for reserved keys in the input object
|
1378
1241
|
* @param obj Generic object
|
1379
|
-
* @param eventType Rudder event type
|
1380
1242
|
* @param parentKeyPath Object's parent key path
|
1381
1243
|
* @param logger Logger instance
|
1382
1244
|
*/const checkForReservedElementsInObject=(obj,parentKeyPath,logger)=>{if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(property=>{if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger?.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
|
@@ -1416,9 +1278,10 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
|
|
1416
1278
|
* @param pageProps Page properties
|
1417
1279
|
* @param logger logger
|
1418
1280
|
* @returns Enriched RudderEvent object
|
1419
|
-
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger)=>{const commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.
|
1420
|
-
commonEventData.anonymousId=generateUUID();
|
1421
|
-
commonEventData.anonymousId=state.session.
|
1281
|
+
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger)=>{const commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.entries.value.anonymousId?.type===NO_STORAGE){// Generate new anonymous id for each request
|
1282
|
+
commonEventData.anonymousId=generateUUID();}else {// Type casting to string as the user session manager will take care of initializing the value
|
1283
|
+
commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
|
1284
|
+
if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type===RudderEventType.Identify){commonEventData.context.traits=state.storage.entries.value.userTraits?.type!==NO_STORAGE?clone$1(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type===RudderEventType.Group){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){commonEventData.traits=state.storage.entries.value.groupTraits?.type!==NO_STORAGE?clone$1(state.session.groupTraits.value):rudderEvent.traits;}}const processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
|
1422
1285
|
// matching with v1.1 payload
|
1423
1286
|
if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);// TODO: We might not need this check altogether
|
1424
1287
|
checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
|
@@ -1492,17 +1355,15 @@ timeout,sessionStart:undefined,autoTrack:true};};/**
|
|
1492
1355
|
* @param id Provided sessionId
|
1493
1356
|
* @param logger Logger module
|
1494
1357
|
* @returns SessionInfo
|
1495
|
-
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};
|
1358
|
+
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>!!(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===MEMORY_STORAGE);
|
1496
1359
|
|
1497
|
-
|
1498
|
-
|
1499
|
-
class UserSessionManager{constructor(errorHandler,logger,pluginsManager,store){this.store=store;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
|
1360
|
+
class UserSessionManager{constructor(errorHandler,logger,pluginsManager,storeManager){this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
|
1500
1361
|
* Initialize User session with values from storage
|
1501
1362
|
* @param store Selected store
|
1502
|
-
*/init(
|
1503
|
-
this.
|
1504
|
-
this.initializeSessionTracking()
|
1505
|
-
this.registerEffects();}
|
1363
|
+
*/init(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
1364
|
+
const userId=this.getUserId();const userTraits=this.getUserTraits();const groupId=this.getGroupId();const groupTraits=this.getGroupTraits();const anonymousId=this.getAnonymousId();if(userId){this.setUserId(userId);}if(userTraits){this.setUserTraits(userTraits);}if(groupId){this.setGroupId(groupId);}if(groupTraits){this.setGroupTraits(groupTraits);}if(anonymousId){this.setAnonymousId(anonymousId);}const initialReferrer=this.getInitialReferrer();const initialReferringDomain=this.getInitialReferringDomain();if(initialReferrer&&initialReferringDomain){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(initialReferringDomain);}else if(initialReferrer){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}else {const referrer=getReferrer();this.setInitialReferrer(referrer);this.setInitialReferringDomain(getReferringDomain(referrer));}// Initialize session tracking
|
1365
|
+
if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.sessionInfo)){this.initializeSessionTracking();}// Register the effect to sync with storage
|
1366
|
+
this.registerEffects();}isPersistenceEnabledForStorageEntry(entryName){const entries=state.storage.entries.value;return isStorageTypeValidForStoringData(entries[entryName]?.type);}migrateDataFromPreviousStorage(){const entries=state.storage.entries.value;Object.keys(entries).forEach(entry=>{const key=entry;const currentStorage=entries[key]?.type;const curStore=this.storeManager?.getStore(storageClientDataStoreNameMap[currentStorage]);const storages=[COOKIE_STORAGE,LOCAL_STORAGE];storages.forEach(storage=>{const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);if(storage!==currentStorage&&store){if(curStore){const value=store?.get(userSessionStorageKeys[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore?.set(userSessionStorageKeys[key],value);}}store?.remove(userSessionStorageKeys[key]);}});});}migrateStorageIfNeeded(){if(!state.storage.migrate.value){return;}const cookieStorage=this.storeManager?.getStore(CLIENT_DATA_STORE_COOKIE);const localStorage=this.storeManager?.getStore(CLIENT_DATA_STORE_LS);const stores=[];if(cookieStorage){stores.push(cookieStorage);}if(localStorage){stores.push(localStorage);}Object.keys(userSessionStorageKeys).forEach(storageEntryKey=>{const key=storageEntryKey;const storageEntry=userSessionStorageKeys[key];stores.forEach(store=>{const migratedVal=this.pluginsManager?.invokeSingle('storage.migrate',storageEntry,store.engine,this.errorHandler,this.logger);if(migratedVal){store.set(storageEntry,migratedVal);}});});}/**
|
1506
1367
|
* A function to initialize sessionTracking
|
1507
1368
|
*/initializeSessionTracking(){const sessionInfo=this.getSessionFromStorage()??defaultSessionInfo;let finalAutoTrackingStatus=!(state.loadOptions.value.sessions.autoTrack===false||sessionInfo.manualTrack===true);let sessionTimeout;const configuredSessionTimeout=state.loadOptions.value.sessions.timeout;if(!isPositiveInteger(configuredSessionTimeout)){this.logger?.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));sessionTimeout=DEFAULT_SESSION_TIMEOUT_MS;}else {sessionTimeout=configuredSessionTimeout;}if(sessionTimeout===0){this.logger?.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));finalAutoTrackingStatus=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
|
1508
1369
|
// and will proceed with it
|
@@ -1514,87 +1375,90 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
1514
1375
|
* A function to sync values in storage
|
1515
1376
|
* @param key
|
1516
1377
|
* @param value
|
1517
|
-
*/syncValueToStorage(
|
1378
|
+
*/syncValueToStorage(sessionKey,value){const entries=state.storage.entries.value;const storage=entries[sessionKey]?.type;const key=entries[sessionKey]?.key;if(isStorageTypeValidForStoringData(storage)){const curStore=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);if(value&&isString(value)||isNonEmptyObject(value)){curStore?.set(key,value);}else {curStore?.remove(key);}}}/**
|
1518
1379
|
* Function to update storage whenever state value changes
|
1519
1380
|
*/registerEffects(){/**
|
1520
1381
|
* Update userId in storage automatically when userId is updated in state
|
1521
|
-
*/
|
1382
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userId,state.session.userId.value);});/**
|
1522
1383
|
* Update user traits in storage automatically when it is updated in state
|
1523
|
-
*/
|
1384
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userTraits,state.session.userTraits.value);});/**
|
1524
1385
|
* Update group id in storage automatically when it is updated in state
|
1525
|
-
*/
|
1386
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupId,state.session.groupId.value);});/**
|
1526
1387
|
* Update group traits in storage automatically when it is updated in state
|
1527
|
-
*/
|
1388
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupTraits,state.session.groupTraits.value);});/**
|
1528
1389
|
* Update anonymous user id in storage automatically when it is updated in state
|
1529
|
-
*/
|
1390
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.anonymousId,state.session.anonymousId.value);});/**
|
1530
1391
|
* Update initial referrer in storage automatically when it is updated in state
|
1531
|
-
*/
|
1392
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferrer,state.session.initialReferrer.value);});/**
|
1532
1393
|
* Update initial referring domain in storage automatically when it is updated in state
|
1533
|
-
*/
|
1394
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferringDomain,state.session.initialReferringDomain.value);});/**
|
1534
1395
|
* Update session tracking info in storage automatically when it is updated in state
|
1535
|
-
*/
|
1396
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.sessionInfo,state.session.sessionInfo.value);});}/**
|
1536
1397
|
* Sets anonymous id in the following precedence:
|
1537
1398
|
*
|
1538
1399
|
* 1. anonymousId: Id directly provided to the function.
|
1539
1400
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
1540
1401
|
* using parseLinker util.
|
1541
1402
|
* 3. generateUUID: A new unique id is generated and assigned.
|
1542
|
-
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){
|
1403
|
+
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){let finalAnonymousId=anonymousId;const storage=state.storage.entries.value.anonymousId?.type;if(isStorageTypeValidForStoringData(storage)){if(!finalAnonymousId&&rudderAmpLinkerParam){const linkerPluginsResult=this.pluginsManager?.invokeMultiple('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult?.[0];}state.session.anonymousId.value=finalAnonymousId||this.generateAnonymousId();}}/**
|
1543
1404
|
* Generate a new anonymousId
|
1544
1405
|
* @returns string anonymousID
|
1545
1406
|
*/generateAnonymousId(){return generateUUID();}/**
|
1546
1407
|
* Fetches anonymousId
|
1547
1408
|
* @param options option to fetch it from external source
|
1548
1409
|
* @returns anonymousId
|
1549
|
-
*/getAnonymousId(options){
|
1550
|
-
|
1551
|
-
const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.
|
1410
|
+
*/getAnonymousId(options){const storage=state.storage.entries.value.anonymousId?.type;const key=state.storage.entries.value.anonymousId?.key;let persistedAnonymousId;// fetch the anonymousId from storage
|
1411
|
+
if(isStorageTypeValidForStoringData(storage)){const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);persistedAnonymousId=store?.get(key);if(!persistedAnonymousId&&options){// fetch anonymousId from external source
|
1412
|
+
const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||this.generateAnonymousId();}return state.session.anonymousId.value;}getItem(sessionKey){const entries=state.storage.entries.value;const storage=entries[sessionKey]?.type;const key=entries[sessionKey]?.key;if(isStorageTypeValidForStoringData(storage)){const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);return store?.get(key)??null;}return null;}/**
|
1552
1413
|
* Fetches User Id
|
1553
1414
|
* @returns
|
1554
|
-
*/getUserId(){return this.
|
1415
|
+
*/getUserId(){return this.getItem(UserSessionKeys.userId);}/**
|
1555
1416
|
* Fetches User Traits
|
1556
1417
|
* @returns
|
1557
|
-
*/getUserTraits(){return this.
|
1418
|
+
*/getUserTraits(){return this.getItem(UserSessionKeys.userTraits);}/**
|
1558
1419
|
* Fetches Group Id
|
1559
1420
|
* @returns
|
1560
|
-
*/getGroupId(){return this.
|
1421
|
+
*/getGroupId(){return this.getItem(UserSessionKeys.groupId);}/**
|
1561
1422
|
* Fetches Group Traits
|
1562
1423
|
* @returns
|
1563
|
-
*/getGroupTraits(){return this.
|
1424
|
+
*/getGroupTraits(){return this.getItem(UserSessionKeys.groupTraits);}/**
|
1564
1425
|
* Fetches Initial Referrer
|
1565
1426
|
* @returns
|
1566
|
-
*/getInitialReferrer(){return this.
|
1427
|
+
*/getInitialReferrer(){return this.getItem(UserSessionKeys.initialReferrer);}/**
|
1567
1428
|
* Fetches Initial Referring domain
|
1568
1429
|
* @returns
|
1569
|
-
*/getInitialReferringDomain(){return this.
|
1430
|
+
*/getInitialReferringDomain(){return this.getItem(UserSessionKeys.initialReferringDomain);}/**
|
1570
1431
|
* Fetches session tracking information from storage
|
1571
1432
|
* @returns
|
1572
|
-
*/getSessionFromStorage(){return this.
|
1433
|
+
*/getSessionFromStorage(){return this.getItem(UserSessionKeys.sessionInfo);}/**
|
1434
|
+
* If session is active it returns the sessionId
|
1435
|
+
* @returns
|
1436
|
+
*/getSessionId(){if(state.session.sessionInfo.value.autoTrack&&!hasSessionExpired(state.session.sessionInfo.value.expiresAt)||state.session.sessionInfo.value.manualTrack){return state.session.sessionInfo.value.id||null;}return null;}/**
|
1573
1437
|
* A function to update current session info after each event call
|
1574
1438
|
*/refreshSession(){if(state.session.sessionInfo.value.autoTrack||state.session.sessionInfo.value.manualTrack){if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}if(state.session.sessionInfo.value.sessionStart===undefined){state.session.sessionInfo.value={...state.session.sessionInfo.value,sessionStart:true};}else if(state.session.sessionInfo.value.sessionStart){state.session.sessionInfo.value={...state.session.sessionInfo.value,sessionStart:false};}}}/**
|
1575
1439
|
* Reset state values
|
1576
1440
|
* @param resetAnonymousId
|
1577
1441
|
* @param noNewSessionStart
|
1578
1442
|
* @returns
|
1579
|
-
*/reset(resetAnonymousId,noNewSessionStart){const{manualTrack,autoTrack}=state.session.sessionInfo.value;
|
1443
|
+
*/reset(resetAnonymousId,noNewSessionStart){const{manualTrack,autoTrack}=state.session.sessionInfo.value;r(()=>{state.session.userId.value=defaultUserSessionValues.userId;state.session.userTraits.value=defaultUserSessionValues.userTraits;state.session.groupId.value=defaultUserSessionValues.groupId;state.session.groupTraits.value=defaultUserSessionValues.groupTraits;if(resetAnonymousId){state.session.anonymousId.value=defaultUserSessionValues.anonymousId;}if(noNewSessionStart){return;}if(autoTrack){state.session.sessionInfo.value=defaultUserSessionValues.sessionInfo;this.startOrRenewAutoTracking();}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
1580
1444
|
* Set user Id
|
1581
1445
|
* @param userId
|
1582
|
-
*/setUserId(userId){if(this.
|
1446
|
+
*/setUserId(userId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userId)){state.session.userId.value=userId;}}/**
|
1583
1447
|
* Set user traits
|
1584
1448
|
* @param traits
|
1585
|
-
*/setUserTraits(traits){if(
|
1449
|
+
*/setUserTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userTraits)&&traits){state.session.userTraits.value=mergeDeepRight(state.session.userTraits.value??{},traits);}}/**
|
1586
1450
|
* Set group Id
|
1587
1451
|
* @param groupId
|
1588
|
-
*/setGroupId(groupId){if(this.
|
1452
|
+
*/setGroupId(groupId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupId)){state.session.groupId.value=groupId;}}/**
|
1589
1453
|
* Set group traits
|
1590
1454
|
* @param traits
|
1591
|
-
*/setGroupTraits(traits){if(
|
1455
|
+
*/setGroupTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupTraits)&&traits){state.session.groupTraits.value=mergeDeepRight(state.session.groupTraits.value??{},traits);}}/**
|
1592
1456
|
* Set initial referrer
|
1593
1457
|
* @param referrer
|
1594
|
-
*/setInitialReferrer(referrer){if(this.
|
1458
|
+
*/setInitialReferrer(referrer){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferrer)){state.session.initialReferrer.value=referrer;}}/**
|
1595
1459
|
* Set initial referring domain
|
1596
1460
|
* @param referrer
|
1597
|
-
*/setInitialReferringDomain(
|
1461
|
+
*/setInitialReferringDomain(referringDomain){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferringDomain)){state.session.initialReferringDomain.value=referringDomain;}}/**
|
1598
1462
|
* A function to check for existing session details and depending on that create a new session.
|
1599
1463
|
*/startOrRenewAutoTracking(){if(hasSessionExpired(state.session.sessionInfo.value.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(state.session.sessionInfo.value.timeout);}else {const timestamp=Date.now();const timeout=state.session.sessionInfo.value.timeout;state.session.sessionInfo.value=mergeDeepRight(state.session.sessionInfo.value,{expiresAt:timestamp+timeout// set the expiry time of the session
|
1600
1464
|
});}}/**
|
@@ -1605,10 +1469,7 @@ const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnon
|
|
1605
1469
|
* An internal function to start manual session
|
1606
1470
|
*/startManualTrackingInternal(){this.start(Date.now());}/**
|
1607
1471
|
* A public method to end an ongoing session.
|
1608
|
-
*/end(){state.session.sessionInfo.value={};}
|
1609
|
-
* Clear storage
|
1610
|
-
* @param resetAnonymousId
|
1611
|
-
*/clearUserSessionStorage(resetAnonymousId){this.store?.remove(userSessionStorageKeys.userId);this.store?.remove(userSessionStorageKeys.userTraits);this.store?.remove(userSessionStorageKeys.groupId);this.store?.remove(userSessionStorageKeys.groupTraits);if(resetAnonymousId){this.store?.remove(userSessionStorageKeys.anonymousUserId);}}}
|
1472
|
+
*/end(){state.session.sessionInfo.value={};}}
|
1612
1473
|
|
1613
1474
|
/**
|
1614
1475
|
* A buffer queue to serve as a store for any type of data
|
@@ -1616,6 +1477,20 @@ const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnon
|
|
1616
1477
|
|
1617
1478
|
const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';
|
1618
1479
|
|
1480
|
+
/**
|
1481
|
+
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1482
|
+
* @param eventIntgConfig User supplied integrations config at event level
|
1483
|
+
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
1484
|
+
* @returns Filtered user supplied integrations config
|
1485
|
+
*/const getOverriddenIntegrationOptions=(eventIntgConfig,destinationsIntgConfig)=>Object.keys(eventIntgConfig).filter(intgName=>eventIntgConfig[intgName]!==true||!destinationsIntgConfig[intgName]).reduce((obj,key)=>{const retVal=clone$1(obj);retVal[key]=eventIntgConfig[key];return retVal;},{});/**
|
1486
|
+
* Returns the event object with final integrations config
|
1487
|
+
* @param event RudderEvent object
|
1488
|
+
* @param state Application state
|
1489
|
+
* @returns Mutated event with final integrations config
|
1490
|
+
*/const getFinalEvent=(event,state)=>{const finalEvent=clone$1(event);// Merge the destination specific integrations config with the event's integrations config
|
1491
|
+
// In general, the preference is given to the event's integrations config
|
1492
|
+
const eventIntgConfig=event.integrations??DEFAULT_INTEGRATIONS_CONFIG;const destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;const overriddenIntgOpts=getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};
|
1493
|
+
|
1619
1494
|
/**
|
1620
1495
|
* Event repository class responsible for queuing events for further processing and delivery
|
1621
1496
|
*/class EventRepository{/**
|
@@ -1627,16 +1502,16 @@ const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATION
|
|
1627
1502
|
*/constructor(pluginsManager,storeManager,errorHandler,logger){this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
|
1628
1503
|
* Initializes the event repository
|
1629
1504
|
*/init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.init`,state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.init`,state,this.pluginsManager,this.storeManager,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
|
1630
|
-
|
1505
|
+
E(()=>{if(state.nativeDestinations.clientDestinationsReady.value===true){this.destinationsEventsQueue?.start();}});// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
1631
1506
|
// However, events will be enqueued for now.
|
1632
1507
|
// At the time of processing the events, the integrations config data from destinations
|
1633
1508
|
// is merged into the event object
|
1634
|
-
let timeoutId;
|
1509
|
+
let timeoutId;E(()=>{const shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;const hybridDestExist=state.nativeDestinations.activeDestinations.value.some(dest=>isHybridModeDestination(dest));if((hybridDestExist===false||shouldBufferDpEvents===false)&&this.dataplaneEventsQueue?.scheduleTimeoutActive!==true){globalThis.clearTimeout(timeoutId);this.dataplaneEventsQueue?.start();}});// Force start the data plane events queue processing after a timeout
|
1635
1510
|
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(()=>{if(this.dataplaneEventsQueue?.scheduleTimeoutActive!==true){this.dataplaneEventsQueue?.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}/**
|
1636
1511
|
* Enqueues the event for processing
|
1637
1512
|
* @param event RudderEvent object
|
1638
1513
|
* @param callback API callback function
|
1639
|
-
*/enqueue(event,callback){const dpQEvent=
|
1514
|
+
*/enqueue(event,callback){const dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle(`${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.enqueue`,state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);const dQEvent=clone$1(event);this.pluginsManager.invokeSingle(`${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.enqueue`,state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
|
1640
1515
|
try{// Using the event sent to the data plane queue here
|
1641
1516
|
// to ensure the mutated (if any) event is sent to the callback
|
1642
1517
|
callback?.(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
@@ -1654,25 +1529,25 @@ callback?.(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR)
|
|
1654
1529
|
* Start application lifecycle if not already started
|
1655
1530
|
*/load(writeKey,dataPlaneUrl,loadOptions={}){if(state.lifecycle.status.value){return;}let clonedDataPlaneUrl=clone$1(dataPlaneUrl);let clonedLoadOptions=clone$1(loadOptions);// dataPlaneUrl is not provided
|
1656
1531
|
if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
|
1657
|
-
|
1532
|
+
r(()=>{state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value=LifecycleStatus.Mounted;});// Expose state to global objects
|
1658
1533
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
1659
1534
|
// State application lifecycle
|
1660
1535
|
this.startLifecycle();}// Start lifecycle methods
|
1661
1536
|
/**
|
1662
1537
|
* Orchestrate the lifecycle of the application phases/status
|
1663
|
-
*/startLifecycle(){
|
1538
|
+
*/startLifecycle(){E(()=>{try{switch(state.lifecycle.status.value){case LifecycleStatus.Mounted:this.prepareBrowserCapabilities();break;case LifecycleStatus.BrowserCapabilitiesReady:// initialize the preloaded events enqueuing
|
1664
1539
|
retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();break;case LifecycleStatus.Configured:this.loadPlugins();break;case LifecycleStatus.PluginsLoading:break;case LifecycleStatus.PluginsReady:this.init();break;case LifecycleStatus.Initialized:this.onInitialized();break;case LifecycleStatus.Loaded:this.loadDestinations();this.processBufferedEvents();break;case LifecycleStatus.DestinationsLoading:break;case LifecycleStatus.DestinationsReady:this.onDestinationsReady();break;case LifecycleStatus.Ready:this.onReady();break;default:break;}}catch(err){const issue='Failed to load the SDK';this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}/**
|
1665
1540
|
* Load browser polyfill if required
|
1666
1541
|
*/prepareBrowserCapabilities(){this.capabilitiesManager.init();}/**
|
1667
1542
|
* Enqueue in SDK preload buffer events, used from preloadBuffer component
|
1668
1543
|
*/enqueuePreloadBufferEvents(bufferedEvents){if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(bufferedEvent=>this.preloadBuffer.enqueue(clone$1(bufferedEvent)));}}/**
|
1669
1544
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
1670
|
-
*/processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){const eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent([...eventToProcess],this);}}}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.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
1545
|
+
*/processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){const eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent([...eventToProcess],this);}}}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);}/**
|
1671
1546
|
* Load configuration
|
1672
1547
|
*/loadConfig(){if(!state.lifecycle.writeKey.value){this.errorHandler.onError(new Error('A write key is required to load the SDK. Please provide a valid write key.'),LOAD_CONFIGURATION);return;}this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);this.configManager?.init();}/**
|
1673
1548
|
* Initialize the storage and event queue
|
1674
1549
|
*/init(){this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
1675
|
-
this.storeManager?.init();this.
|
1550
|
+
this.storeManager?.init();this.userSessionManager?.init();// Initialize consent manager
|
1676
1551
|
if(state.consents.activeConsentManagerPluginName.value){this.pluginsManager?.invokeSingle(`consentManager.init`,state,this.storeManager,this.logger);}// Initialize event manager
|
1677
1552
|
this.eventManager?.init();// Mark the SDK as initialized
|
1678
1553
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
@@ -1686,7 +1561,7 @@ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window o
|
|
1686
1561
|
// as this will prevent us from supporting multiple SDK instances in the same page
|
1687
1562
|
// Execute onLoaded callback if provided in load options
|
1688
1563
|
if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
|
1689
|
-
|
1564
|
+
r(()=>{state.lifecycle.loaded.value=true;state.lifecycle.status.value=LifecycleStatus.Loaded;});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
|
1690
1565
|
const initializedEvent=new CustomEvent('RSA_Initialised',{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(initializedEvent);}/**
|
1691
1566
|
* Emit ready event
|
1692
1567
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -1699,7 +1574,7 @@ state.eventBuffer.toBeProcessedArray.value.forEach(bufferedItem=>{const methodNa
|
|
1699
1574
|
*/loadDestinations(){// Set in state the desired activeDestinations to inject in DOM
|
1700
1575
|
this.pluginsManager?.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);const totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;return;}// Start loading native integration scripts and create instances
|
1701
1576
|
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;this.pluginsManager?.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
|
1702
|
-
|
1577
|
+
E(()=>{const areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){r(()=>{state.lifecycle.status.value=LifecycleStatus.DestinationsReady;state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
|
1703
1578
|
* Invoke the ready callbacks if any exist
|
1704
1579
|
*/ // eslint-disable-next-line class-methods-use-this
|
1705
1580
|
onDestinationsReady(){state.eventBuffer.readyCallbacksArray.value.forEach(callback=>{try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}});state.lifecycle.status.value=LifecycleStatus.Ready;}// End lifecycle methods
|
@@ -1721,7 +1596,7 @@ getUserId(){return state.session.userId.value;}// eslint-disable-next-line class
|
|
1721
1596
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
1722
1597
|
getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
1723
1598
|
getGroupTraits(){return state.session.groupTraits.value;}startSession(sessionId){const type='startSession';this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}this.userSessionManager?.start(sessionId);}endSession(){const type='endSession';this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type]);return;}this.userSessionManager?.end();}// eslint-disable-next-line class-methods-use-this
|
1724
|
-
getSessionId(){this.userSessionManager?.
|
1599
|
+
getSessionId(){const sessionId=this.userSessionManager?.getSessionId();return sessionId??null;}// End consumer exposed methods
|
1725
1600
|
}
|
1726
1601
|
|
1727
1602
|
/*
|
@@ -1739,7 +1614,7 @@ this.triggerBufferedLoadEvent();}/**
|
|
1739
1614
|
* Set instance to use if no specific writeKey is provided in methods
|
1740
1615
|
* automatically for the first created instance
|
1741
1616
|
* TODO: to support multiple analytics instances in the near future
|
1742
|
-
*/setDefaultInstanceKey(writeKey){if(
|
1617
|
+
*/setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
1743
1618
|
* Retrieve an existing analytics instance
|
1744
1619
|
*/getAnalyticsInstance(writeKey){const instanceId=writeKey??this.defaultAnalyticsKey;const analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
|
1745
1620
|
* Create new analytics instance and trigger application lifecycle start
|