@rudderstack/analytics-js 3.9.1 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/npm/index.d.cts +12 -8
- package/dist/npm/index.d.mts +12 -8
- package/dist/npm/legacy/bundled/cjs/index.cjs +121 -91
- package/dist/npm/legacy/bundled/esm/index.mjs +121 -91
- package/dist/npm/legacy/bundled/umd/index.js +121 -91
- package/dist/npm/legacy/cjs/index.cjs +121 -91
- package/dist/npm/legacy/content-script/cjs/index.cjs +119 -89
- package/dist/npm/legacy/content-script/esm/index.mjs +119 -89
- package/dist/npm/legacy/content-script/umd/index.js +119 -89
- package/dist/npm/legacy/esm/index.mjs +121 -91
- package/dist/npm/legacy/umd/index.js +121 -91
- package/dist/npm/modern/bundled/cjs/index.cjs +113 -83
- package/dist/npm/modern/bundled/esm/index.mjs +113 -83
- package/dist/npm/modern/bundled/umd/index.js +113 -83
- package/dist/npm/modern/cjs/index.cjs +109 -79
- package/dist/npm/modern/content-script/cjs/index.cjs +111 -81
- package/dist/npm/modern/content-script/esm/index.mjs +111 -81
- package/dist/npm/modern/content-script/umd/index.js +111 -81
- package/dist/npm/modern/esm/index.mjs +109 -79
- package/dist/npm/modern/umd/index.js +109 -79
- package/package.json +1 -1
@@ -835,6 +835,10 @@ var isFunction=function isFunction(value){return typeof value==='function'&&Bool
|
|
835
835
|
* @param value input value
|
836
836
|
* @returns boolean
|
837
837
|
*/var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
|
838
|
+
* Checks if the input is a BigInt
|
839
|
+
* @param value input value
|
840
|
+
* @returns True if the input is a BigInt
|
841
|
+
*/var isBigInt=function isBigInt(value){return typeof value==='bigint';};/**
|
838
842
|
* A function to check given value is defined
|
839
843
|
* @param value input value
|
840
844
|
* @returns boolean
|
@@ -852,11 +856,11 @@ var isFunction=function isFunction(value){return typeof value==='function'&&Bool
|
|
852
856
|
* @returns true if the input is an instance of Error and false otherwise
|
853
857
|
*/var isTypeOfError=function isTypeOfError(obj){return obj instanceof Error;};
|
854
858
|
|
855
|
-
var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};/**
|
859
|
+
var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};var isObject=function isObject(value){return _typeof(value)==='object';};/**
|
856
860
|
* Checks if the input is an object literal or built-in object type and not null
|
857
861
|
* @param value Input value
|
858
862
|
* @returns true if the input is an object and not null
|
859
|
-
*/var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&
|
863
|
+
*/var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&isObject(value)&&!Array.isArray(value);};/**
|
860
864
|
* Checks if the input is an object literal and not null
|
861
865
|
* @param value Input value
|
862
866
|
* @returns true if the input is an object and not null
|
@@ -899,37 +903,69 @@ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var remov
|
|
899
903
|
* @returns decoded string
|
900
904
|
*/var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
|
901
905
|
|
906
|
+
var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_ALREADY_EXISTS_ERROR(id){return "A script with the id \"".concat(id,"\" is already loaded. Skipping the loading of this script to prevent conflicts.");};var SCRIPT_LOAD_ERROR=function SCRIPT_LOAD_ERROR(id,url){return "Failed to load the script with the id \"".concat(id,"\" from URL \"").concat(url,"\".");};var SCRIPT_LOAD_TIMEOUT_ERROR=function SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout){return "A timeout of ".concat(timeout," ms occurred while trying to load the script with id \"").concat(id,"\" from URL \"").concat(url,"\".");};
|
907
|
+
|
908
|
+
/**
|
909
|
+
* Utility method for JSON stringify object excluding null values & circular references
|
910
|
+
*
|
911
|
+
* @param {*} value input value
|
912
|
+
* @param {boolean} excludeNull optional flag to exclude null values
|
913
|
+
* @param {string[]} excludeKeys optional array of keys to exclude
|
914
|
+
* @returns string
|
915
|
+
*/var stringifyData=function stringifyData(value){var excludeNull=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var excludeKeys=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];return JSON.stringify(value,function(key,value){if(excludeNull&&isNull(value)||excludeKeys.includes(key)){return undefined;}return value;});};var getReplacer=function getReplacer(logger){var ancestors=[];// Array to track ancestor objects
|
916
|
+
// Using a regular function to use `this` for the parent context
|
917
|
+
return function replacer(key,value){if(isBigInt(value)){return '[BigInt]';// Replace BigInt values
|
918
|
+
}// `this` is the object that value is contained in, i.e., its direct parent.
|
919
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
920
|
+
// @ts-ignore-next-line
|
921
|
+
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();// Remove ancestors that are no longer part of the chain
|
922
|
+
}// Check for circular references (if the value is already in the ancestors)
|
923
|
+
if(ancestors.includes(value)){return '[Circular Reference]';}// Add current value to ancestors
|
924
|
+
ancestors.push(value);return value;};};var _traverseWithThis=function traverseWithThis(obj,replacer){// Create a new result object or array
|
925
|
+
var result=Array.isArray(obj)?[]:{};// Traverse object properties or array elements
|
926
|
+
// eslint-disable-next-line no-restricted-syntax
|
927
|
+
for(var key in obj){if(Object.hasOwnProperty.call(obj,key)){var value=obj[key];// Recursively apply the replacer and traversal
|
928
|
+
var sanitizedValue=replacer.call(obj,key,value);// If the value is an object or array, continue traversal
|
929
|
+
if(isObjectLiteralAndNotNull(sanitizedValue)||Array.isArray(sanitizedValue)){result[key]=_traverseWithThis(sanitizedValue,replacer);}else {result[key]=sanitizedValue;}}}return result;};/**
|
930
|
+
* Recursively traverses an object similar to JSON.stringify,
|
931
|
+
* sanitizing BigInts and circular references
|
932
|
+
* @param value Input object
|
933
|
+
* @param logger Logger instance
|
934
|
+
* @returns Sanitized value
|
935
|
+
*/var getSanitizedValue=function getSanitizedValue(value,logger){var replacer=getReplacer();// This is needed for registering the first ancestor
|
936
|
+
var newValue=replacer.call(value,'',value);if(isObjectLiteralAndNotNull(value)||Array.isArray(value)){return _traverseWithThis(value,replacer);}return newValue;};
|
937
|
+
|
902
938
|
// if yes make them null instead of omitting in overloaded cases
|
903
939
|
/*
|
904
940
|
* Normalise the overloaded arguments of the page call facade
|
905
|
-
*/var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var payload={category:
|
941
|
+
*/var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var sanitizedCategory=getSanitizedValue(category);var sanitizedName=getSanitizedValue(name);var sanitizedProperties=getSanitizedValue(properties);var sanitizedOptions=getSanitizedValue(options);var sanitizedCallback=getSanitizedValue(callback);var payload={category:sanitizedCategory,name:sanitizedName,properties:sanitizedProperties,options:sanitizedOptions,callback:undefined};if(isFunction(sanitizedCallback)){payload.callback=sanitizedCallback;}if(isFunction(sanitizedOptions)){payload.category=sanitizedCategory;payload.name=sanitizedName;payload.properties=sanitizedProperties;payload.options=undefined;payload.callback=sanitizedOptions;}if(isFunction(sanitizedProperties)){payload.category=sanitizedCategory;payload.name=sanitizedName;payload.properties=undefined;payload.options=undefined;payload.callback=sanitizedProperties;}if(isFunction(sanitizedName)){payload.category=sanitizedCategory;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=sanitizedName;}if(isFunction(sanitizedCategory)){payload.category=undefined;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=sanitizedCategory;}if(isObjectLiteralAndNotNull(sanitizedCategory)){payload.name=undefined;payload.category=undefined;payload.properties=sanitizedCategory;if(!isFunction(sanitizedName)){payload.options=sanitizedName;}else {payload.options=undefined;}}else if(isObjectLiteralAndNotNull(sanitizedName)){payload.name=undefined;payload.properties=sanitizedName;if(!isFunction(sanitizedProperties)){payload.options=sanitizedProperties;}else {payload.options=undefined;}}// if the category argument alone is provided b/w category and name,
|
906
942
|
// use it as name and set category to undefined
|
907
|
-
if(isString(
|
943
|
+
if(isString(sanitizedCategory)&&!isString(sanitizedName)){payload.category=undefined;payload.name=sanitizedCategory;}// Rest of the code is just to clean up undefined values
|
908
944
|
// and set some proper defaults
|
909
945
|
// Also, to clone the incoming object type arguments
|
910
946
|
if(!isDefined(payload.category)){payload.category=undefined;}if(!isDefined(payload.name)){payload.name=undefined;}payload.properties=payload.properties?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}var nameForProperties=isString(payload.name)?payload.name:payload.properties.name;var categoryForProperties=isString(payload.category)?payload.category:payload.properties.category;// add name and category to properties
|
911
947
|
payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},_objectSpread2(_objectSpread2({},nameForProperties&&{name:nameForProperties}),categoryForProperties&&{category:categoryForProperties}));return payload;};/*
|
912
948
|
* Normalise the overloaded arguments of the track call facade
|
913
|
-
*/var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var payload={name:
|
949
|
+
*/var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var sanitizedEvent=getSanitizedValue(event);var sanitizedProperties=getSanitizedValue(properties);var sanitizedOptions=getSanitizedValue(options);var sanitizedCallback=getSanitizedValue(callback);var payload={name:sanitizedEvent,properties:sanitizedProperties,options:sanitizedOptions,callback:undefined};if(isFunction(sanitizedCallback)){payload.callback=sanitizedCallback;}if(isFunction(sanitizedOptions)){payload.properties=sanitizedProperties;payload.options=undefined;payload.callback=sanitizedOptions;}if(isFunction(sanitizedProperties)){payload.properties=undefined;payload.options=undefined;payload.callback=sanitizedProperties;}// Rest of the code is just to clean up undefined values
|
914
950
|
// and set some proper defaults
|
915
951
|
// Also, to clone the incoming object type arguments
|
916
952
|
payload.properties=isDefinedAndNotNull(payload.properties)?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
|
917
953
|
* Normalise the overloaded arguments of the identify call facade
|
918
|
-
*/var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var payload={userId:
|
954
|
+
*/var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var sanitizedUserId=getSanitizedValue(userId);var sanitizedTraits=getSanitizedValue(traits);var sanitizedOptions=getSanitizedValue(options);var sanitizedCallback=getSanitizedValue(callback);var payload={userId:sanitizedUserId,traits:sanitizedTraits,options:sanitizedOptions,callback:undefined};if(isFunction(sanitizedCallback)){payload.callback=sanitizedCallback;}if(isFunction(sanitizedOptions)){payload.userId=sanitizedUserId;payload.traits=sanitizedTraits;payload.options=undefined;payload.callback=sanitizedOptions;}if(isFunction(sanitizedTraits)){payload.userId=sanitizedUserId;payload.traits=undefined;payload.options=undefined;payload.callback=sanitizedTraits;}if(isObjectLiteralAndNotNull(sanitizedUserId)||isNull(sanitizedUserId)){// Explicitly set null to prevent resetting the existing value
|
919
955
|
// in the Analytics class
|
920
|
-
payload.userId=null;payload.traits=
|
956
|
+
payload.userId=null;payload.traits=sanitizedUserId;if(!isFunction(sanitizedTraits)){payload.options=sanitizedTraits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
|
921
957
|
// and set some proper defaults
|
922
958
|
// Also, to clone the incoming object type arguments
|
923
959
|
payload.userId=tryStringify(payload.userId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
|
924
960
|
* Normalise the overloaded arguments of the alias call facade
|
925
|
-
*/var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var payload={to:
|
961
|
+
*/var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var sanitizedTo=getSanitizedValue(to);var sanitizedFrom=getSanitizedValue(from);var sanitizedOptions=getSanitizedValue(options);var sanitizedCallback=getSanitizedValue(callback);var payload={to:sanitizedTo,from:sanitizedFrom,options:sanitizedOptions,callback:undefined};if(isFunction(sanitizedCallback)){payload.callback=sanitizedCallback;}if(isFunction(sanitizedOptions)){payload.to=sanitizedTo;payload.from=sanitizedFrom;payload.options=undefined;payload.callback=sanitizedOptions;}if(isFunction(sanitizedFrom)){payload.to=sanitizedTo;payload.from=undefined;payload.options=undefined;payload.callback=sanitizedFrom;}else if(isObjectLiteralAndNotNull(sanitizedFrom)||isNull(sanitizedFrom)){payload.to=sanitizedTo;payload.from=undefined;payload.options=sanitizedFrom;}// Rest of the code is just to clean up undefined values
|
926
962
|
// and set some proper defaults
|
927
963
|
// Also, to clone the incoming object type arguments
|
928
964
|
if(isDefined(payload.to)){payload.to=tryStringify(payload.to);}if(isDefined(payload.from)){payload.from=tryStringify(payload.from);}else {payload.from=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
|
929
965
|
* Normalise the overloaded arguments of the group call facade
|
930
|
-
*/var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var payload={groupId:
|
966
|
+
*/var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var sanitizedGroupId=getSanitizedValue(groupId);var sanitizedTraits=getSanitizedValue(traits);var sanitizedOptions=getSanitizedValue(options);var sanitizedCallback=getSanitizedValue(callback);var payload={groupId:sanitizedGroupId,traits:sanitizedTraits,options:sanitizedOptions,callback:undefined};if(isFunction(sanitizedCallback)){payload.callback=sanitizedCallback;}if(isFunction(sanitizedOptions)){payload.groupId=sanitizedGroupId;payload.traits=sanitizedTraits;payload.options=undefined;payload.callback=sanitizedOptions;}if(isFunction(sanitizedTraits)){payload.groupId=sanitizedGroupId;payload.traits=undefined;payload.options=undefined;payload.callback=sanitizedTraits;}if(isObjectLiteralAndNotNull(sanitizedGroupId)||isNull(sanitizedGroupId)){// Explicitly set null to prevent resetting the existing value
|
931
967
|
// in the Analytics class
|
932
|
-
payload.groupId=null;payload.traits=
|
968
|
+
payload.groupId=null;payload.traits=sanitizedGroupId;if(!isFunction(sanitizedTraits)){payload.options=sanitizedTraits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
|
933
969
|
// and set some proper defaults
|
934
970
|
// Also, to clone the incoming object type arguments
|
935
971
|
payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};
|
@@ -946,7 +982,7 @@ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(paylo
|
|
946
982
|
* Represents the options parameter in the load API
|
947
983
|
*/
|
948
984
|
|
949
|
-
var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var
|
985
|
+
var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RSA='RudderStackAnalytics';var ANALYTICS_CORE='AnalyticsCore';
|
950
986
|
|
951
987
|
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
952
988
|
|
@@ -977,7 +1013,14 @@ var getFormattedTimestamp=function getFormattedTimestamp(date){return date.toISO
|
|
977
1013
|
* @returns ISO formatted timestamp string
|
978
1014
|
*/var getCurrentTimeFormatted=function getCurrentTimeFormatted(){return getFormattedTimestamp(new Date());};
|
979
1015
|
|
980
|
-
var
|
1016
|
+
var MANUAL_ERROR_IDENTIFIER='[MANUAL ERROR]';/**
|
1017
|
+
* Get mutated error with issue prepended to error message
|
1018
|
+
* @param err Original error
|
1019
|
+
* @param issue Issue to prepend to error message
|
1020
|
+
* @returns Instance of Error with message prepended with issue
|
1021
|
+
*/var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyData(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var _error$stack;error.stack="".concat((_error$stack=error.stack)!==null&&_error$stack!==void 0?_error$stack:'',"\n").concat(MANUAL_ERROR_IDENTIFIER);}globalThis.dispatchEvent(new ErrorEvent('error',{error:error}));};
|
1022
|
+
|
1023
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.10.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
981
1024
|
|
982
1025
|
var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
983
1026
|
|
@@ -1024,29 +1067,6 @@ if(preloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(preloadedE
|
|
1024
1067
|
|
1025
1068
|
var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
|
1026
1069
|
|
1027
|
-
var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_ALREADY_EXISTS_ERROR(id){return "A script with the id \"".concat(id,"\" is already loaded. Skipping the loading of this script to prevent conflicts.");};var SCRIPT_LOAD_ERROR=function SCRIPT_LOAD_ERROR(id,url){return "Failed to load the script with the id \"".concat(id,"\" from URL \"").concat(url,"\".");};var SCRIPT_LOAD_TIMEOUT_ERROR=function SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout){return "A timeout of ".concat(timeout," ms occurred while trying to load the script with id \"").concat(id,"\" from URL \"").concat(url,"\".");};var CIRCULAR_REFERENCE_WARNING=function CIRCULAR_REFERENCE_WARNING(context,key){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"A circular reference has been detected in the object and the property \"").concat(key,"\" has been dropped from the output.");};var JSON_STRINGIFY_WARNING="Failed to convert the value to a JSON string.";
|
1028
|
-
|
1029
|
-
var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
|
1030
|
-
// eslint-disable-next-line func-names
|
1031
|
-
return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
|
1032
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
1033
|
-
// @ts-ignore-next-line
|
1034
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
|
1035
|
-
* Utility method for JSON stringify object excluding null values & circular references
|
1036
|
-
*
|
1037
|
-
* @param {*} value input
|
1038
|
-
* @param {boolean} excludeNull if it should exclude nul or not
|
1039
|
-
* @param {function} logger optional logger methods for warning
|
1040
|
-
* @returns string
|
1041
|
-
*/var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};
|
1042
|
-
|
1043
|
-
/**
|
1044
|
-
* Get mutated error with issue prepended to error message
|
1045
|
-
* @param err Original error
|
1046
|
-
* @param issue Issue to prepend to error message
|
1047
|
-
* @returns Instance of Error with message prepended with issue
|
1048
|
-
*/var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};
|
1049
|
-
|
1050
1070
|
var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
|
1051
1071
|
|
1052
1072
|
/**
|
@@ -1119,8 +1139,8 @@ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="ha
|
|
1119
1139
|
var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
|
1120
1140
|
|
1121
1141
|
var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(component){return "Failed to load the SDK as the base URL for ".concat(component," is not valid.");};// ERROR
|
1122
|
-
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
|
1123
|
-
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var
|
1142
|
+
var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(context,dataPlaneUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data plane URL \"").concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
|
1143
|
+
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var NATIVE_DEST_PLUGIN_INITIALIZE_ERROR="NativeDestinationQueuePlugin initialization failed";var DATAPLANE_PLUGIN_INITIALIZE_ERROR="XhrQueuePlugin initialization failed";var DMT_PLUGIN_INITIALIZE_ERROR="DeviceModeTransformationPlugin initialization failed";var NATIVE_DEST_PLUGIN_ENQUEUE_ERROR="NativeDestinationQueuePlugin event enqueue failed";var DATAPLANE_PLUGIN_ENQUEUE_ERROR="XhrQueuePlugin event enqueue failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};var BAD_COOKIES_WARNING=function BAD_COOKIES_WARNING(key){return "The cookie data for ".concat(key," seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.");};var PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=function PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Page Unloaded event can only be tracked when the Beacon transport is active. Please enable \"useBeacon\" load API option.");};
|
1124
1144
|
|
1125
1145
|
var DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
1126
1146
|
|
@@ -1190,7 +1210,7 @@ var LOAD_ORIGIN='RS_JS_SDK';
|
|
1190
1210
|
|
1191
1211
|
/**
|
1192
1212
|
* Utility method to normalise errors
|
1193
|
-
*/var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else if(error instanceof ErrorEvent){errorMessage=error.message;}else {errorMessage=error.message?error.message:
|
1213
|
+
*/var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else if(error instanceof ErrorEvent){errorMessage=error.message;}else {errorMessage=error.message?error.message:stringifyData(error);}}catch(e){errorMessage="Unknown error: ".concat(e.message);}return errorMessage;};var getNormalizedErrorForUnhandledError=function getNormalizedErrorForUnhandledError(error){try{if(error instanceof Error||error instanceof ErrorEvent||error instanceof PromiseRejectionEvent&&error.reason){return error;}// TODO: remove this block once all device mode integrations start using the v3 script loader module (TS)
|
1194
1214
|
if(error instanceof Event){var eventTarget=error.target;// Discard all the non-script loading errors
|
1195
1215
|
if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
|
1196
1216
|
if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.dataset.loader!==LOAD_ORIGIN||eventTarget.dataset.isnonnativesdk!=='true')){return undefined;}var errorMessage="Error in loading a third-party script from URL ".concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.src," with ID ").concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.id,".");return Object.create(error,{message:{value:errorMessage}});}return error;}catch(e){return e;}};
|
@@ -1201,9 +1221,9 @@ if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.d
|
|
1201
1221
|
function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;this.errorBuffer=new BufferQueue();this.attachEffect();}return _createClass(ErrorHandler,[{key:"attachEffect",value:function attachEffect(){if(state.reporting.isErrorReportingPluginLoaded.value===true){while(this.errorBuffer.size()>0){var errorToProcess=this.errorBuffer.dequeue();if(errorToProcess){// send it to the plugin
|
1202
1222
|
this.notifyError(errorToProcess.error,errorToProcess.errorState);}}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDREJECTION);});}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.debug("Failed to attach global error listeners.");}}},{key:"init",value:function init(httpClient,externalSrcLoader){var _this2=this;this.httpClient=httpClient;// Below lines are only kept for backward compatibility
|
1203
1223
|
// TODO: Remove this in the next major release
|
1204
|
-
if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this2.errReportingClient=client;}).catch(function(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var errorType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ErrorType.HANDLEDEXCEPTION;var normalizedError;var errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1224
|
+
if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this2.errReportingClient=client;}).catch(function(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var _error;var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var errorType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ErrorType.HANDLEDEXCEPTION;var normalizedError;var errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1205
1225
|
if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}}else {normalizedError=getNormalizedErrorForUnhandledError(error);}var isErrorReportingEnabled=state.reporting.isErrorReportingEnabled.value;var isErrorReportingPluginLoaded=state.reporting.isErrorReportingPluginLoaded.value;try{if(isErrorReportingEnabled){var errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};if(!isErrorReportingPluginLoaded){// buffer the error
|
1206
|
-
this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}}/**
|
1226
|
+
this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}else if((_error=error.error)!==null&&_error!==void 0&&(_error=_error.stack)!==null&&_error!==void 0&&_error.includes(MANUAL_ERROR_IDENTIFIER)){var _this$logger3,_error2;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error('An unknown error occurred:',(_error2=error.error)===null||_error2===void 0?void 0:_error2.message);}}/**
|
1207
1227
|
* Add breadcrumbs to add insight of a user's journey before an error
|
1208
1228
|
* occurred and send to external error monitoring service via a plugin
|
1209
1229
|
*
|
@@ -1216,8 +1236,8 @@ breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorR
|
|
1216
1236
|
* @param {Error} error Error instance from handled error
|
1217
1237
|
*/},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
|
1218
1238
|
this.errReportingClient,// deprecated parameter
|
1219
|
-
error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$
|
1220
|
-
(_this$
|
1239
|
+
error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$logger4;// Not calling onError here as we don't want to go into infinite loop
|
1240
|
+
(_this$logger4=this.logger)===null||_this$logger4===void 0||_this$logger4.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1221
1241
|
|
1222
1242
|
/**
|
1223
1243
|
* A function to filter and return non cloud mode destinations
|
@@ -1278,16 +1298,16 @@ var encryptBrowser=function encryptBrowser(value){return "".concat(ENCRYPTION_PR
|
|
1278
1298
|
|
1279
1299
|
var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
|
1280
1300
|
|
1281
|
-
var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(context,payloadSize,sizeLimit){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The size of the event payload (").concat(payloadSize," bytes) exceeds the maximum limit of ").concat(sizeLimit," bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.");};var
|
1301
|
+
var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(context,payloadSize,sizeLimit){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The size of the event payload (").concat(payloadSize," bytes) exceeds the maximum limit of ").concat(sizeLimit," bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.");};var QUEUE_UTILITIES='QueueUtilities';/**
|
1282
1302
|
* Utility to get the stringified event payload
|
1283
1303
|
* @param event RudderEvent object
|
1284
1304
|
* @param logger Logger instance
|
1285
1305
|
* @returns stringified event payload. Empty string if error occurs.
|
1286
|
-
*/var getDeliveryPayload=function getDeliveryPayload(event
|
1306
|
+
*/var getDeliveryPayload=function getDeliveryPayload(event){return stringifyData(event);};var getDMTDeliveryPayload=function getDMTDeliveryPayload(dmtRequestPayload){return stringifyData(dmtRequestPayload);};/**
|
1287
1307
|
* Utility to validate final payload size before sending to server
|
1288
1308
|
* @param event RudderEvent object
|
1289
1309
|
* @param logger Logger instance
|
1290
|
-
*/var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event
|
1310
|
+
*/var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event);var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}};/**
|
1291
1311
|
* Mutates the event and return final event for delivery
|
1292
1312
|
* Updates certain parameters like sentAt timestamp, integrations config etc.
|
1293
1313
|
* @param event RudderEvent object
|
@@ -1307,7 +1327,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
|
|
1307
1327
|
* @param events RudderEvent object array
|
1308
1328
|
* @param logger Logger instance
|
1309
1329
|
* @returns stringified events payload as Blob, undefined if error occurs.
|
1310
|
-
*/var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,currentTime,logger){var data={batch:events,sentAt:currentTime};try{var blobPayload=
|
1330
|
+
*/var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,currentTime,logger){var data={batch:events,sentAt:currentTime};try{var blobPayload=stringifyData(data);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===void 0||logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/','beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
|
1311
1331
|
|
1312
1332
|
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1313
1333
|
|
@@ -1442,14 +1462,14 @@ var SDK_FILE_NAME_PREFIXES$1=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// P
|
|
1442
1462
|
// Potential PII or sensitive data
|
1443
1463
|
var APP_STATE_EXCLUDE_KEYS$1=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
|
1444
1464
|
'eventBuffer',// pre-load event buffer (may contain PII)
|
1445
|
-
'traits'];var BUGSNAG_PLUGIN='BugsnagPlugin';
|
1465
|
+
'traits','authToken'];var BUGSNAG_PLUGIN='BugsnagPlugin';
|
1446
1466
|
|
1447
1467
|
var isValidVersion=function isValidVersion(globalLibInstance){var _globalLibInstance$_c;// For version 7
|
1448
1468
|
// eslint-disable-next-line no-underscore-dangle
|
1449
1469
|
var version=globalLibInstance===null||globalLibInstance===void 0||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===void 0||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===void 0?void 0:_globalLibInstance$_c.version;// For versions older than 7
|
1450
1470
|
if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
|
1451
1471
|
beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===void 0?void 0:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError$1=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}// Prefix folder for all the destination SDK scripts
|
1452
|
-
var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES$1().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata$1=function getAppStateForMetadata(state){var stateStr=
|
1472
|
+
var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES$1().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata$1=function getAppStateForMetadata(state){var stateStr=stringifyData(state,true,APP_STATE_EXCLUDE_KEYS$1);return JSON.parse(stateStr);};var enhanceErrorEventMutator=function enhanceErrorEventMutator(state,event){var _getAppStateForMetada;event.updateMetaData('source',{snippetVersion:globalThis.RudderSnippetVersion});event.updateMetaData('state',(_getAppStateForMetada=getAppStateForMetadata$1(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
|
1453
1473
|
event.context=errorMessage;// Hack for easily grouping the script load errors
|
1454
1474
|
// on the dashboard
|
1455
1475
|
if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
|
@@ -1708,10 +1728,10 @@ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Pre
|
|
1708
1728
|
// Potential PII or sensitive data
|
1709
1729
|
var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
|
1710
1730
|
'eventBuffer',// pre-load event buffer (may contain PII)
|
1711
|
-
'traits'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
|
1731
|
+
'traits','authToken'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
|
1712
1732
|
var NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';var SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';var SOURCE_NAME='js';var ERROR_REPORTING_PLUGIN='ErrorReportingPlugin';
|
1713
1733
|
|
1714
|
-
var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==void 0?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=
|
1734
|
+
var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==void 0?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyData(state,true,APP_STATE_EXCLUDE_KEYS);return JSON.parse(stateStr);};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getErrorContext=function getErrorContext(event){var message=event.message;var context=message;// Hack for easily grouping the script load errors
|
1715
1735
|
// on the dashboard
|
1716
1736
|
if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};var getBugsnagErrorEvent=function getBugsnagErrorEvent(payload,errorState,state){var _state$context$locale,_state$context$userAg,_getAppStateForMetada,_state$source$value$i,_state$source$value;return {notifier:{name:NOTIFIER_NAME,version:state.context.app.value.version,url:SDK_GITHUB_URL},events:[{payloadVersion:'5',exceptions:clone(payload.errors),severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:state.context.app.value.version,releaseStage:getReleaseStage()},device:{locale:(_state$context$locale=state.context.locale.value)!==null&&_state$context$locale!==void 0?_state$context$locale:undefined,userAgent:(_state$context$userAg=state.context.userAgent.value)!==null&&_state$context$userAg!==void 0?_state$context$userAg:undefined,time:new Date()},request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(state.reporting.breadcrumbs.value),context:getErrorContext(payload.errors[0]),metaData:{sdk:{name:'JS',installType:state.context.app.value.installType},state:(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:(_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)!==null&&_state$source$value$i!==void 0?_state$source$value$i:state.lifecycle.writeKey.value}}]};};/**
|
1717
1737
|
* A function to determine whether the error should be promoted to notify or not
|
@@ -1723,7 +1743,7 @@ if(message.includes('Error in loading a third-party script')){context='Script lo
|
|
1723
1743
|
* @returns
|
1724
1744
|
*/var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
|
1725
1745
|
// Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
|
1726
|
-
var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return
|
1746
|
+
var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return stringifyData(data);};
|
1727
1747
|
|
1728
1748
|
function getDefaultExportFromCjs (x) {
|
1729
1749
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
@@ -1766,7 +1786,7 @@ var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName
|
|
1766
1786
|
// This adds one.
|
1767
1787
|
if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};var ensureString=function ensureString(str){return typeof str==='string'?str:'';};function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
|
1768
1788
|
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
|
1769
|
-
var getStacktrace=function getStacktrace(error){if(hasStack(error))return ErrorStackParser.parse(error);return [];};var normaliseError=function normaliseError(maybeError,component,logger){var error;if(isError(maybeError)){error=maybeError;}else {logger===null||logger===void 0||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(
|
1789
|
+
var getStacktrace=function getStacktrace(error){if(hasStack(error))return ErrorStackParser.parse(error);return [];};var normaliseError=function normaliseError(maybeError,component,logger){var error;if(isError(maybeError)){error=maybeError;}else {logger===null||logger===void 0||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(stringifyData(error,false)));error=undefined;}if(error&&!hasStack(error)){error=undefined;}return error;};var ErrorFormat=/*#__PURE__*/function(){function ErrorFormat(errorClass,errorMessage,stacktrace){_classCallCheck(this,ErrorFormat);this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}return _createClass(ErrorFormat,null,[{key:"create",value:function create(maybeError,component,logger){var error=normaliseError(maybeError,component,logger);if(!error){return undefined;}var event;try{var stacktrace=getStacktrace(error);event=new ErrorFormat(error.name,error.message,stacktrace);}catch(e){event=new ErrorFormat(error.name,error.message,[]);}return event;}}]);}();
|
1770
1790
|
|
1771
1791
|
var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
|
1772
1792
|
|
@@ -3033,7 +3053,7 @@ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='Xh
|
|
3033
3053
|
|
3034
3054
|
var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s) to ").concat(url,".");};
|
3035
3055
|
|
3036
|
-
var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime
|
3056
|
+
var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime){var batchPayload={batch:events,sentAt:currentTime};return stringifyData(batchPayload);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===void 0?void 0:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===void 0||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state){var data;var headers;var url;var currentTime=getCurrentTimeFormatted();if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});data=getBatchDeliveryPayload(finalEvents,currentTime);headers=itemData[0]?clone(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,currentTime);data=getDeliveryPayload(finalEvent);headers=clone(eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
|
3037
3057
|
|
3038
3058
|
var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginName,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName]);},dataplaneEventsQueue:{/**
|
3039
3059
|
* Initialize the queue for delivery
|
@@ -3044,9 +3064,9 @@ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginNa
|
|
3044
3064
|
* @param logger Logger instance
|
3045
3065
|
* @returns RetryQueue instance
|
3046
3066
|
*/init:function init(state,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var finalQOpts=getNormalizedQueueOptions(state.loadOptions.value.queueOptions);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
|
3047
|
-
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state
|
3067
|
+
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
|
3048
3068
|
var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});},storeManager,LOCAL_STORAGE,logger,function(itemData){var _getBatchDeliveryPayl;var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to string as we know that the event has already been validated prior to enqueue
|
3049
|
-
return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime
|
3069
|
+
return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
|
3050
3070
|
* Add event to the queue for delivery
|
3051
3071
|
* @param state Application state
|
3052
3072
|
* @param eventsQueue RetryQueue instance
|
@@ -3128,7 +3148,7 @@ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Typ
|
|
3128
3148
|
* Utility implementation of XHR, fetch cannot be used as it requires explicit
|
3129
3149
|
* origin allowed values and not wildcard for CORS requests with credentials and
|
3130
3150
|
* this is not supported by our sourceConfig API
|
3131
|
-
*/var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;
|
3151
|
+
*/var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyData(options.data);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
|
3132
3152
|
return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
3133
3153
|
var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url,true);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
|
3134
3154
|
// and the first call to the send method in legacy browsers
|
@@ -3138,9 +3158,9 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
3138
3158
|
* Service to handle data communication with APIs
|
3139
3159
|
*/var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
|
3140
3160
|
* Implement requests in a blocking way
|
3141
|
-
*/return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout
|
3161
|
+
*/return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==void 0?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case"end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
|
3142
3162
|
* Implement requests in a non-blocking way
|
3143
|
-
*/)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout
|
3163
|
+
*/)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==void 0?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
|
3144
3164
|
* Handle errors
|
3145
3165
|
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
|
3146
3166
|
* Set basic authentication header (eg writekey)
|
@@ -3280,7 +3300,7 @@ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key])
|
|
3280
3300
|
_this.remove(key);});this.engine=inMemoryStorage;}/**
|
3281
3301
|
* Set value by key.
|
3282
3302
|
*/},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
|
3283
|
-
this.engine.setItem(validKey,this.encrypt(
|
3303
|
+
this.engine.setItem(validKey,this.encrypt(stringifyData(value,false)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
|
3284
3304
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
3285
3305
|
this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
|
3286
3306
|
* Get by Key.
|
@@ -3323,7 +3343,7 @@ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngi
|
|
3323
3343
|
* Handle errors
|
3324
3344
|
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);}();
|
3325
3345
|
|
3326
|
-
var
|
3346
|
+
var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomain=function getTopDomain(url){// Create a URL object
|
3327
3347
|
var urlObj=new URL(url);// Extract the host and protocol
|
3328
3348
|
var host=urlObj.host,protocol=urlObj.protocol;// Split the host into parts
|
3329
3349
|
var parts=host.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
@@ -3443,7 +3463,7 @@ var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuf
|
|
3443
3463
|
var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;E(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
3444
3464
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3445
3465
|
* config related information in global state
|
3446
|
-
*/},{key:"init",value:function init(){var _this2=this;this.attachEffects();
|
3466
|
+
*/},{key:"init",value:function init(){var _this2=this;this.attachEffects();var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL,pluginsSDKBaseURL=_state$loadOptions$va.pluginsSDKBaseURL,integrations=_state$loadOptions$va.integrations;state.lifecycle.activeDataplaneUrl.value=_removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
3447
3467
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL);// determine the path to fetch remote plugins from
|
3448
3468
|
var pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
|
3449
3469
|
r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,lockPluginsVersion,_this2.logger);state.metrics.metricsServiceUrl.value="".concat(state.lifecycle.activeDataplaneUrl.value,"/").concat(METRICS_SERVICE_ENDPOINT);// Data in the loadOptions state is already normalized
|
@@ -3698,33 +3718,33 @@ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=t
|
|
3698
3718
|
* @param cookiesData
|
3699
3719
|
* @param store
|
3700
3720
|
* @returns
|
3701
|
-
*/},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var
|
3721
|
+
*/},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var encryptedCookieData=[];cookiesData.forEach(function(cData){var encryptedValue=store===null||store===void 0?void 0:store.encrypt(stringifyData(cData.value,false));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
|
3702
3722
|
* A function that makes request to data service to set the cookie
|
3703
3723
|
* @param encryptedCookieData
|
3704
3724
|
* @param callback
|
3705
|
-
*/},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:
|
3725
|
+
*/},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyData({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}},false),sendRawData:true,withCredentials:true},isRawResponse:true,callback:callback});}/**
|
3706
3726
|
* A function to make an external request to set the cookie from server side
|
3707
3727
|
* @param key cookie name
|
3708
3728
|
* @param value encrypted cookie value
|
3709
|
-
*/},{key:"setServerSideCookies",value:function setServerSideCookies(cookiesData,cb,store){var
|
3729
|
+
*/},{key:"setServerSideCookies",value:function setServerSideCookies(cookiesData,cb,store){var _this3=this;try{// encrypt cookies values
|
3710
3730
|
var encryptedCookieData=this.getEncryptedCookieData(cookiesData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
3711
|
-
this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=
|
3731
|
+
this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=stringifyData(cData.value,false);var after=stringifyData(cookieValue,false);if(after!==before){var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===void 0||_this3$logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));if(cb){cb(cData.name,cData.value);}}});}else {var _this3$logger2,_details$xhr2;(_this3$logger2=_this3.logger)===null||_this3$logger2===void 0||_this3$logger2.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
|
3712
3732
|
* A function to sync values in storage
|
3713
3733
|
* @param sessionKey
|
3714
3734
|
* @param value
|
3715
|
-
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey,
|
3735
|
+
*/},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey,_this4=this;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
|
3716
3736
|
// set the cookie from server side
|
3717
|
-
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){if(this.serverSideCookieDebounceFuncs[sessionKey]){globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[sessionKey]);}this.serverSideCookieDebounceFuncs[sessionKey]=globalThis.setTimeout(function(){
|
3737
|
+
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){if(this.serverSideCookieDebounceFuncs[sessionKey]){globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[sessionKey]);}this.serverSideCookieDebounceFuncs[sessionKey]=globalThis.setTimeout(function(){_this4.setServerSideCookies([{name:key,value:value}],function(cookieName,cookieValue){curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===void 0||curStore.set(key,value);}}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
|
3718
3738
|
* Function to update storage whenever state value changes
|
3719
|
-
*/},{key:"registerEffects",value:function registerEffects(){var
|
3720
|
-
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){
|
3739
|
+
*/},{key:"registerEffects",value:function registerEffects(){var _this5=this;// This will work as long as the user session entry key names are same as the state keys
|
3740
|
+
USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this5.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
|
3721
3741
|
* Sets anonymous id in the following precedence:
|
3722
3742
|
*
|
3723
3743
|
* 1. anonymousId: Id directly provided to the function.
|
3724
3744
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
3725
3745
|
* using parseLinker util.
|
3726
3746
|
* 3. generateUUID: A new unique id is generated and assigned.
|
3727
|
-
*/},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
|
3747
|
+
*/},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
|
3728
3748
|
* Fetches anonymousId
|
3729
3749
|
* @param options option to fetch it from external source
|
3730
3750
|
* @returns anonymousId
|
@@ -3775,8 +3795,8 @@ this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
|
|
3775
3795
|
* @param resetAnonymousId
|
3776
3796
|
* @param noNewSessionStart
|
3777
3797
|
* @returns
|
3778
|
-
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var
|
3779
|
-
|
3798
|
+
*/},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this6=this;var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack;r(function(){session.userId.value=DEFAULT_USER_SESSION_VALUES.userId;session.userTraits.value=DEFAULT_USER_SESSION_VALUES.userTraits;session.groupId.value=DEFAULT_USER_SESSION_VALUES.groupId;session.groupTraits.value=DEFAULT_USER_SESSION_VALUES.groupTraits;session.authToken.value=DEFAULT_USER_SESSION_VALUES.authToken;if(resetAnonymousId===true){// This will generate a new anonymous ID
|
3799
|
+
_this6.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;_this6.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){_this6.startManualTrackingInternal();}});}/**
|
3780
3800
|
* Set user Id
|
3781
3801
|
* @param userId
|
3782
3802
|
*/},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
@@ -3863,7 +3883,7 @@ callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onErro
|
|
3863
3883
|
* @param shouldAlwaysThrow if it should throw or use logger
|
3864
3884
|
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
|
3865
3885
|
|
3866
|
-
var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
|
3886
|
+
var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};var isWriteKeyValid=function isWriteKeyValid(writeKey){return isString(writeKey)&&writeKey.trim().length>0;};var isDataPlaneUrlValid=function isDataPlaneUrlValid(dataPlaneUrl){return isValidURL(dataPlaneUrl);};
|
3867
3887
|
|
3868
3888
|
/*
|
3869
3889
|
* Analytics class with lifecycle based on state ad user triggered events
|
@@ -3871,9 +3891,8 @@ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new Custom
|
|
3871
3891
|
* Initialize services and components or use default ones if singletons
|
3872
3892
|
*/function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;}/**
|
3873
3893
|
* Start application lifecycle if not already started
|
3874
|
-
*/return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _this$logger,_state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}
|
3875
|
-
|
3876
|
-
r(function(){state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
|
3894
|
+
*/return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _this$logger,_state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}// Set initial state values
|
3895
|
+
r(function(){state.lifecycle.writeKey.value=clone(writeKey);state.lifecycle.dataPlaneUrl.value=clone(dataPlaneUrl);state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,loadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
|
3877
3896
|
(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
|
3878
3897
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
3879
3898
|
// State application lifecycle
|
@@ -3939,7 +3958,7 @@ if(state.lifecycle.status.value!=='ready'){state.lifecycle.status.value='ready';
|
|
3939
3958
|
// Check page category to avoid infinite loop
|
3940
3959
|
if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
|
3941
3960
|
// in v3 implementation
|
3942
|
-
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
3961
|
+
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event - ").concat(payload.name));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
3943
3962
|
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getUserId())!==null&&_ref2!==void 0?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0?void 0:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana7,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
3944
3963
|
if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,resetAnonymousId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0||_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0?void 0:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
3945
3964
|
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,anonymousId,rudderAmpLinkerParam]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
@@ -3962,23 +3981,32 @@ if(state.consents.postConsent.value.trackConsent){var trackOptions=trackArgument
|
|
3962
3981
|
* handle multiple Analytics instances
|
3963
3982
|
* consume SDK preload event buffer
|
3964
3983
|
*/var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
|
3965
|
-
function RudderAnalytics(){_classCallCheck(this,RudderAnalytics)
|
3984
|
+
function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);// END-NO-SONAR-SCAN
|
3985
|
+
_defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
|
3966
3986
|
// eslint-disable-next-line no-constructor-return
|
3967
3987
|
return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
|
3968
3988
|
}defaultErrorHandler.attachErrorListeners();this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);RudderAnalytics.globalSingleton=this;state.autoTrack.pageLifecycle.visitId.value=generateUUID();state.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now();// start loading if a load event was buffered or wait for explicit load call
|
3969
3989
|
this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
|
3970
3990
|
// for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
|
3971
|
-
globalThis.rudderanalytics=this;}/**
|
3991
|
+
globalThis.rudderanalytics=this;}catch(error){dispatchErrorEvent(error);}}/**
|
3972
3992
|
* Set instance to use if no specific writeKey is provided in methods
|
3973
3993
|
* automatically for the first created instance
|
3974
3994
|
* TODO: to support multiple analytics instances in the near future
|
3975
|
-
*/return _createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){
|
3995
|
+
*/return _createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){// IMP: Add try-catch block to handle any unhandled errors
|
3996
|
+
// similar to other public methods
|
3997
|
+
// if the implementation of this method goes beyond
|
3998
|
+
// this simple implementation
|
3999
|
+
if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
3976
4000
|
* Retrieve an existing analytics instance
|
3977
|
-
*/},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){var instanceId=writeKey
|
3978
|
-
*
|
3979
|
-
|
4001
|
+
*/},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){try{var instanceId=writeKey;if(!isString(instanceId)||!instanceId){instanceId=this.defaultAnalyticsKey;}var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}catch(error){dispatchErrorEvent(error);return undefined;}}/**
|
4002
|
+
* Loads the SDK
|
4003
|
+
* @param writeKey Source write key
|
4004
|
+
* @param dataPlaneUrl Data plane URL
|
4005
|
+
* @param loadOptions Additional options for loading the SDK
|
4006
|
+
* @returns none
|
4007
|
+
*/},{key:"load",value:function load(writeKey,dataPlaneUrl,loadOptions){try{var _this$getAnalyticsIns;if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);var preloadedEventsArray=this.getPreloadedEvents();// Track page loaded lifecycle event if enabled
|
3980
4008
|
this.trackPageLifecycleEvents(preloadedEventsArray,loadOptions);// The array will be mutated in the below method
|
3981
|
-
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey).load(writeKey,dataPlaneUrl,loadOptions);}/**
|
4009
|
+
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));this.analyticsInstances[writeKey]=new Analytics();(_this$getAnalyticsIns=this.getAnalyticsInstance(writeKey))===null||_this$getAnalyticsIns===void 0||_this$getAnalyticsIns.load(writeKey,dataPlaneUrl,getSanitizedValue(loadOptions));}catch(error){dispatchErrorEvent(error);}}/**
|
3982
4010
|
* A function to get preloaded events array from global object
|
3983
4011
|
* @returns preloaded events array
|
3984
4012
|
*/// eslint-disable-next-line class-methods-use-this
|
@@ -4002,7 +4030,7 @@ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLif
|
|
4002
4030
|
* @param useBeacon
|
4003
4031
|
* @param options
|
4004
4032
|
*/},{key:"setupPageUnloadTracking",value:function setupPageUnloadTracking(events,useBeacon,options){var _this=this;if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(function(isAccessible){if(isAccessible===false&&state.lifecycle.loaded.value){var pageUnloadedTimestamp=Date.now();var visitDuration=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;_this.track(PageLifecycleEvents.UNLOADED,{visitDuration:visitDuration},_objectSpread2(_objectSpread2({},options),{},{originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))}));}});}else {// throw warning if beacon is disabled
|
4005
|
-
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(
|
4033
|
+
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
|
4006
4034
|
* Trigger load event in buffer queue if exists and stores the
|
4007
4035
|
* remaining preloaded events array in global object
|
4008
4036
|
*/},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=this.getPreloadedEvents();// Get any load method call that is buffered if any
|
@@ -4015,21 +4043,23 @@ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
4015
4043
|
// @ts-ignore
|
4016
4044
|
this.load.apply(null,loadEvent);}}/**
|
4017
4045
|
* Get ready callback arguments and forward to ready call
|
4018
|
-
*/},{key:"ready",value:function ready(callback){this.getAnalyticsInstance().ready(callback);}/**
|
4046
|
+
*/},{key:"ready",value:function ready(callback){try{var _this$getAnalyticsIns2;(_this$getAnalyticsIns2=this.getAnalyticsInstance())===null||_this$getAnalyticsIns2===void 0||_this$getAnalyticsIns2.ready(getSanitizedValue(callback));}catch(error){dispatchErrorEvent(error);}}/**
|
4019
4047
|
* Process page arguments and forward to page call
|
4020
4048
|
*/// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
4021
|
-
},{key:"page",value:function page(category,name,properties,options,callback){this.getAnalyticsInstance().page(pageArgumentsToCallOptions(category,name,properties,options,callback));}/**
|
4049
|
+
},{key:"page",value:function page(category,name,properties,options,callback){try{var _this$getAnalyticsIns3;(_this$getAnalyticsIns3=this.getAnalyticsInstance())===null||_this$getAnalyticsIns3===void 0||_this$getAnalyticsIns3.page(pageArgumentsToCallOptions(category,name,properties,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
4022
4050
|
* Process track arguments and forward to page call
|
4023
4051
|
*/// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
4024
|
-
},{key:"track",value:function track(event,properties,options,callback){this.getAnalyticsInstance().track(trackArgumentsToCallOptions(event,properties,options,callback));}/**
|
4052
|
+
},{key:"track",value:function track(event,properties,options,callback){try{var _this$getAnalyticsIns4;(_this$getAnalyticsIns4=this.getAnalyticsInstance())===null||_this$getAnalyticsIns4===void 0||_this$getAnalyticsIns4.track(trackArgumentsToCallOptions(event,properties,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
4025
4053
|
* Process identify arguments and forward to page call
|
4026
4054
|
*/// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
4027
|
-
},{key:"identify",value:function identify(userId,traits,options,callback){this.getAnalyticsInstance().identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}/**
|
4055
|
+
},{key:"identify",value:function identify(userId,traits,options,callback){try{var _this$getAnalyticsIns5;(_this$getAnalyticsIns5=this.getAnalyticsInstance())===null||_this$getAnalyticsIns5===void 0||_this$getAnalyticsIns5.identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
4028
4056
|
* Process alias arguments and forward to page call
|
4029
4057
|
*/// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
4030
|
-
},{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
|
4058
|
+
},{key:"alias",value:function alias(to,from,options,callback){try{var _this$getAnalyticsIns6;(_this$getAnalyticsIns6=this.getAnalyticsInstance())===null||_this$getAnalyticsIns6===void 0||_this$getAnalyticsIns6.alias(aliasArgumentsToCallOptions(to,from,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
4031
4059
|
* Process group arguments and forward to page call
|
4032
4060
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
4033
|
-
},{key:"group",value:function group(groupId,traits,options,callback){
|
4061
|
+
},{key:"group",value:function group(groupId,traits,options,callback){try{var _this$getAnalyticsIns7;(_this$getAnalyticsIns7=this.getAnalyticsInstance())===null||_this$getAnalyticsIns7===void 0||_this$getAnalyticsIns7.group(groupArgumentsToCallOptions(groupId,traits,options,callback));}catch(error){dispatchErrorEvent(error);}}},{key:"reset",value:function reset(resetAnonymousId){try{var _this$getAnalyticsIns8;(_this$getAnalyticsIns8=this.getAnalyticsInstance())===null||_this$getAnalyticsIns8===void 0||_this$getAnalyticsIns8.reset(getSanitizedValue(resetAnonymousId));}catch(error){dispatchErrorEvent(error);}}},{key:"getAnonymousId",value:function getAnonymousId(options){try{var _this$getAnalyticsIns9;return (_this$getAnalyticsIns9=this.getAnalyticsInstance())===null||_this$getAnalyticsIns9===void 0?void 0:_this$getAnalyticsIns9.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){try{var _this$getAnalyticsIns10;(_this$getAnalyticsIns10=this.getAnalyticsInstance())===null||_this$getAnalyticsIns10===void 0||_this$getAnalyticsIns10.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}},{key:"getUserId",value:function getUserId(){try{var _this$getAnalyticsIns11;return (_this$getAnalyticsIns11=this.getAnalyticsInstance())===null||_this$getAnalyticsIns11===void 0?void 0:_this$getAnalyticsIns11.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getUserTraits",value:function getUserTraits(){try{var _this$getAnalyticsIns12;return (_this$getAnalyticsIns12=this.getAnalyticsInstance())===null||_this$getAnalyticsIns12===void 0?void 0:_this$getAnalyticsIns12.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getGroupId",value:function getGroupId(){try{var _this$getAnalyticsIns13;return (_this$getAnalyticsIns13=this.getAnalyticsInstance())===null||_this$getAnalyticsIns13===void 0?void 0:_this$getAnalyticsIns13.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getGroupTraits",value:function getGroupTraits(){try{var _this$getAnalyticsIns14;return (_this$getAnalyticsIns14=this.getAnalyticsInstance())===null||_this$getAnalyticsIns14===void 0?void 0:_this$getAnalyticsIns14.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"startSession",value:function startSession(sessionId){try{var _this$getAnalyticsIns15;(_this$getAnalyticsIns15=this.getAnalyticsInstance())===null||_this$getAnalyticsIns15===void 0||_this$getAnalyticsIns15.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}},{key:"endSession",value:function endSession(){try{var _this$getAnalyticsIns16;(_this$getAnalyticsIns16=this.getAnalyticsInstance())===null||_this$getAnalyticsIns16===void 0||_this$getAnalyticsIns16.endSession();}catch(error){dispatchErrorEvent(error);}}},{key:"getSessionId",value:function getSessionId(){try{var _this$getAnalyticsIns17;return (_this$getAnalyticsIns17=this.getAnalyticsInstance())===null||_this$getAnalyticsIns17===void 0?void 0:_this$getAnalyticsIns17.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"setAuthToken",value:function setAuthToken(token){try{var _this$getAnalyticsIns18;(_this$getAnalyticsIns18=this.getAnalyticsInstance())===null||_this$getAnalyticsIns18===void 0||_this$getAnalyticsIns18.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}},{key:"consent",value:function consent(options){try{var _this$getAnalyticsIns19;(_this$getAnalyticsIns19=this.getAnalyticsInstance())===null||_this$getAnalyticsIns19===void 0||_this$getAnalyticsIns19.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}}]);}();// START-NO-SONAR-SCAN
|
4062
|
+
// eslint-disable-next-line sonarjs/public-static-readonly
|
4063
|
+
_defineProperty(RudderAnalytics,"globalSingleton",null);
|
4034
4064
|
|
4035
4065
|
export { RudderAnalytics };
|