posthog-react-native 4.76.0 → 4.77.1

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.
@@ -0,0 +1,14 @@
1
+ import { JsonType, PostHogEventProperties } from '@posthog/core';
2
+ export interface FatalExceptionPayload {
3
+ distinctId: string;
4
+ timestamp: string;
5
+ properties: {
6
+ [key: string]: JsonType;
7
+ };
8
+ }
9
+ export interface BuildFatalExceptionPayloadInput {
10
+ timestamp: string;
11
+ distinctId: string;
12
+ properties: PostHogEventProperties;
13
+ }
14
+ export declare const buildFatalExceptionPayload: (input: BuildFatalExceptionPayloadInput) => FatalExceptionPayload;
@@ -0,0 +1,2 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.buildFatalExceptionPayload=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var FATAL_PAYLOAD_MAX_BYTES=64*1024;var MAX_PROPERTIES_BYTES=8*1024;var MAX_EXCEPTION_LIST_BYTES=44*1024;var MAX_EXCEPTION_STEPS_BYTES=8*1024;var MAX_EXCEPTION_LIST_ITEMS=32;var MAX_EXCEPTION_STEPS_ITEMS=64;var MAX_JSON_DEPTH=20;var STRING_LIMITS={timestamp:128,distinctId:1024,exceptionLevel:64};var utf8ByteLength=function utf8ByteLength(value){var bytes=0;for(var index=0;index<value.length;index++){var code=value.charCodeAt(index);if(code<=0x7f){bytes+=1;}else if(code<=0x7ff){bytes+=2;}else if(code>=0xd800&&code<=0xdbff&&index+1<value.length){var next=value.charCodeAt(index+1);if(next>=0xdc00&&next<=0xdfff){bytes+=4;index+=1;}else{bytes+=3;}}else{bytes+=3;}}return bytes;};var safeJson=function safeJson(value){try{var result=JSON.stringify(value);return typeof result==='string'?result:null;}catch(_a){return null;}};var jsonBytes=function jsonBytes(value){var serialized=safeJson(value);return serialized===null?Number.MAX_SAFE_INTEGER:utf8ByteLength(serialized);};var isRecord=function isRecord(value){return value!==null&&(0,_typeof2["default"])(value)==='object'&&!Array.isArray(value);};var _isJsonValue=function isJsonValue(value){var depth=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var ancestors=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];if(value===null||typeof value==='string'||typeof value==='boolean'){return true;}if(typeof value==='number'){return Number.isFinite(value);}if(depth>=MAX_JSON_DEPTH||(0,_typeof2["default"])(value)!=='object'){return false;}if(ancestors.includes(value)){return false;}var nextAncestors=[].concat((0,_toConsumableArray2["default"])(ancestors),[value]);if(Array.isArray(value)){return value.every(function(item){return _isJsonValue(item,depth+1,nextAncestors);});}return Object.keys(value).every(function(key){return _isJsonValue(value[key],depth+1,nextAncestors);});};var boundedString=function boundedString(value,maxJsonBytes){var bytes=2;var end=0;for(var index=0;index<value.length;index++){var code=value.charCodeAt(index);var nextBytes=void 0;var codeUnits=1;if(code===0x22||code===0x5c||code===0x08||code===0x09||code===0x0a||code===0x0c||code===0x0d){nextBytes=2;}else if(code<=0x1f){nextBytes=6;}else if(code<=0x7f){nextBytes=1;}else if(code<=0x7ff){nextBytes=2;}else if(code>=0xd800&&code<=0xdbff){var low=value.charCodeAt(index+1);if(low>=0xdc00&&low<=0xdfff){nextBytes=4;codeUnits=2;}else{nextBytes=6;}}else if(code>=0xdc00&&code<=0xdfff){nextBytes=6;}else{nextBytes=3;}if(bytes+nextBytes>maxJsonBytes){break;}bytes+=nextBytes;end=index+codeUnits;index+=codeUnits-1;}return end===value.length?value:value.slice(0,end);};var boundedObject=function boundedObject(input,maxBytes){var output={};for(var _i=0,_Object$keys=Object.keys(input);_i<_Object$keys.length;_i++){var key=_Object$keys[_i];var value=input[key];if(!_isJsonValue(value)){continue;}if(typeof value==='string'){var valueBudget=maxBytes-jsonBytes(output)-jsonBytes(key)-1-(Object.keys(output).length===0?0:1);var bounded=boundedString(value,valueBudget);if(bounded.length>0||value.length===0){output[key]=bounded;}continue;}output[key]=value;if(jsonBytes(output)>maxBytes){delete output[key];}}return output;};var boundedObjectArray=function boundedObjectArray(input,maxItems,maxBytes){var output=[];var usedBytes=2;for(var index=0;index<input.length&&output.length<maxItems;index++){var commaBytes=output.length===0?0:1;var remaining=maxBytes-usedBytes-commaBytes;if(remaining<2){break;}var item=boundedObject(input[index],remaining);var itemBytes=jsonBytes(item);if(itemBytes>remaining){break;}output.push(item);usedBytes+=commaBytes+itemBytes;}return output;};var asObjectArray=function asObjectArray(value,name){if(!Array.isArray(value)||value.length===0||!value.every(isRecord)){throw new Error("buildFatalExceptionPayload: ".concat(name," must be a non-empty array of objects"));}return value;};var EXCEPTION_KEYS=new Set(['$exception_list','$exception_steps']);var PRIORITY_KEYS=['$session_id','$device_id','$process_person_profile','$is_identified','$geoip_disable','$app_version','$app_build','$lib','$lib_version','$app_state','$expo_update_id','$expo_runtime_version','$expo_channel','$expo_is_embedded_launch'];var PRIORITY_KEY_SET=new Set(PRIORITY_KEYS);var byPriority=function byPriority(input){var ordered={};for(var _i2=0,_PRIORITY_KEYS=PRIORITY_KEYS;_i2<_PRIORITY_KEYS.length;_i2++){var key=_PRIORITY_KEYS[_i2];if(Object.prototype.hasOwnProperty.call(input,key)){ordered[key]=input[key];}}for(var _i3=0,_Object$keys2=Object.keys(input);_i3<_Object$keys2.length;_i3++){var _key=_Object$keys2[_i3];if(!PRIORITY_KEY_SET.has(_key)){ordered[_key]=input[_key];}}return ordered;};var buildFatalExceptionPayload=exports.buildFatalExceptionPayload=function buildFatalExceptionPayload(input){if(!input.timestamp){throw new Error('buildFatalExceptionPayload: timestamp is required');}var source=isRecord(input.properties)?input.properties:{};var exceptionList=boundedObjectArray(asObjectArray(source.$exception_list,'$exception_list'),MAX_EXCEPTION_LIST_ITEMS,MAX_EXCEPTION_LIST_BYTES);if(exceptionList.length===0){throw new Error('buildFatalExceptionPayload: $exception_list could not be serialized');}var rest={};for(var _i4=0,_Object$keys3=Object.keys(source);_i4<_Object$keys3.length;_i4++){var key=_Object$keys3[_i4];if(!EXCEPTION_KEYS.has(key)){rest[key]=source[key];}}var properties=boundedObject(byPriority(rest),MAX_PROPERTIES_BYTES);properties.$exception_list=exceptionList;properties.$exception_level=boundedString(typeof source.$exception_level==='string'&&source.$exception_level?source.$exception_level:'fatal',STRING_LIMITS.exceptionLevel);if(Array.isArray(source.$exception_steps)){var steps=boundedObjectArray(source.$exception_steps.filter(isRecord),MAX_EXCEPTION_STEPS_ITEMS,MAX_EXCEPTION_STEPS_BYTES);if(steps.length>0){properties.$exception_steps=steps;}}var payload={distinctId:boundedString(input.distinctId||'',STRING_LIMITS.distinctId),timestamp:boundedString(input.timestamp,STRING_LIMITS.timestamp),properties:properties};if(jsonBytes(payload)>FATAL_PAYLOAD_MAX_BYTES){throw new Error('buildFatalExceptionPayload: serialized payload exceeds 64 KiB');}return payload;};
2
+ //# sourceMappingURL=fatal-payload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fatal-payload.js","names":["FATAL_PAYLOAD_MAX_BYTES","MAX_PROPERTIES_BYTES","MAX_EXCEPTION_LIST_BYTES","MAX_EXCEPTION_STEPS_BYTES","MAX_EXCEPTION_LIST_ITEMS","MAX_EXCEPTION_STEPS_ITEMS","MAX_JSON_DEPTH","STRING_LIMITS","timestamp","distinctId","exceptionLevel","utf8ByteLength","value","bytes","index","length","code","charCodeAt","next","safeJson","result","JSON","stringify","jsonBytes","serialized","Number","MAX_SAFE_INTEGER","isRecord","_typeof2","Array","isArray","isJsonValue","depth","arguments","undefined","ancestors","isFinite","includes","nextAncestors","concat","_toConsumableArray2","every","item","Object","keys","key","boundedString","maxJsonBytes","end","nextBytes","codeUnits","low","slice","boundedObject","input","maxBytes","output","_i","_Object$keys","valueBudget","bounded","boundedObjectArray","maxItems","usedBytes","commaBytes","remaining","itemBytes","push","asObjectArray","name","Error","EXCEPTION_KEYS","Set","PRIORITY_KEYS","PRIORITY_KEY_SET","byPriority","ordered","_i2","_PRIORITY_KEYS","prototype","hasOwnProperty","call","_i3","_Object$keys2","has","buildFatalExceptionPayload","exports","source","properties","exceptionList","$exception_list","rest","_i4","_Object$keys3","$exception_level","$exception_steps","steps","filter","payload"],"sources":["../../src/error-tracking/fatal-payload.ts"],"sourcesContent":["import { JsonType, PostHogEventProperties } from '@posthog/core'\n\n// The payload handed to the native SDK on the fatal path. Native captures it as a\n// `$exception` event with `$exception_level: 'fatal'`, which both native SDKs persist to\n// disk synchronously before the call returns — that synchronous write is the durability\n// this path exists for, so the payload has to stay small and strictly JSON-safe.\n//\n// Crash-time attribution needs no special handling here: native captures inside the dying\n// process, so its own static context (app version, OS, device) is already the crash-time\n// context. Only properties native cannot know — the JS exception itself, `$app_state`, the\n// Expo update context — travel in this payload.\nconst FATAL_PAYLOAD_MAX_BYTES = 64 * 1024\n// 8 + 44 + 8 KiB of content, leaving ~4 KiB of the 64 KiB cap for keys and structure.\nconst MAX_PROPERTIES_BYTES = 8 * 1024\nconst MAX_EXCEPTION_LIST_BYTES = 44 * 1024\nconst MAX_EXCEPTION_STEPS_BYTES = 8 * 1024\nconst MAX_EXCEPTION_LIST_ITEMS = 32\nconst MAX_EXCEPTION_STEPS_ITEMS = 64\nconst MAX_JSON_DEPTH = 20\n\nconst STRING_LIMITS = {\n timestamp: 128,\n distinctId: 1024,\n exceptionLevel: 64,\n} as const\n\nconst utf8ByteLength = (value: string): number => {\n let bytes = 0\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code <= 0x7f) {\n bytes += 1\n } else if (code <= 0x7ff) {\n bytes += 2\n } else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {\n const next = value.charCodeAt(index + 1)\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4\n index += 1\n } else {\n bytes += 3\n }\n } else {\n bytes += 3\n }\n }\n return bytes\n}\n\nconst safeJson = (value: unknown): string | null => {\n try {\n const result = JSON.stringify(value)\n return typeof result === 'string' ? result : null\n } catch {\n return null\n }\n}\n\nconst jsonBytes = (value: unknown): number => {\n const serialized = safeJson(value)\n return serialized === null ? Number.MAX_SAFE_INTEGER : utf8ByteLength(serialized)\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value)\n\nconst isJsonValue = (value: unknown, depth = 0, ancestors: unknown[] = []): value is JsonType => {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') {\n return true\n }\n if (typeof value === 'number') {\n return Number.isFinite(value)\n }\n if (depth >= MAX_JSON_DEPTH || typeof value !== 'object') {\n return false\n }\n if (ancestors.includes(value)) {\n return false\n }\n const nextAncestors = [...ancestors, value]\n if (Array.isArray(value)) {\n return value.every((item) => isJsonValue(item, depth + 1, nextAncestors))\n }\n return Object.keys(value as Record<string, unknown>).every((key) =>\n isJsonValue((value as Record<string, unknown>)[key], depth + 1, nextAncestors)\n )\n}\n\n// Return the longest prefix whose JSON string representation fits. Measure as we scan instead\n// of serializing the whole value: fatal-path values can be very large, and JSON escaping means\n// a JavaScript string's length is not its serialized UTF-8 size.\nconst boundedString = (value: string, maxJsonBytes: number): string => {\n let bytes = 2 // surrounding quotes\n let end = 0\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n let nextBytes: number\n let codeUnits = 1\n if (\n code === 0x22 ||\n code === 0x5c ||\n code === 0x08 ||\n code === 0x09 ||\n code === 0x0a ||\n code === 0x0c ||\n code === 0x0d\n ) {\n nextBytes = 2\n } else if (code <= 0x1f) {\n nextBytes = 6\n } else if (code <= 0x7f) {\n nextBytes = 1\n } else if (code <= 0x7ff) {\n nextBytes = 2\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const low = value.charCodeAt(index + 1)\n if (low >= 0xdc00 && low <= 0xdfff) {\n nextBytes = 4\n codeUnits = 2\n } else {\n nextBytes = 6 // JSON.stringify escapes lone surrogates\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n nextBytes = 6\n } else {\n nextBytes = 3\n }\n if (bytes + nextBytes > maxJsonBytes) {\n break\n }\n bytes += nextBytes\n end = index + codeUnits\n index += codeUnits - 1\n }\n return end === value.length ? value : value.slice(0, end)\n}\n\n// Values are retained by reference when they fit. This avoids cloning arbitrary customer data\n// on the fatal path. Only an oversized string is copied, as a bounded prefix.\nconst boundedObject = (input: Record<string, unknown>, maxBytes: number): { [key: string]: JsonType } => {\n const output: { [key: string]: JsonType } = {}\n for (const key of Object.keys(input)) {\n const value = input[key]\n if (!isJsonValue(value)) {\n continue\n }\n if (typeof value === 'string') {\n // Work out how much of this string can fit in the object, including its key and commas,\n // without first creating a serialized copy of the potentially unbounded input.\n const valueBudget = maxBytes - jsonBytes(output) - jsonBytes(key) - 1 - (Object.keys(output).length === 0 ? 0 : 1)\n const bounded = boundedString(value, valueBudget)\n if (bounded.length > 0 || value.length === 0) {\n output[key] = bounded\n }\n continue\n }\n output[key] = value\n if (jsonBytes(output) > maxBytes) {\n delete output[key]\n }\n }\n return output\n}\n\nconst boundedObjectArray = (\n input: ReadonlyArray<Record<string, unknown>>,\n maxItems: number,\n maxBytes: number\n): Array<{ [key: string]: JsonType }> => {\n const output: Array<{ [key: string]: JsonType }> = []\n let usedBytes = 2 // []\n for (let index = 0; index < input.length && output.length < maxItems; index++) {\n const commaBytes = output.length === 0 ? 0 : 1\n const remaining = maxBytes - usedBytes - commaBytes\n if (remaining < 2) {\n break\n }\n const item = boundedObject(input[index], remaining)\n const itemBytes = jsonBytes(item)\n if (itemBytes > remaining) {\n break\n }\n output.push(item)\n usedBytes += commaBytes + itemBytes\n }\n return output\n}\n\nconst asObjectArray = (value: unknown, name: string): Array<Record<string, unknown>> => {\n if (!Array.isArray(value) || value.length === 0 || !value.every(isRecord)) {\n throw new Error(`buildFatalExceptionPayload: ${name} must be a non-empty array of objects`)\n }\n return value\n}\n\nexport interface FatalExceptionPayload {\n distinctId: string\n timestamp: string\n properties: { [key: string]: JsonType }\n}\n\nexport interface BuildFatalExceptionPayloadInput {\n timestamp: string\n distinctId: string\n // The full property bag of the `before_send`-accepted event. Everything native cannot\n // reconstruct itself is carried through; conflicting keys are native's to resolve.\n properties: PostHogEventProperties\n}\n\n// `$exception_list` and `$exception_steps` get their own budgets: they are the unbounded,\n// customer-influenced parts of the payload, and one must not be able to crowd out the rest.\nconst EXCEPTION_KEYS = new Set(['$exception_list', '$exception_steps'])\n\n// The remaining properties are bounded as one bag, and `boundedObject` fills in key order\n// until the budget runs out. An app with a large flag set therefore pushes whatever sorts\n// after `$feature/*` off the end — session linkage and release attribution included. These\n// keys are written first so a big property bag can only cost bulk properties, never the\n// attribution a crash report is useless without.\nconst PRIORITY_KEYS = [\n '$session_id',\n '$device_id',\n // Consent and identity resolution: native cannot re-derive what JS decided.\n '$process_person_profile',\n '$is_identified',\n '$geoip_disable',\n // Release attribution — what a crash gets triaged by.\n '$app_version',\n '$app_build',\n '$lib',\n '$lib_version',\n // Crash-time context native has no view of.\n '$app_state',\n '$expo_update_id',\n '$expo_runtime_version',\n '$expo_channel',\n '$expo_is_embedded_launch',\n] as const\nconst PRIORITY_KEY_SET = new Set<string>(PRIORITY_KEYS)\n\n// Priority keys first, then everything else in its original order.\nconst byPriority = (input: Record<string, unknown>): Record<string, unknown> => {\n const ordered: Record<string, unknown> = {}\n for (const key of PRIORITY_KEYS) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n ordered[key] = input[key]\n }\n }\n for (const key of Object.keys(input)) {\n if (!PRIORITY_KEY_SET.has(key)) {\n ordered[key] = input[key]\n }\n }\n return ordered\n}\n\nexport const buildFatalExceptionPayload = (input: BuildFatalExceptionPayloadInput): FatalExceptionPayload => {\n if (!input.timestamp) {\n throw new Error('buildFatalExceptionPayload: timestamp is required')\n }\n\n const source = isRecord(input.properties) ? input.properties : {}\n const exceptionList = boundedObjectArray(\n asObjectArray(source.$exception_list, '$exception_list'),\n MAX_EXCEPTION_LIST_ITEMS,\n MAX_EXCEPTION_LIST_BYTES\n )\n if (exceptionList.length === 0) {\n throw new Error('buildFatalExceptionPayload: $exception_list could not be serialized')\n }\n\n const rest: Record<string, unknown> = {}\n for (const key of Object.keys(source)) {\n if (!EXCEPTION_KEYS.has(key)) {\n rest[key] = source[key]\n }\n }\n\n const properties: { [key: string]: JsonType } = boundedObject(byPriority(rest), MAX_PROPERTIES_BYTES)\n properties.$exception_list = exceptionList\n // Native's fatal fast path keys off this exact value; without it the record is queued\n // asynchronously and the process can die before it reaches disk.\n properties.$exception_level = boundedString(\n typeof source.$exception_level === 'string' && source.$exception_level ? source.$exception_level : 'fatal',\n STRING_LIMITS.exceptionLevel\n )\n\n if (Array.isArray(source.$exception_steps)) {\n const steps = boundedObjectArray(\n (source.$exception_steps as unknown[]).filter(isRecord),\n MAX_EXCEPTION_STEPS_ITEMS,\n MAX_EXCEPTION_STEPS_BYTES\n )\n if (steps.length > 0) {\n properties.$exception_steps = steps\n }\n }\n\n const payload: FatalExceptionPayload = {\n distinctId: boundedString(input.distinctId || '', STRING_LIMITS.distinctId),\n timestamp: boundedString(input.timestamp, STRING_LIMITS.timestamp),\n properties,\n }\n\n // The per-field budgets leave headroom for keys and fixed metadata. Keep the total check\n // anyway: it is the invariant the native bridge relies on.\n if (jsonBytes(payload) > FATAL_PAYLOAD_MAX_BYTES) {\n throw new Error('buildFatalExceptionPayload: serialized payload exceeds 64 KiB')\n }\n return payload\n}\n"],"mappings":"qXAWA,GAAM,CAAAA,uBAAuB,CAAG,EAAE,CAAG,IAAI,CAEzC,GAAM,CAAAC,oBAAoB,CAAG,CAAC,CAAG,IAAI,CACrC,GAAM,CAAAC,wBAAwB,CAAG,EAAE,CAAG,IAAI,CAC1C,GAAM,CAAAC,yBAAyB,CAAG,CAAC,CAAG,IAAI,CAC1C,GAAM,CAAAC,wBAAwB,CAAG,EAAE,CACnC,GAAM,CAAAC,yBAAyB,CAAG,EAAE,CACpC,GAAM,CAAAC,cAAc,CAAG,EAAE,CAEzB,GAAM,CAAAC,aAAa,CAAG,CACpBC,SAAS,CAAE,GAAG,CACd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AAED,aAAa,CAACC,SAAS,CAAC,CAClEgF,UAAU,CAAVA,U,CACD,CAID,GAAIjE,SAAS,CAAC2E,OAAO,CAAC,CAAGlG,uBAAuB,CAAE,CAChD,KAAM,IAAI,CAAAsE,KAAK,CAAC,+DAA+D,CAAC,CAClF,CACA,MAAO,CAAA4B,OAAO,CAChB,CAAC","ignoreList":[]}
@@ -32,9 +32,19 @@ export interface ErrorTrackingOptions {
32
32
  autocapture?: AutocaptureOptions | boolean;
33
33
  exceptionSteps?: ExceptionStepsOptions;
34
34
  }
35
+ interface FatalCaptureHooks {
36
+ captureFatalException: (error: unknown, hint: CoreErrorTracking.EventHint, eventUuid: string, timestamp: Date, prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined) => {
37
+ queued: boolean;
38
+ nativeCapture?: () => Promise<void>;
39
+ };
40
+ waitForJSPersist: () => Promise<boolean>;
41
+ waitForStorageReady: () => Promise<boolean>;
42
+ getPersistenceMode: () => 'memory' | 'file' | undefined;
43
+ isNativeCaptureReady: () => boolean;
44
+ }
35
45
  export declare class ErrorTracking {
36
46
  private instance;
37
- private readonly persistFatalException?;
47
+ private readonly fatalCaptureHooks?;
38
48
  private logger;
39
49
  private options;
40
50
  private _exceptionStepsConfig;
@@ -48,7 +58,7 @@ export declare class ErrorTracking {
48
58
  * Defaults to true (don't block locally enabled capture before remote config loads).
49
59
  */
50
60
  private _autocaptureEnabled;
51
- constructor(instance: PostHog, options: ErrorTrackingOptions | undefined, logger: Logger, persistFatalException?: (() => Promise<void>) | undefined);
61
+ constructor(instance: PostHog, options: ErrorTrackingOptions | undefined, logger: Logger, fatalCaptureHooks?: FatalCaptureHooks | undefined);
52
62
  /**
53
63
  * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one
54
64
  * logical buffer with the same byte budget and enabled state.
@@ -90,10 +100,19 @@ export declare class ErrorTracking {
90
100
  onRemoteConfig(errorTracking: boolean | {
91
101
  [key: string]: JsonType;
92
102
  } | undefined): void;
103
+ /**
104
+ * Whether the app asked for fatal JavaScript exceptions to be autocaptured. This is the
105
+ * locally configured value, deliberately not gated on the remote kill-switch: it decides
106
+ * whether the native SDK is worth initializing, and that happens before remote config has
107
+ * been fetched.
108
+ */
109
+ isUncaughtExceptionAutocaptureEnabled(): boolean;
93
110
  private resolveOptions;
94
111
  private resolveAutocaptureOptions;
95
112
  private resolveConsoleOptions;
96
113
  private autocaptureUncaughtErrors;
114
+ private handleFatalException;
115
+ private prepareFatalNativeCapture;
97
116
  private autocaptureUnhandledRejections;
98
117
  private autocaptureConsole;
99
118
  private autocapture;
@@ -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 _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");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 persistFatalException=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,ErrorTracking);this.instance=instance;this.persistFatalException=persistFatalException;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:"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 _a;if(!_this2._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onuncaughtexception',handled:false}};var additionalProperties={};if(isFatal){additionalProperties['$exception_level']='fatal';}_this2.instance.captureException(error,additionalProperties,hint);if(isFatal){var persisted=(_a=_this2.persistFatalException)===null||_a===void 0?void 0:_a.call(_this2);void _this2.instance.flush()["catch"](function(){_this2.logger.critical('Failed to flush events');});return persisted;}};try{this._unsubscribeUncaughtExceptions=(0,_utils.trackUncaughtExceptions)(onUncaughtException);}catch(err){this.logger.warn('Failed to track uncaught exceptions: ',err);}}},{key:"autocaptureUnhandledRejections",value:function autocaptureUnhandledRejections(){var _this3=this;var onUnhandledRejection=function onUnhandledRejection(error){if(!_this3._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onunhandledrejection',handled:false}};_this3.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 _this4=this;var onConsole=function onConsole(level){return function(error,isFatal,syntheticException){if(!_this4._autocaptureEnabled){return;}var hint={mechanism:{type:'onconsole',handled:true},syntheticException:syntheticException};var additionalProperties={$exception_level:level};_this4.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 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);}}}]);}();
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_core","require","_utils","_utils2","_OptionalPlugin","_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","persistFatalException","_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","autocaptureOptions","resolveAutocaptureOptions","uncaughtExceptions","unhandledRejections","console","resolveConsoleOptions","level","includes","autocaptureUncaughtErrors","_this2","onUncaughtException","isFatal","isPostHogFetchNetworkError","hint","mechanism","type","handled","additionalProperties","captureException","persisted","flush","critical","trackUncaughtExceptions","autocaptureUnhandledRejections","_this3","onUnhandledRejection","trackUnhandledRejections","autocaptureConsole","levels","_this4","onConsole","syntheticException","$exception_level","_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} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport { trackConsole, trackUncaughtExceptions, trackUnhandledRejections } from './utils'\nimport { getRemoteConfigBool } from '../utils'\nimport { OptionalReactNativePlugin } from '../optional/OptionalPlugin'\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 * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: 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\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 persistFatalException?: () => Promise<void>\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 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) => {\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: 'onuncaughtexception',\n handled: false,\n },\n }\n const additionalProperties: any = {}\n\n if (isFatal) {\n additionalProperties['$exception_level'] = 'fatal' as CoreErrorTracking.SeverityLevel\n }\n\n this.instance.captureException(error, additionalProperties, hint)\n\n if (isFatal) {\n const persisted = this.persistFatalException?.()\n void this.instance.flush().catch(() => {\n this.logger.critical('Failed to flush events')\n })\n return persisted\n }\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 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":"0cACA,IAAAA,KAAA,CAAAC,OAAA,kBAWA,IAAAC,MAAA,CAAAD,OAAA,YACA,IAAAE,OAAA,CAAAF,OAAA,aACA,IAAAG,eAAA,CAAAH,OAAA,+BAAsE,SAAAI,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,EAAAT,CAAA,CAAAQ,MAAA,EAAAK,IAAA,MAAAA,IAAA,IAAAC,KAAA,CAAAd,CAAA,CAAAS,EA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,QAAQ,CAACuF,gBAAgB,CAAC7C,KAAK,CAAE4C,oBAAoB,CAAEJ,IAAI,CAAC,CACnE,CAAC,GAED,GAAI,KAAAoB,UAAA,CAAAvJ,0BAAA,CACkBkJ,MAAM,EAAAM,MAAA,KAA1B,IAAAD,UAAA,CAAA3I,CAAA,KAAA4I,MAAA,CAAAD,UAAA,CAAA1I,CAAA,IAAAC,IAAA,EAA4B,IAAjB,CAAA8G,KAAK,CAAA4B,MAAA,CAAAzI,KAAA,CACd,GAAA0I,mBAAY,EAAC7B,KAAK,CAAEwB,SAAS,CAACxB,KAAK,CAAC,CAAC,CACvC,CAAC,OAAA1B,GAAA,EAAAqD,UAAA,CAAArJ,CAAA,CAAAgG,GAAA,WAAAqD,UAAA,CAAAvI,CAAA,IACH,CAAE,MAAOkF,GAAG,CAAE,CACZ,IAAI,CAAC9C,MAAM,CAACyB,IAAI,CAAC,kCAAkC,CAAEqB,GAAG,CAAC,CAC3D,CACF,CAAC,GAAA5B,GAAA,eAAAvD,KAAA,CAEO,SAAAqD,WAAWA,CAACkD,kBAA8C,EAChE,GAAIA,kBAAkB,CAACE,kBAAkB,GAAK,IAAI,CAAE,CAClD,IAAI,CAACM,yBAAyB,EAAE,CAClC,CACA,GAAIR,kBAAkB,CAACG,mBAAmB,GAAK,IAAI,CAAE,CACnD,IAAI,CAACoB,8BAA8B,EAAE,CACvC,CACA,GAAIvB,kBAAkB,CAACI,OAAO,CAACjH,MAAM,CAAG,CAAC,CAAE,CACzC,IAAI,CAACwI,kBAAkB,CAAC3B,kBAAkB,CAACI,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","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 * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: 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,EAAAT,CAAA,CAAAQ,MAAA,EAAAK,IAAA,MAAAA,IAAA,IAAAC,KAAA,CAAAd,CAAA,CAAAS,EAAA,OAAAR,CAAA,UAAAA,EAAAD,CAAA,QAAAA,CAA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AkB,CAACG,OAAO,CAAC,CACrD,CACF,CAAC","ignoreList":[]}
@@ -5,6 +5,10 @@ import type { PostHogPushIdentityProvider } from '../types';
5
5
  * `posthog-react-native-session-replay` (same surface minus the newer methods)
6
6
  * when only the legacy package is installed. Optional methods are absent on
7
7
  * older plugins, so callers check availability at runtime.
8
+ *
9
+ * `captureFatalException` is part of `PostHogReactNativePlugin` since the version that
10
+ * moved fatal JavaScript exceptions onto the native SDK's own queue. Older plugins do not
11
+ * expose it, so callers check existence before use and fall back to the JS event queue.
8
12
  */
9
13
  export type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin & {
10
14
  setup?: (sessionId: string, sdkOptions: {
@@ -25,6 +29,9 @@ export type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin &
25
29
  }) => Promise<void>;
26
30
  setPushIdentityProvider?: (provider: PostHogPushIdentityProvider) => void;
27
31
  reset?: (distinctId: string, anonymousId: string) => Promise<void>;
32
+ captureFatalException?: (distinctId: string, timestamp: string, properties: {
33
+ [key: string]: any;
34
+ }) => Promise<void>;
28
35
  };
29
36
  export type OptionalPluginLoaders = {
30
37
  loadPrimary: () => PostHogReactNativePluginExtended;
@@ -1 +1 @@
1
- {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","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 */\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}\n\nexport type OptionalPluginLoaders = {\n loadPrimary: () => PostHogReactNativePluginExtended\n loadPrimaryVersion: () => string | undefined\n loadLegacy: () => PostHogReactNativePluginExtended\n}\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 }\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,iBA+BO,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,CAAGP,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFM,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAT,OAAO,CAAC,2CAA2C,CAAC,UAAAS,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,CAAGV,OAAO,CAAC,qCAAqC,CAAC,CAC1F,C,SAAQ,CAAC,CACX,CACF,CAEA,MAAO,CAAEK,MAAM,CAANA,MAAM,CAAEC,OAAO,CAAPA,OAAO,CAAE,CAC5B,CAAC,CAED,GAAM,CAAAK,cAAc,CAAGV,qBAAqB,CAACW,qBAAQ,CAACC,EAAE,CAAC,CAElD,GAAM,CAAAC,yBAAyB,CAAAZ,OAAA,CAAAY,yBAAA,CAAGH,cAAc,CAACN,MAAM,CAKvD,GAAM,CAAAU,gCAAgC,CAAAb,OAAA,CAAAa,gCAAA,CAAGJ,cAAc,CAACL,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","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\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 }\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,iBAoCO,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,CAAGP,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFM,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAT,OAAO,CAAC,2CAA2C,CAAC,UAAAS,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,CAAGV,OAAO,CAAC,qCAAqC,CAAC,CAC1F,C,SAAQ,CAAC,CACX,CACF,CAEA,MAAO,CAAEK,MAAM,CAANA,MAAM,CAAEC,OAAO,CAAPA,OAAO,CAAE,CAC5B,CAAC,CAED,GAAM,CAAAK,cAAc,CAAGV,qBAAqB,CAACW,qBAAQ,CAACC,EAAE,CAAC,CAElD,GAAM,CAAAC,yBAAyB,CAAAZ,OAAA,CAAAY,yBAAA,CAAGH,cAAc,CAACN,MAAM,CAKvD,GAAM,CAAAU,gCAAgC,CAAAb,OAAA,CAAAa,gCAAA,CAAGJ,cAAc,CAACL,OAAO","ignoreList":[]}
@@ -199,6 +199,7 @@ export declare class PostHog extends PostHogCore {
199
199
  private _sessionReplayNativeInitialized;
200
200
  private _nativeErrorTrackingInitialized;
201
201
  private _pushNativeInitialized;
202
+ private _fatalJsCaptureNativeInitialized;
202
203
  private _pushNativeUnsupported;
203
204
  private _sessionReplayMacOSWarned;
204
205
  private _sessionReplayRecordingActive?;
@@ -207,6 +208,8 @@ export declare class PostHog extends PostHogCore {
207
208
  private _nativeChain;
208
209
  private _sessionReplayOptions?;
209
210
  private _sessionReplayEventTriggers;
211
+ private _eventsStoragePreloadSucceeded;
212
+ private _fatalCaptureObservation?;
210
213
  private _disableSurveys;
211
214
  private _errorTracking;
212
215
  private _logs;
@@ -1051,6 +1054,8 @@ export declare class PostHog extends PostHogCore {
1051
1054
  * @returns {void}
1052
1055
  */
1053
1056
  captureException(error: Error | unknown, additionalProperties?: PostHogEventProperties, hint?: CoreErrorTracking.EventHint): void;
1057
+ private captureExceptionInternal;
1058
+ private buildExceptionProperties;
1054
1059
  /**
1055
1060
  * Records a breadcrumb-style exception step. Steps accumulate in a rolling, byte-bounded buffer
1056
1061
  * and are attached to every captured `$exception` as `$exception_steps`, giving the error tracking
@@ -1249,6 +1254,14 @@ export declare class PostHog extends PostHogCore {
1249
1254
  private _enqueueNative;
1250
1255
  private _ensureNativeInitialized;
1251
1256
  private _isAutocaptureNativeErrors;
1257
+ /**
1258
+ * Fatal JavaScript exceptions are handed to the native SDK, which persists them to its own
1259
+ * disk queue synchronously before the process dies. That only works if the native SDK is
1260
+ * set up, so JS uncaught-exception autocapture now warrants native init on its own — an app
1261
+ * that enabled neither replay, native crashes nor push would otherwise have no durable
1262
+ * fatal path at all.
1263
+ */
1264
+ private _isFatalJsCaptureNativeEnabled;
1252
1265
  private _isNativePluginInitialized;
1253
1266
  private _isPushNativeEnabled;
1254
1267
  /**
@@ -1286,6 +1299,12 @@ export declare class PostHog extends PostHogCore {
1286
1299
  * trigger check never drops an event or throws into the capture path.
1287
1300
  */
1288
1301
  protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null;
1302
+ /**
1303
+ * Capture a fatal exception and decide which queue owns it. The native SDK persists a
1304
+ * fatal `$exception` synchronously, so when it is available it takes the event and the JS
1305
+ * queue copy is dropped; otherwise the event stays in the JS queue as usual.
1306
+ */
1307
+ private _captureFatalAndChooseOwner;
1289
1308
  private _maybeActivateEventTrigger;
1290
1309
  private _parseEventTriggers;
1291
1310
  private _isEventTriggerActivatedForSession;