posthog-react-native 4.81.1 → 4.81.2

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.
@@ -129,6 +129,7 @@ export declare class ErrorTracking {
129
129
  private resolveAutocaptureOptions;
130
130
  private resolveConsoleOptions;
131
131
  private autocaptureUncaughtErrors;
132
+ private markFatalExceptionHandled;
132
133
  private handleFatalException;
133
134
  private prepareFatalNativeCapture;
134
135
  private autocaptureUnhandledRejections;
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ErrorTracking=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _core=require("@posthog/core");var _utils=require("./utils");var _utils2=require("../utils");var _OptionalPlugin=require("../optional/OptionalPlugin");var _fatalPayload=require("./fatal-payload");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var LogLevelList=['debug','log','info','warn','error'];var ErrorTracking=exports.ErrorTracking=function(){function ErrorTracking(instance){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var logger=arguments.length>2?arguments[2]:undefined;var fatalCaptureHooks=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,ErrorTracking);this.instance=instance;this.fatalCaptureHooks=fatalCaptureHooks;this._nativeForwardingEnabled=false;this._autocaptureEnabled=true;this.logger=logger.createLogger('[ErrorTracking]');this.options=this.resolveOptions(options);var exceptionSteps=options.exceptionSteps;this._exceptionStepsConfig=_core.ErrorTracking.resolveExceptionStepsConfig(exceptionSteps?{enabled:exceptionSteps.enabled,max_bytes:exceptionSteps.maxBytes}:undefined);this._exceptionStepsBuffer=new _core.ErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig);this.autocapture(this.options.autocapture);}return(0,_createClass2["default"])(ErrorTracking,[{key:"getNativePluginExceptionStepsConfig",value:function getNativePluginExceptionStepsConfig(){return{enabled:this._exceptionStepsConfig.enabled,maxBytes:this._exceptionStepsConfig.max_bytes};}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){if(!this._exceptionStepsConfig.enabled){return;}try{if(!(0,_core.isString)(message)||message.trim().length===0){this.logger.warn('Ignoring exception step because message must be a non-empty string');return;}var userProperties=(0,_core.isObject)(properties)?_objectSpread({},properties):{};var _CoreErrorTracking$st=_core.ErrorTracking.stripReservedExceptionStepFields(userProperties),sanitizedProperties=_CoreErrorTracking$st.sanitizedProperties,droppedKeys=_CoreErrorTracking$st.droppedKeys;if(droppedKeys.length>0){this.logger.warn('Ignoring reserved exception step fields',{droppedKeys:droppedKeys});}this._exceptionStepsBuffer.add(_objectSpread((0,_defineProperty2["default"])((0,_defineProperty2["default"])({},_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,message),_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP,new Date().toISOString()),sanitizedProperties));this.forwardExceptionStepToNative(message,properties);}catch(error){this.logger.error('Failed to add exception step. Ignoring breadcrumb.',error);}}},{key:"onNativeErrorTrackingReady",value:function onNativeErrorTrackingReady(){this._nativeForwardingEnabled=true;var _iterator=_createForOfIteratorHelper(this.getAttachableExceptionSteps()),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var step=_step.value;this.forwardExceptionStepToNative(step.$message,step);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}},{key:"forwardExceptionStepToNative",value:function forwardExceptionStepToNative(message,properties){var _this=this;if(!this._nativeForwardingEnabled||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep)){return;}try{void Promise.resolve(_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep(message,properties))["catch"](function(e){_this.logger.warn("Failed to forward exception step to native: ".concat(e));});}catch(e){this.logger.warn("Failed to forward exception step to native: ".concat(e));}}},{key:"attachExceptionSteps",value:function attachExceptionSteps(properties){if(!this._exceptionStepsConfig.enabled||!(0,_core.isNullish)(properties.$exception_steps)){return properties;}var steps=this.getAttachableExceptionSteps();if(steps.length===0){return properties;}return _objectSpread(_objectSpread({},properties),{},{$exception_steps:steps});}},{key:"getAttachableExceptionSteps",value:function getAttachableExceptionSteps(){if(!this._exceptionStepsConfig.enabled){return[];}try{return this._exceptionStepsBuffer.getAttachable();}catch(error){this.logger.error('Failed to read buffered exception steps.',error);return[];}}},{key:"clearExceptionSteps",value:function clearExceptionSteps(){this._exceptionStepsBuffer.clear();}},{key:"shutdown",value:function shutdown(){var _a;this._autocaptureEnabled=false;(_a=this._unsubscribeUncaughtExceptions)===null||_a===void 0?void 0:_a.call(this);this._unsubscribeUncaughtExceptions=undefined;this.clearExceptionSteps();}},{key:"onRemoteConfig",value:function onRemoteConfig(errorTracking){if(errorTracking==null){return;}this._autocaptureEnabled=(0,_utils2.getRemoteConfigBool)(errorTracking,'autocaptureExceptions',false);this.logger.info("Error tracking autocapture ".concat(this._autocaptureEnabled?'enabled':'disabled'," by remote config."));}},{key:"isUncaughtExceptionAutocaptureEnabled",value:function isUncaughtExceptionAutocaptureEnabled(){return this.options.autocapture.uncaughtExceptions;}},{key:"resolveOptions",value:function resolveOptions(options){var autocaptureOptions=this.resolveAutocaptureOptions(options.autocapture);return{autocapture:autocaptureOptions};}},{key:"resolveAutocaptureOptions",value:function resolveAutocaptureOptions(){var autocapture=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof autocapture==='boolean'){return{uncaughtExceptions:autocapture,unhandledRejections:autocapture,console:[]};}return{uncaughtExceptions:!!autocapture.uncaughtExceptions,unhandledRejections:!!autocapture.unhandledRejections,console:this.resolveConsoleOptions(autocapture.console)};}},{key:"resolveConsoleOptions",value:function resolveConsoleOptions(){var console=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof console==='boolean'){return console?['error']:[];}return Array.isArray(console)?console.filter(function(level){return LogLevelList.includes(level);}):[];}},{key:"autocaptureUncaughtErrors",value:function autocaptureUncaughtErrors(){var _this2=this;var onUncaughtException=function onUncaughtException(error,isFatal){if(!_this2._autocaptureEnabled||(0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onuncaughtexception',handled:false}};if(!isFatal){_this2.instance.captureException(error,{},hint);return;}return _this2.handleFatalException(error,hint,(0,_core.uuidv7)(),new Date());};try{this._unsubscribeUncaughtExceptions=(0,_utils.trackUncaughtExceptions)(onUncaughtException);}catch(err){this.logger.warn('Failed to track uncaught exceptions: ',err);}}},{key:"handleFatalException",value:function(){var _handleFatalException=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(error,hint,eventUuid,timestamp){var _this3=this;var storageReady,result,_result,queued,nativeCapture,persisted,nativeWrite,_yield$Promise$all,_yield$Promise$all2,persistedOk,_t,_t2,_t3;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:storageReady=!this.fatalCaptureHooks;if(!this.fatalCaptureHooks){_context.next=4;break;}_context.prev=1;_context.next=2;return this.fatalCaptureHooks.waitForStorageReady();case 2:_t=_context.sent;storageReady=_t===true;_context.next=4;break;case 3:_context.prev=3;_t2=_context["catch"](1);this.logger.warn('Fatal capture skipped because events storage did not initialize.',_t2);case 4:if(!(!storageReady||!this._autocaptureEnabled||this.instance.isDisabled||this.instance.optedOut)){_context.next=5;break;}return _context.abrupt("return");case 5:if(this.fatalCaptureHooks){_context.next=6;break;}this.instance.captureException(error,{$exception_level:'fatal'},hint);return _context.abrupt("return");case 6:_context.prev=6;result=this.fatalCaptureHooks.captureFatalException(error,hint,eventUuid,timestamp,function(queued){return _this3.prepareFatalNativeCapture(queued);});_context.next=8;break;case 7:_context.prev=7;_t3=_context["catch"](6);this.logger.error('Fatal exception capture failed before enqueue.',_t3);return _context.abrupt("return");case 8:_result=result,queued=_result.queued,nativeCapture=_result.nativeCapture;if(!(!queued&&!nativeCapture)){_context.next=9;break;}return _context.abrupt("return");case 9:void this.instance.flush()["catch"](function(){_this3.logger.critical('Failed to flush events');});persisted=this.fatalCaptureHooks.waitForJSPersist();if(nativeCapture){try{nativeWrite=nativeCapture()["catch"](function(e){_this3.logger.warn("Fatal exception native capture failed: ".concat(e));});}catch(e){this.logger.warn("Fatal exception native capture failed: ".concat(e));}}_context.next=10;return Promise.all([persisted,nativeWrite]);case 10:_yield$Promise$all=_context.sent;_yield$Promise$all2=(0,_slicedToArray2["default"])(_yield$Promise$all,1);persistedOk=_yield$Promise$all2[0];if(!persistedOk&&!nativeCapture){this.logger.warn('Fatal exception JS persist failed and no native capture path was available.');}case 11:case"end":return _context.stop();}},_callee,this,[[1,3],[6,7]]);}));function handleFatalException(_x,_x2,_x3,_x4){return _handleFatalException.apply(this,arguments);}return handleFatalException;}()},{key:"prepareFatalNativeCapture",value:function prepareFatalNativeCapture(queuedEvent){var _a,_b;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.captureFatalException;if(!bridge){return undefined;}if(!((_a=this.fatalCaptureHooks)===null||_a===void 0?void 0:_a.isNativeCaptureReady())){return undefined;}if(((_b=this.fatalCaptureHooks)===null||_b===void 0?void 0:_b.getPersistenceMode())==='memory'){return undefined;}if(this.instance.isDisabled||this.instance.optedOut){return undefined;}var properties=(0,_core.isObject)(queuedEvent.properties)?queuedEvent.properties:{};var payload=(0,_fatalPayload.buildFatalExceptionPayload)({timestamp:(0,_core.isString)(queuedEvent.timestamp)?queuedEvent.timestamp:new Date().toISOString(),distinctId:(0,_core.isString)(queuedEvent.distinct_id)?queuedEvent.distinct_id:'',properties:properties});return function(){return bridge(payload.distinctId,payload.timestamp,payload.properties);};}},{key:"autocaptureUnhandledRejections",value:function autocaptureUnhandledRejections(){var _this4=this;var onUnhandledRejection=function onUnhandledRejection(error){if(!_this4._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onunhandledrejection',handled:false}};_this4.instance.captureException(error,{},hint);};try{(0,_utils.trackUnhandledRejections)(onUnhandledRejection);}catch(err){this.logger.warn('Failed to track unhandled rejections: ',err);}}},{key:"autocaptureConsole",value:function autocaptureConsole(levels){var _this5=this;var onConsole=function onConsole(level){return function(error,isFatal,syntheticException){if(!_this5._autocaptureEnabled){return;}var hint={mechanism:{type:'onconsole',handled:true},syntheticException:syntheticException};var additionalProperties={$exception_level:level};_this5.instance.captureException(error,additionalProperties,hint);};};try{var _iterator2=_createForOfIteratorHelper(levels),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var level=_step2.value;(0,_utils.trackConsole)(level,onConsole(level));}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}catch(err){this.logger.warn('Failed to track console errors: ',err);}}},{key:"autocapture",value:function autocapture(autocaptureOptions){if(autocaptureOptions.uncaughtExceptions===true){this.autocaptureUncaughtErrors();}if(autocaptureOptions.unhandledRejections===true){this.autocaptureUnhandledRejections();}if(autocaptureOptions.console.length>0){this.autocaptureConsole(autocaptureOptions.console);}}}]);}();
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ErrorTracking=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _core=require("@posthog/core");var _utils=require("./utils");var _utils2=require("../utils");var _OptionalPlugin=require("../optional/OptionalPlugin");var _fatalPayload=require("./fatal-payload");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var LogLevelList=['debug','log','info','warn','error'];var FATAL_MESSAGE_KEY_LENGTH=80;function fatalMessageKey(error){var message;if(error instanceof Error){var namePrefix=error.name?"".concat(error.name,": "):'';message=error.message||'';if(!message.startsWith(namePrefix)){message=namePrefix+message;}}else{message=error===undefined?'':String(error);}return Array.from(message).slice(0,FATAL_MESSAGE_KEY_LENGTH).join('');}var ErrorTracking=exports.ErrorTracking=function(){function ErrorTracking(instance){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var logger=arguments.length>2?arguments[2]:undefined;var fatalCaptureHooks=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,ErrorTracking);this.instance=instance;this.fatalCaptureHooks=fatalCaptureHooks;this._nativeForwardingEnabled=false;this._autocaptureEnabled=true;this.logger=logger.createLogger('[ErrorTracking]');this.options=this.resolveOptions(options);var exceptionSteps=options.exceptionSteps;this._exceptionStepsConfig=_core.ErrorTracking.resolveExceptionStepsConfig(exceptionSteps?{enabled:exceptionSteps.enabled,max_bytes:exceptionSteps.maxBytes}:undefined);this._exceptionStepsBuffer=new _core.ErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig);this.autocapture(this.options.autocapture);}return(0,_createClass2["default"])(ErrorTracking,[{key:"getNativePluginExceptionStepsConfig",value:function getNativePluginExceptionStepsConfig(){return{enabled:this._exceptionStepsConfig.enabled,maxBytes:this._exceptionStepsConfig.max_bytes};}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){if(!this._exceptionStepsConfig.enabled){return;}try{if(!(0,_core.isString)(message)||message.trim().length===0){this.logger.warn('Ignoring exception step because message must be a non-empty string');return;}var userProperties=(0,_core.isObject)(properties)?_objectSpread({},properties):{};var _CoreErrorTracking$st=_core.ErrorTracking.stripReservedExceptionStepFields(userProperties),sanitizedProperties=_CoreErrorTracking$st.sanitizedProperties,droppedKeys=_CoreErrorTracking$st.droppedKeys;if(droppedKeys.length>0){this.logger.warn('Ignoring reserved exception step fields',{droppedKeys:droppedKeys});}this._exceptionStepsBuffer.add(_objectSpread((0,_defineProperty2["default"])((0,_defineProperty2["default"])({},_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,message),_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP,new Date().toISOString()),sanitizedProperties));this.forwardExceptionStepToNative(message,properties);}catch(error){this.logger.error('Failed to add exception step. Ignoring breadcrumb.',error);}}},{key:"onNativeErrorTrackingReady",value:function onNativeErrorTrackingReady(){this._nativeForwardingEnabled=true;var _iterator=_createForOfIteratorHelper(this.getAttachableExceptionSteps()),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var step=_step.value;this.forwardExceptionStepToNative(step.$message,step);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}},{key:"forwardExceptionStepToNative",value:function forwardExceptionStepToNative(message,properties){var _this=this;if(!this._nativeForwardingEnabled||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep)){return;}try{void Promise.resolve(_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep(message,properties))["catch"](function(e){_this.logger.warn("Failed to forward exception step to native: ".concat(e));});}catch(e){this.logger.warn("Failed to forward exception step to native: ".concat(e));}}},{key:"attachExceptionSteps",value:function attachExceptionSteps(properties){if(!this._exceptionStepsConfig.enabled||!(0,_core.isNullish)(properties.$exception_steps)){return properties;}var steps=this.getAttachableExceptionSteps();if(steps.length===0){return properties;}return _objectSpread(_objectSpread({},properties),{},{$exception_steps:steps});}},{key:"getAttachableExceptionSteps",value:function getAttachableExceptionSteps(){if(!this._exceptionStepsConfig.enabled){return[];}try{return this._exceptionStepsBuffer.getAttachable();}catch(error){this.logger.error('Failed to read buffered exception steps.',error);return[];}}},{key:"clearExceptionSteps",value:function clearExceptionSteps(){this._exceptionStepsBuffer.clear();}},{key:"shutdown",value:function shutdown(){var _a;this._autocaptureEnabled=false;(_a=this._unsubscribeUncaughtExceptions)===null||_a===void 0?void 0:_a.call(this);this._unsubscribeUncaughtExceptions=undefined;this.clearExceptionSteps();}},{key:"onRemoteConfig",value:function onRemoteConfig(errorTracking){if(errorTracking==null){return;}this._autocaptureEnabled=(0,_utils2.getRemoteConfigBool)(errorTracking,'autocaptureExceptions',false);this.logger.info("Error tracking autocapture ".concat(this._autocaptureEnabled?'enabled':'disabled'," by remote config."));}},{key:"isUncaughtExceptionAutocaptureEnabled",value:function isUncaughtExceptionAutocaptureEnabled(){return this.options.autocapture.uncaughtExceptions;}},{key:"resolveOptions",value:function resolveOptions(options){var autocaptureOptions=this.resolveAutocaptureOptions(options.autocapture);return{autocapture:autocaptureOptions};}},{key:"resolveAutocaptureOptions",value:function resolveAutocaptureOptions(){var autocapture=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof autocapture==='boolean'){return{uncaughtExceptions:autocapture,unhandledRejections:autocapture,console:[]};}return{uncaughtExceptions:!!autocapture.uncaughtExceptions,unhandledRejections:!!autocapture.unhandledRejections,console:this.resolveConsoleOptions(autocapture.console)};}},{key:"resolveConsoleOptions",value:function resolveConsoleOptions(){var console=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof console==='boolean'){return console?['error']:[];}return Array.isArray(console)?console.filter(function(level){return LogLevelList.includes(level);}):[];}},{key:"autocaptureUncaughtErrors",value:function autocaptureUncaughtErrors(){var _this2=this;var onUncaughtException=function onUncaughtException(error,isFatal){var marked=isFatal?_this2.markFatalExceptionHandled(error):undefined;if(!_this2._autocaptureEnabled||(0,_core.isPostHogFetchNetworkError)(error)){return marked;}var hint={mechanism:{type:'onuncaughtexception',handled:false}};if(!isFatal){_this2.instance.captureException(error,{},hint);return;}return Promise.all([marked,_this2.handleFatalException(error,hint,(0,_core.uuidv7)(),new Date())]).then(function(){});};try{this._unsubscribeUncaughtExceptions=(0,_utils.trackUncaughtExceptions)(onUncaughtException);}catch(err){this.logger.warn('Failed to track uncaught exceptions: ',err);}}},{key:"markFatalExceptionHandled",value:function markFatalExceptionHandled(error){var _this3=this;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.markFatalExceptionHandled;if(!bridge){return undefined;}try{return Promise.resolve(bridge(fatalMessageKey(error)))["catch"](function(e){_this3.logger.warn("Failed to mark fatal exception as handled: ".concat(e));});}catch(e){this.logger.warn("Failed to mark fatal exception as handled: ".concat(e));return undefined;}}},{key:"handleFatalException",value:function(){var _handleFatalException=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(error,hint,eventUuid,timestamp){var _this4=this;var storageReady,result,_result,queued,nativeCapture,persisted,nativeWrite,_yield$Promise$all,_yield$Promise$all2,persistedOk,_t,_t2,_t3;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:storageReady=!this.fatalCaptureHooks;if(!this.fatalCaptureHooks){_context.next=4;break;}_context.prev=1;_context.next=2;return this.fatalCaptureHooks.waitForStorageReady();case 2:_t=_context.sent;storageReady=_t===true;_context.next=4;break;case 3:_context.prev=3;_t2=_context["catch"](1);this.logger.warn('Fatal capture skipped because events storage did not initialize.',_t2);case 4:if(!(!storageReady||!this._autocaptureEnabled||this.instance.isDisabled||this.instance.optedOut)){_context.next=5;break;}return _context.abrupt("return");case 5:if(this.fatalCaptureHooks){_context.next=6;break;}this.instance.captureException(error,{$exception_level:'fatal'},hint);return _context.abrupt("return");case 6:_context.prev=6;result=this.fatalCaptureHooks.captureFatalException(error,hint,eventUuid,timestamp,function(queued){return _this4.prepareFatalNativeCapture(queued);});_context.next=8;break;case 7:_context.prev=7;_t3=_context["catch"](6);this.logger.error('Fatal exception capture failed before enqueue.',_t3);return _context.abrupt("return");case 8:_result=result,queued=_result.queued,nativeCapture=_result.nativeCapture;if(!(!queued&&!nativeCapture)){_context.next=9;break;}return _context.abrupt("return");case 9:void this.instance.flush()["catch"](function(){_this4.logger.critical('Failed to flush events');});persisted=this.fatalCaptureHooks.waitForJSPersist();if(nativeCapture){try{nativeWrite=nativeCapture()["catch"](function(e){_this4.logger.warn("Fatal exception native capture failed: ".concat(e));});}catch(e){this.logger.warn("Fatal exception native capture failed: ".concat(e));}}_context.next=10;return Promise.all([persisted,nativeWrite]);case 10:_yield$Promise$all=_context.sent;_yield$Promise$all2=(0,_slicedToArray2["default"])(_yield$Promise$all,1);persistedOk=_yield$Promise$all2[0];if(!persistedOk&&!nativeCapture){this.logger.warn('Fatal exception JS persist failed and no native capture path was available.');}case 11:case"end":return _context.stop();}},_callee,this,[[1,3],[6,7]]);}));function handleFatalException(_x,_x2,_x3,_x4){return _handleFatalException.apply(this,arguments);}return handleFatalException;}()},{key:"prepareFatalNativeCapture",value:function prepareFatalNativeCapture(queuedEvent){var _a,_b;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.captureFatalException;if(!bridge){return undefined;}if(!((_a=this.fatalCaptureHooks)===null||_a===void 0?void 0:_a.isNativeCaptureReady())){return undefined;}if(((_b=this.fatalCaptureHooks)===null||_b===void 0?void 0:_b.getPersistenceMode())==='memory'){return undefined;}if(this.instance.isDisabled||this.instance.optedOut){return undefined;}var properties=(0,_core.isObject)(queuedEvent.properties)?queuedEvent.properties:{};var payload=(0,_fatalPayload.buildFatalExceptionPayload)({timestamp:(0,_core.isString)(queuedEvent.timestamp)?queuedEvent.timestamp:new Date().toISOString(),distinctId:(0,_core.isString)(queuedEvent.distinct_id)?queuedEvent.distinct_id:'',properties:properties});return function(){return bridge(payload.distinctId,payload.timestamp,payload.properties);};}},{key:"autocaptureUnhandledRejections",value:function autocaptureUnhandledRejections(){var _this5=this;var onUnhandledRejection=function onUnhandledRejection(error){if(!_this5._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onunhandledrejection',handled:false}};_this5.instance.captureException(error,{},hint);};try{(0,_utils.trackUnhandledRejections)(onUnhandledRejection);}catch(err){this.logger.warn('Failed to track unhandled rejections: ',err);}}},{key:"autocaptureConsole",value:function autocaptureConsole(levels){var _this6=this;var onConsole=function onConsole(level){return function(error,isFatal,syntheticException){if(!_this6._autocaptureEnabled){return;}var hint={mechanism:{type:'onconsole',handled:true},syntheticException:syntheticException};var additionalProperties={$exception_level:level};_this6.instance.captureException(error,additionalProperties,hint);};};try{var _iterator2=_createForOfIteratorHelper(levels),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var level=_step2.value;(0,_utils.trackConsole)(level,onConsole(level));}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}catch(err){this.logger.warn('Failed to track console errors: ',err);}}},{key:"autocapture",value:function autocapture(autocaptureOptions){if(autocaptureOptions.uncaughtExceptions===true){this.autocaptureUncaughtErrors();}if(autocaptureOptions.unhandledRejections===true){this.autocaptureUnhandledRejections();}if(autocaptureOptions.console.length>0){this.autocaptureConsole(autocaptureOptions.console);}}}]);}();
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_core","require","_utils","_utils2","_OptionalPlugin","_fatalPayload","_createForOfIteratorHelper","r","e","t","Symbol","iterator","Array","isArray","_unsupportedIterableToArray","length","_n","F","s","n","done","value","f","TypeError","o","a","u","call","next","_arrayLikeToArray","toString","slice","constructor","name","from","test","ownKeys","Object","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","LogLevelList","ErrorTracking","exports","instance","options","undefined","logger","fatalCaptureHooks","_classCallCheck2","_nativeForwardingEnabled","_autocaptureEnabled","createLogger","resolveOptions","exceptionSteps","_exceptionStepsConfig","CoreErrorTracking","resolveExceptionStepsConfig","enabled","max_bytes","maxBytes","_exceptionStepsBuffer","ExceptionStepsBuffer","autocapture","_createClass2","key","getNativePluginExceptionStepsConfig","addExceptionStep","message","properties","isString","trim","warn","userProperties","isObject","_CoreErrorTracking$st","stripReservedExceptionStepFields","sanitizedProperties","droppedKeys","add","EXCEPTION_STEP_INTERNAL_FIELDS","MESSAGE","TIMESTAMP","Date","toISOString","forwardExceptionStepToNative","error","onNativeErrorTrackingReady","_iterator","getAttachableExceptionSteps","_step","step","$message","err","_this","OptionalReactNativePlugin","Promise","resolve","concat","attachExceptionSteps","isNullish","$exception_steps","steps","getAttachable","clearExceptionSteps","clear","shutdown","_a","_unsubscribeUncaughtExceptions","onRemoteConfig","errorTracking","getRemoteConfigBool","info","isUncaughtExceptionAutocaptureEnabled","uncaughtExceptions","autocaptureOptions","resolveAutocaptureOptions","unhandledRejections","console","resolveConsoleOptions","level","includes","autocaptureUncaughtErrors","_this2","onUncaughtException","isFatal","isPostHogFetchNetworkError","hint","mechanism","type","handled","captureException","handleFatalException","uuidv7","trackUncaughtExceptions","_handleFatalException","_asyncToGenerator2","_regenerator","mark","_callee","eventUuid","timestamp","_this3","storageReady","result","_result","queued","nativeCapture","persisted","nativeWrite","_yield$Promise$all","_yield$Promise$all2","persistedOk","_t","_t2","_t3","wrap","_context","prev","waitForStorageReady","sent","isDisabled","optedOut","abrupt","$exception_level","captureFatalException","prepareFatalNativeCapture","flush","critical","waitForJSPersist","all","_slicedToArray2","stop","_x","_x2","_x3","_x4","queuedEvent","bridge","isNativeCaptureReady","_b","getPersistenceMode","payload","buildFatalExceptionPayload","distinctId","distinct_id","autocaptureUnhandledRejections","_this4","onUnhandledRejection","trackUnhandledRejections","autocaptureConsole","levels","_this5","onConsole","syntheticException","additionalProperties","_iterator2","_step2","trackConsole"],"sources":["../../src/error-tracking/index.ts"],"sourcesContent":["import type { PostHog } from '../posthog-rn'\nimport {\n JsonType,\n Logger,\n ErrorTracking as CoreErrorTracking,\n isPostHogFetchNetworkError,\n isNullish,\n isObject,\n isString,\n PostHogEventProperties,\n uuidv7,\n} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport { trackConsole, trackUncaughtExceptions, trackUnhandledRejections } from './utils'\nimport { getRemoteConfigBool } from '../utils'\nimport { OptionalReactNativePlugin } from '../optional/OptionalPlugin'\nimport { buildFatalExceptionPayload } from './fatal-payload'\n\ntype LogLevel = 'debug' | 'log' | 'info' | 'warn' | 'error'\n\nconst LogLevelList: LogLevel[] = ['debug', 'log', 'info', 'warn', 'error']\n\n// user provided configuration\ninterface AutocaptureOptions {\n uncaughtExceptions?: boolean\n unhandledRejections?: boolean\n console?: boolean | LogLevel[]\n /**\n * Enables native iOS/Android/macOS crash autocapture through the optional native plugin.\n * On Android this covers Java/Kotlin crashes; native C/C++ (NDK) crashes are enabled with\n * `androidNdkCrashes`. On Apple platforms it covers signal crashes too.\n * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: boolean\n /**\n * Enables autocapture of native C/C++ (NDK) crashes on Android, through the optional native\n * plugin. Requires Android 12 (API 31) or later and exception autocapture enabled in the\n * project's error tracking settings.\n *\n * An NDK crash kills the process immediately, so it is captured on the next app launch from\n * the records the OS kept, which means properties such as `$app_version` and the identity\n * describe that launch rather than the crash. The first launch after enabling this also\n * captures the native crashes the OS still holds from before.\n *\n * For readable stack traces, upload the app's `.so` debug symbols. With Expo, set `uploadNativeSymbols`\n * on the `posthog-react-native/expo` config plugin: https://posthog.com/docs/error-tracking/upload-source-maps/react-native#native-crash-symbolication\n *\n * Ignored on other platforms. Disabled by default. Requires `@posthog/react-native-plugin` 2.12.0 or newer.\n */\n androidNdkCrashes?: boolean\n}\n\n/**\n * Controls the breadcrumb-style exception steps recorded via `addExceptionStep` and attached\n * to captured exceptions as `$exception_steps`.\n */\nexport interface ExceptionStepsOptions {\n /**\n * Whether exception steps are recorded and attached.\n * @default true\n */\n enabled?: boolean\n /**\n * Total UTF-8 byte budget (~32KB) for the in-memory buffer. Oldest steps are evicted first when exceeded.\n * @default 32768\n */\n maxBytes?: number\n}\n\nexport interface ErrorTrackingOptions {\n autocapture?: AutocaptureOptions | boolean\n exceptionSteps?: ExceptionStepsOptions\n}\n\n// resolved configuration\ninterface ResolvedAutocaptureOptions {\n uncaughtExceptions: boolean\n unhandledRejections: boolean\n console: LogLevel[]\n}\n\ninterface ResolvedErrorTrackingOptions {\n autocapture: ResolvedAutocaptureOptions\n}\n\n// Hooks supplied by PostHogRN for coordinating the fatal capture with its event storage.\n// Storage readiness is explicit so unknown persisted consent fails closed rather than being\n// mistaken for the in-memory default.\ninterface FatalCaptureHooks {\n // `prepareNativeCapture` is offered the final, before_send-accepted message at the moment\n // it would be enqueued. Returning a thunk transfers ownership of the exception to the\n // native SDK and the JS queue copy is dropped; returning undefined leaves the event in the\n // JS queue as usual. The choice has to be made there, in one step, so a payload that fails\n // to build cannot leave the exception dropped from both queues.\n captureFatalException: (\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n ) => { queued: boolean; nativeCapture?: () => Promise<void> }\n waitForJSPersist: () => Promise<boolean>\n waitForStorageReady: () => Promise<boolean>\n getPersistenceMode: () => 'memory' | 'file' | undefined\n // Both native SDKs silently no-op a capture before setup() has run. Native init is async\n // and happens after the storage preload, so an early-startup crash can arrive first —\n // exactly the crashes this path exists for. Ownership only transfers once native is up.\n isNativeCaptureReady: () => boolean\n}\n\nexport class ErrorTracking {\n private logger: Logger\n private options: ResolvedErrorTrackingOptions\n private _exceptionStepsConfig: CoreErrorTracking.ResolvedExceptionStepsConfig\n private _exceptionStepsBuffer: CoreErrorTracking.ExceptionStepsBuffer\n private _nativeForwardingEnabled: boolean = false\n private _unsubscribeUncaughtExceptions?: () => void\n\n /**\n * Controls whether autocaptured exceptions are actually sent.\n * When remote config disables error tracking, this is set to false\n * so that installed handlers become no-ops.\n * Defaults to true (don't block locally enabled capture before remote config loads).\n */\n private _autocaptureEnabled: boolean = true\n\n constructor(\n private instance: PostHog,\n options: ErrorTrackingOptions = {},\n logger: Logger,\n private readonly fatalCaptureHooks?: FatalCaptureHooks\n ) {\n this.logger = logger.createLogger('[ErrorTracking]')\n this.options = this.resolveOptions(options)\n const exceptionSteps = options.exceptionSteps\n this._exceptionStepsConfig = CoreErrorTracking.resolveExceptionStepsConfig(\n exceptionSteps ? { enabled: exceptionSteps.enabled, max_bytes: exceptionSteps.maxBytes } : undefined\n )\n this._exceptionStepsBuffer = new CoreErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig)\n this.autocapture(this.options.autocapture)\n }\n\n /**\n * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one\n * logical buffer with the same byte budget and enabled state.\n */\n getNativePluginExceptionStepsConfig(): ExceptionStepsOptions {\n return { enabled: this._exceptionStepsConfig.enabled, maxBytes: this._exceptionStepsConfig.max_bytes }\n }\n\n /**\n * Records a breadcrumb-style exception step in the instance buffer and mirrors it to the embedded\n * native SDK. The `$timestamp` is captured at call time. Invalid messages are ignored with a\n * warning and never throw. The step only reaches native when it was actually buffered.\n */\n addExceptionStep(message: string, properties?: Properties): void {\n if (!this._exceptionStepsConfig.enabled) {\n return\n }\n\n try {\n if (!isString(message) || message.trim().length === 0) {\n this.logger.warn('Ignoring exception step because message must be a non-empty string')\n return\n }\n\n const userProperties = isObject(properties) ? { ...properties } : {}\n const { sanitizedProperties, droppedKeys } = CoreErrorTracking.stripReservedExceptionStepFields(userProperties)\n\n if (droppedKeys.length > 0) {\n this.logger.warn('Ignoring reserved exception step fields', { droppedKeys })\n }\n\n this._exceptionStepsBuffer.add({\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE]: message,\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP]: new Date().toISOString(),\n ...sanitizedProperties,\n })\n this.forwardExceptionStepToNative(message, properties)\n } catch (error) {\n this.logger.error('Failed to add exception step. Ignoring breadcrumb.', error)\n }\n }\n\n /**\n * Native error tracking initializes asynchronously, so steps recorded before then are buffered\n * only in JS. The host calls this once native is ready to enable forwarding and replay the buffer,\n * so a native crash shortly after startup carries the steps recorded before native was ready.\n */\n onNativeErrorTrackingReady(): void {\n this._nativeForwardingEnabled = true\n for (const step of this.getAttachableExceptionSteps()) {\n this.forwardExceptionStepToNative(step.$message, step as Properties)\n }\n }\n\n private forwardExceptionStepToNative(message: string, properties?: Properties): void {\n if (!this._nativeForwardingEnabled || !OptionalReactNativePlugin?.addExceptionStep) {\n return\n }\n try {\n // Fire-and-forget: the native layer validates and buffers independently and must never block.\n void Promise.resolve(OptionalReactNativePlugin.addExceptionStep(message, properties)).catch((e) => {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n }\n }\n\n /**\n * Returns `properties` with a snapshot of the buffered steps attached as `$exception_steps`,\n * unless the feature is disabled, the caller already provided that key, or the buffer is empty.\n * The buffer is left intact so subsequent exceptions read the same steps.\n */\n attachExceptionSteps(properties: PostHogEventProperties): PostHogEventProperties {\n if (!this._exceptionStepsConfig.enabled || !isNullish(properties.$exception_steps)) {\n return properties\n }\n const steps = this.getAttachableExceptionSteps()\n if (steps.length === 0) {\n return properties\n }\n // Steps are already normalized to their JSON-safe wire form by the buffer.\n return { ...properties, $exception_steps: steps as unknown as JsonType }\n }\n\n /**\n * Snapshot of the buffered steps (oldest first), or an empty array when disabled or empty.\n */\n getAttachableExceptionSteps(): CoreErrorTracking.ExceptionStep[] {\n if (!this._exceptionStepsConfig.enabled) {\n return []\n }\n try {\n return this._exceptionStepsBuffer.getAttachable()\n } catch (error) {\n this.logger.error('Failed to read buffered exception steps.', error)\n return []\n }\n }\n\n /**\n * Clears the buffer. Called on SDK close, not on capture or identity changes.\n */\n clearExceptionSteps(): void {\n this._exceptionStepsBuffer.clear()\n }\n\n shutdown(): void {\n this._autocaptureEnabled = false\n this._unsubscribeUncaughtExceptions?.()\n this._unsubscribeUncaughtExceptions = undefined\n this.clearExceptionSteps()\n }\n\n /**\n * Called when remote config is loaded.\n * If errorTracking.autocaptureExceptions is explicitly false, autocapture is disabled.\n * If it's true or undefined (not yet loaded / not present), autocapture follows local config.\n */\n onRemoteConfig(errorTracking: boolean | { [key: string]: JsonType } | undefined): void {\n if (errorTracking == null) {\n // Remote config doesn't include errorTracking — don't change anything\n return\n }\n\n // Default to false: if remote config is present but the key is missing, disable autocapture\n this._autocaptureEnabled = getRemoteConfigBool(errorTracking, 'autocaptureExceptions', false)\n\n this.logger.info(\n `Error tracking autocapture ${this._autocaptureEnabled ? 'enabled' : 'disabled'} by remote config.`\n )\n }\n\n /**\n * Whether the app asked for fatal JavaScript exceptions to be autocaptured. This is the\n * locally configured value, deliberately not gated on the remote kill-switch: it decides\n * whether the native SDK is worth initializing, and that happens before remote config has\n * been fetched.\n */\n isUncaughtExceptionAutocaptureEnabled(): boolean {\n return this.options.autocapture.uncaughtExceptions\n }\n\n private resolveOptions(options: ErrorTrackingOptions): ResolvedErrorTrackingOptions {\n const autocaptureOptions = this.resolveAutocaptureOptions(options.autocapture)\n return {\n autocapture: autocaptureOptions,\n }\n }\n\n private resolveAutocaptureOptions(autocapture: AutocaptureOptions | boolean = false): ResolvedAutocaptureOptions {\n if (typeof autocapture === 'boolean') {\n return {\n uncaughtExceptions: autocapture,\n unhandledRejections: autocapture,\n console: [],\n }\n }\n return {\n uncaughtExceptions: !!autocapture.uncaughtExceptions,\n unhandledRejections: !!autocapture.unhandledRejections,\n console: this.resolveConsoleOptions(autocapture.console),\n }\n }\n\n private resolveConsoleOptions(console: boolean | LogLevel[] = false): LogLevel[] {\n if (typeof console === 'boolean') {\n return console ? ['error'] : []\n }\n return Array.isArray(console) ? console.filter((level) => LogLevelList.includes(level)) : []\n }\n\n private autocaptureUncaughtErrors() {\n const onUncaughtException = (error: unknown, isFatal: boolean): void | Promise<void> => {\n if (!this._autocaptureEnabled || isPostHogFetchNetworkError(error)) {\n return\n }\n const hint: CoreErrorTracking.EventHint = {\n mechanism: { type: 'onuncaughtexception', handled: false },\n }\n if (!isFatal) {\n this.instance.captureException(error, {}, hint)\n return\n }\n return this.handleFatalException(error, hint, uuidv7(), new Date())\n }\n try {\n this._unsubscribeUncaughtExceptions = trackUncaughtExceptions(onUncaughtException)\n } catch (err) {\n this.logger.warn('Failed to track uncaught exceptions: ', err)\n }\n }\n\n private async handleFatalException(\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date\n ): Promise<void> {\n let storageReady = !this.fatalCaptureHooks\n if (this.fatalCaptureHooks) {\n try {\n storageReady = (await this.fatalCaptureHooks.waitForStorageReady()) === true\n } catch (e) {\n this.logger.warn('Fatal capture skipped because events storage did not initialize.', e)\n }\n }\n // Unknown consent must fail closed. A crash is less important than persisting data\n // for a user whose opt-out state could not be loaded.\n if (!storageReady || !this._autocaptureEnabled || this.instance.isDisabled || this.instance.optedOut) {\n return\n }\n\n if (!this.fatalCaptureHooks) {\n this.instance.captureException(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint)\n return\n }\n\n // Hand the final payload to the native SDK. Both native SDKs recognise a `$exception`\n // with `$exception_level: 'fatal'` and write it to their own disk queue synchronously\n // before returning, which is the durability the JS queue cannot promise while\n // AsyncStorage is still draining. Native owns delivery from there, including retry\n // across the relaunch, so there is nothing for the next launch to recover — and the JS\n // queue copy is dropped so the exception is not sent twice.\n let result: { queued: boolean; nativeCapture?: () => Promise<void> }\n try {\n result = this.fatalCaptureHooks.captureFatalException(error, hint, eventUuid, timestamp, (queued) =>\n this.prepareFatalNativeCapture(queued)\n )\n } catch (e) {\n // Without the final queued event we cannot know whether before_send accepted or\n // redacted the exception, so sending a raw fallback would bypass filtering.\n this.logger.error('Fatal exception capture failed before enqueue.', e)\n return\n }\n const { queued, nativeCapture } = result\n if (!queued && !nativeCapture) {\n // before_send dropped it.\n return\n }\n\n void this.instance.flush().catch(() => {\n this.logger.critical('Failed to flush events')\n })\n // Other events may still be queued behind this one, so the JS store is still worth\n // draining even when native owns the exception itself.\n const persisted = this.fatalCaptureHooks.waitForJSPersist()\n let nativeWrite: Promise<void> | undefined\n if (nativeCapture) {\n try {\n nativeWrite = nativeCapture().catch((e) => {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n }\n }\n const [persistedOk] = await Promise.all([persisted, nativeWrite])\n if (!persistedOk && !nativeCapture) {\n this.logger.warn('Fatal exception JS persist failed and no native capture path was available.')\n }\n }\n\n private prepareFatalNativeCapture(queuedEvent: PostHogEventProperties): (() => Promise<void>) | undefined {\n const bridge = OptionalReactNativePlugin?.captureFatalException\n if (!bridge) {\n return undefined\n }\n // Handing the event to a native SDK that is not set up yet would drop it: native\n // no-ops the capture, and the JS queue copy has already been given up.\n if (!this.fatalCaptureHooks?.isNativeCaptureReady()) {\n return undefined\n }\n // Memory-persistence apps asked for nothing on disk. The native queue is disk-backed,\n // so honour that here rather than routing around it.\n if (this.fatalCaptureHooks?.getPersistenceMode() === 'memory') {\n return undefined\n }\n if (this.instance.isDisabled || this.instance.optedOut) {\n return undefined\n }\n\n const properties = isObject(queuedEvent.properties) ? (queuedEvent.properties as PostHogEventProperties) : {}\n const payload = buildFatalExceptionPayload({\n timestamp: isString(queuedEvent.timestamp) ? queuedEvent.timestamp : new Date().toISOString(),\n distinctId: isString(queuedEvent.distinct_id) ? queuedEvent.distinct_id : '',\n // The event was normalized and emitted only after before_send accepted it.\n properties,\n })\n return () => bridge(payload.distinctId, payload.timestamp, payload.properties)\n }\n\n private autocaptureUnhandledRejections() {\n const onUnhandledRejection = (error: unknown) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n // Offline/timeout failures are expected, not application errors.\n if (isPostHogFetchNetworkError(error)) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false,\n },\n }\n this.instance.captureException(error, {}, hint)\n }\n\n try {\n trackUnhandledRejections(onUnhandledRejection)\n } catch (err) {\n this.logger.warn('Failed to track unhandled rejections: ', err)\n }\n }\n\n private autocaptureConsole(levels: LogLevel[]) {\n const onConsole = (level: LogLevel) => (error: unknown, isFatal: boolean, syntheticException?: Error) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onconsole',\n handled: true,\n },\n syntheticException,\n }\n const additionalProperties = {\n $exception_level: level as CoreErrorTracking.SeverityLevel,\n }\n this.instance.captureException(error, additionalProperties, hint)\n }\n\n try {\n for (const level of levels) {\n trackConsole(level, onConsole(level))\n }\n } catch (err) {\n this.logger.warn('Failed to track console errors: ', err)\n }\n }\n\n private autocapture(autocaptureOptions: ResolvedAutocaptureOptions) {\n if (autocaptureOptions.uncaughtExceptions === true) {\n this.autocaptureUncaughtErrors()\n }\n if (autocaptureOptions.unhandledRejections === true) {\n this.autocaptureUnhandledRejections()\n }\n if (autocaptureOptions.console.length > 0) {\n this.autocaptureConsole(autocaptureOptions.console)\n }\n }\n}\n"],"mappings":"utBACA,IAAAA,KAAA,CAAAC,OAAA,kBAYA,IAAAC,MAAA,CAAAD,OAAA,YACA,IAAAE,OAAA,CAAAF,OAAA,aACA,IAAAG,eAAA,CAAAH,OAAA,+BACA,IAAAI,aAAA,CAAAJ,OAAA,oBAA4D,SAAAK,2BAAAC,CAAA,CAAAC,CAAA,MAAAC,CAAA,qBAAAC,MAAA,EAAAH,CAAA,CAAAG,MAAA,CAAAC,QAAA,GAAAJ,CAAA,mBAAAE,CAAA,KAAAG,KAAA,CAAAC,OAAA,CAAAN,CAAA,IAAAE,CAAA,CAAAK,2BAAA,CAAAP,CAAA,IAAAC,CAAA,EAAAD,CAAA,mBAAAA,CAAA,CAAAQ,MAAA,EAAAN,CAAA,GAAAF,CAAA,CAAAE,CAAA,MAAAO,EAAA,GAAAC,CAAA,UAAAA,EAAA,WAAAC,CAAA,CAAAD,CAAA,CAAAE,CAAA,UAAAA,EAAA,SAAAH,EAAA,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AAI,CAACqE,8BAA8B,EAAE,CACvC,CACA,GAAIvE,kBAAkB,CAACG,OAAO,CAAClH,MAAM,CAAG,CAAC,CAAE,CACzC,IAAI,CAAC0L,kBAAkB,CAAC3E,kBAAkB,CAACG,OAAO,CAAC,CACrD,CACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_core","require","_utils","_utils2","_OptionalPlugin","_fatalPayload","_createForOfIteratorHelper","r","e","t","Symbol","iterator","Array","isArray","_unsupportedIterableToArray","length","_n","F","s","n","done","value","f","TypeError","o","a","u","call","next","_arrayLikeToArray","toString","slice","constructor","name","from","test","ownKeys","Object","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","LogLevelList","FATAL_MESSAGE_KEY_LENGTH","fatalMessageKey","error","message","Error","namePrefix","concat","startsWith","undefined","String","join","ErrorTracking","exports","instance","options","logger","fatalCaptureHooks","_classCallCheck2","_nativeForwardingEnabled","_autocaptureEnabled","createLogger","resolveOptions","exceptionSteps","_exceptionStepsConfig","CoreErrorTracking","resolveExceptionStepsConfig","enabled","max_bytes","maxBytes","_exceptionStepsBuffer","ExceptionStepsBuffer","autocapture","_createClass2","key","getNativePluginExceptionStepsConfig","addExceptionStep","properties","isString","trim","warn","userProperties","isObject","_CoreErrorTracking$st","stripReservedExceptionStepFields","sanitizedProperties","droppedKeys","add","EXCEPTION_STEP_INTERNAL_FIELDS","MESSAGE","TIMESTAMP","Date","toISOString","forwardExceptionStepToNative","onNativeErrorTrackingReady","_iterator","getAttachableExceptionSteps","_step","step","$message","err","_this","OptionalReactNativePlugin","Promise","resolve","attachExceptionSteps","isNullish","$exception_steps","steps","getAttachable","clearExceptionSteps","clear","shutdown","_a","_unsubscribeUncaughtExceptions","onRemoteConfig","errorTracking","getRemoteConfigBool","info","isUncaughtExceptionAutocaptureEnabled","uncaughtExceptions","autocaptureOptions","resolveAutocaptureOptions","unhandledRejections","console","resolveConsoleOptions","level","includes","autocaptureUncaughtErrors","_this2","onUncaughtException","isFatal","marked","markFatalExceptionHandled","isPostHogFetchNetworkError","hint","mechanism","type","handled","captureException","all","handleFatalException","uuidv7","then","trackUncaughtExceptions","_this3","bridge","_handleFatalException","_asyncToGenerator2","_regenerator","mark","_callee","eventUuid","timestamp","_this4","storageReady","result","_result","queued","nativeCapture","persisted","nativeWrite","_yield$Promise$all","_yield$Promise$all2","persistedOk","_t","_t2","_t3","wrap","_context","prev","waitForStorageReady","sent","isDisabled","optedOut","abrupt","$exception_level","captureFatalException","prepareFatalNativeCapture","flush","critical","waitForJSPersist","_slicedToArray2","stop","_x","_x2","_x3","_x4","queuedEvent","isNativeCaptureReady","_b","getPersistenceMode","payload","buildFatalExceptionPayload","distinctId","distinct_id","autocaptureUnhandledRejections","_this5","onUnhandledRejection","trackUnhandledRejections","autocaptureConsole","levels","_this6","onConsole","syntheticException","additionalProperties","_iterator2","_step2","trackConsole"],"sources":["../../src/error-tracking/index.ts"],"sourcesContent":["import type { PostHog } from '../posthog-rn'\nimport {\n JsonType,\n Logger,\n ErrorTracking as CoreErrorTracking,\n isPostHogFetchNetworkError,\n isNullish,\n isObject,\n isString,\n PostHogEventProperties,\n uuidv7,\n} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport { trackConsole, trackUncaughtExceptions, trackUnhandledRejections } from './utils'\nimport { getRemoteConfigBool } from '../utils'\nimport { OptionalReactNativePlugin } from '../optional/OptionalPlugin'\nimport { buildFatalExceptionPayload } from './fatal-payload'\n\ntype LogLevel = 'debug' | 'log' | 'info' | 'warn' | 'error'\n\nconst LogLevelList: LogLevel[] = ['debug', 'log', 'info', 'warn', 'error']\n\n// Native crash reports truncate the JS message (iOS keeps 175 characters, including its own\n// prefix), so the start of the message is what both sides reliably share.\nconst FATAL_MESSAGE_KEY_LENGTH = 80\n\n// The start of the message React Native's ExceptionsManager sends native for this error:\n// `<name>: <message>`, where a thrown non-Error has no name and is converted to a string.\nfunction fatalMessageKey(error: unknown): string {\n let message: string\n if (error instanceof Error) {\n const namePrefix = error.name ? `${error.name}: ` : ''\n message = error.message || ''\n if (!message.startsWith(namePrefix)) {\n message = namePrefix + message\n }\n } else {\n message = error === undefined ? '' : String(error)\n }\n return Array.from(message).slice(0, FATAL_MESSAGE_KEY_LENGTH).join('')\n}\n\n// user provided configuration\ninterface AutocaptureOptions {\n uncaughtExceptions?: boolean\n unhandledRejections?: boolean\n console?: boolean | LogLevel[]\n /**\n * Enables native iOS/Android/macOS crash autocapture through the optional native plugin.\n * On Android this covers Java/Kotlin crashes; native C/C++ (NDK) crashes are enabled with\n * `androidNdkCrashes`. On Apple platforms it covers signal crashes too.\n * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: boolean\n /**\n * Enables autocapture of native C/C++ (NDK) crashes on Android, through the optional native\n * plugin. Requires Android 12 (API 31) or later and exception autocapture enabled in the\n * project's error tracking settings.\n *\n * An NDK crash kills the process immediately, so it is captured on the next app launch from\n * the records the OS kept, which means properties such as `$app_version` and the identity\n * describe that launch rather than the crash. The first launch after enabling this also\n * captures the native crashes the OS still holds from before.\n *\n * For readable stack traces, upload the app's `.so` debug symbols. With Expo, set `uploadNativeSymbols`\n * on the `posthog-react-native/expo` config plugin: https://posthog.com/docs/error-tracking/upload-source-maps/react-native#native-crash-symbolication\n *\n * Ignored on other platforms. Disabled by default. Requires `@posthog/react-native-plugin` 2.12.0 or newer.\n */\n androidNdkCrashes?: boolean\n}\n\n/**\n * Controls the breadcrumb-style exception steps recorded via `addExceptionStep` and attached\n * to captured exceptions as `$exception_steps`.\n */\nexport interface ExceptionStepsOptions {\n /**\n * Whether exception steps are recorded and attached.\n * @default true\n */\n enabled?: boolean\n /**\n * Total UTF-8 byte budget (~32KB) for the in-memory buffer. Oldest steps are evicted first when exceeded.\n * @default 32768\n */\n maxBytes?: number\n}\n\nexport interface ErrorTrackingOptions {\n autocapture?: AutocaptureOptions | boolean\n exceptionSteps?: ExceptionStepsOptions\n}\n\n// resolved configuration\ninterface ResolvedAutocaptureOptions {\n uncaughtExceptions: boolean\n unhandledRejections: boolean\n console: LogLevel[]\n}\n\ninterface ResolvedErrorTrackingOptions {\n autocapture: ResolvedAutocaptureOptions\n}\n\n// Hooks supplied by PostHogRN for coordinating the fatal capture with its event storage.\n// Storage readiness is explicit so unknown persisted consent fails closed rather than being\n// mistaken for the in-memory default.\ninterface FatalCaptureHooks {\n // `prepareNativeCapture` is offered the final, before_send-accepted message at the moment\n // it would be enqueued. Returning a thunk transfers ownership of the exception to the\n // native SDK and the JS queue copy is dropped; returning undefined leaves the event in the\n // JS queue as usual. The choice has to be made there, in one step, so a payload that fails\n // to build cannot leave the exception dropped from both queues.\n captureFatalException: (\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n ) => { queued: boolean; nativeCapture?: () => Promise<void> }\n waitForJSPersist: () => Promise<boolean>\n waitForStorageReady: () => Promise<boolean>\n getPersistenceMode: () => 'memory' | 'file' | undefined\n // Both native SDKs silently no-op a capture before setup() has run. Native init is async\n // and happens after the storage preload, so an early-startup crash can arrive first —\n // exactly the crashes this path exists for. Ownership only transfers once native is up.\n isNativeCaptureReady: () => boolean\n}\n\nexport class ErrorTracking {\n private logger: Logger\n private options: ResolvedErrorTrackingOptions\n private _exceptionStepsConfig: CoreErrorTracking.ResolvedExceptionStepsConfig\n private _exceptionStepsBuffer: CoreErrorTracking.ExceptionStepsBuffer\n private _nativeForwardingEnabled: boolean = false\n private _unsubscribeUncaughtExceptions?: () => void\n\n /**\n * Controls whether autocaptured exceptions are actually sent.\n * When remote config disables error tracking, this is set to false\n * so that installed handlers become no-ops.\n * Defaults to true (don't block locally enabled capture before remote config loads).\n */\n private _autocaptureEnabled: boolean = true\n\n constructor(\n private instance: PostHog,\n options: ErrorTrackingOptions = {},\n logger: Logger,\n private readonly fatalCaptureHooks?: FatalCaptureHooks\n ) {\n this.logger = logger.createLogger('[ErrorTracking]')\n this.options = this.resolveOptions(options)\n const exceptionSteps = options.exceptionSteps\n this._exceptionStepsConfig = CoreErrorTracking.resolveExceptionStepsConfig(\n exceptionSteps ? { enabled: exceptionSteps.enabled, max_bytes: exceptionSteps.maxBytes } : undefined\n )\n this._exceptionStepsBuffer = new CoreErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig)\n this.autocapture(this.options.autocapture)\n }\n\n /**\n * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one\n * logical buffer with the same byte budget and enabled state.\n */\n getNativePluginExceptionStepsConfig(): ExceptionStepsOptions {\n return { enabled: this._exceptionStepsConfig.enabled, maxBytes: this._exceptionStepsConfig.max_bytes }\n }\n\n /**\n * Records a breadcrumb-style exception step in the instance buffer and mirrors it to the embedded\n * native SDK. The `$timestamp` is captured at call time. Invalid messages are ignored with a\n * warning and never throw. The step only reaches native when it was actually buffered.\n */\n addExceptionStep(message: string, properties?: Properties): void {\n if (!this._exceptionStepsConfig.enabled) {\n return\n }\n\n try {\n if (!isString(message) || message.trim().length === 0) {\n this.logger.warn('Ignoring exception step because message must be a non-empty string')\n return\n }\n\n const userProperties = isObject(properties) ? { ...properties } : {}\n const { sanitizedProperties, droppedKeys } = CoreErrorTracking.stripReservedExceptionStepFields(userProperties)\n\n if (droppedKeys.length > 0) {\n this.logger.warn('Ignoring reserved exception step fields', { droppedKeys })\n }\n\n this._exceptionStepsBuffer.add({\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE]: message,\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP]: new Date().toISOString(),\n ...sanitizedProperties,\n })\n this.forwardExceptionStepToNative(message, properties)\n } catch (error) {\n this.logger.error('Failed to add exception step. Ignoring breadcrumb.', error)\n }\n }\n\n /**\n * Native error tracking initializes asynchronously, so steps recorded before then are buffered\n * only in JS. The host calls this once native is ready to enable forwarding and replay the buffer,\n * so a native crash shortly after startup carries the steps recorded before native was ready.\n */\n onNativeErrorTrackingReady(): void {\n this._nativeForwardingEnabled = true\n for (const step of this.getAttachableExceptionSteps()) {\n this.forwardExceptionStepToNative(step.$message, step as Properties)\n }\n }\n\n private forwardExceptionStepToNative(message: string, properties?: Properties): void {\n if (!this._nativeForwardingEnabled || !OptionalReactNativePlugin?.addExceptionStep) {\n return\n }\n try {\n // Fire-and-forget: the native layer validates and buffers independently and must never block.\n void Promise.resolve(OptionalReactNativePlugin.addExceptionStep(message, properties)).catch((e) => {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n }\n }\n\n /**\n * Returns `properties` with a snapshot of the buffered steps attached as `$exception_steps`,\n * unless the feature is disabled, the caller already provided that key, or the buffer is empty.\n * The buffer is left intact so subsequent exceptions read the same steps.\n */\n attachExceptionSteps(properties: PostHogEventProperties): PostHogEventProperties {\n if (!this._exceptionStepsConfig.enabled || !isNullish(properties.$exception_steps)) {\n return properties\n }\n const steps = this.getAttachableExceptionSteps()\n if (steps.length === 0) {\n return properties\n }\n // Steps are already normalized to their JSON-safe wire form by the buffer.\n return { ...properties, $exception_steps: steps as unknown as JsonType }\n }\n\n /**\n * Snapshot of the buffered steps (oldest first), or an empty array when disabled or empty.\n */\n getAttachableExceptionSteps(): CoreErrorTracking.ExceptionStep[] {\n if (!this._exceptionStepsConfig.enabled) {\n return []\n }\n try {\n return this._exceptionStepsBuffer.getAttachable()\n } catch (error) {\n this.logger.error('Failed to read buffered exception steps.', error)\n return []\n }\n }\n\n /**\n * Clears the buffer. Called on SDK close, not on capture or identity changes.\n */\n clearExceptionSteps(): void {\n this._exceptionStepsBuffer.clear()\n }\n\n shutdown(): void {\n this._autocaptureEnabled = false\n this._unsubscribeUncaughtExceptions?.()\n this._unsubscribeUncaughtExceptions = undefined\n this.clearExceptionSteps()\n }\n\n /**\n * Called when remote config is loaded.\n * If errorTracking.autocaptureExceptions is explicitly false, autocapture is disabled.\n * If it's true or undefined (not yet loaded / not present), autocapture follows local config.\n */\n onRemoteConfig(errorTracking: boolean | { [key: string]: JsonType } | undefined): void {\n if (errorTracking == null) {\n // Remote config doesn't include errorTracking — don't change anything\n return\n }\n\n // Default to false: if remote config is present but the key is missing, disable autocapture\n this._autocaptureEnabled = getRemoteConfigBool(errorTracking, 'autocaptureExceptions', false)\n\n this.logger.info(\n `Error tracking autocapture ${this._autocaptureEnabled ? 'enabled' : 'disabled'} by remote config.`\n )\n }\n\n /**\n * Whether the app asked for fatal JavaScript exceptions to be autocaptured. This is the\n * locally configured value, deliberately not gated on the remote kill-switch: it decides\n * whether the native SDK is worth initializing, and that happens before remote config has\n * been fetched.\n */\n isUncaughtExceptionAutocaptureEnabled(): boolean {\n return this.options.autocapture.uncaughtExceptions\n }\n\n private resolveOptions(options: ErrorTrackingOptions): ResolvedErrorTrackingOptions {\n const autocaptureOptions = this.resolveAutocaptureOptions(options.autocapture)\n return {\n autocapture: autocaptureOptions,\n }\n }\n\n private resolveAutocaptureOptions(autocapture: AutocaptureOptions | boolean = false): ResolvedAutocaptureOptions {\n if (typeof autocapture === 'boolean') {\n return {\n uncaughtExceptions: autocapture,\n unhandledRejections: autocapture,\n console: [],\n }\n }\n return {\n uncaughtExceptions: !!autocapture.uncaughtExceptions,\n unhandledRejections: !!autocapture.unhandledRejections,\n console: this.resolveConsoleOptions(autocapture.console),\n }\n }\n\n private resolveConsoleOptions(console: boolean | LogLevel[] = false): LogLevel[] {\n if (typeof console === 'boolean') {\n return console ? ['error'] : []\n }\n return Array.isArray(console) ? console.filter((level) => LogLevelList.includes(level)) : []\n }\n\n private autocaptureUncaughtErrors() {\n const onUncaughtException = (error: unknown, isFatal: boolean): void | Promise<void> => {\n const marked = isFatal ? this.markFatalExceptionHandled(error) : undefined\n if (!this._autocaptureEnabled || isPostHogFetchNetworkError(error)) {\n return marked\n }\n const hint: CoreErrorTracking.EventHint = {\n mechanism: { type: 'onuncaughtexception', handled: false },\n }\n if (!isFatal) {\n this.instance.captureException(error, {}, hint)\n return\n }\n return Promise.all([marked, this.handleFatalException(error, hint, uuidv7(), new Date())]).then(() => {})\n }\n try {\n this._unsubscribeUncaughtExceptions = trackUncaughtExceptions(onUncaughtException)\n } catch (err) {\n this.logger.warn('Failed to track uncaught exceptions: ', err)\n }\n }\n\n // React Native turns this fatal into a native crash once the handler chain finishes. The\n // native plugin drops that crash report only when it contains the message marked here, so\n // fatals that bypass this handler (React render errors) still reach error tracking.\n private markFatalExceptionHandled(error: unknown): Promise<void> | undefined {\n const bridge = OptionalReactNativePlugin?.markFatalExceptionHandled\n if (!bridge) {\n return undefined\n }\n try {\n return Promise.resolve(bridge(fatalMessageKey(error))).catch((e) => {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n return undefined\n }\n }\n\n private async handleFatalException(\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date\n ): Promise<void> {\n let storageReady = !this.fatalCaptureHooks\n if (this.fatalCaptureHooks) {\n try {\n storageReady = (await this.fatalCaptureHooks.waitForStorageReady()) === true\n } catch (e) {\n this.logger.warn('Fatal capture skipped because events storage did not initialize.', e)\n }\n }\n // Unknown consent must fail closed. A crash is less important than persisting data\n // for a user whose opt-out state could not be loaded.\n if (!storageReady || !this._autocaptureEnabled || this.instance.isDisabled || this.instance.optedOut) {\n return\n }\n\n if (!this.fatalCaptureHooks) {\n this.instance.captureException(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint)\n return\n }\n\n // Hand the final payload to the native SDK. Both native SDKs recognise a `$exception`\n // with `$exception_level: 'fatal'` and write it to their own disk queue synchronously\n // before returning, which is the durability the JS queue cannot promise while\n // AsyncStorage is still draining. Native owns delivery from there, including retry\n // across the relaunch, so there is nothing for the next launch to recover — and the JS\n // queue copy is dropped so the exception is not sent twice.\n let result: { queued: boolean; nativeCapture?: () => Promise<void> }\n try {\n result = this.fatalCaptureHooks.captureFatalException(error, hint, eventUuid, timestamp, (queued) =>\n this.prepareFatalNativeCapture(queued)\n )\n } catch (e) {\n // Without the final queued event we cannot know whether before_send accepted or\n // redacted the exception, so sending a raw fallback would bypass filtering.\n this.logger.error('Fatal exception capture failed before enqueue.', e)\n return\n }\n const { queued, nativeCapture } = result\n if (!queued && !nativeCapture) {\n // before_send dropped it.\n return\n }\n\n void this.instance.flush().catch(() => {\n this.logger.critical('Failed to flush events')\n })\n // Other events may still be queued behind this one, so the JS store is still worth\n // draining even when native owns the exception itself.\n const persisted = this.fatalCaptureHooks.waitForJSPersist()\n let nativeWrite: Promise<void> | undefined\n if (nativeCapture) {\n try {\n nativeWrite = nativeCapture().catch((e) => {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n }\n }\n const [persistedOk] = await Promise.all([persisted, nativeWrite])\n if (!persistedOk && !nativeCapture) {\n this.logger.warn('Fatal exception JS persist failed and no native capture path was available.')\n }\n }\n\n private prepareFatalNativeCapture(queuedEvent: PostHogEventProperties): (() => Promise<void>) | undefined {\n const bridge = OptionalReactNativePlugin?.captureFatalException\n if (!bridge) {\n return undefined\n }\n // Handing the event to a native SDK that is not set up yet would drop it: native\n // no-ops the capture, and the JS queue copy has already been given up.\n if (!this.fatalCaptureHooks?.isNativeCaptureReady()) {\n return undefined\n }\n // Memory-persistence apps asked for nothing on disk. The native queue is disk-backed,\n // so honour that here rather than routing around it.\n if (this.fatalCaptureHooks?.getPersistenceMode() === 'memory') {\n return undefined\n }\n if (this.instance.isDisabled || this.instance.optedOut) {\n return undefined\n }\n\n const properties = isObject(queuedEvent.properties) ? (queuedEvent.properties as PostHogEventProperties) : {}\n const payload = buildFatalExceptionPayload({\n timestamp: isString(queuedEvent.timestamp) ? queuedEvent.timestamp : new Date().toISOString(),\n distinctId: isString(queuedEvent.distinct_id) ? queuedEvent.distinct_id : '',\n // The event was normalized and emitted only after before_send accepted it.\n properties,\n })\n return () => bridge(payload.distinctId, payload.timestamp, payload.properties)\n }\n\n private autocaptureUnhandledRejections() {\n const onUnhandledRejection = (error: unknown) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n // Offline/timeout failures are expected, not application errors.\n if (isPostHogFetchNetworkError(error)) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false,\n },\n }\n this.instance.captureException(error, {}, hint)\n }\n\n try {\n trackUnhandledRejections(onUnhandledRejection)\n } catch (err) {\n this.logger.warn('Failed to track unhandled rejections: ', err)\n }\n }\n\n private autocaptureConsole(levels: LogLevel[]) {\n const onConsole = (level: LogLevel) => (error: unknown, isFatal: boolean, syntheticException?: Error) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onconsole',\n handled: true,\n },\n syntheticException,\n }\n const additionalProperties = {\n $exception_level: level as CoreErrorTracking.SeverityLevel,\n }\n this.instance.captureException(error, additionalProperties, hint)\n }\n\n try {\n for (const level of levels) {\n trackConsole(level, onConsole(level))\n }\n } catch (err) {\n this.logger.warn('Failed to track console errors: ', err)\n }\n }\n\n private autocapture(autocaptureOptions: ResolvedAutocaptureOptions) {\n if (autocaptureOptions.uncaughtExceptions === true) {\n this.autocaptureUncaughtErrors()\n }\n if (autocaptureOptions.unhandledRejections === true) {\n this.autocaptureUnhandledRejections()\n }\n if (autocaptureOptions.console.length > 0) {\n this.autocaptureConsole(autocaptureOptions.console)\n }\n }\n}\n"],"mappings":"utBACA,IAAAA,KAAA,CAAAC,OAAA,kBAYA,IAAAC,MAAA,CAAAD,OAAA,YACA,IAAAE,OAAA,CAAAF,OAAA,aACA,IAAAG,eAAA,CAAAH,OAAA,+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B,CAAEtE,IAAI,CAAC,CACnE,CAAC,GAED,GAAI,KAAAuE,UAAA,CAAApN,0BAAA,CACkB+M,MAAM,EAAAM,MAAA,KAA1B,IAAAD,UAAA,CAAAxM,CAAA,KAAAyM,MAAA,CAAAD,UAAA,CAAAvM,CAAA,IAAAC,IAAA,EAA4B,IAAjB,CAAAsH,KAAK,CAAAiF,MAAA,CAAAtM,KAAA,CACd,GAAAuM,mBAAY,EAAClF,KAAK,CAAE6E,SAAS,CAAC7E,KAAK,CAAC,CAAC,CACvC,CAAC,OAAA1B,GAAA,EAAA0G,UAAA,CAAAlN,CAAA,CAAAwG,GAAA,WAAA0G,UAAA,CAAApM,CAAA,IACH,CAAE,MAAO0F,GAAG,CAAE,CACZ,IAAI,CAAC5C,MAAM,CAACwB,IAAI,CAAC,kCAAkC,CAAEoB,GAAG,CAAC,CAC3D,CACF,CAAC,GAAA1B,GAAA,eAAAjE,KAAA,CAEO,SAAA+D,WAAWA,CAACiD,kBAA8C,EAChE,GAAIA,kBAAkB,CAACD,kBAAkB,GAAK,IAAI,CAAE,CAClD,IAAI,CAACQ,yBAAyB,EAAE,CAClC,CACA,GAAIP,kBAAkB,CAACE,mBAAmB,GAAK,IAAI,CAAE,CACnD,IAAI,CAACyE,8BAA8B,EAAE,CACvC,CACA,GAAI3E,kBAAkB,CAACG,OAAO,CAACzH,MAAM,CAAG,CAAC,CAAE,CACzC,IAAI,CAACqM,kBAAkB,CAAC/E,kBAAkB,CAACG,OAAO,CAAC,CACrD,CACF,CAAC","ignoreList":[]}
@@ -32,6 +32,7 @@ export type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin &
32
32
  captureFatalException?: (distinctId: string, timestamp: string, properties: {
33
33
  [key: string]: any;
34
34
  }) => Promise<void>;
35
+ markFatalExceptionHandled?: (message: string) => Promise<void>;
35
36
  };
36
37
  export type OptionalPluginLoaders = {
37
38
  loadPrimary: () => PostHogReactNativePluginExtended;
@@ -1 +1 @@
1
- {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","legacyPluginWarned","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","console","warn","optionalPlugin","Platform","OS","OptionalReactNativePlugin","OptionalReactNativePluginVersion"],"sources":["../../src/optional/OptionalPlugin.ts"],"sourcesContent":["import { Platform } from 'react-native'\n\n// Optional native dependency; resolved at runtime via require()/try-catch below.\nimport type PostHogReactNativePlugin from '@posthog/react-native-plugin'\nimport type { PostHogPushIdentityProvider } from '../types'\n\n/**\n * `@posthog/react-native-plugin` is the primary native plugin; we fall back to\n * `posthog-react-native-session-replay` (same surface minus the newer methods)\n * when only the legacy package is installed. Optional methods are absent on\n * older plugins, so callers check availability at runtime.\n *\n * `captureFatalException` is part of `PostHogReactNativePlugin` since the version that\n * moved fatal JavaScript exceptions onto the native SDK's own queue. Older plugins do not\n * expose it, so callers check existence before use and fall back to the JS event queue.\n */\nexport type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin & {\n setup?: (sessionId: string, sdkOptions: { [key: string]: any }, pluginConfig: { [key: string]: any }) => Promise<void>\n startRecording?: (resumeCurrent: boolean) => Promise<void>\n stopRecording?: () => Promise<void>\n addExceptionStep?: (message: string, properties?: { [key: string]: any }) => Promise<void>\n registerPushNotificationToken?: (deviceToken: string, appId: string | null) => Promise<void>\n unregisterPushNotificationToken?: () => Promise<void>\n setOptOut?: (optOut: boolean) => Promise<void>\n capturePushNotificationOpened?: (properties: { [key: string]: any }) => Promise<void>\n setPushIdentityProvider?: (provider: PostHogPushIdentityProvider) => void\n reset?: (distinctId: string, anonymousId: string) => Promise<void>\n captureFatalException?: (distinctId: string, timestamp: string, properties: { [key: string]: any }) => Promise<void>\n}\n\nexport type OptionalPluginLoaders = {\n loadPrimary: () => PostHogReactNativePluginExtended\n loadPrimaryVersion: () => string | undefined\n loadLegacy: () => PostHogReactNativePluginExtended\n}\n\nlet legacyPluginWarned = false\n\nexport const resolveOptionalPlugin = (\n platformOS: string,\n loaders?: OptionalPluginLoaders\n): { plugin: PostHogReactNativePluginExtended | undefined; version: string | undefined } => {\n let plugin: PostHogReactNativePluginExtended | undefined\n let version: string | undefined\n\n if (platformOS !== 'web') {\n try {\n plugin = loaders ? loaders.loadPrimary() : require('@posthog/react-native-plugin')\n try {\n version = loaders ? loaders.loadPrimaryVersion() : require('@posthog/react-native-plugin/package.json')?.version\n } catch {\n // Strict resolvers can reject this unexported subpath on older plugin versions.\n // Metro falls back to file-based resolution, so version logging only degrades to unknown where needed.\n }\n } catch {}\n\n // The legacy fallback is session-replay only and has no macOS support, so it's skipped on macOS.\n if (!plugin && platformOS !== 'macos') {\n try {\n plugin = loaders ? loaders.loadLegacy() : require('posthog-react-native-session-replay')\n } catch {}\n\n // Always visible (not gated on debug): it resolves at import, before any client or logger exists.\n if (plugin && !legacyPluginWarned) {\n legacyPluginWarned = true\n console.warn(\n '[PostHog] posthog-react-native-session-replay is deprecated and no longer receives native SDK updates. ' +\n 'Replace it with @posthog/react-native-plugin.'\n )\n }\n }\n }\n\n return { plugin, version }\n}\n\nconst optionalPlugin = resolveOptionalPlugin(Platform.OS)\n\nexport const OptionalReactNativePlugin = optionalPlugin.plugin\n\n// Resolved version of the loaded native plugin. It is logged next to the replay\n// config so a stale plugin, which silently ignores newer options such as sampleRate,\n// is visible in a debug log.\nexport const OptionalReactNativePluginVersion = optionalPlugin.version\n"],"mappings":"sLAAA,IAAAA,YAAA,CAAAC,OAAA,iBAoCA,GAAI,CAAAC,kBAAkB,CAAG,KAAK,CAEvB,GAAM,CAAAC,qBAAqB,CAAAC,OAAA,CAAAD,qBAAA,CAAG,QAAxB,CAAAA,qBAAqBA,CAChCE,UAAkB,CAClBC,OAA+B,CAC0D,C,OACzF,GAAI,CAAAC,MAAoD,CACxD,GAAI,CAAAC,OAA2B,CAE/B,GAAIH,UAAU,GAAK,KAAK,CAAE,CACxB,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACG,WAAW,EAAE,CAAGR,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFO,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAV,OAAO,CAAC,2CAA2C,CAAC,UAAAU,EAAA,iBAAAA,EAAA,CAAEH,OAAO,CAClH,C,SAAQ,CAGR,CACF,C,SAAQ,CAAC,CAGT,GAAI,CAACD,MAAM,EAAIF,UAAU,GAAK,OAAO,CAAE,CACrC,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACM,UAAU,EAAE,CAAGX,OAAO,CAAC,qCAAqC,CAAC,CAC1F,C,SAAQ,CAAC,CAGT,GAAIM,MAAM,EAAI,CAACL,kBAAkB,CAAE,CACjCA,kBAAkB,CAAG,IAAI,CACzBW,OAAO,CAACC,IAAI,CACV,yGAAyG,CACvG,+CAA+C,CAClD,CACH,CACF,CACF,CAEA,MAAO,CAAEP,MAAM,CAANA,MAAM,CAAEC,OAAO,CAAPA,OAAO,CAAE,CAC5B,CAAC,CAED,GAAM,CAAAO,cAAc,CAAGZ,qBAAqB,CAACa,qBAAQ,CAACC,EAAE,CAAC,CAElD,GAAM,CAAAC,yBAAyB,CAAAd,OAAA,CAAAc,yBAAA,CAAGH,cAAc,CAACR,MAAM,CAKvD,GAAM,CAAAY,gCAAgC,CAAAf,OAAA,CAAAe,gCAAA,CAAGJ,cAAc,CAACP,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","legacyPluginWarned","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","console","warn","optionalPlugin","Platform","OS","OptionalReactNativePlugin","OptionalReactNativePluginVersion"],"sources":["../../src/optional/OptionalPlugin.ts"],"sourcesContent":["import { Platform } from 'react-native'\n\n// Optional native dependency; resolved at runtime via require()/try-catch below.\nimport type PostHogReactNativePlugin from '@posthog/react-native-plugin'\nimport type { PostHogPushIdentityProvider } from '../types'\n\n/**\n * `@posthog/react-native-plugin` is the primary native plugin; we fall back to\n * `posthog-react-native-session-replay` (same surface minus the newer methods)\n * when only the legacy package is installed. Optional methods are absent on\n * older plugins, so callers check availability at runtime.\n *\n * `captureFatalException` is part of `PostHogReactNativePlugin` since the version that\n * moved fatal JavaScript exceptions onto the native SDK's own queue. Older plugins do not\n * expose it, so callers check existence before use and fall back to the JS event queue.\n */\nexport type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin & {\n setup?: (sessionId: string, sdkOptions: { [key: string]: any }, pluginConfig: { [key: string]: any }) => Promise<void>\n startRecording?: (resumeCurrent: boolean) => Promise<void>\n stopRecording?: () => Promise<void>\n addExceptionStep?: (message: string, properties?: { [key: string]: any }) => Promise<void>\n registerPushNotificationToken?: (deviceToken: string, appId: string | null) => Promise<void>\n unregisterPushNotificationToken?: () => Promise<void>\n setOptOut?: (optOut: boolean) => Promise<void>\n capturePushNotificationOpened?: (properties: { [key: string]: any }) => Promise<void>\n setPushIdentityProvider?: (provider: PostHogPushIdentityProvider) => void\n reset?: (distinctId: string, anonymousId: string) => Promise<void>\n captureFatalException?: (distinctId: string, timestamp: string, properties: { [key: string]: any }) => Promise<void>\n markFatalExceptionHandled?: (message: string) => Promise<void>\n}\n\nexport type OptionalPluginLoaders = {\n loadPrimary: () => PostHogReactNativePluginExtended\n loadPrimaryVersion: () => string | undefined\n loadLegacy: () => PostHogReactNativePluginExtended\n}\n\nlet legacyPluginWarned = false\n\nexport const resolveOptionalPlugin = (\n platformOS: string,\n loaders?: OptionalPluginLoaders\n): { plugin: PostHogReactNativePluginExtended | undefined; version: string | undefined } => {\n let plugin: PostHogReactNativePluginExtended | undefined\n let version: string | undefined\n\n if (platformOS !== 'web') {\n try {\n plugin = loaders ? loaders.loadPrimary() : require('@posthog/react-native-plugin')\n try {\n version = loaders ? loaders.loadPrimaryVersion() : require('@posthog/react-native-plugin/package.json')?.version\n } catch {\n // Strict resolvers can reject this unexported subpath on older plugin versions.\n // Metro falls back to file-based resolution, so version logging only degrades to unknown where needed.\n }\n } catch {}\n\n // The legacy fallback is session-replay only and has no macOS support, so it's skipped on macOS.\n if (!plugin && platformOS !== 'macos') {\n try {\n plugin = loaders ? loaders.loadLegacy() : require('posthog-react-native-session-replay')\n } catch {}\n\n // Always visible (not gated on debug): it resolves at import, before any client or logger exists.\n if (plugin && !legacyPluginWarned) {\n legacyPluginWarned = true\n console.warn(\n '[PostHog] posthog-react-native-session-replay is deprecated and no longer receives native SDK updates. ' +\n 'Replace it with @posthog/react-native-plugin.'\n )\n }\n }\n }\n\n return { plugin, version }\n}\n\nconst optionalPlugin = resolveOptionalPlugin(Platform.OS)\n\nexport const OptionalReactNativePlugin = optionalPlugin.plugin\n\n// Resolved version of the loaded native plugin. It is logged next to the replay\n// config so a stale plugin, which silently ignores newer options such as sampleRate,\n// is visible in a debug log.\nexport const OptionalReactNativePluginVersion = optionalPlugin.version\n"],"mappings":"sLAAA,IAAAA,YAAA,CAAAC,OAAA,iBAqCA,GAAI,CAAAC,kBAAkB,CAAG,KAAK,CAEvB,GAAM,CAAAC,qBAAqB,CAAAC,OAAA,CAAAD,qBAAA,CAAG,QAAxB,CAAAA,qBAAqBA,CAChCE,UAAkB,CAClBC,OAA+B,CAC0D,C,OACzF,GAAI,CAAAC,MAAoD,CACxD,GAAI,CAAAC,OAA2B,CAE/B,GAAIH,UAAU,GAAK,KAAK,CAAE,CACxB,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACG,WAAW,EAAE,CAAGR,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFO,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAV,OAAO,CAAC,2CAA2C,CAAC,UAAAU,EAAA,iBAAAA,EAAA,CAAEH,OAAO,CAClH,C,SAAQ,CAGR,CACF,C,SAAQ,CAAC,CAGT,GAAI,CAACD,MAAM,EAAIF,UAAU,GAA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