@rudderstack/analytics-js 3.10.1 → 3.11.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 +19 -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 +96 -61
- package/dist/npm/legacy/bundled/esm/index.mjs +96 -61
- package/dist/npm/legacy/bundled/umd/index.js +96 -61
- package/dist/npm/legacy/cjs/index.cjs +96 -61
- package/dist/npm/legacy/content-script/cjs/index.cjs +96 -61
- package/dist/npm/legacy/content-script/esm/index.mjs +96 -61
- package/dist/npm/legacy/content-script/umd/index.js +96 -61
- package/dist/npm/legacy/esm/index.mjs +96 -61
- package/dist/npm/legacy/umd/index.js +96 -61
- package/dist/npm/modern/bundled/cjs/index.cjs +94 -59
- package/dist/npm/modern/bundled/esm/index.mjs +94 -59
- package/dist/npm/modern/bundled/umd/index.js +94 -59
- package/dist/npm/modern/cjs/index.cjs +103 -68
- package/dist/npm/modern/content-script/cjs/index.cjs +94 -59
- package/dist/npm/modern/content-script/esm/index.mjs +94 -59
- package/dist/npm/modern/content-script/umd/index.js +94 -59
- package/dist/npm/modern/esm/index.mjs +103 -68
- package/dist/npm/modern/umd/index.js +103 -68
- package/package.json +1 -1
@@ -275,6 +275,10 @@
|
|
275
275
|
* @param value input value
|
276
276
|
* @returns boolean
|
277
277
|
*/const isNullOrUndefined=value=>isNull(value)||isUndefined(value);/**
|
278
|
+
* Checks if the input is a BigInt
|
279
|
+
* @param value input value
|
280
|
+
* @returns True if the input is a BigInt
|
281
|
+
*/const isBigInt=value=>typeof value==='bigint';/**
|
278
282
|
* A function to check given value is defined
|
279
283
|
* @param value input value
|
280
284
|
* @returns boolean
|
@@ -292,11 +296,11 @@
|
|
292
296
|
* @returns true if the input is an instance of Error and false otherwise
|
293
297
|
*/const isTypeOfError=obj=>obj instanceof Error;
|
294
298
|
|
295
|
-
const getValueByPath=(obj,keyPath)=>{const pathParts=keyPath.split('.');return path(pathParts,obj);};const hasValueByPath=(obj,path)=>Boolean(getValueByPath(obj,path));/**
|
299
|
+
const getValueByPath=(obj,keyPath)=>{const pathParts=keyPath.split('.');return path(pathParts,obj);};const hasValueByPath=(obj,path)=>Boolean(getValueByPath(obj,path));const isObject=value=>typeof value==='object';/**
|
296
300
|
* Checks if the input is an object literal or built-in object type and not null
|
297
301
|
* @param value Input value
|
298
302
|
* @returns true if the input is an object and not null
|
299
|
-
*/const isObjectAndNotNull=value=>!isNull(value)&&
|
303
|
+
*/const isObjectAndNotNull=value=>!isNull(value)&&isObject(value)&&!Array.isArray(value);/**
|
300
304
|
* Checks if the input is an object literal and not null
|
301
305
|
* @param value Input value
|
302
306
|
* @returns true if the input is an object and not null
|
@@ -330,37 +334,74 @@
|
|
330
334
|
* @returns base64 encoded string
|
331
335
|
*/const toBase64=value=>bytesToBase64(new TextEncoder().encode(value));
|
332
336
|
|
337
|
+
const LOG_CONTEXT_SEPARATOR=':: ';const SCRIPT_ALREADY_EXISTS_ERROR=id=>`A script with the id "${id}" is already loaded. Skipping the loading of this script to prevent conflicts.`;const SCRIPT_LOAD_ERROR=(id,url)=>`Failed to load the script with the id "${id}" from URL "${url}".`;const SCRIPT_LOAD_TIMEOUT_ERROR=(id,url,timeout)=>`A timeout of ${timeout} ms occurred while trying to load the script with id "${id}" from URL "${url}".`;const CIRCULAR_REFERENCE_WARNING=(context,key)=>`${context}${LOG_CONTEXT_SEPARATOR}A circular reference has been detected in the object and the property "${key}" has been dropped from the output.`;const JSON_STRINGIFY_WARNING=`Failed to convert the value to a JSON string.`;
|
338
|
+
|
339
|
+
const JSON_STRINGIFY='JSONStringify';const getCircularReplacer=(excludeNull,excludeKeys,logger)=>{const ancestors=[];// Here we do not want to use arrow function to use "this" in function context
|
340
|
+
// eslint-disable-next-line func-names
|
341
|
+
return function(key,value){if(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.
|
342
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
343
|
+
// @ts-ignore-next-line
|
344
|
+
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger?.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
|
345
|
+
* Utility method for JSON stringify object excluding null values & circular references
|
346
|
+
*
|
347
|
+
* @param {*} value input
|
348
|
+
* @param {boolean} excludeNull if it should exclude nul or not
|
349
|
+
* @param {function} logger optional logger methods for warning
|
350
|
+
* @returns string
|
351
|
+
*/const stringifyWithoutCircular=(value,excludeNull,excludeKeys,logger)=>{try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger?.warn(JSON_STRINGIFY_WARNING,err);return null;}};const getReplacer=logger=>{const ancestors=[];// Array to track ancestor objects
|
352
|
+
// Using a regular function to use `this` for the parent context
|
353
|
+
return function replacer(key,value){if(isBigInt(value)){return '[BigInt]';// Replace BigInt values
|
354
|
+
}// `this` is the object that value is contained in, i.e., its direct parent.
|
355
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
356
|
+
// @ts-ignore-next-line
|
357
|
+
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();// Remove ancestors that are no longer part of the chain
|
358
|
+
}// Check for circular references (if the value is already in the ancestors)
|
359
|
+
if(ancestors.includes(value)){return '[Circular Reference]';}// Add current value to ancestors
|
360
|
+
ancestors.push(value);return value;};};const traverseWithThis=(obj,replacer)=>{// Create a new result object or array
|
361
|
+
const result=Array.isArray(obj)?[]:{};// Traverse object properties or array elements
|
362
|
+
// eslint-disable-next-line no-restricted-syntax
|
363
|
+
for(const key in obj){if(Object.hasOwnProperty.call(obj,key)){const value=obj[key];// Recursively apply the replacer and traversal
|
364
|
+
const sanitizedValue=replacer.call(obj,key,value);// If the value is an object or array, continue traversal
|
365
|
+
if(isObjectLiteralAndNotNull(sanitizedValue)||Array.isArray(sanitizedValue)){result[key]=traverseWithThis(sanitizedValue,replacer);}else {result[key]=sanitizedValue;}}}return result;};/**
|
366
|
+
* Recursively traverses an object similar to JSON.stringify,
|
367
|
+
* sanitizing BigInts and circular references
|
368
|
+
* @param value Input object
|
369
|
+
* @param logger Logger instance
|
370
|
+
* @returns Sanitized value
|
371
|
+
*/const getSanitizedValue=(value,logger)=>{const replacer=getReplacer();// This is needed for registering the first ancestor
|
372
|
+
const newValue=replacer.call(value,'',value);if(isObjectLiteralAndNotNull(value)||Array.isArray(value)){return traverseWithThis(value,replacer);}return newValue;};
|
373
|
+
|
333
374
|
// if yes make them null instead of omitting in overloaded cases
|
334
375
|
/*
|
335
376
|
* Normalise the overloaded arguments of the page call facade
|
336
|
-
*/const pageArgumentsToCallOptions=(category,name,properties,options,callback)=>{const payload={category:
|
377
|
+
*/const pageArgumentsToCallOptions=(category,name,properties,options,callback)=>{const sanitizedCategory=getSanitizedValue(category);const sanitizedName=getSanitizedValue(name);const sanitizedProperties=getSanitizedValue(properties);const sanitizedOptions=getSanitizedValue(options);const sanitizedCallback=getSanitizedValue(callback);const 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,
|
337
378
|
// use it as name and set category to undefined
|
338
|
-
if(isString(
|
379
|
+
if(isString(sanitizedCategory)&&!isString(sanitizedName)){payload.category=undefined;payload.name=sanitizedCategory;}// Rest of the code is just to clean up undefined values
|
339
380
|
// and set some proper defaults
|
340
381
|
// Also, to clone the incoming object type arguments
|
341
382
|
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;}const nameForProperties=isString(payload.name)?payload.name:payload.properties.name;const categoryForProperties=isString(payload.category)?payload.category:payload.properties.category;// add name and category to properties
|
342
383
|
payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},{...(nameForProperties&&{name:nameForProperties}),...(categoryForProperties&&{category:categoryForProperties})});return payload;};/*
|
343
384
|
* Normalise the overloaded arguments of the track call facade
|
344
|
-
*/const trackArgumentsToCallOptions=(event,properties,options,callback)=>{const payload={name:
|
385
|
+
*/const trackArgumentsToCallOptions=(event,properties,options,callback)=>{const sanitizedEvent=getSanitizedValue(event);const sanitizedProperties=getSanitizedValue(properties);const sanitizedOptions=getSanitizedValue(options);const sanitizedCallback=getSanitizedValue(callback);const 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
|
345
386
|
// and set some proper defaults
|
346
387
|
// Also, to clone the incoming object type arguments
|
347
388
|
payload.properties=isDefinedAndNotNull(payload.properties)?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
|
348
389
|
* Normalise the overloaded arguments of the identify call facade
|
349
|
-
*/const identifyArgumentsToCallOptions=(userId,traits,options,callback)=>{const payload={userId:
|
390
|
+
*/const identifyArgumentsToCallOptions=(userId,traits,options,callback)=>{const sanitizedUserId=getSanitizedValue(userId);const sanitizedTraits=getSanitizedValue(traits);const sanitizedOptions=getSanitizedValue(options);const sanitizedCallback=getSanitizedValue(callback);const 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
|
350
391
|
// in the Analytics class
|
351
|
-
payload.userId=null;payload.traits=
|
392
|
+
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
|
352
393
|
// and set some proper defaults
|
353
394
|
// Also, to clone the incoming object type arguments
|
354
395
|
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;};/*
|
355
396
|
* Normalise the overloaded arguments of the alias call facade
|
356
|
-
*/const aliasArgumentsToCallOptions=(to,from,options,callback)=>{const payload={to,from:
|
397
|
+
*/const aliasArgumentsToCallOptions=(to,from,options,callback)=>{const sanitizedTo=getSanitizedValue(to);const sanitizedFrom=getSanitizedValue(from);const sanitizedOptions=getSanitizedValue(options);const sanitizedCallback=getSanitizedValue(callback);const 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
|
357
398
|
// and set some proper defaults
|
358
399
|
// Also, to clone the incoming object type arguments
|
359
400
|
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;};/*
|
360
401
|
* Normalise the overloaded arguments of the group call facade
|
361
|
-
*/const groupArgumentsToCallOptions=(groupId,traits,options,callback)=>{const payload={groupId:
|
402
|
+
*/const groupArgumentsToCallOptions=(groupId,traits,options,callback)=>{const sanitizedGroupId=getSanitizedValue(groupId);const sanitizedTraits=getSanitizedValue(traits);const sanitizedOptions=getSanitizedValue(options);const sanitizedCallback=getSanitizedValue(callback);const 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
|
362
403
|
// in the Analytics class
|
363
|
-
payload.groupId=null;payload.traits=
|
404
|
+
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
|
364
405
|
// and set some proper defaults
|
365
406
|
// Also, to clone the incoming object type arguments
|
366
407
|
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;};
|
@@ -377,7 +418,7 @@
|
|
377
418
|
* Represents the options parameter in the load API
|
378
419
|
*/
|
379
420
|
|
380
|
-
const CAPABILITIES_MANAGER='CapabilitiesManager';const CONFIG_MANAGER='ConfigManager';const EVENT_MANAGER='EventManager';const PLUGINS_MANAGER='PluginsManager';const USER_SESSION_MANAGER='UserSessionManager';const ERROR_HANDLER='ErrorHandler';const PLUGIN_ENGINE='PluginEngine';const STORE_MANAGER='StoreManager';const READY_API='readyApi';const EVENT_REPOSITORY='EventRepository';const EXTERNAL_SRC_LOADER='ExternalSrcLoader';const HTTP_CLIENT='HttpClient';const
|
421
|
+
const CAPABILITIES_MANAGER='CapabilitiesManager';const CONFIG_MANAGER='ConfigManager';const EVENT_MANAGER='EventManager';const PLUGINS_MANAGER='PluginsManager';const USER_SESSION_MANAGER='UserSessionManager';const ERROR_HANDLER='ErrorHandler';const PLUGIN_ENGINE='PluginEngine';const STORE_MANAGER='StoreManager';const READY_API='readyApi';const EVENT_REPOSITORY='EventRepository';const EXTERNAL_SRC_LOADER='ExternalSrcLoader';const HTTP_CLIENT='HttpClient';const RSA='RudderStackAnalytics';const ANALYTICS_CORE='AnalyticsCore';
|
381
422
|
|
382
423
|
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
383
424
|
|
@@ -408,7 +449,14 @@
|
|
408
449
|
* @returns ISO formatted timestamp string
|
409
450
|
*/const getCurrentTimeFormatted=()=>getFormattedTimestamp(new Date());
|
410
451
|
|
411
|
-
const
|
452
|
+
const MANUAL_ERROR_IDENTIFIER='[MANUAL ERROR]';/**
|
453
|
+
* Get mutated error with issue prepended to error message
|
454
|
+
* @param err Original error
|
455
|
+
* @param issue Issue to prepend to error message
|
456
|
+
* @returns Instance of Error with message prepended with issue
|
457
|
+
*/const getMutatedError=(err,issue)=>{let finalError=err;if(!isTypeOfError(err)){finalError=new Error(`${issue}: ${stringifyWithoutCircular(err)}`);}else {finalError.message=`${issue}: ${err.message}`;}return finalError;};const dispatchErrorEvent=error=>{if(isTypeOfError(error)){error.stack=`${error.stack??''}\n${MANUAL_ERROR_IDENTIFIER}`;}globalThis.dispatchEvent(new ErrorEvent('error',{error}));};
|
458
|
+
|
459
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.11.0';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
412
460
|
|
413
461
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
414
462
|
|
@@ -455,29 +503,6 @@
|
|
455
503
|
|
456
504
|
const DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
|
457
505
|
|
458
|
-
const LOG_CONTEXT_SEPARATOR=':: ';const SCRIPT_ALREADY_EXISTS_ERROR=id=>`A script with the id "${id}" is already loaded. Skipping the loading of this script to prevent conflicts.`;const SCRIPT_LOAD_ERROR=(id,url)=>`Failed to load the script with the id "${id}" from URL "${url}".`;const SCRIPT_LOAD_TIMEOUT_ERROR=(id,url,timeout)=>`A timeout of ${timeout} ms occurred while trying to load the script with id "${id}" from URL "${url}".`;const CIRCULAR_REFERENCE_WARNING=(context,key)=>`${context}${LOG_CONTEXT_SEPARATOR}A circular reference has been detected in the object and the property "${key}" has been dropped from the output.`;const JSON_STRINGIFY_WARNING=`Failed to convert the value to a JSON string.`;
|
459
|
-
|
460
|
-
const JSON_STRINGIFY='JSONStringify';const getCircularReplacer=(excludeNull,excludeKeys,logger)=>{const ancestors=[];// Here we do not want to use arrow function to use "this" in function context
|
461
|
-
// eslint-disable-next-line func-names
|
462
|
-
return function(key,value){if(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.
|
463
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
464
|
-
// @ts-ignore-next-line
|
465
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger?.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
|
466
|
-
* Utility method for JSON stringify object excluding null values & circular references
|
467
|
-
*
|
468
|
-
* @param {*} value input
|
469
|
-
* @param {boolean} excludeNull if it should exclude nul or not
|
470
|
-
* @param {function} logger optional logger methods for warning
|
471
|
-
* @returns string
|
472
|
-
*/const stringifyWithoutCircular=(value,excludeNull,excludeKeys,logger)=>{try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger?.warn(JSON_STRINGIFY_WARNING,err);return null;}};
|
473
|
-
|
474
|
-
/**
|
475
|
-
* Get mutated error with issue prepended to error message
|
476
|
-
* @param err Original error
|
477
|
-
* @param issue Issue to prepend to error message
|
478
|
-
* @returns Instance of Error with message prepended with issue
|
479
|
-
*/const getMutatedError=(err,issue)=>{let finalError=err;if(!isTypeOfError(err)){finalError=new Error(`${issue}: ${stringifyWithoutCircular(err)}`);}else {finalError.message=`${issue}: ${err.message}`;}return finalError;};
|
480
|
-
|
481
506
|
const EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
|
482
507
|
|
483
508
|
/**
|
@@ -550,8 +575,8 @@
|
|
550
575
|
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';
|
551
576
|
|
552
577
|
const SOURCE_CONFIG_OPTION_ERROR=`"getSourceConfig" must be a function. Please make sure that it is defined and returns a valid source configuration object.`;const SOURCE_CONFIG_RESOLUTION_ERROR=`Unable to process/parse source configuration response.`;const SOURCE_DISABLED_ERROR=`The source is disabled. Please enable the source in the dashboard to send events.`;const XHR_PAYLOAD_PREP_ERROR=`Failed to prepare data for the request.`;const EVENT_OBJECT_GENERATION_ERROR=`Failed to generate the event object.`;const PLUGIN_EXT_POINT_MISSING_ERROR=`Failed to invoke plugin because the extension point name is missing.`;const PLUGIN_EXT_POINT_INVALID_ERROR=`Failed to invoke plugin because the extension point name is invalid.`;const COMPONENT_BASE_URL_ERROR=component=>`Failed to load the SDK as the base URL for ${component} is not valid.`;// ERROR
|
553
|
-
const UNSUPPORTED_CONSENT_MANAGER_ERROR=(context,selectedConsentManager,consentManagersToPluginNameMap)=>`${context}${LOG_CONTEXT_SEPARATOR}The consent manager "${selectedConsentManager}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(consentManagersToPluginNameMap)}".`;const REPORTING_PLUGIN_INIT_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to initialize the error reporting plugin.`;const NOTIFY_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to notify the error.`;const PLUGIN_NAME_MISSING_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin name is missing.`;const PLUGIN_ALREADY_EXISTS_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" already exists.`;const PLUGIN_NOT_FOUND_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found.`;const PLUGIN_ENGINE_BUG_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`;const PLUGIN_DEPS_ERROR=(context,pluginName,notExistDeps)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" could not be loaded because some of its dependencies "${notExistDeps}" do not exist.`;const PLUGIN_INVOCATION_ERROR=(context,extPoint,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to invoke the "${extPoint}" extension point of plugin "${pluginName}".`;const STORAGE_UNAVAILABILITY_ERROR_PREFIX=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${storageType}" storage type is `;const SOURCE_CONFIG_FETCH_ERROR=reason=>`Failed to fetch the source config. Reason: ${reason}`;const WRITE_KEY_VALIDATION_ERROR=writeKey
|
554
|
-
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default type "${defaultStorageType}" will be used instead.`;const UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version "${selectedStorageEncryptionVersion}" is not supported. Please choose one of the following supported versions: "${Object.keys(storageEncryptionVersionsToPluginNameMap)}". The default version "${defaultVersion}" will be used instead.`;const STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=(context,storageEncryptionVersion,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;const SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=(context,providedCookieDomain,currentCookieDomain)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided cookie domain (${providedCookieDomain}) does not match the current webpage's domain (${currentCookieDomain}). Hence, the cookies will be set client-side.`;const RESERVED_KEYWORD_WARNING=(context,property,parentKeyPath,reservedElements)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${property}" property defined under "${parentKeyPath}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;const UNSUPPORTED_BEACON_API_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;const TIMEOUT_NOT_NUMBER_WARNING=(context,timeout,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value "${timeout}" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;const TIMEOUT_ZERO_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.`;const TIMEOUT_NOT_RECOMMENDED_WARNING=(context,timeout,minTimeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;const INVALID_SESSION_ID_WARNING=(context,sessionId,minSessionIdLength)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least "${minSessionIdLength}" digits long. A new session ID will be auto-generated instead.`;const STORAGE_QUOTA_EXCEEDED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;const STORAGE_UNAVAILABLE_WARNING=(context,entry,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`;const
|
578
|
+
const UNSUPPORTED_CONSENT_MANAGER_ERROR=(context,selectedConsentManager,consentManagersToPluginNameMap)=>`${context}${LOG_CONTEXT_SEPARATOR}The consent manager "${selectedConsentManager}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(consentManagersToPluginNameMap)}".`;const REPORTING_PLUGIN_INIT_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to initialize the error reporting plugin.`;const NOTIFY_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to notify the error.`;const PLUGIN_NAME_MISSING_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin name is missing.`;const PLUGIN_ALREADY_EXISTS_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" already exists.`;const PLUGIN_NOT_FOUND_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found.`;const PLUGIN_ENGINE_BUG_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`;const PLUGIN_DEPS_ERROR=(context,pluginName,notExistDeps)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" could not be loaded because some of its dependencies "${notExistDeps}" do not exist.`;const PLUGIN_INVOCATION_ERROR=(context,extPoint,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to invoke the "${extPoint}" extension point of plugin "${pluginName}".`;const STORAGE_UNAVAILABILITY_ERROR_PREFIX=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${storageType}" storage type is `;const SOURCE_CONFIG_FETCH_ERROR=reason=>`Failed to fetch the source config. Reason: ${reason}`;const WRITE_KEY_VALIDATION_ERROR=(context,writeKey)=>`${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`;const DATA_PLANE_URL_VALIDATION_ERROR=(context,dataPlaneUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The data plane URL "${dataPlaneUrl}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`;const READY_API_CALLBACK_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The provided callback is not a function.`;const XHR_DELIVERY_ERROR=(prefix,status,statusText,url)=>`${prefix} with status: ${status}, ${statusText} for URL: ${url}.`;const XHR_REQUEST_ERROR=(prefix,e,url)=>`${prefix} due to timeout or no connection (${e?e.type:''}) for URL: ${url}.`;const XHR_SEND_ERROR=(prefix,url)=>`${prefix} for URL: ${url}`;const STORE_DATA_SAVE_ERROR=key=>`Failed to save the value for "${key}" to storage`;const STORE_DATA_FETCH_ERROR=key=>`Failed to retrieve or parse data for "${key}" from storage`;const DATA_SERVER_REQUEST_FAIL_ERROR=status=>`The server responded with status ${status} while setting the cookies. As a fallback, the cookies will be set client side.`;const FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=key=>`The server failed to set the ${key} cookie. As a fallback, the cookies will be set client side.`;const 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
|
579
|
+
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default type "${defaultStorageType}" will be used instead.`;const UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version "${selectedStorageEncryptionVersion}" is not supported. Please choose one of the following supported versions: "${Object.keys(storageEncryptionVersionsToPluginNameMap)}". The default version "${defaultVersion}" will be used instead.`;const STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=(context,storageEncryptionVersion,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;const SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=(context,providedCookieDomain,currentCookieDomain)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided cookie domain (${providedCookieDomain}) does not match the current webpage's domain (${currentCookieDomain}). Hence, the cookies will be set client-side.`;const RESERVED_KEYWORD_WARNING=(context,property,parentKeyPath,reservedElements)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${property}" property defined under "${parentKeyPath}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;const UNSUPPORTED_BEACON_API_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;const TIMEOUT_NOT_NUMBER_WARNING=(context,timeout,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value "${timeout}" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;const TIMEOUT_ZERO_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.`;const TIMEOUT_NOT_RECOMMENDED_WARNING=(context,timeout,minTimeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;const INVALID_SESSION_ID_WARNING=(context,sessionId,minSessionIdLength)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least "${minSessionIdLength}" digits long. A new session ID will be auto-generated instead.`;const STORAGE_QUOTA_EXCEEDED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;const STORAGE_UNAVAILABLE_WARNING=(context,entry,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`;const READY_CALLBACK_INVOKE_ERROR=`Failed to invoke the ready callback`;const API_CALLBACK_INVOKE_ERROR=`API Callback Invocation Failed`;const NATIVE_DEST_PLUGIN_INITIALIZE_ERROR=`NativeDestinationQueuePlugin initialization failed`;const DATAPLANE_PLUGIN_INITIALIZE_ERROR=`XhrQueuePlugin initialization failed`;const DMT_PLUGIN_INITIALIZE_ERROR=`DeviceModeTransformationPlugin initialization failed`;const NATIVE_DEST_PLUGIN_ENQUEUE_ERROR=`NativeDestinationQueuePlugin event enqueue failed`;const DATAPLANE_PLUGIN_ENQUEUE_ERROR=`XhrQueuePlugin event enqueue failed`;const INVALID_CONFIG_URL_WARNING=(context,configUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided source config URL "${configUrl}" is invalid. Using the default source config URL instead.`;const POLYFILL_SCRIPT_LOAD_ERROR=(scriptId,url)=>`Failed to load the polyfill script with ID "${scriptId}" from URL ${url}.`;const UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=(context,selectedStrategy,defaultStrategy)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent storage strategy "${selectedStrategy}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${defaultStrategy}" will be used instead.`;const UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=(context,selectedDeliveryType,defaultDeliveryType)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent events delivery type "${selectedDeliveryType}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${defaultDeliveryType}" will be used instead.`;const generateMisconfiguredPluginsWarning=(context,configurationStatus,missingPlugins,shouldAddMissingPlugins)=>{const isSinglePlugin=missingPlugins.length===1;const pluginsString=isSinglePlugin?` '${missingPlugins[0]}' plugin was`:` ['${missingPlugins.join("', '")}'] plugins were`;const baseWarning=`${context}${LOG_CONTEXT_SEPARATOR}${configurationStatus}, but${pluginsString} not configured to load.`;if(shouldAddMissingPlugins){return `${baseWarning} So, ${isSinglePlugin?'the plugin':'those plugins'} will be loaded automatically.`;}return `${baseWarning} Ignore if this was intentional. Otherwise, consider adding ${isSinglePlugin?'it':'them'} to the 'plugins' load API option.`;};const INVALID_POLYFILL_URL_WARNING=(context,customPolyfillUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided polyfill URL "${customPolyfillUrl}" is invalid. The default polyfill URL will be used instead.`;const BAD_COOKIES_WARNING=key=>`The cookie data for ${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.`;const PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`;
|
555
580
|
|
556
581
|
const DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
557
582
|
|
@@ -634,7 +659,7 @@
|
|
634
659
|
// TODO: Remove this in the next major release
|
635
660
|
if(!this.pluginEngine){return;}try{const extPoint='errorReporting.init';const errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(client=>{this.errReportingClient=client;}).catch(err=>{this.logger?.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}onError(error,context='',customMessage='',shouldAlwaysThrow=false,errorType=ErrorType.HANDLEDEXCEPTION){let normalizedError;let errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
636
661
|
if(!errorMessage){return;}errorMessage=removeDoubleSpaces(`${context}${LOG_CONTEXT_SEPARATOR}${customMessage} ${errorMessage}`);normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}}else {normalizedError=getNormalizedErrorForUnhandledError(error);}const isErrorReportingEnabled=state.reporting.isErrorReportingEnabled.value;const isErrorReportingPluginLoaded=state.reporting.isErrorReportingPluginLoaded.value;try{if(isErrorReportingEnabled){const errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};if(!isErrorReportingPluginLoaded){// buffer the error
|
637
|
-
this.errorBuffer.enqueue({error:normalizedError,errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){this.logger?.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;}}}/**
|
662
|
+
this.errorBuffer.enqueue({error:normalizedError,errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){this.logger?.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?.stack?.includes(MANUAL_ERROR_IDENTIFIER)){this.logger?.error('An unknown error occurred:',error.error?.message);}}/**
|
638
663
|
* Add breadcrumbs to add insight of a user's journey before an error
|
639
664
|
* occurred and send to external error monitoring service via a plugin
|
640
665
|
*
|
@@ -1044,16 +1069,7 @@
|
|
1044
1069
|
* Handle errors
|
1045
1070
|
*/onError(error){if(this.hasErrorHandler){this.errorHandler?.onError(error,STORE_MANAGER);}else {throw error;}}}
|
1046
1071
|
|
1047
|
-
const
|
1048
|
-
* Checks if provided url is valid or not
|
1049
|
-
* @param url
|
1050
|
-
* @returns true if `url` is valid and false otherwise
|
1051
|
-
*/const isValidURL=url=>{if(!isString(url)){return false;}try{// If URL is supported by the browser, we can use it to validate the URL
|
1052
|
-
// Otherwise, we can at least check if the URL matches the pattern
|
1053
|
-
if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
|
1054
|
-
new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
1055
|
-
|
1056
|
-
const validateWriteKey=writeKey=>{if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};const validateDataPlaneUrl=dataPlaneUrl=>{if(!isValidURL(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};const validateLoadArgs=(writeKey,dataPlaneUrl)=>{validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};const isValidSourceConfig=res=>isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);const isValidStorageType=storageType=>typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);const getTopDomain=url=>{// Create a URL object
|
1072
|
+
const isValidSourceConfig=res=>isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);const isValidStorageType=storageType=>typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);const getTopDomain=url=>{// Create a URL object
|
1057
1073
|
const urlObj=new URL(url);// Extract the host and protocol
|
1058
1074
|
const{host,protocol}=urlObj;// Split the host into parts
|
1059
1075
|
const parts=host.split('.');let topDomain;// Handle different cases, especially for co.uk or similar TLDs
|
@@ -1089,6 +1105,15 @@
|
|
1089
1105
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
1090
1106
|
}return urlWithoutHash;};
|
1091
1107
|
|
1108
|
+
const removeDuplicateSlashes=str=>str.replace(/\/{2,}/g,'/');/**
|
1109
|
+
* Checks if provided url is valid or not
|
1110
|
+
* @param url
|
1111
|
+
* @returns true if `url` is valid and false otherwise
|
1112
|
+
*/const isValidURL=url=>{if(!isString(url)){return false;}try{// If URL is supported by the browser, we can use it to validate the URL
|
1113
|
+
// Otherwise, we can at least check if the URL matches the pattern
|
1114
|
+
if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
|
1115
|
+
new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
1116
|
+
|
1092
1117
|
/**
|
1093
1118
|
* Determines if the SDK is running inside a chrome extension
|
1094
1119
|
* @returns boolean
|
@@ -1173,7 +1198,7 @@
|
|
1173
1198
|
class ConfigManager{hasErrorHandler=false;constructor(httpClient,errorHandler,logger){this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}attachEffects(){E(()=>{this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
1174
1199
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
1175
1200
|
* config related information in global state
|
1176
|
-
*/init(){this.attachEffects();
|
1201
|
+
*/init(){this.attachEffects();const{logLevel,configUrl,lockIntegrationsVersion,lockPluginsVersion,destSDKBaseURL,pluginsSDKBaseURL,integrations}=state.loadOptions.value;state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
1177
1202
|
const intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL);// determine the path to fetch remote plugins from
|
1178
1203
|
const pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
|
1179
1204
|
r(()=>{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,this.logger);state.metrics.metricsServiceUrl.value=`${state.lifecycle.activeDataplaneUrl.value}/${METRICS_SERVICE_ENDPOINT}`;// Data in the loadOptions state is already normalized
|
@@ -1595,7 +1620,7 @@
|
|
1595
1620
|
* @param shouldAlwaysThrow if it should throw or use logger
|
1596
1621
|
*/onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}
|
1597
1622
|
|
1598
|
-
const dispatchSDKEvent=event=>{const customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
|
1623
|
+
const dispatchSDKEvent=event=>{const customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};const isWriteKeyValid=writeKey=>isString(writeKey)&&writeKey.trim().length>0;const isDataPlaneUrlValid=dataPlaneUrl=>isValidURL(dataPlaneUrl);
|
1599
1624
|
|
1600
1625
|
/*
|
1601
1626
|
* Analytics class with lifecycle based on state ad user triggered events
|
@@ -1603,9 +1628,8 @@
|
|
1603
1628
|
* Initialize services and components or use default ones if singletons
|
1604
1629
|
*/constructor(){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;}/**
|
1605
1630
|
* Start application lifecycle if not already started
|
1606
|
-
*/load(writeKey,dataPlaneUrl,loadOptions={}){if(state.lifecycle.status.value){return;}
|
1607
|
-
|
1608
|
-
r(()=>{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
|
1631
|
+
*/load(writeKey,dataPlaneUrl,loadOptions={}){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
|
1632
|
+
r(()=>{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
|
1609
1633
|
this.logger?.setMinLogLevel(state.loadOptions.value.logLevel??POST_LOAD_LOG_LEVEL);// Expose state to global objects
|
1610
1634
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
1611
1635
|
// State application lifecycle
|
@@ -1693,24 +1717,35 @@
|
|
1693
1717
|
* expose overloaded methods
|
1694
1718
|
* handle multiple Analytics instances
|
1695
1719
|
* consume SDK preload event buffer
|
1696
|
-
*/class RudderAnalytics{
|
1697
|
-
|
1720
|
+
*/class RudderAnalytics{// START-NO-SONAR-SCAN
|
1721
|
+
// eslint-disable-next-line sonarjs/public-static-readonly
|
1722
|
+
static globalSingleton=null;// END-NO-SONAR-SCAN
|
1723
|
+
analyticsInstances={};defaultAnalyticsKey='';logger=(()=>defaultLogger)();// Singleton with constructor bind methods
|
1724
|
+
constructor(){try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
|
1698
1725
|
// eslint-disable-next-line no-constructor-return
|
1699
1726
|
return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
|
1700
1727
|
}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
|
1701
1728
|
this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
|
1702
1729
|
// for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
|
1703
|
-
globalThis.rudderanalytics=this;}/**
|
1730
|
+
globalThis.rudderanalytics=this;}catch(error){dispatchErrorEvent(error);}}/**
|
1704
1731
|
* Set instance to use if no specific writeKey is provided in methods
|
1705
1732
|
* automatically for the first created instance
|
1706
1733
|
* TODO: to support multiple analytics instances in the near future
|
1707
|
-
*/setDefaultInstanceKey(writeKey){
|
1734
|
+
*/setDefaultInstanceKey(writeKey){// IMP: Add try-catch block to handle any unhandled errors
|
1735
|
+
// similar to other public methods
|
1736
|
+
// if the implementation of this method goes beyond
|
1737
|
+
// this simple implementation
|
1738
|
+
if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
1708
1739
|
* Retrieve an existing analytics instance
|
1709
|
-
*/getAnalyticsInstance(writeKey){
|
1710
|
-
*
|
1711
|
-
|
1740
|
+
*/getAnalyticsInstance(writeKey){try{let instanceId=writeKey;if(!isString(instanceId)||!instanceId){instanceId=this.defaultAnalyticsKey;}const analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}catch(error){dispatchErrorEvent(error);return undefined;}}/**
|
1741
|
+
* Loads the SDK
|
1742
|
+
* @param writeKey Source write key
|
1743
|
+
* @param dataPlaneUrl Data plane URL
|
1744
|
+
* @param loadOptions Additional options for loading the SDK
|
1745
|
+
* @returns none
|
1746
|
+
*/load(writeKey,dataPlaneUrl,loadOptions){try{if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);const preloadedEventsArray=this.getPreloadedEvents();// Track page loaded lifecycle event if enabled
|
1712
1747
|
this.trackPageLifecycleEvents(preloadedEventsArray,loadOptions);// The array will be mutated in the below method
|
1713
|
-
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey)
|
1748
|
+
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey)?.load(writeKey,dataPlaneUrl,getSanitizedValue(loadOptions));}catch(error){dispatchErrorEvent(error);}}/**
|
1714
1749
|
* A function to get preloaded events array from global object
|
1715
1750
|
* @returns preloaded events array
|
1716
1751
|
*/// eslint-disable-next-line class-methods-use-this
|
@@ -1734,7 +1769,7 @@
|
|
1734
1769
|
* @param useBeacon
|
1735
1770
|
* @param options
|
1736
1771
|
*/setupPageUnloadTracking(events,useBeacon,options){if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(isAccessible=>{if(isAccessible===false&&state.lifecycle.loaded.value){const pageUnloadedTimestamp=Date.now();const visitDuration=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(PageLifecycleEvents.UNLOADED,{visitDuration},{...options,originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))});}});}else {// throw warning if beacon is disabled
|
1737
|
-
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(
|
1772
|
+
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
|
1738
1773
|
* Trigger load event in buffer queue if exists and stores the
|
1739
1774
|
* remaining preloaded events array in global object
|
1740
1775
|
*/triggerBufferedLoadEvent(){const preloadedEventsArray=this.getPreloadedEvents();// Get any load method call that is buffered if any
|
@@ -1747,22 +1782,22 @@
|
|
1747
1782
|
// @ts-ignore
|
1748
1783
|
this.load.apply(null,loadEvent);}}/**
|
1749
1784
|
* Get ready callback arguments and forward to ready call
|
1750
|
-
*/ready(callback){this.getAnalyticsInstance()
|
1785
|
+
*/ready(callback){try{this.getAnalyticsInstance()?.ready(getSanitizedValue(callback));}catch(error){dispatchErrorEvent(error);}}/**
|
1751
1786
|
* Process page arguments and forward to page call
|
1752
1787
|
*/// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1753
|
-
page(category,name,properties,options,callback){this.getAnalyticsInstance()
|
1788
|
+
page(category,name,properties,options,callback){try{this.getAnalyticsInstance()?.page(pageArgumentsToCallOptions(category,name,properties,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
1754
1789
|
* Process track arguments and forward to page call
|
1755
1790
|
*/// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1756
|
-
track(event,properties,options,callback){this.getAnalyticsInstance()
|
1791
|
+
track(event,properties,options,callback){try{this.getAnalyticsInstance()?.track(trackArgumentsToCallOptions(event,properties,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
1757
1792
|
* Process identify arguments and forward to page call
|
1758
1793
|
*/// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1759
|
-
identify(userId,traits,options,callback){this.getAnalyticsInstance()
|
1794
|
+
identify(userId,traits,options,callback){try{this.getAnalyticsInstance()?.identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
1760
1795
|
* Process alias arguments and forward to page call
|
1761
1796
|
*/// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1762
|
-
alias(to,from,options,callback){this.getAnalyticsInstance()
|
1797
|
+
alias(to,from,options,callback){try{this.getAnalyticsInstance()?.alias(aliasArgumentsToCallOptions(to,from,options,callback));}catch(error){dispatchErrorEvent(error);}}/**
|
1763
1798
|
* Process group arguments and forward to page call
|
1764
1799
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
1765
|
-
group(groupId,traits,options,callback){
|
1800
|
+
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(groupArgumentsToCallOptions(groupId,traits,options,callback));}catch(error){dispatchErrorEvent(error);}}reset(resetAnonymousId){try{this.getAnalyticsInstance()?.reset(getSanitizedValue(resetAnonymousId));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{return this.getAnalyticsInstance()?.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{this.getAnalyticsInstance()?.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}startSession(sessionId){try{this.getAnalyticsInstance()?.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{this.getAnalyticsInstance()?.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{this.getAnalyticsInstance()?.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{this.getAnalyticsInstance()?.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}}
|
1766
1801
|
|
1767
1802
|
exports.RudderAnalytics = RudderAnalytics;
|
1768
1803
|
|