@rudderstack/analytics-js 3.7.6 → 3.7.8
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 +17 -0
- package/dist/npm/legacy/bundled/cjs/index.cjs +29 -47
- package/dist/npm/legacy/bundled/esm/index.mjs +29 -47
- package/dist/npm/legacy/bundled/umd/index.js +29 -47
- package/dist/npm/legacy/cjs/index.cjs +29 -47
- package/dist/npm/legacy/content-script/cjs/index.cjs +29 -47
- package/dist/npm/legacy/content-script/esm/index.mjs +29 -47
- package/dist/npm/legacy/content-script/umd/index.js +29 -47
- package/dist/npm/legacy/esm/index.mjs +29 -47
- package/dist/npm/legacy/umd/index.js +29 -47
- package/dist/npm/modern/bundled/cjs/index.cjs +29 -47
- package/dist/npm/modern/bundled/esm/index.mjs +29 -47
- package/dist/npm/modern/bundled/umd/index.js +29 -47
- package/dist/npm/modern/cjs/index.cjs +15 -32
- package/dist/npm/modern/content-script/cjs/index.cjs +29 -47
- package/dist/npm/modern/content-script/esm/index.mjs +29 -47
- package/dist/npm/modern/content-script/umd/index.js +29 -47
- package/dist/npm/modern/esm/index.mjs +15 -32
- package/dist/npm/modern/umd/index.js +15 -32
- package/package.json +1 -1
@@ -936,7 +936,7 @@
|
|
936
936
|
|
937
937
|
var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
|
938
938
|
|
939
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.7.
|
939
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.7.8';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
940
940
|
|
941
941
|
var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
942
942
|
|
@@ -1141,35 +1141,14 @@
|
|
1141
1141
|
extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
|
1142
1142
|
if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
|
1143
1143
|
|
1144
|
-
var
|
1144
|
+
var LOAD_ORIGIN='RS_JS_SDK';
|
1145
1145
|
|
1146
1146
|
/**
|
1147
1147
|
* Utility method to normalise errors
|
1148
1148
|
*/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:stringifyWithoutCircular(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)
|
1149
|
-
|
1150
|
-
//
|
1151
|
-
|
1152
|
-
// if (eventTarget && eventTarget.localName !== 'script') {
|
1153
|
-
// return undefined;
|
1154
|
-
// }
|
1155
|
-
// // Discard script errors that are not originated at SDK or from native SDKs
|
1156
|
-
// if (
|
1157
|
-
// eventTarget?.dataset &&
|
1158
|
-
// (eventTarget.dataset.loader !== LOAD_ORIGIN ||
|
1159
|
-
// eventTarget.dataset.isnonnativesdk !== 'true')
|
1160
|
-
// ) {
|
1161
|
-
// return undefined;
|
1162
|
-
// }
|
1163
|
-
// const errorMessage = `Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;
|
1164
|
-
// return Object.create(error, {
|
1165
|
-
// message: { value: errorMessage },
|
1166
|
-
// });
|
1167
|
-
// }
|
1168
|
-
return undefined;}catch(e){return e;}};/**
|
1169
|
-
* A function to determine whether the error should be promoted to notify or not
|
1170
|
-
* @param {Error} error
|
1171
|
-
* @returns
|
1172
|
-
*/var isAllowedToBeNotified=function isAllowedToBeNotified(error){if((error instanceof Error||error instanceof ErrorEvent)&&error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.message.includes(e);});}if(error instanceof PromiseRejectionEvent&&typeof error.reason==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.reason.includes(e);});}return true;};
|
1149
|
+
if(error instanceof Event){var eventTarget=error.target;// Discard all the non-script loading errors
|
1150
|
+
if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
|
1151
|
+
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;}};
|
1173
1152
|
|
1174
1153
|
/**
|
1175
1154
|
* A service to handle errors
|
@@ -1190,7 +1169,7 @@
|
|
1190
1169
|
* Send handled errors to external error monitoring service via a plugin
|
1191
1170
|
*
|
1192
1171
|
* @param {Error} error Error instance from handled error
|
1193
|
-
*/},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient
|
1172
|
+
*/},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
|
1194
1173
|
this.errReportingClient,// deprecated parameter
|
1195
1174
|
error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$logger3;// Not calling onError here as we don't want to go into infinite loop
|
1196
1175
|
(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
@@ -1697,6 +1676,8 @@
|
|
1697
1676
|
|
1698
1677
|
var METRICS_PAYLOAD_VERSION='1';
|
1699
1678
|
|
1679
|
+
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1680
|
+
|
1700
1681
|
// Errors from the below scripts are NOT allowed to reach Bugsnag
|
1701
1682
|
var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
|
1702
1683
|
];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
|
@@ -1704,11 +1685,19 @@
|
|
1704
1685
|
var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
|
1705
1686
|
'eventBuffer',// pre-load event buffer (may contain PII)
|
1706
1687
|
'traits'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
|
1707
|
-
var NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';var SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';var SOURCE_NAME='js';
|
1688
|
+
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';
|
1708
1689
|
|
1709
1690
|
var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',tolerateNonErrors:true,errorFramesToSkip:1,normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',tolerateNonErrors:false,errorFramesToSkip:1,normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',tolerateNonErrors:true,errorFramesToSkip:2,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=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?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
|
1710
1691
|
// on the dashboard
|
1711
|
-
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}}]};}
|
1692
|
+
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}}]};};/**
|
1693
|
+
* A function to determine whether the error should be promoted to notify or not
|
1694
|
+
* @param {Error} error
|
1695
|
+
* @returns
|
1696
|
+
*/var isAllowedToBeNotified=function isAllowedToBeNotified(event){var errorMessage=event.message;if(errorMessage&&typeof errorMessage==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return errorMessage.includes(e);});}return true;};/**
|
1697
|
+
* A function to determine if the error is from Rudder SDK
|
1698
|
+
* @param {Error} event
|
1699
|
+
* @returns
|
1700
|
+
*/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
|
1712
1701
|
// Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
|
1713
1702
|
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 stringifyWithoutCircular(data);};
|
1714
1703
|
|
@@ -1752,19 +1741,10 @@
|
|
1752
1741
|
// This adds one.
|
1753
1742
|
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
|
1754
1743
|
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
|
1755
|
-
var getStacktrace=function getStacktrace(error,errorFramesToSkip){if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};var hasNecessaryFields=function hasNecessaryFields(error){return (typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');};var normaliseError=function normaliseError(maybeError,
|
1756
|
-
//
|
1757
|
-
// - the promise rejection handler (both in the browser and node)
|
1758
|
-
// - the node uncaughtException handler
|
1759
|
-
//
|
1760
|
-
// We are really limited in what we can do to get a stacktrace. So we use the
|
1761
|
-
// tolerateNonErrors option to ensure that the resulting error communicates as
|
1762
|
-
// such.
|
1763
|
-
if(!tolerateNonErrors){if(isError(maybeError)){error=maybeError;}else {error=createAndLogInputError(_typeof(maybeError));internalFrames+=2;}}else {switch(_typeof(maybeError)){case'string':case'number':case'boolean':error=new Error(String(maybeError));internalFrames+=1;break;case'function':error=createAndLogInputError('function');internalFrames+=2;break;case'object':if(maybeError!==null&&isError(maybeError)){error=maybeError;}else if(maybeError!==null&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {error=createAndLogInputError(maybeError===null?'null':'unsupported object');internalFrames+=2;}break;default:error=createAndLogInputError('nothing');internalFrames+=2;}}if(!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1744
|
+
var getStacktrace=function getStacktrace(error,errorFramesToSkip){if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};var hasNecessaryFields=function hasNecessaryFields(error){return (typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');};var normaliseError=function normaliseError(maybeError,component,logger){var error;var internalFrames=0;if(isError(maybeError)){error=maybeError;}else if(_typeof(maybeError)==='object'&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {logger===null||logger===void 0||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(stringifyWithoutCircular(error)));error=undefined;}if(error&&!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1764
1745
|
try{throw error;}catch(e){if(hasStack(e)){error=e;// if the error only got a stacktrace after we threw it here, we know it
|
1765
|
-
// will only have one extra internal frame from this function
|
1766
|
-
|
1767
|
-
internalFrames=1;}}}return [error,internalFrames];};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,tolerateNonErrors,handledState,component){var errorFramesToSkip=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var logger=arguments.length>5?arguments[5]:undefined;var _normaliseError=normaliseError(maybeError,tolerateNonErrors,component,logger),_normaliseError2=_slicedToArray(_normaliseError,2),error=_normaliseError2[0],internalFrames=_normaliseError2[1];var event;try{var stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1746
|
+
// will only have one extra internal frame from this function
|
1747
|
+
internalFrames=1;}}}return [error,internalFrames];};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,tolerateNonErrors,handledState,component){var errorFramesToSkip=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var logger=arguments.length>5?arguments[5]:undefined;var _normaliseError=normaliseError(maybeError,component,logger),_normaliseError2=_slicedToArray(_normaliseError,2),error=_normaliseError2[0],internalFrames=_normaliseError2[1];if(!error){return undefined;}var event;try{var stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1768
1748
|
// tell the getStacktrace() function to skip the number of frames we know will
|
1769
1749
|
// be from our own functions. This is added to the number of frames deep we
|
1770
1750
|
// were told about
|
@@ -1775,7 +1755,7 @@
|
|
1775
1755
|
var pluginName$9='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$9,deps:[],initialize:function initialize(state){var _state$reporting$brea;state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);state.reporting.isErrorReportingPluginLoaded.value=true;if((_state$reporting$brea=state.reporting.breadcrumbs)!==null&&_state$reporting$brea!==void 0&&_state$reporting$brea.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
|
1776
1756
|
// TODO: Remove this in the next major release
|
1777
1757
|
init:function init(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore){var _state$source$value,_state$source$value2;if(isInvokedFromLatestCore){return undefined;}if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==void 0&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==void 0&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger,httpClient,errorState){if(httpClient){var _getConfigForPayloadC=getConfigForPayloadCreation(error,errorState===null||errorState===void 0?void 0:errorState.severityReason.type),component=_getConfigForPayloadC.component,tolerateNonErrors=_getConfigForPayloadC.tolerateNonErrors,errorFramesToSkip=_getConfigForPayloadC.errorFramesToSkip,normalizedError=_getConfigForPayloadC.normalizedError;// Generate the error payload
|
1778
|
-
var errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger)
|
1758
|
+
var errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger);if(!errorPayload||!isAllowedToBeNotified(errorPayload.errors[0])){return;}// filter errors
|
1779
1759
|
if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
|
1780
1760
|
var bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
|
1781
1761
|
httpClient===null||httpClient===void 0||httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// do nothing
|
@@ -3320,9 +3300,14 @@
|
|
3320
3300
|
*/var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
3321
3301
|
}return urlWithoutHash;};
|
3322
3302
|
|
3303
|
+
/**
|
3304
|
+
* Determines if the SDK is running inside a chrome extension
|
3305
|
+
* @returns boolean
|
3306
|
+
*/var isSDKRunningInChromeExtension=function isSDKRunningInChromeExtension(){return !!(window.chrome&&window.chrome.runtime&&window.chrome.runtime.id);};
|
3307
|
+
|
3323
3308
|
var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
3324
3309
|
|
3325
|
-
var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
|
3310
|
+
var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
|
3326
3311
|
|
3327
3312
|
/**
|
3328
3313
|
* Validates and normalizes the consent options provided by the user
|
@@ -3356,10 +3341,7 @@
|
|
3356
3341
|
* Updates the reporting state variables from the source config data
|
3357
3342
|
* @param res Source config
|
3358
3343
|
* @param logger Logger instance
|
3359
|
-
*/var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=
|
3360
|
-
// state.reporting.isErrorReportingEnabled.value =
|
3361
|
-
// isErrorReportingEnabled(res.source.config) && !isSDKRunningInChromeExtension();
|
3362
|
-
state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
3344
|
+
*/var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
3363
3345
|
logger===null||logger===void 0||logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
|
3364
3346
|
var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(function(){var _storageOptsFromLoad$2;state.storage.type.value=storageType;var cookieOptions=(_storageOptsFromLoad$2=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie)!==null&&_storageOptsFromLoad$2!==void 0?_storageOptsFromLoad$2:{};if(useServerSideCookies){var _cookieOptions$domain;state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;var providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==void 0?_cookieOptions$domain:setCookieDomain;/**
|
3365
3347
|
* Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
|
@@ -374,7 +374,7 @@ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(paylo
|
|
374
374
|
|
375
375
|
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 RS_APP='RudderStackApplication';const ANALYTICS_CORE='AnalyticsCore';
|
376
376
|
|
377
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.7.
|
377
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.7.8';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
378
378
|
|
379
379
|
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';
|
380
380
|
|
@@ -579,35 +579,14 @@ processRawPlugins(callback){callback(this.plugins);this.cache={};}invoke(extPoin
|
|
579
579
|
extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}const extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();const pluginMethodPath=extensionPointNameParts.join('.');const pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(plugin=>{const method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
|
580
580
|
if(throws){throw err;}else {this.logger?.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}invokeSingle(extPoint,...args){return this.invoke(extPoint,false,...args)[0];}invokeMultiple(extPoint,...args){return this.invoke(extPoint,true,...args);}}const defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
|
581
581
|
|
582
|
-
const
|
582
|
+
const LOAD_ORIGIN='RS_JS_SDK';
|
583
583
|
|
584
584
|
/**
|
585
585
|
* Utility method to normalise errors
|
586
586
|
*/const processError=error=>{let 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:stringifyWithoutCircular(error);}}catch(e){errorMessage=`Unknown error: ${e.message}`;}return errorMessage;};const 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)
|
587
|
-
|
588
|
-
//
|
589
|
-
|
590
|
-
// if (eventTarget && eventTarget.localName !== 'script') {
|
591
|
-
// return undefined;
|
592
|
-
// }
|
593
|
-
// // Discard script errors that are not originated at SDK or from native SDKs
|
594
|
-
// if (
|
595
|
-
// eventTarget?.dataset &&
|
596
|
-
// (eventTarget.dataset.loader !== LOAD_ORIGIN ||
|
597
|
-
// eventTarget.dataset.isnonnativesdk !== 'true')
|
598
|
-
// ) {
|
599
|
-
// return undefined;
|
600
|
-
// }
|
601
|
-
// const errorMessage = `Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;
|
602
|
-
// return Object.create(error, {
|
603
|
-
// message: { value: errorMessage },
|
604
|
-
// });
|
605
|
-
// }
|
606
|
-
return undefined;}catch(e){return e;}};/**
|
607
|
-
* A function to determine whether the error should be promoted to notify or not
|
608
|
-
* @param {Error} error
|
609
|
-
* @returns
|
610
|
-
*/const isAllowedToBeNotified=error=>{if((error instanceof Error||error instanceof ErrorEvent)&&error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>error.message.includes(e));}if(error instanceof PromiseRejectionEvent&&typeof error.reason==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>error.reason.includes(e));}return true;};
|
587
|
+
if(error instanceof Event){const eventTarget=error.target;// Discard all the non-script loading errors
|
588
|
+
if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
|
589
|
+
if(eventTarget?.dataset&&(eventTarget.dataset.loader!==LOAD_ORIGIN||eventTarget.dataset.isnonnativesdk!=='true')){return undefined;}const errorMessage=`Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;return Object.create(error,{message:{value:errorMessage}});}return error;}catch(e){return e;}};
|
611
590
|
|
612
591
|
/**
|
613
592
|
* A service to handle errors
|
@@ -628,7 +607,7 @@ breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorR
|
|
628
607
|
* Send handled errors to external error monitoring service via a plugin
|
629
608
|
*
|
630
609
|
* @param {Error} error Error instance from handled error
|
631
|
-
*/notifyError(error,errorState){if(this.pluginEngine&&this.httpClient
|
610
|
+
*/notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
|
632
611
|
this.errReportingClient,// deprecated parameter
|
633
612
|
error,state,this.logger,this.httpClient,errorState);}catch(err){// Not calling onError here as we don't want to go into infinite loop
|
634
613
|
this.logger?.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}const defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
@@ -1135,6 +1114,8 @@ const queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemp
|
|
1135
1114
|
|
1136
1115
|
const METRICS_PAYLOAD_VERSION='1';
|
1137
1116
|
|
1117
|
+
const FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';const ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1118
|
+
|
1138
1119
|
// Errors from the below scripts are NOT allowed to reach Bugsnag
|
1139
1120
|
const SDK_FILE_NAME_PREFIXES=()=>['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
|
1140
1121
|
];const DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
|
@@ -1142,11 +1123,19 @@ const SDK_FILE_NAME_PREFIXES=()=>['rsa'// Prefix for all the SDK scripts includi
|
|
1142
1123
|
const APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
|
1143
1124
|
'eventBuffer',// pre-load event buffer (may contain PII)
|
1144
1125
|
'traits'];const REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
|
1145
|
-
const NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';const SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';const SOURCE_NAME='js';
|
1126
|
+
const NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';const SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';const SOURCE_NAME='js';const ERROR_REPORTING_PLUGIN='ErrorReportingPlugin';
|
1146
1127
|
|
1147
1128
|
const getConfigForPayloadCreation=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{const{error}=err;return {component:'unhandledException handler',tolerateNonErrors:true,errorFramesToSkip:1,normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{const error=err;return {component:'unhandledrejection handler',tolerateNonErrors:false,errorFramesToSkip:1,normalizedError:error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',tolerateNonErrors:true,errorFramesToSkip:2,normalizedError:err};}};const createNewBreadcrumb=(message,metaData)=>({type:'manual',name:message,timestamp:new Date(),metaData:metaData??{}});const getReleaseStage=()=>{const host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getErrorContext=event=>{const{message}=event;let context=message;// Hack for easily grouping the script load errors
|
1148
1129
|
// on the dashboard
|
1149
|
-
if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};const getBugsnagErrorEvent=(payload,errorState,state)=>({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.value??undefined,userAgent:state.context.userAgent.value??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:getAppStateForMetadata(state)??{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:state.source.value?.id??state.lifecycle.writeKey.value}}]})
|
1130
|
+
if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};const getBugsnagErrorEvent=(payload,errorState,state)=>({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.value??undefined,userAgent:state.context.userAgent.value??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:getAppStateForMetadata(state)??{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:state.source.value?.id??state.lifecycle.writeKey.value}}]});/**
|
1131
|
+
* A function to determine whether the error should be promoted to notify or not
|
1132
|
+
* @param {Error} error
|
1133
|
+
* @returns
|
1134
|
+
*/const isAllowedToBeNotified=event=>{const errorMessage=event.message;if(errorMessage&&typeof errorMessage==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>errorMessage.includes(e));}return true;};/**
|
1135
|
+
* A function to determine if the error is from Rudder SDK
|
1136
|
+
* @param {Error} event
|
1137
|
+
* @returns
|
1138
|
+
*/const isRudderSDKError=event=>{const errorOrigin=event.stacktrace?.[0]?.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}const srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);const paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
|
1150
1139
|
// Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
|
1151
1140
|
const parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(prefix=>srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js'));};const getErrorDeliveryPayload=(payload,state)=>{const 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 stringifyWithoutCircular(data);};
|
1152
1141
|
|
@@ -1190,19 +1179,10 @@ const formatStackframe=frame=>{const f={file:frame.fileName,method:normaliseFunc
|
|
1190
1179
|
// This adds one.
|
1191
1180
|
if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};const ensureString=str=>typeof str==='string'?str:'';function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce((accum,frame)=>{const f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
|
1192
1181
|
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
|
1193
|
-
const getStacktrace=(error,errorFramesToSkip)=>{if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};const hasNecessaryFields=error=>(typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');const normaliseError=(maybeError,
|
1194
|
-
//
|
1195
|
-
// - the promise rejection handler (both in the browser and node)
|
1196
|
-
// - the node uncaughtException handler
|
1197
|
-
//
|
1198
|
-
// We are really limited in what we can do to get a stacktrace. So we use the
|
1199
|
-
// tolerateNonErrors option to ensure that the resulting error communicates as
|
1200
|
-
// such.
|
1201
|
-
if(!tolerateNonErrors){if(isError(maybeError)){error=maybeError;}else {error=createAndLogInputError(typeof maybeError);internalFrames+=2;}}else {switch(typeof maybeError){case'string':case'number':case'boolean':error=new Error(String(maybeError));internalFrames+=1;break;case'function':error=createAndLogInputError('function');internalFrames+=2;break;case'object':if(maybeError!==null&&isError(maybeError)){error=maybeError;}else if(maybeError!==null&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {error=createAndLogInputError(maybeError===null?'null':'unsupported object');internalFrames+=2;}break;default:error=createAndLogInputError('nothing');internalFrames+=2;}}if(!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1182
|
+
const getStacktrace=(error,errorFramesToSkip)=>{if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};const hasNecessaryFields=error=>(typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');const normaliseError=(maybeError,component,logger)=>{let error;let internalFrames=0;if(isError(maybeError)){error=maybeError;}else if(typeof maybeError==='object'&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {logger?.warn(`${ERROR_REPORTING_PLUGIN}:: ${component} received a non-error: ${stringifyWithoutCircular(error)}`);error=undefined;}if(error&&!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1202
1183
|
try{throw error;}catch(e){if(hasStack(e)){error=e;// if the error only got a stacktrace after we threw it here, we know it
|
1203
|
-
// will only have one extra internal frame from this function
|
1204
|
-
|
1205
|
-
internalFrames=1;}}}return [error,internalFrames];};class ErrorFormat{constructor(errorClass,errorMessage,stacktrace){this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}static create(maybeError,tolerateNonErrors,handledState,component,errorFramesToSkip=0,logger){const[error,internalFrames]=normaliseError(maybeError,tolerateNonErrors,component,logger);let event;try{const stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1184
|
+
// will only have one extra internal frame from this function
|
1185
|
+
internalFrames=1;}}}return [error,internalFrames];};class ErrorFormat{constructor(errorClass,errorMessage,stacktrace){this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}static create(maybeError,tolerateNonErrors,handledState,component,errorFramesToSkip=0,logger){const[error,internalFrames]=normaliseError(maybeError,component,logger);if(!error){return undefined;}let event;try{const stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1206
1186
|
// tell the getStacktrace() function to skip the number of frames we know will
|
1207
1187
|
// be from our own functions. This is added to the number of frames deep we
|
1208
1188
|
// were told about
|
@@ -1213,7 +1193,7 @@ const INVALID_SOURCE_CONFIG_ERROR=`Invalid source configuration or source id.`;
|
|
1213
1193
|
const pluginName$9='ErrorReporting';const ErrorReporting=()=>({name:pluginName$9,deps:[],initialize:state=>{state.plugins.loadedPlugins.value=[...state.plugins.loadedPlugins.value,pluginName$9];state.reporting.isErrorReportingPluginLoaded.value=true;if(state.reporting.breadcrumbs?.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
|
1214
1194
|
// TODO: Remove this in the next major release
|
1215
1195
|
init:(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore)=>{if(isInvokedFromLatestCore){return undefined;}if(!state.source.value?.config||!state.source.value?.id){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:(pluginEngine,client,error,state,logger,httpClient,errorState)=>{if(httpClient){const{component,tolerateNonErrors,errorFramesToSkip,normalizedError}=getConfigForPayloadCreation(error,errorState?.severityReason.type);// Generate the error payload
|
1216
|
-
const errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger)
|
1196
|
+
const errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger);if(!errorPayload||!isAllowedToBeNotified(errorPayload.errors[0])){return;}// filter errors
|
1217
1197
|
if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
|
1218
1198
|
const bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
|
1219
1199
|
httpClient?.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:(result,details)=>{// do nothing
|
@@ -2732,9 +2712,14 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
|
|
2732
2712
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
2733
2713
|
}return urlWithoutHash;};
|
2734
2714
|
|
2715
|
+
/**
|
2716
|
+
* Determines if the SDK is running inside a chrome extension
|
2717
|
+
* @returns boolean
|
2718
|
+
*/const isSDKRunningInChromeExtension=()=>!!(window.chrome&&window.chrome.runtime&&window.chrome.runtime.id);
|
2719
|
+
|
2735
2720
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
2736
2721
|
|
2737
|
-
const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
2722
|
+
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
2738
2723
|
|
2739
2724
|
/**
|
2740
2725
|
* Validates and normalizes the consent options provided by the user
|
@@ -2768,10 +2753,7 @@ for(const script of scripts){const src=script.getAttribute('src');if(src&&sdkFil
|
|
2768
2753
|
* Updates the reporting state variables from the source config data
|
2769
2754
|
* @param res Source config
|
2770
2755
|
* @param logger Logger instance
|
2771
|
-
*/const updateReportingState=res=>{state.reporting.isErrorReportingEnabled.value=
|
2772
|
-
// state.reporting.isErrorReportingEnabled.value =
|
2773
|
-
// isErrorReportingEnabled(res.source.config) && !isSDKRunningInChromeExtension();
|
2774
|
-
state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};const updateStorageStateFromLoadOptions=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
2756
|
+
*/const updateReportingState=res=>{state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};const updateStorageStateFromLoadOptions=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
2775
2757
|
logger?.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
|
2776
2758
|
const configuredMigrationValue=storageOptsFromLoad?.migrate;const finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger?.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(()=>{state.storage.type.value=storageType;let cookieOptions=storageOptsFromLoad?.cookie??{};if(useServerSideCookies){state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;const providedCookieDomain=cookieOptions.domain??setCookieDomain;/**
|
2777
2759
|
* Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
|
@@ -370,7 +370,7 @@ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(paylo
|
|
370
370
|
|
371
371
|
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 RS_APP='RudderStackApplication';const ANALYTICS_CORE='AnalyticsCore';
|
372
372
|
|
373
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.7.
|
373
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.7.8';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
374
374
|
|
375
375
|
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';
|
376
376
|
|
@@ -575,35 +575,14 @@ processRawPlugins(callback){callback(this.plugins);this.cache={};}invoke(extPoin
|
|
575
575
|
extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}const extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();const pluginMethodPath=extensionPointNameParts.join('.');const pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(plugin=>{const method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
|
576
576
|
if(throws){throw err;}else {this.logger?.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}invokeSingle(extPoint,...args){return this.invoke(extPoint,false,...args)[0];}invokeMultiple(extPoint,...args){return this.invoke(extPoint,true,...args);}}const defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
|
577
577
|
|
578
|
-
const
|
578
|
+
const LOAD_ORIGIN='RS_JS_SDK';
|
579
579
|
|
580
580
|
/**
|
581
581
|
* Utility method to normalise errors
|
582
582
|
*/const processError=error=>{let 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:stringifyWithoutCircular(error);}}catch(e){errorMessage=`Unknown error: ${e.message}`;}return errorMessage;};const 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)
|
583
|
-
|
584
|
-
//
|
585
|
-
|
586
|
-
// if (eventTarget && eventTarget.localName !== 'script') {
|
587
|
-
// return undefined;
|
588
|
-
// }
|
589
|
-
// // Discard script errors that are not originated at SDK or from native SDKs
|
590
|
-
// if (
|
591
|
-
// eventTarget?.dataset &&
|
592
|
-
// (eventTarget.dataset.loader !== LOAD_ORIGIN ||
|
593
|
-
// eventTarget.dataset.isnonnativesdk !== 'true')
|
594
|
-
// ) {
|
595
|
-
// return undefined;
|
596
|
-
// }
|
597
|
-
// const errorMessage = `Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;
|
598
|
-
// return Object.create(error, {
|
599
|
-
// message: { value: errorMessage },
|
600
|
-
// });
|
601
|
-
// }
|
602
|
-
return undefined;}catch(e){return e;}};/**
|
603
|
-
* A function to determine whether the error should be promoted to notify or not
|
604
|
-
* @param {Error} error
|
605
|
-
* @returns
|
606
|
-
*/const isAllowedToBeNotified=error=>{if((error instanceof Error||error instanceof ErrorEvent)&&error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>error.message.includes(e));}if(error instanceof PromiseRejectionEvent&&typeof error.reason==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>error.reason.includes(e));}return true;};
|
583
|
+
if(error instanceof Event){const eventTarget=error.target;// Discard all the non-script loading errors
|
584
|
+
if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
|
585
|
+
if(eventTarget?.dataset&&(eventTarget.dataset.loader!==LOAD_ORIGIN||eventTarget.dataset.isnonnativesdk!=='true')){return undefined;}const errorMessage=`Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;return Object.create(error,{message:{value:errorMessage}});}return error;}catch(e){return e;}};
|
607
586
|
|
608
587
|
/**
|
609
588
|
* A service to handle errors
|
@@ -624,7 +603,7 @@ breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorR
|
|
624
603
|
* Send handled errors to external error monitoring service via a plugin
|
625
604
|
*
|
626
605
|
* @param {Error} error Error instance from handled error
|
627
|
-
*/notifyError(error,errorState){if(this.pluginEngine&&this.httpClient
|
606
|
+
*/notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
|
628
607
|
this.errReportingClient,// deprecated parameter
|
629
608
|
error,state,this.logger,this.httpClient,errorState);}catch(err){// Not calling onError here as we don't want to go into infinite loop
|
630
609
|
this.logger?.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}const defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
@@ -1131,6 +1110,8 @@ const queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemp
|
|
1131
1110
|
|
1132
1111
|
const METRICS_PAYLOAD_VERSION='1';
|
1133
1112
|
|
1113
|
+
const FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';const ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1114
|
+
|
1134
1115
|
// Errors from the below scripts are NOT allowed to reach Bugsnag
|
1135
1116
|
const SDK_FILE_NAME_PREFIXES=()=>['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
|
1136
1117
|
];const DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
|
@@ -1138,11 +1119,19 @@ const SDK_FILE_NAME_PREFIXES=()=>['rsa'// Prefix for all the SDK scripts includi
|
|
1138
1119
|
const APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
|
1139
1120
|
'eventBuffer',// pre-load event buffer (may contain PII)
|
1140
1121
|
'traits'];const REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
|
1141
|
-
const NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';const SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';const SOURCE_NAME='js';
|
1122
|
+
const NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';const SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';const SOURCE_NAME='js';const ERROR_REPORTING_PLUGIN='ErrorReportingPlugin';
|
1142
1123
|
|
1143
1124
|
const getConfigForPayloadCreation=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{const{error}=err;return {component:'unhandledException handler',tolerateNonErrors:true,errorFramesToSkip:1,normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{const error=err;return {component:'unhandledrejection handler',tolerateNonErrors:false,errorFramesToSkip:1,normalizedError:error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',tolerateNonErrors:true,errorFramesToSkip:2,normalizedError:err};}};const createNewBreadcrumb=(message,metaData)=>({type:'manual',name:message,timestamp:new Date(),metaData:metaData??{}});const getReleaseStage=()=>{const host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getErrorContext=event=>{const{message}=event;let context=message;// Hack for easily grouping the script load errors
|
1144
1125
|
// on the dashboard
|
1145
|
-
if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};const getBugsnagErrorEvent=(payload,errorState,state)=>({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.value??undefined,userAgent:state.context.userAgent.value??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:getAppStateForMetadata(state)??{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:state.source.value?.id??state.lifecycle.writeKey.value}}]})
|
1126
|
+
if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};const getBugsnagErrorEvent=(payload,errorState,state)=>({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.value??undefined,userAgent:state.context.userAgent.value??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:getAppStateForMetadata(state)??{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:state.source.value?.id??state.lifecycle.writeKey.value}}]});/**
|
1127
|
+
* A function to determine whether the error should be promoted to notify or not
|
1128
|
+
* @param {Error} error
|
1129
|
+
* @returns
|
1130
|
+
*/const isAllowedToBeNotified=event=>{const errorMessage=event.message;if(errorMessage&&typeof errorMessage==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(e=>errorMessage.includes(e));}return true;};/**
|
1131
|
+
* A function to determine if the error is from Rudder SDK
|
1132
|
+
* @param {Error} event
|
1133
|
+
* @returns
|
1134
|
+
*/const isRudderSDKError=event=>{const errorOrigin=event.stacktrace?.[0]?.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}const srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);const paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
|
1146
1135
|
// Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
|
1147
1136
|
const parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(prefix=>srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js'));};const getErrorDeliveryPayload=(payload,state)=>{const 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 stringifyWithoutCircular(data);};
|
1148
1137
|
|
@@ -1186,19 +1175,10 @@ const formatStackframe=frame=>{const f={file:frame.fileName,method:normaliseFunc
|
|
1186
1175
|
// This adds one.
|
1187
1176
|
if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};const ensureString=str=>typeof str==='string'?str:'';function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce((accum,frame)=>{const f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
|
1188
1177
|
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
|
1189
|
-
const getStacktrace=(error,errorFramesToSkip)=>{if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};const hasNecessaryFields=error=>(typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');const normaliseError=(maybeError,
|
1190
|
-
//
|
1191
|
-
// - the promise rejection handler (both in the browser and node)
|
1192
|
-
// - the node uncaughtException handler
|
1193
|
-
//
|
1194
|
-
// We are really limited in what we can do to get a stacktrace. So we use the
|
1195
|
-
// tolerateNonErrors option to ensure that the resulting error communicates as
|
1196
|
-
// such.
|
1197
|
-
if(!tolerateNonErrors){if(isError(maybeError)){error=maybeError;}else {error=createAndLogInputError(typeof maybeError);internalFrames+=2;}}else {switch(typeof maybeError){case'string':case'number':case'boolean':error=new Error(String(maybeError));internalFrames+=1;break;case'function':error=createAndLogInputError('function');internalFrames+=2;break;case'object':if(maybeError!==null&&isError(maybeError)){error=maybeError;}else if(maybeError!==null&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {error=createAndLogInputError(maybeError===null?'null':'unsupported object');internalFrames+=2;}break;default:error=createAndLogInputError('nothing');internalFrames+=2;}}if(!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1178
|
+
const getStacktrace=(error,errorFramesToSkip)=>{if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};const hasNecessaryFields=error=>(typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');const normaliseError=(maybeError,component,logger)=>{let error;let internalFrames=0;if(isError(maybeError)){error=maybeError;}else if(typeof maybeError==='object'&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {logger?.warn(`${ERROR_REPORTING_PLUGIN}:: ${component} received a non-error: ${stringifyWithoutCircular(error)}`);error=undefined;}if(error&&!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
|
1198
1179
|
try{throw error;}catch(e){if(hasStack(e)){error=e;// if the error only got a stacktrace after we threw it here, we know it
|
1199
|
-
// will only have one extra internal frame from this function
|
1200
|
-
|
1201
|
-
internalFrames=1;}}}return [error,internalFrames];};class ErrorFormat{constructor(errorClass,errorMessage,stacktrace){this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}static create(maybeError,tolerateNonErrors,handledState,component,errorFramesToSkip=0,logger){const[error,internalFrames]=normaliseError(maybeError,tolerateNonErrors,component,logger);let event;try{const stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1180
|
+
// will only have one extra internal frame from this function
|
1181
|
+
internalFrames=1;}}}return [error,internalFrames];};class ErrorFormat{constructor(errorClass,errorMessage,stacktrace){this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}static create(maybeError,tolerateNonErrors,handledState,component,errorFramesToSkip=0,logger){const[error,internalFrames]=normaliseError(maybeError,component,logger);if(!error){return undefined;}let event;try{const stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
|
1202
1182
|
// tell the getStacktrace() function to skip the number of frames we know will
|
1203
1183
|
// be from our own functions. This is added to the number of frames deep we
|
1204
1184
|
// were told about
|
@@ -1209,7 +1189,7 @@ const INVALID_SOURCE_CONFIG_ERROR=`Invalid source configuration or source id.`;
|
|
1209
1189
|
const pluginName$9='ErrorReporting';const ErrorReporting=()=>({name:pluginName$9,deps:[],initialize:state=>{state.plugins.loadedPlugins.value=[...state.plugins.loadedPlugins.value,pluginName$9];state.reporting.isErrorReportingPluginLoaded.value=true;if(state.reporting.breadcrumbs?.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
|
1210
1190
|
// TODO: Remove this in the next major release
|
1211
1191
|
init:(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore)=>{if(isInvokedFromLatestCore){return undefined;}if(!state.source.value?.config||!state.source.value?.id){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:(pluginEngine,client,error,state,logger,httpClient,errorState)=>{if(httpClient){const{component,tolerateNonErrors,errorFramesToSkip,normalizedError}=getConfigForPayloadCreation(error,errorState?.severityReason.type);// Generate the error payload
|
1212
|
-
const errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger)
|
1192
|
+
const errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger);if(!errorPayload||!isAllowedToBeNotified(errorPayload.errors[0])){return;}// filter errors
|
1213
1193
|
if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
|
1214
1194
|
const bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
|
1215
1195
|
httpClient?.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:(result,details)=>{// do nothing
|
@@ -2728,9 +2708,14 @@ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(err
|
|
2728
2708
|
*/const getUrlWithoutHash=url=>{let urlWithoutHash=url;try{const urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
|
2729
2709
|
}return urlWithoutHash;};
|
2730
2710
|
|
2711
|
+
/**
|
2712
|
+
* Determines if the SDK is running inside a chrome extension
|
2713
|
+
* @returns boolean
|
2714
|
+
*/const isSDKRunningInChromeExtension=()=>!!(window.chrome&&window.chrome.runtime&&window.chrome.runtime.id);
|
2715
|
+
|
2731
2716
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
2732
2717
|
|
2733
|
-
const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
2718
|
+
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
2734
2719
|
|
2735
2720
|
/**
|
2736
2721
|
* Validates and normalizes the consent options provided by the user
|
@@ -2764,10 +2749,7 @@ for(const script of scripts){const src=script.getAttribute('src');if(src&&sdkFil
|
|
2764
2749
|
* Updates the reporting state variables from the source config data
|
2765
2750
|
* @param res Source config
|
2766
2751
|
* @param logger Logger instance
|
2767
|
-
*/const updateReportingState=res=>{state.reporting.isErrorReportingEnabled.value=
|
2768
|
-
// state.reporting.isErrorReportingEnabled.value =
|
2769
|
-
// isErrorReportingEnabled(res.source.config) && !isSDKRunningInChromeExtension();
|
2770
|
-
state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};const updateStorageStateFromLoadOptions=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
2752
|
+
*/const updateReportingState=res=>{state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};const updateStorageStateFromLoadOptions=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
2771
2753
|
logger?.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
|
2772
2754
|
const configuredMigrationValue=storageOptsFromLoad?.migrate;const finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger?.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(()=>{state.storage.type.value=storageType;let cookieOptions=storageOptsFromLoad?.cookie??{};if(useServerSideCookies){state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;const providedCookieDomain=cookieOptions.domain??setCookieDomain;/**
|
2773
2755
|
* Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
|