posthog-react-native 4.81.10 → 4.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,6 +32,9 @@ export type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin &
32
32
  captureFatalException?: (distinctId: string, timestamp: string, properties: {
33
33
  [key: string]: any;
34
34
  }) => Promise<void>;
35
+ getSessionReplayDebugProperties?: () => Promise<{
36
+ [key: string]: any;
37
+ }>;
35
38
  markFatalExceptionHandled?: (message: string) => Promise<void>;
36
39
  };
37
40
  export type OptionalPluginLoaders = {
@@ -1 +1 @@
1
- {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","legacyPluginWarned","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","console","warn","optionalPlugin","Platform","OS","OptionalReactNativePlugin","OptionalReactNativePluginVersion"],"sources":["../../src/optional/OptionalPlugin.ts"],"sourcesContent":["import { Platform } from 'react-native'\n\n// Optional native dependency; resolved at runtime via require()/try-catch below.\nimport type PostHogReactNativePlugin from '@posthog/react-native-plugin'\nimport type { PostHogPushIdentityProvider } from '../types'\n\n/**\n * `@posthog/react-native-plugin` is the primary native plugin; we fall back to\n * `posthog-react-native-session-replay` (same surface minus the newer methods)\n * when only the legacy package is installed. Optional methods are absent on\n * older plugins, so callers check availability at runtime.\n *\n * `captureFatalException` is part of `PostHogReactNativePlugin` since the version that\n * moved fatal JavaScript exceptions onto the native SDK's own queue. Older plugins do not\n * expose it, so callers check existence before use and fall back to the JS event queue.\n */\nexport type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin & {\n setup?: (sessionId: string, sdkOptions: { [key: string]: any }, pluginConfig: { [key: string]: any }) => Promise<void>\n startRecording?: (resumeCurrent: boolean) => Promise<void>\n stopRecording?: () => Promise<void>\n addExceptionStep?: (message: string, properties?: { [key: string]: any }) => Promise<void>\n registerPushNotificationToken?: (deviceToken: string, appId: string | null) => Promise<void>\n unregisterPushNotificationToken?: () => Promise<void>\n setOptOut?: (optOut: boolean) => Promise<void>\n capturePushNotificationOpened?: (properties: { [key: string]: any }) => Promise<void>\n setPushIdentityProvider?: (provider: PostHogPushIdentityProvider) => void\n reset?: (distinctId: string, anonymousId: string) => Promise<void>\n captureFatalException?: (distinctId: string, timestamp: string, properties: { [key: string]: any }) => Promise<void>\n markFatalExceptionHandled?: (message: string) => Promise<void>\n}\n\nexport type OptionalPluginLoaders = {\n loadPrimary: () => PostHogReactNativePluginExtended\n loadPrimaryVersion: () => string | undefined\n loadLegacy: () => PostHogReactNativePluginExtended\n}\n\nlet legacyPluginWarned = false\n\nexport const resolveOptionalPlugin = (\n platformOS: string,\n loaders?: OptionalPluginLoaders\n): { plugin: PostHogReactNativePluginExtended | undefined; version: string | undefined } => {\n let plugin: PostHogReactNativePluginExtended | undefined\n let version: string | undefined\n\n if (platformOS !== 'web') {\n try {\n plugin = loaders ? loaders.loadPrimary() : require('@posthog/react-native-plugin')\n try {\n version = loaders ? loaders.loadPrimaryVersion() : require('@posthog/react-native-plugin/package.json')?.version\n } catch {\n // Strict resolvers can reject this unexported subpath on older plugin versions.\n // Metro falls back to file-based resolution, so version logging only degrades to unknown where needed.\n }\n } catch {}\n\n // The legacy fallback is session-replay only and has no macOS support, so it's skipped on macOS.\n if (!plugin && platformOS !== 'macos') {\n try {\n plugin = loaders ? loaders.loadLegacy() : require('posthog-react-native-session-replay')\n } catch {}\n\n // Always visible (not gated on debug): it resolves at import, before any client or logger exists.\n if (plugin && !legacyPluginWarned) {\n legacyPluginWarned = true\n console.warn(\n '[PostHog] posthog-react-native-session-replay is deprecated and no longer receives native SDK updates. ' +\n 'Replace it with @posthog/react-native-plugin.'\n )\n }\n }\n }\n\n return { plugin, version }\n}\n\nconst optionalPlugin = resolveOptionalPlugin(Platform.OS)\n\nexport const OptionalReactNativePlugin = optionalPlugin.plugin\n\n// Resolved version of the loaded native plugin. It is logged next to the replay\n// config so a stale plugin, which silently ignores newer options such as sampleRate,\n// is visible in a debug log.\nexport const OptionalReactNativePluginVersion = optionalPlugin.version\n"],"mappings":"sLAAA,IAAAA,YAAA,CAAAC,OAAA,iBAqCA,GAAI,CAAAC,kBAAkB,CAAG,KAAK,CAEvB,GAAM,CAAAC,qBAAqB,CAAAC,OAAA,CAAAD,qBAAA,CAAG,QAAxB,CAAAA,qBAAqBA,CAChCE,UAAkB,CAClBC,OAA+B,CAC0D,C,OACzF,GAAI,CAAAC,MAAoD,CACxD,GAAI,CAAAC,OAA2B,CAE/B,GAAIH,UAAU,GAAK,KAAK,CAAE,CACxB,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACG,WAAW,EAAE,CAAGR,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFO,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAV,OAAO,CAAC,2CAA2C,CAAC,UAAAU,EAAA,iBAAAA,EAAA,CAAEH,OAAO,CAClH,C,SAAQ,CAGR,CACF,C,SAAQ,CAAC,CAGT,GAAI,CAACD,MAAM,EAAIF,UAAU,GAAK,OAAO,CAAE,CACrC,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACM,UAAU,EAAE,CAAGX,OAAO,CAAC,qCAAqC,CAAC,CAC1F,C,SAAQ,CAAC,CAGT,GAAIM,MAAM,EAAI,CAACL,kBAAkB,CAAE,CACjCA,kBAAkB,CAAG,IAAI,CACzBW,OAAO,CAACC,IAAI,CACV,yGAAyG,CACvG,+CAA+C,CAClD,CACH,CACF,CACF,CAEA,MAAO,CAAEP,MAAM,CAANA,MAAM,CAAEC,OAAO,CAAPA,OAAO,CAAE,CAC5B,CAAC,CAED,GAAM,CAAAO,cAAc,CAAGZ,qBAAqB,CAACa,qBAAQ,CAACC,EAAE,CAAC,CAElD,GAAM,CAAAC,yBAAyB,CAAAd,OAAA,CAAAc,yBAAA,CAAGH,cAAc,CAACR,MAAM,CAKvD,GAAM,CAAAY,gCAAgC,CAAAf,OAAA,CAAAe,gCAAA,CAAGJ,cAAc,CAACP,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"OptionalPlugin.js","names":["_reactNative","require","legacyPluginWarned","resolveOptionalPlugin","exports","platformOS","loaders","plugin","version","loadPrimary","loadPrimaryVersion","_a","loadLegacy","console","warn","optionalPlugin","Platform","OS","OptionalReactNativePlugin","OptionalReactNativePluginVersion"],"sources":["../../src/optional/OptionalPlugin.ts"],"sourcesContent":["import { Platform } from 'react-native'\n\n// Optional native dependency; resolved at runtime via require()/try-catch below.\nimport type PostHogReactNativePlugin from '@posthog/react-native-plugin'\nimport type { PostHogPushIdentityProvider } from '../types'\n\n/**\n * `@posthog/react-native-plugin` is the primary native plugin; we fall back to\n * `posthog-react-native-session-replay` (same surface minus the newer methods)\n * when only the legacy package is installed. Optional methods are absent on\n * older plugins, so callers check availability at runtime.\n *\n * `captureFatalException` is part of `PostHogReactNativePlugin` since the version that\n * moved fatal JavaScript exceptions onto the native SDK's own queue. Older plugins do not\n * expose it, so callers check existence before use and fall back to the JS event queue.\n */\nexport type PostHogReactNativePluginExtended = typeof PostHogReactNativePlugin & {\n setup?: (sessionId: string, sdkOptions: { [key: string]: any }, pluginConfig: { [key: string]: any }) => Promise<void>\n startRecording?: (resumeCurrent: boolean) => Promise<void>\n stopRecording?: () => Promise<void>\n addExceptionStep?: (message: string, properties?: { [key: string]: any }) => Promise<void>\n registerPushNotificationToken?: (deviceToken: string, appId: string | null) => Promise<void>\n unregisterPushNotificationToken?: () => Promise<void>\n setOptOut?: (optOut: boolean) => Promise<void>\n capturePushNotificationOpened?: (properties: { [key: string]: any }) => Promise<void>\n setPushIdentityProvider?: (provider: PostHogPushIdentityProvider) => void\n reset?: (distinctId: string, anonymousId: string) => Promise<void>\n captureFatalException?: (distinctId: string, timestamp: string, properties: { [key: string]: any }) => Promise<void>\n getSessionReplayDebugProperties?: () => Promise<{ [key: string]: any }>\n markFatalExceptionHandled?: (message: string) => Promise<void>\n}\n\nexport type OptionalPluginLoaders = {\n loadPrimary: () => PostHogReactNativePluginExtended\n loadPrimaryVersion: () => string | undefined\n loadLegacy: () => PostHogReactNativePluginExtended\n}\n\nlet legacyPluginWarned = false\n\nexport const resolveOptionalPlugin = (\n platformOS: string,\n loaders?: OptionalPluginLoaders\n): { plugin: PostHogReactNativePluginExtended | undefined; version: string | undefined } => {\n let plugin: PostHogReactNativePluginExtended | undefined\n let version: string | undefined\n\n if (platformOS !== 'web') {\n try {\n plugin = loaders ? loaders.loadPrimary() : require('@posthog/react-native-plugin')\n try {\n version = loaders ? loaders.loadPrimaryVersion() : require('@posthog/react-native-plugin/package.json')?.version\n } catch {\n // Strict resolvers can reject this unexported subpath on older plugin versions.\n // Metro falls back to file-based resolution, so version logging only degrades to unknown where needed.\n }\n } catch {}\n\n // The legacy fallback is session-replay only and has no macOS support, so it's skipped on macOS.\n if (!plugin && platformOS !== 'macos') {\n try {\n plugin = loaders ? loaders.loadLegacy() : require('posthog-react-native-session-replay')\n } catch {}\n\n // Always visible (not gated on debug): it resolves at import, before any client or logger exists.\n if (plugin && !legacyPluginWarned) {\n legacyPluginWarned = true\n console.warn(\n '[PostHog] posthog-react-native-session-replay is deprecated and no longer receives native SDK updates. ' +\n 'Replace it with @posthog/react-native-plugin.'\n )\n }\n }\n }\n\n return { plugin, version }\n}\n\nconst optionalPlugin = resolveOptionalPlugin(Platform.OS)\n\nexport const OptionalReactNativePlugin = optionalPlugin.plugin\n\n// Resolved version of the loaded native plugin. It is logged next to the replay\n// config so a stale plugin, which silently ignores newer options such as sampleRate,\n// is visible in a debug log.\nexport const OptionalReactNativePluginVersion = optionalPlugin.version\n"],"mappings":"sLAAA,IAAAA,YAAA,CAAAC,OAAA,iBAsCA,GAAI,CAAAC,kBAAkB,CAAG,KAAK,CAEvB,GAAM,CAAAC,qBAAqB,CAAAC,OAAA,CAAAD,qBAAA,CAAG,QAAxB,CAAAA,qBAAqBA,CAChCE,UAAkB,CAClBC,OAA+B,CAC0D,C,OACzF,GAAI,CAAAC,MAAoD,CACxD,GAAI,CAAAC,OAA2B,CAE/B,GAAIH,UAAU,GAAK,KAAK,CAAE,CACxB,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACG,WAAW,EAAE,CAAGR,OAAO,CAAC,8BAA8B,CAAC,CAClF,GAAI,CACFO,OAAO,CAAGF,OAAO,CAAGA,OAAO,CAACI,kBAAkB,EAAE,CAAG,CAAAC,EAAA,CAAAV,OAAO,CAAC,2CAA2C,CAAC,UAAAU,EAAA,iBAAAA,EAAA,CAAEH,OAAO,CAClH,C,SAAQ,CAGR,CACF,C,SAAQ,CAAC,CAGT,GAAI,CAACD,MAAM,EAAIF,UAAU,GAAK,OAAO,CAAE,CACrC,GAAI,CACFE,MAAM,CAAGD,OAAO,CAAGA,OAAO,CAACM,UAAU,EAAE,CAAGX,OAAO,CAAC,qCAAqC,CAAC,CAC1F,C,SAAQ,CAAC,CAGT,GAAIM,MAAM,EAAI,CAACL,kBAAkB,CAAE,CACjCA,kBAAkB,CAAG,IAAI,CACzBW,OAAO,CAACC,IAAI,CACV,yGAAyG,CACvG,+CAA+C,CAClD,CACH,CACF,CACF,CAEA,MAAO,CAAEP,MAAM,CAANA,MAAM,CAAEC,OAAO,CAAPA,OAAO,CAAE,CAC5B,CAAC,CAED,GAAM,CAAAO,cAAc,CAAGZ,qBAAqB,CAACa,qBAAQ,CAACC,EAAE,CAAC,CAElD,GAAM,CAAAC,yBAAyB,CAAAd,OAAA,CAAAc,yBAAA,CAAGH,cAAc,CAACR,MAAM,CAKvD,GAAM,CAAAY,gCAAgC,CAAAf,OAAA,CAAAe,gCAAA,CAAGJ,cAAc,CAACP,OAAO","ignoreList":[]}
@@ -210,6 +210,12 @@ export declare class PostHog extends PostHogCore {
210
210
  private _sessionReplayEvalChain;
211
211
  private _nativeChain;
212
212
  private _sessionReplayOptions?;
213
+ private _nativeSessionReplayDebugProperties?;
214
+ private _nativeSessionReplayDebugRefreshQueued;
215
+ private _nativeSessionReplayDebugRefreshedAt;
216
+ private _nativeSessionReplayDebugGeneration;
217
+ private _replayDebugBundleAcceptedAt?;
218
+ private _replayDebugBundleClaimed;
213
219
  private _sessionReplayEventTriggers;
214
220
  private _eventsStoragePreloadSucceeded;
215
221
  private _fatalCaptureObservation?;
@@ -318,6 +324,13 @@ export declare class PostHog extends PostHogCore {
318
324
  [key: string]: string;
319
325
  };
320
326
  getCommonEventProperties(): PostHogEventProperties;
327
+ private _stampReplayDebugProperties;
328
+ private _sessionReplayDebugProperties;
329
+ private _pendingQueueSize;
330
+ private _refreshNativeSessionReplayDebugProperties;
331
+ private _refreshStaleNativeStatus;
332
+ private _invalidateNativeSessionReplayDebugProperties;
333
+ private _linkedFlagTriggerStatus;
321
334
  getSurveyDisplayLanguageOverride(): string | null;
322
335
  /**
323
336
  * Registers super properties that are sent with every event.
@@ -1310,15 +1323,21 @@ export declare class PostHog extends PostHogCore {
1310
1323
  * autocapture, lifecycle) passes through here. Chains to super first so `before_send` still runs;
1311
1324
  * when a surviving event's name matches an armed trigger and the session hasn't activated yet, it
1312
1325
  * activates replay for the session and kicks a re-evaluation that starts native recording. The
1313
- * trigger check never drops an event or throws into the capture path.
1326
+ * trigger check never drops an event or throws into the capture path. It also stamps the replay
1327
+ * debug keys and gates the optional bundle to one accepted eligible event per
1328
+ * REPLAY_DEBUG_PROPERTIES_INTERVAL_MS.
1314
1329
  */
1315
1330
  protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null;
1331
+ private _claimReplayDebugBundle;
1332
+ private _settleReplayDebugBundleClaim;
1316
1333
  /**
1317
1334
  * Capture a fatal exception and decide which queue owns it. The native SDK persists a
1318
1335
  * fatal `$exception` synchronously, so when it is available it takes the event and the JS
1319
1336
  * queue copy is dropped; otherwise the event stays in the JS queue as usual.
1320
1337
  */
1321
1338
  private _captureFatalAndChooseOwner;
1339
+ private _isBackdatedBeforeSession;
1340
+ private _stripDebugPropertiesIfBackdated;
1322
1341
  private _maybeActivateEventTrigger;
1323
1342
  private _parseEventTriggers;
1324
1343
  private _isEventTriggerActivatedForSession;
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHog=void 0;Object.defineProperty(exports,"PostHogPersistedProperty",{enumerable:true,get:function get(){return _core.PostHogPersistedProperty;}});var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _reactNative=require("react-native");var _core=require("@posthog/core");var _storage=require("./storage");var _surveyProgress=require("./surveys/survey-progress");var _logsDefaults=require("./logs-defaults");var _version=require("./version");var _nativeDeps=require("./native-deps");var _utils=require("./utils");var _wixNavigation=require("./frameworks/wix-navigation");var _OptionalPlugin=require("./optional/OptionalPlugin");var _errorTracking=require("./error-tracking");var _exceptionContext=require("./error-tracking/exception-context");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;}function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}function _superPropGet(t,o,e,r){var p=(0,_get2["default"])((0,_getPrototypeOf2["default"])(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t);}:p;}var nativeSessionOwner;function mapAppStateForLogs(state){if(state==='background'){return'background';}if(!state||state==='unknown'){return undefined;}return'foreground';}var NATIVE_CALL_TIMEOUT_MS=10000;var MANUAL_RECORDING_START_RETRY_DELAYS_MS=[1000,2000,4000,8000,16000];var PostHog=exports.PostHog=function(_PostHogCore){function PostHog(apiKey,options){var _this;(0,_classCallCheck2["default"])(this,PostHog);var _a;var _b,_c,_d,_e,_f;var normalizedApiKey=typeof apiKey==='string'?apiKey.trim():'';if(!normalizedApiKey){console.error('You must pass your PostHog project token. The client will be disabled.');}_this=_callSuper(this,PostHog,[normalizedApiKey,options]);_this._appProperties={};_this._sessionReplayNativeInitialized=false;_this._nativeErrorTrackingInitialized=false;_this._androidNdkCrashesUnsupportedWarned=false;_this._pushNativeInitialized=false;_this._fatalJsCaptureNativeInitialized=false;_this._pushNativeUnsupported=false;_this._sessionReplayMacOSWarned=false;_this._sessionReplayWanted=false;_this._sessionReplayStartedByApp=false;_this._sessionReplayEvalChain=Promise.resolve();_this._nativeChain=Promise.resolve();_this._sessionReplayEventTriggers=[];_this._eventsStoragePreloadSucceeded=true;_this._surveysReadyPromise=null;_this._surveysReady=false;_this._requestHeaders={};_this._surveysReadyResolve=null;_this._isInitialized=false;_this._sessionReplayWanted=(options===null||options===void 0?void 0:options.enableSessionReplay)===true&&!(0,_utils.isMacOS)();_this._persistence=(_b=options===null||options===void 0?void 0:options.persistence)!==null&&_b!==void 0?_b:'file';_this._disableSurveys=(_c=options===null||options===void 0?void 0:options.disableSurveys)!==null&&_c!==void 0?_c:false;_this._errorTracking=new _errorTracking.ErrorTracking(_this,options===null||options===void 0?void 0:options.errorTracking,_this._logger,{captureFatalException:function captureFatalException(error,hint,eventUuid,timestamp,prepareNativeCapture){return _this._captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,function(){return _this.captureExceptionInternal(error,{$exception_level:'fatal'},hint,{uuid:eventUuid,timestamp:timestamp});});},waitForJSPersist:function(){var _waitForJSPersist=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=1;return _this._initPromise;case 1:return _context.abrupt("return",_this._eventsStorage.waitForPersistSuccess());case 2:case"end":return _context.stop();}},_callee);}));function waitForJSPersist(){return _waitForJSPersist.apply(this,arguments);}return waitForJSPersist;}(),getPersistenceMode:function getPersistenceMode(){return _this._persistence||'file';},waitForStorageReady:function(){var _waitForStorageReady=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(){return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=1;return _this._initPromise;case 1:return _context2.abrupt("return",_this._eventsStoragePreloadSucceeded);case 2:case"end":return _context2.stop();}},_callee2);}));function waitForStorageReady(){return _waitForStorageReady.apply(this,arguments);}return waitForStorageReady;}(),isNativeCaptureReady:function isNativeCaptureReady(){return _this._isNativePluginInitialized();}});_this._setDefaultPersonProperties=(_d=options===null||options===void 0?void 0:options.setDefaultPersonProperties)!==null&&_d!==void 0?_d:true;_this._overrideDisplayLanguage=((_a=options===null||options===void 0?void 0:options.overrideDisplayLanguage)===null||_a===void 0?void 0:_a.trim())||null;_this._requestHeaders=(_e=options===null||options===void 0?void 0:options.requestHeaders)!==null&&_e!==void 0?_e:{};_this._appProperties=typeof(options===null||options===void 0?void 0:options.customAppProperties)==='function'?options.customAppProperties((0,_nativeDeps.getAppProperties)()):(options===null||options===void 0?void 0:options.customAppProperties)||(0,_nativeDeps.getAppProperties)();var storagePromise;var theStorage;if(_this._persistence==='file'){theStorage=(_f=options===null||options===void 0?void 0:options.customStorage)!==null&&_f!==void 0?_f:(0,_nativeDeps.buildOptimisticAsyncStorage)();}if(theStorage){_this._eventsStorage=(0,_storage.createEventsStorage)(theStorage);_this._logsStorage=(0,_storage.createLogsStorage)(theStorage);var preloads=[];if(_this._eventsStorage.preloadPromise){void _this._eventsStorage.preloadPromise["catch"](function(){_this._eventsStoragePreloadSucceeded=false;});preloads.push(['events',_this._eventsStorage.preloadPromise]);}if(_this._logsStorage.preloadPromise){preloads.push(['logs',_this._logsStorage.preloadPromise]);}if(preloads.length>0){storagePromise=(0,_core.allSettled)(preloads.map(function(_ref){var _ref2=(0,_slicedToArray2["default"])(_ref,2),p=_ref2[1];return p;})).then(function(results){results.forEach(function(r,i){if(r.status==='rejected'){_this._logger.error("PostHog ".concat(preloads[i][0]," storage preload failed:"),r.reason);}});});}}else{_this._eventsStorage=(0,_storage.createEventsMemoryStorage)();_this._logsStorage=(0,_storage.createLogsMemoryStorage)();}_this._currentAppState=mapAppStateForLogs(_reactNative.AppState.currentState);_this._resolvedLogsConfig=(0,_logsDefaults.resolveLogsConfig)(options===null||options===void 0?void 0:options.logs);_this._logs=new _core.PostHogLogs(_this,_this._resolvedLogsConfig,_this._logger,function(){var _a;var flags=_this.getFeatureFlags();var flagKeys=flags?Object.keys(flags):undefined;return{distinctId:_this.getDistinctId()||undefined,sessionId:_this.getSessionId()||undefined,screenName:((_a=_this.sessionProps)===null||_a===void 0?void 0:_a.$screen_name)||undefined,appState:_this._currentAppState,activeFeatureFlags:flagKeys&&flagKeys.length>0?flagKeys:undefined};},function(fn){return _this.wrap(fn);},function(){return _this._logsStorage.waitForPersist();});_reactNative.AppState.addEventListener('change',function(state){if(state==='unknown'){return;}var mapped=mapAppStateForLogs(state);if(mapped){_this._currentAppState=mapped;}void _this.flush()["catch"](function(){var _ref3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(err){return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context3.stop();}},_callee3);}));return function(_x3){return _ref3.apply(this,arguments);};}());var isBackgrounding=mapped==='background';var logsFlushPromise=isBackgrounding?_this._logs.flushWithTimeout(_this._resolvedLogsConfig.backgroundFlushBudgetMs):_this._logs.flush();void logsFlushPromise["catch"](function(){var _ref4=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(err){return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context4.stop();}},_callee4);}));return function(_x4){return _ref4.apply(this,arguments);};}());void _this._eventsStorage.waitForPersist();void _this._logsStorage.waitForPersist();if(state==='active'){_this.getSessionId();}});var initAfterStorage=function initAfterStorage(){var enablePersistSessionIdAcrossRestart=options===null||options===void 0?void 0:options.enablePersistSessionIdAcrossRestart;if(!enablePersistSessionIdAcrossRestart){_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionId,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionLastTimestamp,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp,null);}_this.setupBootstrap(options);if(!_this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId)){var anonId=_this.getAnonymousId();if(anonId){_this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);}}if(_this._setDefaultPersonProperties){_this._setDefaultPersonPropertiesForFlags(false);}_this._isInitialized=true;if(_this.isDisabled){return;}var cachedRemoteConfig=_this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(cachedRemoteConfig){_this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking);}_this.reloadRemoteConfigAsync().then(function(response){if(response){_this._errorTracking.onRemoteConfig(response.errorTracking);_this._handleSurveysFromRemoteConfig(response);}})["catch"](function(error){_this._logger.error('Error loading remote config:',error);})["finally"](function(){_this._notifySurveysReady();});if((options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==false){void _this.captureAppLifecycleEvents();}void _this.persistAppVersion();void _this.startSessionReplay(options,cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:undefined);_this.onFeatureFlags(function(){var _a;if(_this._isEnableSessionReplay()||((_a=_this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.pending)){void _this._evaluateAndStartSessionReplay();}});if((options===null||options===void 0?void 0:options.addTracingHeaders)&&options.addTracingHeaders.length>0){(0,_core.patchFetchForTracingHeaders)(_this,options.addTracingHeaders);}};if(storagePromise){_this._initPromise=storagePromise.then(initAfterStorage);}else{_this._initPromise=Promise.resolve();initAfterStorage();}return _this;}(0,_inherits2["default"])(PostHog,_PostHogCore);return(0,_createClass2["default"])(PostHog,[{key:"ready",value:(function(){var _ready=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(){return _regenerator["default"].wrap(function(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.next=1;return this._initPromise;case 1:case"end":return _context5.stop();}},_callee5,this);}));function ready(){return _ready.apply(this,arguments);}return ready;}())},{key:"onRemoteConfig",value:function onRemoteConfig(response){this._errorTracking.onRemoteConfig(response.errorTracking);}},{key:"_storageForKey",value:function _storageForKey(key){return key===_core.PostHogPersistedProperty.LogsQueue?this._logsStorage:this._eventsStorage;}},{key:"getPersistedProperty",value:function getPersistedProperty(key){return this._storageForKey(key).getItem(key);}},{key:"setPersistedProperty",value:function setPersistedProperty(key,value){var storage=this._storageForKey(key);if(key===_core.PostHogPersistedProperty.SurveysInProgress&&value===null){var otherProjects=(0,_surveyProgress.getOtherProjectSurveyProgress)(this);otherProjects.length?storage.setItem(key,otherProjects):storage.removeItem(key);this._events.emit('surveysReset',undefined);}else{value!==null?storage.setItem(key,value):storage.removeItem(key);}if(key===_core.PostHogPersistedProperty.PersonProperties){this._events.emit('personProperties',value);}}},{key:"flushStorage",value:(function(){var _flushStorage=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(){return _regenerator["default"].wrap(function(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=1;return this._eventsStorage.waitForPersist();case 1:case"end":return _context6.stop();}},_callee6,this);}));function flushStorage(){return _flushStorage.apply(this,arguments);}return flushStorage;}())},{key:"_shutdown",value:(function(){var _shutdown2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(){var shutdownTimeoutMs,start,remainingMs,logsBudgetMs,_remainingMs,drain,_args7=arguments;return _regenerator["default"].wrap(function(_context7){while(1)switch(_context7.prev=_context7.next){case 0:shutdownTimeoutMs=_args7.length>0&&_args7[0]!==undefined?_args7[0]:30000;this._cancelManualRecordingStart();if(nativeSessionOwner===this){nativeSessionOwner=undefined;}start=Date.now();_context7.prev=1;remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));logsBudgetMs=Math.min(remainingMs,this._resolvedLogsConfig.terminationFlushBudgetMs);_context7.next=2;return Promise.all([this._logs.shutdown(logsBudgetMs),_superPropGet(PostHog,"_shutdown",this,3)([remainingMs])]);case 2:_context7.prev=2;this._errorTracking.shutdown();_remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));drain=Promise.all([this._eventsStorage.waitForPersist(),this._logsStorage.waitForPersist()]);_context7.next=3;return(0,_core.raceWithTimeout)(drain,_remainingMs);case 3:return _context7.finish(2);case 4:case"end":return _context7.stop();}},_callee7,this,[[1,,2,4]]);}));function _shutdown(){return _shutdown2.apply(this,arguments);}return _shutdown;}())},{key:"fetch",value:function(_fetch){function fetch(_x,_x2){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(url,options){return fetch(url,options);})},{key:"getLibraryId",value:function getLibraryId(){return'posthog-react-native';}},{key:"getLibraryVersion",value:function getLibraryVersion(){return _version.version;}},{key:"getCustomUserAgent",value:function getCustomUserAgent(){if(_reactNative.Platform.OS==='web'){return'';}return"".concat(this.getLibraryId(),"/").concat(this.getLibraryVersion());}},{key:"getCustomHeaders",value:function getCustomHeaders(){return _objectSpread(_objectSpread({},_superPropGet(PostHog,"getCustomHeaders",this,3)([])),this._requestHeaders);}},{key:"getCommonEventProperties",value:function getCommonEventProperties(){var _Dimensions$get=_reactNative.Dimensions.get(_reactNative.Platform.OS==='ios'?'window':'screen'),width=_Dimensions$get.width,height=_Dimensions$get.height;return _objectSpread(_objectSpread(_objectSpread({},_superPropGet(PostHog,"getCommonEventProperties",this,3)([])),this._appProperties),{},{$screen_height:height,$screen_width:width});}},{key:"getSurveyDisplayLanguageOverride",value:function getSurveyDisplayLanguageOverride(){return this._overrideDisplayLanguage;}},{key:"register",value:function register(properties){return _superPropGet(PostHog,"register",this,3)([properties]);}},{key:"unregister",value:function unregister(property){return _superPropGet(PostHog,"unregister",this,3)([property]);}},{key:"reset",value:function reset(propertiesToKeep){var _this2=this;var effectivePropertiesToKeep=propertiesToKeep!==null&&propertiesToKeep!==void 0?propertiesToKeep:[_core.PostHogPersistedProperty.InstalledAppBuild,_core.PostHogPersistedProperty.InstalledAppVersion,_core.PostHogPersistedProperty.DeviceId];this._cancelManualRecordingStart();var wasOptedOut=this.optedOut;_superPropGet(PostHog,"reset",this,3)([[_core.PostHogPersistedProperty.RemoteConfig,_core.PostHogPersistedProperty.SessionReplay,_core.PostHogPersistedProperty.Surveys,_core.PostHogPersistedProperty.PushRegistered].concat((0,_toConsumableArray2["default"])(effectivePropertiesToKeep))]);if(this._setDefaultPersonProperties){this._setDefaultPersonPropertiesForFlags(false);}if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.reset){void this._enqueueNative('reset',function(plugin){var _a;return(_a=plugin.reset)===null||_a===void 0?void 0:_a.call(plugin,String(_this2.getDistinctId()),String(_this2.getAnonymousId()));},this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true);}if(this._isInitialized&&wasOptedOut&&!this.optedOut&&this._sessionReplayWanted){try{this._rotateReplaySession();}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}var nativeOptIn=this._propagateNativeOptOut();if(this._isInitialized&&wasOptedOut&&!this.optedOut){void nativeOptIn.then(function(){return _this2._evaluateAndStartSessionReplay(undefined,true);})["catch"](function(){});}void this._eventsStorage.waitForPersist();}},{key:"_setDefaultPersonPropertiesForFlags",value:function _setDefaultPersonPropertiesForFlags(){var _this3=this;var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var defaultProps={};var relevantKeys=['$app_version','$app_build','$app_namespace','$os_name','$os_version','$device_type'];relevantKeys.forEach(function(key){var value=_this3._appProperties[key];if(value!==null&&value!==undefined){defaultProps[key]=value;}});var commonProps=this.getCommonEventProperties();if(commonProps.$lib){defaultProps.$lib=commonProps.$lib;}if(commonProps.$lib_version){defaultProps.$lib_version=commonProps.$lib_version;}if(Object.keys(defaultProps).length>0){this.setPersonPropertiesForFlags(defaultProps,reloadFeatureFlags);}}},{key:"flush",value:function flush(){return _superPropGet(PostHog,"flush",this,3)([]);}},{key:"captureLog",value:function captureLog(options){this._logs.captureLog(options);}},{key:"flushLogs",value:function flushLogs(){return this._logs.flush();}},{key:"logger",get:function get(){var _this4=this;if(!this._captureLogger){this._captureLogger={trace:function trace(body,attributes){return _this4.captureLog({body:body,level:'trace',attributes:attributes});},debug:function debug(body,attributes){return _this4.captureLog({body:body,level:'debug',attributes:attributes});},info:function info(body,attributes){return _this4.captureLog({body:body,level:'info',attributes:attributes});},warn:function warn(body,attributes){return _this4.captureLog({body:body,level:'warn',attributes:attributes});},error:function error(body,attributes){return _this4.captureLog({body:body,level:'error',attributes:attributes});},fatal:function fatal(body,attributes){return _this4.captureLog({body:body,level:'fatal',attributes:attributes});}};}return this._captureLogger;}},{key:"optIn",value:function optIn(){var _this5=this;var wasOptedOut=this.optedOut;var result=_superPropGet(PostHog,"optIn",this,3)([]);void this._eventsStorage.waitForPersist();if(this._isInitialized&&wasOptedOut&&!this.optedOut&&this._sessionReplayWanted){try{this._rotateReplaySession();}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}var nativeOptIn=this._propagateNativeOptOut();if(this._isInitialized&&wasOptedOut){var replay=Promise.all([result,nativeOptIn]).then(function(){return _this5._evaluateAndStartSessionReplay(undefined,true);})["catch"](function(){});return Promise.all([result,replay]).then(function(){return undefined;});}return result;}},{key:"optOut",value:function optOut(){var _this6=this;this._cancelManualRecordingStart();var coreOptOut=_superPropGet(PostHog,"optOut",this,3)([]);this._sessionReplayStartedByApp=false;var replayStop=this._isInitialized?coreOptOut.then(function(){return _this6._evaluateAndStartSessionReplay();})["catch"](function(){}):Promise.resolve();var persistOptOut=function persistOptOut(){_this6.setPersistedProperty(_core.PostHogPersistedProperty.SurveysInProgress,null);return _this6._eventsStorage.waitForPersist();};var result=Promise.all([coreOptOut,replayStop,this._isInitialized?persistOptOut():this._initPromise.then(persistOptOut)]).then(function(){return undefined;});if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.unregisterPushNotificationToken){void this.unregisterPushNotificationToken();}this._propagateNativeOptOut();return result;}},{key:"_propagateNativeOptOut",value:function _propagateNativeOptOut(){var _this7=this;if(!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.setOptOut)){return Promise.resolve();}var sent=this._enqueueNative('setOptOut',function(plugin){var _a;return(_a=plugin.setOptOut)===null||_a===void 0?void 0:_a.call(plugin,_this7.optedOut);});if(this._isPushNativeEnabled(this._sessionReplayOptions)){void this._ensureNativeInitialized();}return sent;}},{key:"isFeatureEnabled",value:function isFeatureEnabled(key,options){return _superPropGet(PostHog,"isFeatureEnabled",this,3)([key,options]);}},{key:"getFeatureFlag",value:function getFeatureFlag(key,options){return _superPropGet(PostHog,"getFeatureFlag",this,3)([key,options]);}},{key:"getFeatureFlagPayload",value:function getFeatureFlagPayload(key){return _superPropGet(PostHog,"getFeatureFlagPayload",this,3)([key]);}},{key:"reloadFeatureFlags",value:function reloadFeatureFlags(){_superPropGet(PostHog,"reloadFeatureFlags",this,3)([]);}},{key:"reloadFeatureFlagsAsync",value:function reloadFeatureFlagsAsync(){return _superPropGet(PostHog,"reloadFeatureFlagsAsync",this,3)([]);}},{key:"updateFlags",value:function updateFlags(flags,payloads,options){_superPropGet(PostHog,"updateFlags",this,3)([flags,payloads,options]);}},{key:"group",value:function group(groupType,groupKey,properties){_superPropGet(PostHog,"group",this,3)([groupType,groupKey,properties]);if(properties&&Object.keys(properties).length>0){var propsToCache={};Object.keys(properties).forEach(function(key){var value=properties[key];if(value!==null&&value!==undefined){propsToCache[key]=value;}});if(Object.keys(propsToCache).length>0){this.setGroupPropertiesForFlags((0,_defineProperty2["default"])({},groupType,propsToCache));}}}},{key:"alias",value:function alias(_alias){_superPropGet(PostHog,"alias",this,3)([_alias]);}},{key:"getDistinctId",value:function getDistinctId(){return _superPropGet(PostHog,"getDistinctId",this,3)([]);}},{key:"getDeviceId",value:function getDeviceId(){var deviceId=this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId);if(!deviceId){var anonId=this.getAnonymousId();if(anonId){this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);return anonId;}return'';}return deviceId;}},{key:"setPersonPropertiesForFlags",value:function setPersonPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setPersonPropertiesForFlags",this,3)([properties,reloadFeatureFlags]);}},{key:"resetPersonPropertiesForFlags",value:function resetPersonPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetPersonPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"setGroupPropertiesForFlags",value:function setGroupPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setGroupPropertiesForFlags",this,3)([properties]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"resetGroupPropertiesForFlags",value:function resetGroupPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetGroupPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"screen",value:(function(){var _screen=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8(name,properties,options){return _regenerator["default"].wrap(function(_context8){while(1)switch(_context8.prev=_context8.next){case 0:if(this._isInitialized){_context8.next=1;break;}_context8.next=1;return this._initPromise;case 1:this.registerForSession({$screen_name:name});return _context8.abrupt("return",this.capture('$screen',_objectSpread(_objectSpread({},properties),{},{$screen_name:name}),options));case 2:case"end":return _context8.stop();}},_callee8,this);}));function screen(_x5,_x6,_x7){return _screen.apply(this,arguments);}return screen;}())},{key:"_isEnableSessionReplay",value:function _isEnableSessionReplay(){var _a;return!this.isDisabled&&!(0,_utils.isMacOS)()&&((_a=this._enableSessionReplay)!==null&&_a!==void 0?_a:false);}},{key:"_isNativeSessionOwner",value:function _isNativeSessionOwner(){return nativeSessionOwner===undefined||nativeSessionOwner===this;}},{key:"_isSameProjectAs",value:function _isSameProjectAs(other){return other.apiKey===this.apiKey&&other.host===this.host;}},{key:"_canTakeOverNativeSession",value:function _canTakeOverNativeSession(owner){return!this._isNativePluginInitialized()&&this._isSameProjectAs(owner);}},{key:"_resetSessionId",value:function _resetSessionId(reactNativeSessionReplay,sessionId){if(reactNativeSessionReplay&&this._isNativeSessionOwner()){reactNativeSessionReplay.endSession();reactNativeSessionReplay.startSession(sessionId);}}},{key:"getSessionId",value:function getSessionId(){var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!this._isEnableSessionReplay()&&!this._isNativePluginInitialized()){return sessionId;}if(sessionId.length>0&&this._currentSessionId&&sessionId!==this._currentSessionId){if(_OptionalPlugin.OptionalReactNativePlugin){try{this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));this._logger.info("sessionId rotated from ".concat(this._currentSessionId," to ").concat(sessionId,"."));}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}this._currentSessionId=sessionId;if(this._sessionReplayEventTriggers.length>0){void this._evaluateAndStartSessionReplay();}}else{this._logger.info("sessionId not rotated, sessionId ".concat(sessionId," and currentSessionId ").concat(this._currentSessionId,"."));}return sessionId;}},{key:"resetSessionId",value:function resetSessionId(){_superPropGet(PostHog,"resetSessionId",this,3)([]);if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin&&this._isNativeSessionOwner()){try{_OptionalPlugin.OptionalReactNativePlugin.endSession();this._logger.info("Native PostHog session ended.");}catch(e){this._logger.error("Native PostHog session failed to end: ".concat(e,"."));}}}},{key:"startSessionRecording",value:(function(){var _startSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee0(){var _this8=this;var resumeCurrent,request,_args0=arguments;return _regenerator["default"].wrap(function(_context0){while(1)switch(_context0.prev=_context0.next){case 0:resumeCurrent=_args0.length>0&&_args0[0]!==undefined?_args0[0]:true;this._cancelManualRecordingStart();if(!this.optedOut&&!(0,_utils.isMacOS)()){this._sessionReplayWanted=true;}request={pending:false,retryCount:0};this._manualRecordingStartRequest=request;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(){return _regenerator["default"].wrap(function(_context9){while(1)switch(_context9.prev=_context9.next){case 0:_context9.next=1;return _this8._attemptManualRecordingStart(request,resumeCurrent);case 1:case"end":return _context9.stop();}},_callee9);})));_context0.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context0.stop();}},_callee0,this);}));function startSessionRecording(){return _startSessionRecording2.apply(this,arguments);}return startSessionRecording;}())},{key:"_cancelManualRecordingStart",value:function _cancelManualRecordingStart(){var _a;clearTimeout((_a=this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.timer);this._manualRecordingStartRequest=undefined;}},{key:"_attemptManualRecordingStart",value:function(){var _attemptManualRecordingStart2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee1(request,resumeCurrent){var started;return _regenerator["default"].wrap(function(_context1){while(1)switch(_context1.prev=_context1.next){case 0:if(!(this._manualRecordingStartRequest!==request)){_context1.next=1;break;}return _context1.abrupt("return",false);case 1:if(!(this.isDisabled||this.optedOut)){_context1.next=2;break;}this._cancelManualRecordingStart();return _context1.abrupt("return",false);case 2:if(!(request.awaitEventTrigger&&this._sessionReplayEventTriggers.length>0&&!this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([])))){_context1.next=4;break;}request.pending=true;if(!this._sessionReplayNativeInitialized){_context1.next=3;break;}_context1.next=3;return this._stopSessionRecording();case 3:return _context1.abrupt("return",false);case 4:this._sessionReplayStartedByApp=true;_context1.next=5;return this._startSessionRecording(resumeCurrent);case 5:started=_context1.sent;if(!(this._manualRecordingStartRequest!==request)){_context1.next=7;break;}if(!started){_context1.next=6;break;}_context1.next=6;return this._stopSessionRecording();case 6:return _context1.abrupt("return",false);case 7:if(started){this._cancelManualRecordingStart();}else{request.pending=true;this._scheduleManualRecordingStartRetry(request);}return _context1.abrupt("return",started);case 8:case"end":return _context1.stop();}},_callee1,this);}));function _attemptManualRecordingStart(_x8,_x9){return _attemptManualRecordingStart2.apply(this,arguments);}return _attemptManualRecordingStart;}()},{key:"_scheduleManualRecordingStartRetry",value:function _scheduleManualRecordingStartRetry(request){var _this9=this;var delay=MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount];if(request.timer!==undefined||delay===undefined||!this._sessionReplayNativeInitialized||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.startRecording)){return;}request.retryCount++;request.timer=(0,_core.safeSetTimeout)(function(){request.timer=undefined;_this9._sessionReplayEvalChain=_this9._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(){return _regenerator["default"].wrap(function(_context10){while(1)switch(_context10.prev=_context10.next){case 0:_context10.next=1;return _this9._attemptManualRecordingStart(request,true);case 1:case"end":return _context10.stop();}},_callee10);})));},delay);}},{key:"_rotateReplaySession",value:function _rotateReplaySession(){if(!_OptionalPlugin.OptionalReactNativePlugin){return;}_superPropGet(PostHog,"resetSessionId",this,3)([]);var newSessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(newSessionId));this._currentSessionId=newSessionId;}},{key:"_startSessionRecording",value:function(){var _startSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(resumeCurrent){var _this0=this;var initialized,started,_t;return _regenerator["default"].wrap(function(_context11){while(1)switch(_context11.prev=_context11.next){case 0:_context11.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context11.next=2;break;}return _context11.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context11.next=3;break;}return _context11.abrupt("return",false);case 3:_context11.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.startRecording){_context11.next=4;break;}this._logger.warn('startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context11.abrupt("return",false);case 4:if(this._sessionReplayNativeInitialized){_context11.next=6;break;}this._logger.info('Native session replay SDK not initialized, initializing now...');_context11.next=5;return this.initializeNativePlugin(this._sessionReplayOptions,undefined,true);case 5:initialized=_context11.sent;if(initialized){_context11.next=6;break;}this._logger.error('Failed to initialize native session replay SDK.');return _context11.abrupt("return",false);case 6:if(!resumeCurrent){this._rotateReplaySession();}_context11.next=7;return _OptionalPlugin.OptionalReactNativePlugin.startRecording(resumeCurrent);case 7:_context11.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(e){_this0._logger.warn("Failed to confirm the session recording started: ".concat(e));return true;});case 8:started=_context11.sent;if(started){_context11.next=9;break;}this._logger.warn('The native SDK refused to start session recording, usually because its remote config is not loaded yet. '+'PostHog retries on the next feature flags load.');return _context11.abrupt("return",false);case 9:this._logger.info("Session recording ".concat(resumeCurrent?'resumed':'started',"."));return _context11.abrupt("return",true);case 10:_context11.prev=10;_t=_context11["catch"](3);this._logger.error("Failed to start session recording: ".concat(_t));return _context11.abrupt("return",false);case 11:case"end":return _context11.stop();}},_callee11,this,[[3,10]]);}));function _startSessionRecording(_x0){return _startSessionRecording3.apply(this,arguments);}return _startSessionRecording;}()},{key:"stopSessionRecording",value:(function(){var _stopSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(){var _this1=this;return _regenerator["default"].wrap(function(_context13){while(1)switch(_context13.prev=_context13.next){case 0:this._cancelManualRecordingStart();this._sessionReplayStartedByApp=false;if(!this.optedOut){this._sessionReplayWanted=false;}this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(){return _regenerator["default"].wrap(function(_context12){while(1)switch(_context12.prev=_context12.next){case 0:_context12.next=1;return _this1._stopSessionRecording(true);case 1:case"end":return _context12.stop();}},_callee12);})));_context13.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context13.stop();}},_callee13,this);}));function stopSessionRecording(){return _stopSessionRecording2.apply(this,arguments);}return stopSessionRecording;}())},{key:"_stopSessionRecording",value:function(){var _stopSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(){var byApp,_args14=arguments,_t2;return _regenerator["default"].wrap(function(_context14){while(1)switch(_context14.prev=_context14.next){case 0:byApp=_args14.length>0&&_args14[0]!==undefined?_args14[0]:false;_context14.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context14.next=2;break;}return _context14.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context14.next=3;break;}return _context14.abrupt("return",false);case 3:_context14.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.stopRecording){_context14.next=4;break;}this._logger.warn('stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context14.abrupt("return",false);case 4:if(!(!this._isNativeSessionOwner()&&!(byApp&&nativeSessionOwner&&this._isSameProjectAs(nativeSessionOwner)))){_context14.next=5;break;}this._logger.info('Session recording belongs to another PostHog client.');return _context14.abrupt("return",false);case 5:_context14.next=6;return _OptionalPlugin.OptionalReactNativePlugin.stopRecording();case 6:this._logger.info('Session recording stopped.');return _context14.abrupt("return",true);case 7:_context14.prev=7;_t2=_context14["catch"](3);this._logger.error("Failed to stop session recording: ".concat(_t2));return _context14.abrupt("return",false);case 8:case"end":return _context14.stop();}},_callee14,this,[[3,7]]);}));function _stopSessionRecording(){return _stopSessionRecording3.apply(this,arguments);}return _stopSessionRecording;}()},{key:"isSessionReplayActive",value:(function(){var _isSessionReplayActive=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(){var _t3;return _regenerator["default"].wrap(function(_context15){while(1)switch(_context15.prev=_context15.next){case 0:_context15.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context15.next=2;break;}return _context15.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context15.next=3;break;}return _context15.abrupt("return",false);case 3:if(!(nativeSessionOwner&&nativeSessionOwner!==this&&!this._isSameProjectAs(nativeSessionOwner))){_context15.next=4;break;}return _context15.abrupt("return",false);case 4:_context15.prev=4;_context15.next=5;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 5:return _context15.abrupt("return",_context15.sent);case 6:_context15.prev=6;_t3=_context15["catch"](4);this._logger.error("Failed to check session replay status: ".concat(_t3));return _context15.abrupt("return",false);case 7:case"end":return _context15.stop();}},_callee15,this,[[4,6]]);}));function isSessionReplayActive(){return _isSessionReplayActive.apply(this,arguments);}return isSessionReplayActive;}())},{key:"identify",value:function identify(distinctId,properties,options){var _this10=this;var previousDistinctId=this.getDistinctId();var userProps=(properties===null||properties===void 0?void 0:properties.$set)||properties;var userPropsOnce=properties===null||properties===void 0?void 0:properties.$set_once;_superPropGet(PostHog,"identify",this,3)([distinctId,properties,options]);var propsToCache={};if(userProps&&(0,_typeof2["default"])(userProps)==='object'&&!Array.isArray(userProps)){Object.entries(userProps).forEach(function(_ref8){var _ref9=(0,_slicedToArray2["default"])(_ref8,2),key=_ref9[0],value=_ref9[1];if(value!==null&&value!==undefined){propsToCache[key]=value;}});}var propsOnceToCache={};if(userPropsOnce&&(0,_typeof2["default"])(userPropsOnce)==='object'&&!Array.isArray(userPropsOnce)){Object.entries(userPropsOnce).forEach(function(_ref0){var _ref1=(0,_slicedToArray2["default"])(_ref0,2),key=_ref1[0],value=_ref1[1];if(value!==null&&value!==undefined){propsOnceToCache[key]=value;}});}if(Object.keys(propsToCache).length>0||Object.keys(propsOnceToCache).length>0){this.setPersonPropertiesForFlags(_objectSpread({$set:propsToCache},Object.keys(propsOnceToCache).length>0?{$set_once:propsOnceToCache}:{}),false);}if(_OptionalPlugin.OptionalReactNativePlugin){void this._enqueueNative('identify',function(plugin){var nativeDistinctId=String(_this10.getDistinctId()||previousDistinctId);var anonymousId=String(_this10.getAnonymousId());var identified=plugin.identify(nativeDistinctId,anonymousId);_this10._logger.info("Native PostHog identified with distinctId ".concat(nativeDistinctId," and anonymousId ").concat(anonymousId,"."));return identified;});}void this._eventsStorage.waitForPersist();}},{key:"captureException",value:function captureException(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var _a;try{var result=this.captureExceptionInternal(error,additionalProperties,hint);if(((_a=result===null||result===void 0?void 0:result.additionalProperties)===null||_a===void 0?void 0:_a.$exception_level)==='fatal'){void this._eventsStorage.waitForPersist();void this._logsStorage.waitForPersist();}}catch(e){this._logger.error('Error while capturing $exception:',e);}}},{key:"captureExceptionInternal",value:function captureExceptionInternal(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var options=arguments.length>3?arguments[3]:undefined;var _a,_b;var resolvedHint=hint!==null&&hint!==void 0?hint:{mechanism:{handled:true,type:'generic'},syntheticException:new Error('Synthetic Error')};var merged=_objectSpread(_objectSpread({},(0,_exceptionContext.getExceptionContext)()),additionalProperties);var finalAdditional=this._errorTracking.attachExceptionSteps(merged);var captureOptions=_objectSpread(_objectSpread({},options||{}),{},{_originatedFromCaptureException:true});this.capture('$exception',_objectSpread(_objectSpread({},this.buildExceptionProperties(error,resolvedHint)),finalAdditional),captureOptions);var eventUuid=(_a=captureOptions.uuid)!==null&&_a!==void 0?_a:'';var timestamp=((_b=captureOptions.timestamp)!==null&&_b!==void 0?_b:new Date()).toISOString();return{eventUuid:eventUuid,timestamp:timestamp,additionalProperties:finalAdditional};}},{key:"buildExceptionProperties",value:function buildExceptionProperties(error,hint){try{var builder=this.getErrorPropertiesBuilder();var exceptionProperties=builder.buildFromUnknown(error,hint);return exceptionProperties;}catch(e){this._logger.error('Error while building exception properties:',e);return{};}}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){this._errorTracking.addExceptionStep(message,properties);}},{key:"createErrorPropertiesBuilder",value:function createErrorPropertiesBuilder(){return new _core.ErrorTracking.ErrorPropertiesBuilder([new _core.ErrorTracking.PromiseRejectionEventCoercer(),new _core.ErrorTracking.ErrorCoercer(),new _core.ErrorTracking.ErrorEventCoercer(),new _core.ErrorTracking.ObjectCoercer(),new _core.ErrorTracking.StringCoercer(),new _core.ErrorTracking.PrimitiveCoercer()],_core.ErrorTracking.createStackParser((0,_utils.isHermes)()?'hermes':'web:javascript',_core.ErrorTracking.chromeStackLineParser,_core.ErrorTracking.geckoStackLineParser));}},{key:"initReactNativeNavigation",value:function initReactNativeNavigation(options){return(0,_wixNavigation.withReactNativeNavigation)(this,options);}},{key:"createPersonProfile",value:function createPersonProfile(){_superPropGet(PostHog,"createPersonProfile",this,3)([]);}},{key:"setPersonProperties",value:function setPersonProperties(userPropertiesToSet,userPropertiesToSetOnce){var reloadFeatureFlags=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;_superPropGet(PostHog,"setPersonProperties",this,3)([userPropertiesToSet,userPropertiesToSetOnce,reloadFeatureFlags]);}},{key:"unsetPersonProperties",value:function unsetPersonProperties(propertyNames){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"unsetPersonProperties",this,3)([propertyNames,reloadFeatureFlags]);}},{key:"getSurveys",value:function(){var _getSurveys=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16(){var surveys;return _regenerator["default"].wrap(function(_context16){while(1)switch(_context16.prev=_context16.next){case 0:if(!(this._disableSurveys===true)){_context16.next=1;break;}this._logger.info('Loading surveys is disabled.');this._cacheSurveys(null,'disabled in config');return _context16.abrupt("return",[]);case 1:surveys=this.getPersistedProperty(_core.PostHogPersistedProperty.Surveys);if(!(surveys&&surveys.length>0)){_context16.next=2;break;}this._logger.info('Surveys fetched from storage: ',JSON.stringify(surveys));return _context16.abrupt("return",surveys);case 2:this._logger.info('No surveys found in storage');return _context16.abrupt("return",[]);case 3:case"end":return _context16.stop();}},_callee16,this);}));function getSurveys(){return _getSurveys.apply(this,arguments);}return getSurveys;}()},{key:"_onSurveysReady",value:function _onSurveysReady(){var _this11=this;if(this._surveysReady){return Promise.resolve();}if(!this._surveysReadyPromise){this._surveysReadyPromise=new Promise(function(resolve){_this11._surveysReadyResolve=resolve;});}return this._surveysReadyPromise;}},{key:"_cacheSurveys",value:function _cacheSurveys(surveys,source){this.setPersistedProperty(_core.PostHogPersistedProperty.Surveys,surveys);if(surveys&&surveys.length>0){this._logger.info("Surveys cached from ".concat(source,":"),JSON.stringify(surveys));}else if(surveys===null){this._logger.info("Surveys cleared (".concat(source,")"));}else{this._logger.info("No surveys to cache from ".concat(source,")"));}}},{key:"_notifySurveysReady",value:function _notifySurveysReady(){this._surveysReady=true;if(this._surveysReadyResolve){this._surveysReadyResolve();this._surveysReadyResolve=null;this._surveysReadyPromise=null;}}},{key:"_handleSurveysFromRemoteConfig",value:function _handleSurveysFromRemoteConfig(response){if(this._disableSurveys===true){this._logger.info('Loading surveys skipped, disabled.');this._cacheSurveys(null,'remote config (disabled)');return;}var surveys=response.surveys;if(Array.isArray(surveys)){this._cacheSurveys(surveys,'remote config');}else{this._cacheSurveys(null,'remote config');}}},{key:"registerPushNotificationToken",value:(function(){var _registerPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee17(deviceToken,options){var _this12=this;return _regenerator["default"].wrap(function(_context17){while(1)switch(_context17.prev=_context17.next){case 0:return _context17.abrupt("return",this._callPushPlugin('registerPushNotificationToken',{allowMacOS:false,requireInit:true,noop:'token not registered'},function(plugin){var _a;var _b;_this12.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,true);return(_a=plugin.registerPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin,deviceToken,(_b=options===null||options===void 0?void 0:options.appId)!==null&&_b!==void 0?_b:null);}));case 1:case"end":return _context17.stop();}},_callee17,this);}));function registerPushNotificationToken(_x1,_x10){return _registerPushNotificationToken.apply(this,arguments);}return registerPushNotificationToken;}())},{key:"unregisterPushNotificationToken",value:(function(){var _unregisterPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee18(){var _this13=this;return _regenerator["default"].wrap(function(_context18){while(1)switch(_context18.prev=_context18.next){case 0:return _context18.abrupt("return",this._callPushPlugin('unregisterPushNotificationToken',{allowMacOS:false,allowWhenOptedOut:true,requireInit:this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true,noop:'nothing to unregister'},function(plugin){var _a;_this13.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,null);return(_a=plugin.unregisterPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin);}));case 1:case"end":return _context18.stop();}},_callee18,this);}));function unregisterPushNotificationToken(){return _unregisterPushNotificationToken.apply(this,arguments);}return unregisterPushNotificationToken;}())},{key:"capturePushNotificationOpened",value:(function(){var _capturePushNotificationOpened=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee19(options){var properties,_i,_arr,key;return _regenerator["default"].wrap(function(_context19){while(1)switch(_context19.prev=_context19.next){case 0:properties={};for(_i=0,_arr=['title','subtitle','body','payload','action'];_i<_arr.length;_i++){key=_arr[_i];if(options[key]!==undefined){properties[key]=options[key];}}return _context19.abrupt("return",this._callPushPlugin('capturePushNotificationOpened',{allowMacOS:true,requireInit:true,noop:'event not captured'},function(plugin){var _a;return(_a=plugin.capturePushNotificationOpened)===null||_a===void 0?void 0:_a.call(plugin,properties);}));case 1:case"end":return _context19.stop();}},_callee19,this);}));function capturePushNotificationOpened(_x11){return _capturePushNotificationOpened.apply(this,arguments);}return capturePushNotificationOpened;}())},{key:"_callPushPlugin",value:function(){var _callPushPlugin2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee20(method,behavior,invoke){var _this14=this;return _regenerator["default"].wrap(function(_context20){while(1)switch(_context20.prev=_context20.next){case 0:if(!this.isDisabled){_context20.next=1;break;}return _context20.abrupt("return");case 1:if(!(this.optedOut&&!behavior.allowWhenOptedOut)){_context20.next=2;break;}this._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 2:if(!((0,_utils.isWeb)()||!behavior.allowMacOS&&(0,_utils.isMacOS)())){_context20.next=3;break;}this._logger.warn("".concat(method," is not supported on ").concat((0,_utils.isWeb)()?'web':'macOS',"; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 3:if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin[method]){_context20.next=4;break;}this._logger.warn("".concat(method," requires @posthog/react-native-plugin; install or update it."));return _context20.abrupt("return");case 4:return _context20.abrupt("return",this._enqueueNative(method,function(plugin){if(_this14.optedOut&&!behavior.allowWhenOptedOut){_this14._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return;}return invoke(plugin);},behavior.requireInit));case 5:case"end":return _context20.stop();}},_callee20,this);}));function _callPushPlugin(_x12,_x13,_x14){return _callPushPlugin2.apply(this,arguments);}return _callPushPlugin;}()},{key:"_enqueueNative",value:function _enqueueNative(label,run){var _this15=this;var requireInit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var next=this._nativeChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee21(){return _regenerator["default"].wrap(function(_context21){while(1)switch(_context21.prev=_context21.next){case 0:if(!(_this15.isDisabled||(0,_utils.isWeb)()||!_OptionalPlugin.OptionalReactNativePlugin)){_context21.next=1;break;}return _context21.abrupt("return");case 1:_context21.next=2;return _this15._initPromise["catch"](function(){});case 2:_context21.next=3;return _this15._sessionReplayEvalChain["catch"](function(){});case 3:if(_this15._isNativePluginInitialized()){_context21.next=6;break;}if(requireInit){_context21.next=4;break;}return _context21.abrupt("return");case 4:_context21.next=5;return _this15._ensureNativeInitialized();case 5:if(_this15._isNativePluginInitialized()){_context21.next=6;break;}_this15._logger.warn("".concat(label," skipped: the native plugin is not initialized."));return _context21.abrupt("return");case 6:_context21.next=7;return(0,_core.raceWithTimeout)(Promise.resolve(run(_OptionalPlugin.OptionalReactNativePlugin)),NATIVE_CALL_TIMEOUT_MS,function(){return _this15._logger.warn("Native PostHog ".concat(label," timed out after ").concat(NATIVE_CALL_TIMEOUT_MS,"ms; continuing."));});case 7:case"end":return _context21.stop();}},_callee21);})))["catch"](function(e){return _this15._logger.warn("Native PostHog ".concat(label," failed: ").concat(e,"."));});this._nativeChain=next;return next;}},{key:"_ensureNativeInitialized",value:function _ensureNativeInitialized(){var _this16=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee22(){return _regenerator["default"].wrap(function(_context22){while(1)switch(_context22.prev=_context22.next){case 0:if(_this16._isNativePluginInitialized()){_context22.next=1;break;}_context22.next=1;return _this16.initializeNativePlugin(_this16._sessionReplayOptions,undefined,false,true);case 1:case"end":return _context22.stop();}},_callee22);})));return this._sessionReplayEvalChain;}},{key:"_pluginVersionAtLeast",value:function _pluginVersionAtLeast(major,minor){var version=_OptionalPlugin.OptionalReactNativePluginVersion===null||_OptionalPlugin.OptionalReactNativePluginVersion===void 0?void 0:_OptionalPlugin.OptionalReactNativePluginVersion.match(/^(\d+)\.(\d+)\.\d+(?:\+[\w.-]+)?$/);if(!version){return false;}var _ref12=[Number(version[1]),Number(version[2])],installedMajor=_ref12[0],installedMinor=_ref12[1];return installedMajor>major||installedMajor===major&&installedMinor>=minor;}},{key:"_nativeErrorAutocapture",value:function _nativeErrorAutocapture(options){var _a;var autocapture=(_a=options===null||options===void 0?void 0:options.errorTracking)===null||_a===void 0?void 0:_a.autocapture;if(this.isDisabled||(0,_typeof2["default"])(autocapture)!=='object'){return{nativeCrashes:false,androidNdkCrashes:false};}var androidNdkCrashes=_reactNative.Platform.OS==='android'&&autocapture.androidNdkCrashes===true;if(androidNdkCrashes&&!this._pluginVersionAtLeast(2,12)){if(!this._androidNdkCrashesUnsupportedWarned){this._androidNdkCrashesUnsupportedWarned=true;this._logger.warn("errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later "+"(installed: ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',"); ignoring."));}androidNdkCrashes=false;}return{nativeCrashes:autocapture.nativeCrashes===true,androidNdkCrashes:androidNdkCrashes};}},{key:"_isAutocaptureNativeErrors",value:function _isAutocaptureNativeErrors(options){var _this$_nativeErrorAut=this._nativeErrorAutocapture(options),nativeCrashes=_this$_nativeErrorAut.nativeCrashes,androidNdkCrashes=_this$_nativeErrorAut.androidNdkCrashes;return nativeCrashes||androidNdkCrashes;}},{key:"_isFatalJsCaptureNativeEnabled",value:function _isFatalJsCaptureNativeEnabled(){if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._persistence==='memory'){return false;}return this._errorTracking.isUncaughtExceptionAutocaptureEnabled();}},{key:"_isNativePluginInitialized",value:function _isNativePluginInitialized(){return this._sessionReplayNativeInitialized||this._nativeErrorTrackingInitialized||this._pushNativeInitialized||this._fatalJsCaptureNativeInitialized;}},{key:"_isPushNativeEnabled",value:function _isPushNativeEnabled(options){var force=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._pushNativeUnsupported){return false;}return force||(options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==false||(options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==false||!!(options===null||options===void 0?void 0:options.pushIdentityProvider);}},{key:"initializeSessionReplayNative",value:(function(){var _initializeSessionReplayNative=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee23(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context23){while(1)switch(_context23.prev=_context23.next){case 0:return _context23.abrupt("return",this.initializeNativePlugin(options,cachedRemoteConfig,true));case 1:case"end":return _context23.stop();}},_callee23,this);}));function initializeSessionReplayNative(_x15,_x16){return _initializeSessionReplayNative.apply(this,arguments);}return initializeSessionReplayNative;}())},{key:"initializeNativePlugin",value:function(){var _initializeNativePlugin=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee24(options,cachedRemoteConfig){var enableSessionReplay,forcePush,_a,_b,_c,_d,_e,_f,_g,_h,_j,nativeErrorAutocapture,enableNativeErrorTracking,enablePush,enableFatalJsCapture,sessionId,defaultThrottleDelayMs,_ref13,_ref13$maskAllTextInp,maskAllTextInputs,_ref13$maskAllImages,maskAllImages,_ref13$maskAllSandbox,maskAllSandboxedViews,_ref13$captureTouches,captureTouches,_ref13$captureLog,localCaptureLog,_ref13$captureNetwork,localCaptureNetworkTelemetry,_ref13$verifyScreensh,verifyScreenshotMaskAlignment,screenshotScale,screenshotCompressionQuality,screenshotColorMode,_ref13$screenshotMode,screenshotModeBackgroundCapture,localSampleRate,_ref13$iOSdebouncerDe,iOSdebouncerDelayMs,_ref13$androidDebounc,androidDebouncerDelayMs,throttleDelayMs,remoteConsoleLogEnabled,remoteNetworkTimingEnabled,remoteSampleRateRaw,captureLog,captureNetworkTelemetry,localSampleRateValid,remoteSampleRateValid,sampleRate,source,sdkReplayConfig,sessionReplay,cachedSessionReplayConfig,pushOnlyInit,sdkOptions,loggableSdkOptions,wasSessionReplayEnabled,pushIdentityProviderEnabled,pluginConfig,_args24=arguments,_t4,_t5;return _regenerator["default"].wrap(function(_context24){while(1)switch(_context24.prev=_context24.next){case 0:enableSessionReplay=_args24.length>2&&_args24[2]!==undefined?_args24[2]:this._isEnableSessionReplay();forcePush=_args24.length>3&&_args24[3]!==undefined?_args24[3]:false;nativeErrorAutocapture=this._nativeErrorAutocapture(options);enableNativeErrorTracking=nativeErrorAutocapture.nativeCrashes||nativeErrorAutocapture.androidNdkCrashes;enablePush=this._isPushNativeEnabled(options,forcePush);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();if(enableSessionReplay&&(0,_utils.isMacOS)()){if(!this._sessionReplayMacOSWarned){this._sessionReplayMacOSWarned=true;this._logger.warn('Session replay is not supported on macOS; ignoring.');}enableSessionReplay=false;}if(!(!enableSessionReplay&&!enableNativeErrorTracking&&!enablePush&&!enableFatalJsCapture)){_context24.next=1;break;}return _context24.abrupt("return",true);case 1:if(_OptionalPlugin.OptionalReactNativePlugin){_context24.next=2;break;}if(enableSessionReplay||enableNativeErrorTracking){this._logger.warn(enableSessionReplay?'Session replay enabled but not installed.':'Native error tracking enabled but not installed.');}this._pushNativeUnsupported=true;return _context24.abrupt("return",false);case 2:if(!((!enableSessionReplay||this._sessionReplayNativeInitialized)&&(!enableNativeErrorTracking||this._nativeErrorTrackingInitialized)&&(!enablePush||this._pushNativeInitialized)&&(!enableFatalJsCapture||this._fatalJsCaptureNativeInitialized))){_context24.next=3;break;}return _context24.abrupt("return",true);case 3:if(!(this._isNativePluginInitialized()&&enableSessionReplay&&!this._sessionReplayNativeInitialized)){_context24.next=5;break;}this._sessionReplayNativeInitialized=true;_context24.next=4;return(_a=_OptionalPlugin.OptionalReactNativePlugin.startRecording)===null||_a===void 0?void 0:_a.call(_OptionalPlugin.OptionalReactNativePlugin,true);case 4:return _context24.abrupt("return",true);case 5:sessionId=this.getSessionId();if(!(sessionId.length===0)){_context24.next=6;break;}this._logger.warn("Native PostHog plugin enabled but no sessionId found.");return _context24.abrupt("return",false);case 6:defaultThrottleDelayMs=1000;_ref13=(_d=options===null||options===void 0?void 0:options.sessionReplayConfig)!==null&&_d!==void 0?_d:{},_ref13$maskAllTextInp=_ref13.maskAllTextInputs,maskAllTextInputs=_ref13$maskAllTextInp===void 0?true:_ref13$maskAllTextInp,_ref13$maskAllImages=_ref13.maskAllImages,maskAllImages=_ref13$maskAllImages===void 0?true:_ref13$maskAllImages,_ref13$maskAllSandbox=_ref13.maskAllSandboxedViews,maskAllSandboxedViews=_ref13$maskAllSandbox===void 0?true:_ref13$maskAllSandbox,_ref13$captureTouches=_ref13.captureTouches,captureTouches=_ref13$captureTouches===void 0?true:_ref13$captureTouches,_ref13$captureLog=_ref13.captureLog,localCaptureLog=_ref13$captureLog===void 0?true:_ref13$captureLog,_ref13$captureNetwork=_ref13.captureNetworkTelemetry,localCaptureNetworkTelemetry=_ref13$captureNetwork===void 0?true:_ref13$captureNetwork,_ref13$verifyScreensh=_ref13.verifyScreenshotMaskAlignment,verifyScreenshotMaskAlignment=_ref13$verifyScreensh===void 0?false:_ref13$verifyScreensh,screenshotScale=_ref13.screenshotScale,screenshotCompressionQuality=_ref13.screenshotCompressionQuality,screenshotColorMode=_ref13.screenshotColorMode,_ref13$screenshotMode=_ref13.screenshotModeBackgroundCapture,screenshotModeBackgroundCapture=_ref13$screenshotMode===void 0?false:_ref13$screenshotMode,localSampleRate=_ref13.sampleRate,_ref13$iOSdebouncerDe=_ref13.iOSdebouncerDelayMs,iOSdebouncerDelayMs=_ref13$iOSdebouncerDe===void 0?defaultThrottleDelayMs:_ref13$iOSdebouncerDe,_ref13$androidDebounc=_ref13.androidDebouncerDelayMs,androidDebouncerDelayMs=_ref13$androidDebounc===void 0?defaultThrottleDelayMs:_ref13$androidDebounc;if(captureTouches===false&&!(0,_utils.isMacOS)()){if(!this._pluginVersionAtLeast(2,9)){this._logger.warn("sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. "+"The installed plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") may still record touch coordinates. ")+"Upgrade the plugin and rebuild your app before relying on this setting.");}}throttleDelayMs=(_e=(_b=options===null||options===void 0?void 0:options.sessionReplayConfig)===null||_b===void 0?void 0:_b.throttleDelayMs)!==null&&_e!==void 0?_e:defaultThrottleDelayMs;if(throttleDelayMs===defaultThrottleDelayMs&&(iOSdebouncerDelayMs!==defaultThrottleDelayMs||androidDebouncerDelayMs!==defaultThrottleDelayMs)){throttleDelayMs=Math.max(iOSdebouncerDelayMs,androidDebouncerDelayMs);}remoteConsoleLogEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'consoleLogRecordingEnabled',true);remoteNetworkTimingEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.capturePerformance,'network_timing',true);remoteSampleRateRaw=(0,_utils.getRemoteConfigNumber)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'sampleRate');captureLog=localCaptureLog&&remoteConsoleLogEnabled;captureNetworkTelemetry=localCaptureNetworkTelemetry&&remoteNetworkTimingEnabled;localSampleRateValid=localSampleRate===undefined?undefined:(0,_utils.isValidSampleRate)(localSampleRate)?localSampleRate:undefined;remoteSampleRateValid=remoteSampleRateRaw===undefined?undefined:(0,_utils.isValidSampleRate)(remoteSampleRateRaw)?remoteSampleRateRaw:undefined;sampleRate=localSampleRateValid!==null&&localSampleRateValid!==void 0?localSampleRateValid:remoteSampleRateValid;if(localCaptureLog&&!remoteConsoleLogEnabled){this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).');}if(localCaptureNetworkTelemetry&&!remoteNetworkTimingEnabled){this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).');}if(localSampleRate!==undefined&&localSampleRateValid===undefined){this._logger.warn("Ignoring invalid sessionReplayConfig.sampleRate '".concat(localSampleRate,"'. Expected a number between 0 and 1."));}if(remoteSampleRateRaw!==undefined&&remoteSampleRateValid===undefined){this._logger.warn("Ignoring invalid remote config sessionRecording.sampleRate '".concat(remoteSampleRateRaw,"'. Expected a number between 0 and 1."));}if(localSampleRateValid!==undefined&&remoteSampleRateValid!==undefined){this._logger.warn("Local sessionReplayConfig.sampleRate (".concat(localSampleRateValid,") overrides the remote sampleRate ")+"(".concat(remoteSampleRateValid,"). The project setting is ignored while the local option is set. ")+"Remove sessionReplayConfig.sampleRate to follow the project setting.");}else if(typeof sampleRate==='number'){source=localSampleRateValid!==undefined?'local config':'remote config';this._logger.info("sampleRate set from ".concat(source," (").concat(sampleRate,")."));}else if(cachedRemoteConfig===undefined){this._logger.warn('Session replay starts with no sampleRate because no remote config is cached yet. '+'Any project sample rate applies from the next launch.');}sdkReplayConfig=_objectSpread(_objectSpread(_objectSpread(_objectSpread({maskAllTextInputs:maskAllTextInputs,maskAllImages:maskAllImages,maskAllSandboxedViews:maskAllSandboxedViews,captureTouches:captureTouches,captureLog:captureLog,captureNetworkTelemetry:captureNetworkTelemetry,verifyScreenshotMaskAlignment:verifyScreenshotMaskAlignment},Number.isFinite(screenshotScale)?{screenshotScale:screenshotScale}:{}),Number.isFinite(screenshotCompressionQuality)?{screenshotCompressionQuality:screenshotCompressionQuality}:{}),screenshotColorMode!==undefined?{screenshotColorMode:screenshotColorMode}:{}),{},{screenshotModeBackgroundCapture:screenshotModeBackgroundCapture,sampleRate:sampleRate,iOSdebouncerDelayMs:iOSdebouncerDelayMs,androidDebouncerDelayMs:androidDebouncerDelayMs,throttleDelayMs:throttleDelayMs});this._logger.info("Native PostHog plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") replay config: ").concat(JSON.stringify(sdkReplayConfig)));sessionReplay=(_f=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_f!==void 0?_f:{};cachedSessionReplayConfig=(_g=sessionReplay)!==null&&_g!==void 0?_g:{};this._logger.info("Session replay session recording from flags cached config: ".concat(JSON.stringify(cachedSessionReplayConfig)));pushOnlyInit=(enablePush||enableFatalJsCapture)&&!enableSessionReplay&&!enableNativeErrorTracking;sdkOptions={apiKey:this.apiKey,host:this.host,debug:this.isDebug,distinctId:this.getDistinctId(),anonymousId:this.getAnonymousId(),sdkVersion:this.getLibraryVersion(),flushAt:this.flushAt,optOut:this.optedOut,preloadFeatureFlags:!pushOnlyInit,requestHeaders:this._requestHeaders};loggableSdkOptions=_objectSpread(_objectSpread({},sdkOptions),{},{requestHeaders:Object.keys(this._requestHeaders)});this._logger.info("Native PostHog plugin sdk options: ".concat(JSON.stringify(loggableSdkOptions)));_context24.prev=7;if(!enableSessionReplay){_context24.next=9;break;}_context24.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(){return false;});case 8:_t4=_context24.sent;_context24.next=10;break;case 9:_t4=false;case 10:wasSessionReplayEnabled=_t4;if(!(nativeSessionOwner&&nativeSessionOwner!==this&&!this._canTakeOverNativeSession(nativeSessionOwner))){_context24.next=11;break;}this._logger.info('Native PostHog plugin already set up by another PostHog client.');return _context24.abrupt("return",false);case 11:if(!_OptionalPlugin.OptionalReactNativePlugin.setup){_context24.next=14;break;}pushIdentityProviderEnabled=false;if(options===null||options===void 0?void 0:options.pushIdentityProvider){if(_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider){_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider);pushIdentityProviderEnabled=true;}else{this._logger.warn('pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.');}}pluginConfig=_objectSpread({sessionReplay:{enabled:enableSessionReplay,sdkReplayConfig:sdkReplayConfig,decideReplayConfig:cachedSessionReplayConfig},errorTracking:{nativeAutocapture:nativeErrorAutocapture.nativeCrashes,androidNdkCrashes:nativeErrorAutocapture.androidNdkCrashes,exceptionSteps:this._errorTracking.getNativePluginExceptionStepsConfig(),fatalExceptionMarker:true},push:{capturePushNotificationSubscriptions:(_h=options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==null&&_h!==void 0?_h:true,capturePushNotificationOpened:(_j=options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==null&&_j!==void 0?_j:true,pushIdentityProviderEnabled:pushIdentityProviderEnabled}},(options===null||options===void 0?void 0:options.rageClickConfig)&&{rageClick:options.rageClickConfig});nativeSessionOwner=this;_context24.next=12;return _OptionalPlugin.OptionalReactNativePlugin.setup(String(sessionId),sdkOptions,pluginConfig);case 12:_context24.next=13;return(_c=_OptionalPlugin.OptionalReactNativePlugin.setOptOut)===null||_c===void 0?void 0:_c.call(_OptionalPlugin.OptionalReactNativePlugin,this.optedOut);case 13:if(wasSessionReplayEnabled){this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));}_context24.next=19;break;case 14:if(enableNativeErrorTracking){this._logger.warn('Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');enableNativeErrorTracking=false;}if(enablePush){this._logger.warn('Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.');}enablePush=false;this._pushNativeUnsupported=true;if(enableSessionReplay){_context24.next=15;break;}return _context24.abrupt("return",false);case 15:nativeSessionOwner=this;_context24.next=16;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 16:if(_context24.sent){_context24.next=18;break;}_context24.next=17;return _OptionalPlugin.OptionalReactNativePlugin.start(String(sessionId),sdkOptions,sdkReplayConfig,cachedSessionReplayConfig);case 17:_context24.next=19;break;case 18:this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));case 19:this._currentSessionId=sessionId;if(enableSessionReplay){this._sessionReplayNativeInitialized=true;this._logger.info("Session replay started with sessionId ".concat(sessionId,"."));this.getSessionId();}if(enableNativeErrorTracking){this._nativeErrorTrackingInitialized=true;this._errorTracking.onNativeErrorTrackingReady();this._logger.info('Native error tracking started.');}if(enablePush){this._pushNativeInitialized=true;this._logger.info('Push notification native support started.');}if(enableFatalJsCapture){this._fatalJsCaptureNativeInitialized=true;this._logger.info('Native durable capture for fatal JavaScript exceptions started.');}return _context24.abrupt("return",true);case 20:_context24.prev=20;_t5=_context24["catch"](7);if(nativeSessionOwner===this&&!this._isNativePluginInitialized()){nativeSessionOwner=undefined;}this._logger.error("Native PostHog plugin failed to start: ".concat(_t5,"."));return _context24.abrupt("return",false);case 21:case"end":return _context24.stop();}},_callee24,this,[[7,20]]);}));function initializeNativePlugin(_x17,_x18){return _initializeNativePlugin.apply(this,arguments);}return initializeNativePlugin;}()},{key:"startSessionReplay",value:function(){var _startSessionReplay=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee25(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context25){while(1)switch(_context25.prev=_context25.next){case 0:this._enableSessionReplay=options===null||options===void 0?void 0:options.enableSessionReplay;this._sessionReplayOptions=options;_context25.next=1;return this._evaluateAndStartSessionReplay(cachedRemoteConfig);case 1:case"end":return _context25.stop();}},_callee25,this);}));function startSessionReplay(_x19,_x20){return _startSessionReplay.apply(this,arguments);}return startSessionReplay;}()},{key:"_evaluateAndStartSessionReplay",value:function _evaluateAndStartSessionReplay(cachedRemoteConfig){var _this17=this;var freshSession=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then(function(){return _this17._evaluateAndStartSessionReplayInternal(cachedRemoteConfig,freshSession);});return this._sessionReplayEvalChain;}},{key:"_evaluateAndStartSessionReplayInternal",value:function(){var _evaluateAndStartSessionReplayInternal2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee26(cachedRemoteConfig){var freshSession,_a,_b,options,enableNativeErrorTracking,enablePush,enableFatalJsCapture,remoteConfig,restoreAppRecording,request,cachedSessionReplayConfig,recordingActive,eventTriggers,activated,_args26=arguments,_t6;return _regenerator["default"].wrap(function(_context26){while(1)switch(_context26.prev=_context26.next){case 0:freshSession=_args26.length>1&&_args26[1]!==undefined?_args26[1]:false;options=this._sessionReplayOptions;enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);enablePush=this._isPushNativeEnabled(options);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();remoteConfig=cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(this._isEnableSessionReplay()){_context26.next=6;break;}restoreAppRecording=freshSession&&!this.optedOut&&this._sessionReplayWanted&&!this._sessionReplayStartedByApp;this._logger.info('Session replay is not enabled.');this._sessionReplayEventTriggers=this._sessionReplayWanted?this._parseEventTriggers(((_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_a!==void 0?_a:{})['eventTriggers']):[];if(!restoreAppRecording){_context26.next=2;break;}_context26.next=1;return this._restoreAppRecording();case 1:_context26.next=3;break;case 2:if(!(this._sessionReplayNativeInitialized&&(this.optedOut||freshSession&&!this._sessionReplayStartedByApp))){_context26.next=3;break;}_context26.next=3;return this._stopSessionRecording(this.optedOut);case 3:if(!(enableNativeErrorTracking||enablePush||enableFatalJsCapture)){_context26.next=4;break;}_context26.next=4;return this.initializeNativePlugin(options,remoteConfig,false);case 4:request=this._manualRecordingStartRequest;if(!((request===null||request===void 0?void 0:request.pending)&&!restoreAppRecording)){_context26.next=5;break;}_context26.next=5;return this._attemptManualRecordingStart(request,true);case 5:return _context26.abrupt("return");case 6:cachedSessionReplayConfig=(_b=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_b!==void 0?_b:{};recordingActive=this._isSessionReplayLinkedFlagActive(cachedSessionReplayConfig);eventTriggers=this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers']);this._sessionReplayEventTriggers=eventTriggers;if(eventTriggers.length>0){activated=this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([]));if(!activated){recordingActive=false;}this._logger.info("Session replay event triggers configured (".concat(eventTriggers.length,"); activated: ").concat(activated,"."));}if(!this.optedOut){_context26.next=9;break;}if(this._sessionReplayNativeInitialized){_context26.next=7;break;}_context26.next=7;return this.initializeNativePlugin(options,remoteConfig,true);case 7:if(!this._sessionReplayNativeInitialized){_context26.next=8;break;}_context26.next=8;return this._stopSessionRecording(true);case 8:if(this._sessionReplayWanted){this._sessionReplayRecordingActive=false;}return _context26.abrupt("return");case 9:if(!(freshSession&&!this._sessionReplayWanted&&!this._sessionReplayStartedByApp)){_context26.next=11;break;}if(!this._sessionReplayNativeInitialized){_context26.next=10;break;}_context26.next=10;return this._stopSessionRecording(true);case 10:this._sessionReplayRecordingActive=true;return _context26.abrupt("return");case 11:if(!recordingActive){_context26.next=17;break;}if(!(this._sessionReplayRecordingActive===true)){_context26.next=12;break;}return _context26.abrupt("return");case 12:if(!this._sessionReplayNativeInitialized){_context26.next=14;break;}_context26.next=13;return this._startSessionRecording(true);case 13:_t6=_context26.sent;_context26.next=16;break;case 14:_context26.next=15;return this.initializeNativePlugin(options,remoteConfig,true);case 15:_t6=_context26.sent;case 16:this._sessionReplayRecordingActive=_t6;_context26.next=22;break;case 17:this._logger.info('Session replay disabled.');if(!(this._sessionReplayRecordingActive===true)){_context26.next=19;break;}_context26.next=18;return this._stopSessionRecording();case 18:this._sessionReplayRecordingActive=!_context26.sent;_context26.next=21;break;case 19:if(!(freshSession&&!this._sessionReplayStartedByApp&&this._sessionReplayNativeInitialized)){_context26.next=20;break;}_context26.next=20;return this._stopSessionRecording();case 20:this._sessionReplayRecordingActive=false;case 21:if(!(enableNativeErrorTracking||enablePush)){_context26.next=22;break;}_context26.next=22;return this.initializeNativePlugin(options,remoteConfig,false);case 22:case"end":return _context26.stop();}},_callee26,this);}));function _evaluateAndStartSessionReplayInternal(_x21){return _evaluateAndStartSessionReplayInternal2.apply(this,arguments);}return _evaluateAndStartSessionReplayInternal;}()},{key:"_restoreAppRecording",value:function _restoreAppRecording(){this._cancelManualRecordingStart();var request={pending:false,retryCount:0,awaitEventTrigger:true};this._manualRecordingStartRequest=request;return this._attemptManualRecordingStart(request,true);}},{key:"_isSessionReplayLinkedFlagActive",value:function _isSessionReplayLinkedFlagActive(cachedSessionReplayConfig){var _a,_b;var featureFlags=(_a=this.getKnownFeatureFlags())!==null&&_a!==void 0?_a:{};var cachedFeatureFlags=(_b=featureFlags)!==null&&_b!==void 0?_b:{};this._logger.info('Session replay feature flags from flags cached config:',JSON.stringify(cachedFeatureFlags));var recordingActive=true;var linkedFlag=cachedSessionReplayConfig['linkedFlag'];if(typeof linkedFlag==='string'){var value=cachedFeatureFlags[linkedFlag];if(typeof value==='boolean'){recordingActive=value;}else if(typeof value==='string'){recordingActive=true;}else{recordingActive=false;}this._logger.info("Session replay '".concat(linkedFlag,"' linked flag value: '").concat(value,"'"));}else if(linkedFlag&&(0,_typeof2["default"])(linkedFlag)==='object'){var flag=linkedFlag['flag'];var variant=linkedFlag['variant'];if(flag&&variant){var _value=cachedFeatureFlags[flag];recordingActive=_value===variant;this._logger.info("Session replay '".concat(flag,"' linked flag variant '").concat(variant,"' and value '").concat(_value,"'"));}else{this._logger.info("Session replay '".concat(flag,"' linked flag variant: '").concat(variant,"' does not exist/quota limited."));recordingActive=false;}}else{this._logger.info("Session replay has no cached linkedFlag.");}return recordingActive;}},{key:"processBeforeEnqueue",value:function processBeforeEnqueue(message){var observation=this._fatalCaptureObservation;var isObservedFatal=observation!==undefined&&message.uuid===observation.eventUuid&&message.event==='$exception';var processed=_superPropGet(PostHog,"processBeforeEnqueue",this,3)([message]);var suppress=false;if(isObservedFatal&&processed&&observation){try{observation.nativeCapture=observation.prepareNativeCapture(processed);}catch(e){this._logger.warn("Fatal exception payload could not be prepared for native capture: ".concat(e));observation.nativeCapture=undefined;}suppress=observation.nativeCapture!==undefined;observation.queued=!suppress;}try{this._maybeActivateEventTrigger(processed===null||processed===void 0?void 0:processed['event']);}catch(e){this._logger.error("Session replay event trigger check failed: ".concat(e,"."));}return suppress?null:processed;}},{key:"_captureFatalAndChooseOwner",value:function _captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,capture){var observation={eventUuid:eventUuid,prepareNativeCapture:prepareNativeCapture,queued:false};var previousObservation=this._fatalCaptureObservation;this._fatalCaptureObservation=observation;try{capture();}finally{this._fatalCaptureObservation=previousObservation;}return{queued:observation.queued,nativeCapture:observation.nativeCapture};}},{key:"_maybeActivateEventTrigger",value:function _maybeActivateEventTrigger(eventName){if(this._sessionReplayEventTriggers.length===0||typeof eventName!=='string'){return;}if(!this._sessionReplayEventTriggers.includes(eventName)){return;}var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!sessionId){return;}if(this._isEventTriggerActivatedForSession(sessionId)&&this._sessionReplayRecordingActive===true){return;}if(!this._isEventTriggerActivatedForSession(sessionId)){this.setPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession,sessionId);this._logger.info("Session replay event trigger '".concat(eventName,"' activated for session ").concat(sessionId,"."));}void this._evaluateAndStartSessionReplay();}},{key:"_parseEventTriggers",value:function _parseEventTriggers(value){if(!Array.isArray(value)){return[];}return value.filter(function(entry){return typeof entry==='string';});}},{key:"_isEventTriggerActivatedForSession",value:function _isEventTriggerActivatedForSession(sessionId){return this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession)===sessionId;}},{key:"captureAppLifecycleEvents",value:function(){var _captureAppLifecycleEvents=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee27(){var _this18=this;var _a,appBuild,appVersion,isMemoryPersistence,properties,prevAppBuild,prevAppVersion,installProperties,initialUrl,_t7,_t8,_t9;return _regenerator["default"].wrap(function(_context27){while(1)switch(_context27.prev=_context27.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;isMemoryPersistence=this._persistence==='memory';properties={};if(!isMemoryPersistence){prevAppBuild=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild);prevAppVersion=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion);if(!appBuild||!appVersion){this._logger.warn('PostHog could not track installation/update/open, as the build and version were not set. '+'This can happen if some dependencies are not installed correctly, or if you have provided'+'customAppProperties but not included $app_build or $app_version.');}if(appBuild){installProperties=_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('$react_native_version',(0,_utils.getReactNativeVersion)()));if(!prevAppBuild){this.capture('Application Installed',installProperties);}else if(prevAppBuild!==appBuild){this.capture('Application Updated',_objectSpread(_objectSpread(_objectSpread({},(0,_core.maybeAdd)('previous_version',prevAppVersion)),(0,_core.maybeAdd)('previous_build',prevAppBuild)),installProperties));}}}else{this._logger.warn('PostHog was initialised with persistence set to "memory", capturing native app events (Application Installed and Application Updated) is not supported.');}_context27.next=1;return _reactNative.Linking.getInitialURL();case 1:_t8=_a=_context27.sent;_t7=_t8!==null;if(!_t7){_context27.next=2;break;}_t7=_a!==void 0;case 2:if(!_t7){_context27.next=3;break;}_t9=_a;_context27.next=4;break;case 3:_t9=undefined;case 4:initialUrl=_t9;this.capture('Application Opened',_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('url',initialUrl)));_reactNative.AppState.addEventListener('change',function(state){if(state==='active'){_this18.capture('Application Became Active');}else if(state==='background'){_this18.capture('Application Backgrounded');}});case 5:case"end":return _context27.stop();}},_callee27,this);}));function captureAppLifecycleEvents(){return _captureAppLifecycleEvents.apply(this,arguments);}return captureAppLifecycleEvents;}()},{key:"persistAppVersion",value:function(){var _persistAppVersion=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee28(){var appBuild,appVersion;return _regenerator["default"].wrap(function(_context28){while(1)switch(_context28.prev=_context28.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild,appBuild);this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion,appVersion);case 1:case"end":return _context28.stop();}},_callee28,this);}));function persistAppVersion(){return _persistAppVersion.apply(this,arguments);}return persistAppVersion;}()}]);}(_core.PostHogCore);
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHog=void 0;Object.defineProperty(exports,"PostHogPersistedProperty",{enumerable:true,get:function get(){return _core.PostHogPersistedProperty;}});var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _reactNative=require("react-native");var _core=require("@posthog/core");var _storage=require("./storage");var _surveyProgress=require("./surveys/survey-progress");var _logsDefaults=require("./logs-defaults");var _version=require("./version");var _nativeDeps=require("./native-deps");var _utils=require("./utils");var _wixNavigation=require("./frameworks/wix-navigation");var _OptionalPlugin=require("./optional/OptionalPlugin");var _errorTracking=require("./error-tracking");var _exceptionContext=require("./error-tracking/exception-context");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;}function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}function _superPropGet(t,o,e,r){var p=(0,_get2["default"])((0,_getPrototypeOf2["default"])(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t);}:p;}var nativeSessionOwner;function mapAppStateForLogs(state){if(state==='background'){return'background';}if(!state||state==='unknown'){return undefined;}return'foreground';}var NATIVE_CALL_TIMEOUT_MS=10000;var MANUAL_RECORDING_START_RETRY_DELAYS_MS=[1000,2000,4000,8000,16000];var NATIVE_REPLAY_STATUS_REFRESH_INTERVAL_MS=5000;var REPLAY_DEBUG_PROPERTIES_INTERVAL_MS=30000;var OPTIONAL_REPLAY_DEBUG_PROPERTIES=new Set(['$sdk_debug_session_start','$sdk_debug_replay_capture_mode','$sdk_debug_replay_flush_hold_reason','$sdk_debug_replay_pending_trigger_conditions']);var EVENTS_WITHOUT_REPLAY_DEBUG_PROPERTIES=['$feature_flag_called','$snapshot'];var isReplayDebugEvent=function isReplayDebugEvent(eventName){return typeof eventName==='string'&&eventName.startsWith('$')&&!EVENTS_WITHOUT_REPLAY_DEBUG_PROPERTIES.includes(eventName);};var isDebugPropertyKey=function isDebugPropertyKey(key){return key==='$recording_status'||key.startsWith('$sdk_debug_');};var omitProperties=function omitProperties(properties,shouldOmit){if(!(0,_core.isObject)(properties)){return properties;}var kept={};for(var _i=0,_Object$entries=Object.entries(properties);_i<_Object$entries.length;_i++){var _Object$entries$_i=(0,_slicedToArray2["default"])(_Object$entries[_i],2),key=_Object$entries$_i[0],value=_Object$entries$_i[1];if(!shouldOmit(key)){kept[key]=value;}}return kept;};var withoutDebugProperties=function withoutDebugProperties(properties){return omitProperties(properties,isDebugPropertyKey);};var withoutOptionalReplayDebugProperties=function withoutOptionalReplayDebugProperties(properties){return omitProperties(properties,function(key){return OPTIONAL_REPLAY_DEBUG_PROPERTIES.has(key);});};var EMPTY_SESSION_REPLAY_DEBUG_PROPERTIES={$recording_status:undefined,$sdk_debug_session_start:undefined,$sdk_debug_pending_queue_size:undefined,$sdk_debug_replay_capture_mode:undefined,$sdk_debug_replay_event_trigger_status:undefined,$sdk_debug_replay_linked_flag_trigger_status:undefined,$sdk_debug_replay_pending_trigger_conditions:undefined,$sdk_debug_replay_flush_hold_reason:undefined,$sdk_debug_replay_internal_buffer_length:undefined,$sdk_debug_error_capturing_properties:undefined};var PostHog=exports.PostHog=function(_PostHogCore){function PostHog(apiKey,options){var _this;(0,_classCallCheck2["default"])(this,PostHog);var _a;var _b,_c,_d,_e,_f;var normalizedApiKey=typeof apiKey==='string'?apiKey.trim():'';if(!normalizedApiKey){console.error('You must pass your PostHog project token. The client will be disabled.');}_this=_callSuper(this,PostHog,[normalizedApiKey,options]);_this._appProperties={};_this._sessionReplayNativeInitialized=false;_this._nativeErrorTrackingInitialized=false;_this._androidNdkCrashesUnsupportedWarned=false;_this._pushNativeInitialized=false;_this._fatalJsCaptureNativeInitialized=false;_this._pushNativeUnsupported=false;_this._sessionReplayMacOSWarned=false;_this._sessionReplayWanted=false;_this._sessionReplayStartedByApp=false;_this._sessionReplayEvalChain=Promise.resolve();_this._nativeChain=Promise.resolve();_this._nativeSessionReplayDebugRefreshQueued=false;_this._nativeSessionReplayDebugRefreshedAt=0;_this._nativeSessionReplayDebugGeneration=0;_this._replayDebugBundleClaimed=false;_this._sessionReplayEventTriggers=[];_this._eventsStoragePreloadSucceeded=true;_this._surveysReadyPromise=null;_this._surveysReady=false;_this._requestHeaders={};_this._surveysReadyResolve=null;_this._isInitialized=false;_this._sessionReplayWanted=(options===null||options===void 0?void 0:options.enableSessionReplay)===true&&!(0,_utils.isMacOS)();_this._persistence=(_b=options===null||options===void 0?void 0:options.persistence)!==null&&_b!==void 0?_b:'file';_this._disableSurveys=(_c=options===null||options===void 0?void 0:options.disableSurveys)!==null&&_c!==void 0?_c:false;_this._errorTracking=new _errorTracking.ErrorTracking(_this,options===null||options===void 0?void 0:options.errorTracking,_this._logger,{captureFatalException:function captureFatalException(error,hint,eventUuid,timestamp,prepareNativeCapture){return _this._captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,function(){return _this.captureExceptionInternal(error,{$exception_level:'fatal'},hint,{uuid:eventUuid,timestamp:timestamp});});},waitForJSPersist:function(){var _waitForJSPersist=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=1;return _this._initPromise;case 1:return _context.abrupt("return",_this._eventsStorage.waitForPersistSuccess());case 2:case"end":return _context.stop();}},_callee);}));function waitForJSPersist(){return _waitForJSPersist.apply(this,arguments);}return waitForJSPersist;}(),getPersistenceMode:function getPersistenceMode(){return _this._persistence||'file';},waitForStorageReady:function(){var _waitForStorageReady=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(){return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=1;return _this._initPromise;case 1:return _context2.abrupt("return",_this._eventsStoragePreloadSucceeded);case 2:case"end":return _context2.stop();}},_callee2);}));function waitForStorageReady(){return _waitForStorageReady.apply(this,arguments);}return waitForStorageReady;}(),isNativeCaptureReady:function isNativeCaptureReady(){return _this._isNativePluginInitialized();}});_this._setDefaultPersonProperties=(_d=options===null||options===void 0?void 0:options.setDefaultPersonProperties)!==null&&_d!==void 0?_d:true;_this._overrideDisplayLanguage=((_a=options===null||options===void 0?void 0:options.overrideDisplayLanguage)===null||_a===void 0?void 0:_a.trim())||null;_this._requestHeaders=(_e=options===null||options===void 0?void 0:options.requestHeaders)!==null&&_e!==void 0?_e:{};_this._appProperties=typeof(options===null||options===void 0?void 0:options.customAppProperties)==='function'?options.customAppProperties((0,_nativeDeps.getAppProperties)()):(options===null||options===void 0?void 0:options.customAppProperties)||(0,_nativeDeps.getAppProperties)();var storagePromise;var theStorage;if(_this._persistence==='file'){theStorage=(_f=options===null||options===void 0?void 0:options.customStorage)!==null&&_f!==void 0?_f:(0,_nativeDeps.buildOptimisticAsyncStorage)();}if(theStorage){_this._eventsStorage=(0,_storage.createEventsStorage)(theStorage);_this._logsStorage=(0,_storage.createLogsStorage)(theStorage);var preloads=[];if(_this._eventsStorage.preloadPromise){void _this._eventsStorage.preloadPromise["catch"](function(){_this._eventsStoragePreloadSucceeded=false;});preloads.push(['events',_this._eventsStorage.preloadPromise]);}if(_this._logsStorage.preloadPromise){preloads.push(['logs',_this._logsStorage.preloadPromise]);}if(preloads.length>0){storagePromise=(0,_core.allSettled)(preloads.map(function(_ref){var _ref2=(0,_slicedToArray2["default"])(_ref,2),p=_ref2[1];return p;})).then(function(results){results.forEach(function(r,i){if(r.status==='rejected'){_this._logger.error("PostHog ".concat(preloads[i][0]," storage preload failed:"),r.reason);}});});}}else{_this._eventsStorage=(0,_storage.createEventsMemoryStorage)();_this._logsStorage=(0,_storage.createLogsMemoryStorage)();}_this._currentAppState=mapAppStateForLogs(_reactNative.AppState.currentState);_this._resolvedLogsConfig=(0,_logsDefaults.resolveLogsConfig)(options===null||options===void 0?void 0:options.logs);_this._logs=new _core.PostHogLogs(_this,_this._resolvedLogsConfig,_this._logger,function(){var _a;var flags=_this.getFeatureFlags();var flagKeys=flags?Object.keys(flags):undefined;return{distinctId:_this.getDistinctId()||undefined,sessionId:_this.getSessionId()||undefined,screenName:((_a=_this.sessionProps)===null||_a===void 0?void 0:_a.$screen_name)||undefined,appState:_this._currentAppState,activeFeatureFlags:flagKeys&&flagKeys.length>0?flagKeys:undefined};},function(fn){return _this.wrap(fn);},function(){return _this._logsStorage.waitForPersist();});_reactNative.AppState.addEventListener('change',function(state){if(state==='unknown'){return;}var mapped=mapAppStateForLogs(state);if(mapped){_this._currentAppState=mapped;}void _this.flush()["catch"](function(){var _ref3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(err){return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context3.stop();}},_callee3);}));return function(_x3){return _ref3.apply(this,arguments);};}());var isBackgrounding=mapped==='background';var logsFlushPromise=isBackgrounding?_this._logs.flushWithTimeout(_this._resolvedLogsConfig.backgroundFlushBudgetMs):_this._logs.flush();void logsFlushPromise["catch"](function(){var _ref4=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(err){return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context4.stop();}},_callee4);}));return function(_x4){return _ref4.apply(this,arguments);};}());void _this._eventsStorage.waitForPersist();void _this._logsStorage.waitForPersist();if(state==='active'){_this.getSessionId();_this._refreshNativeSessionReplayDebugProperties();}});var initAfterStorage=function initAfterStorage(){var enablePersistSessionIdAcrossRestart=options===null||options===void 0?void 0:options.enablePersistSessionIdAcrossRestart;if(!enablePersistSessionIdAcrossRestart){_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionId,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionLastTimestamp,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp,null);}_this.setupBootstrap(options);if(!_this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId)){var anonId=_this.getAnonymousId();if(anonId){_this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);}}if(_this._setDefaultPersonProperties){_this._setDefaultPersonPropertiesForFlags(false);}_this._isInitialized=true;if(_this.isDisabled){return;}var cachedRemoteConfig=_this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(cachedRemoteConfig){_this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking);}_this.reloadRemoteConfigAsync().then(function(response){if(response){_this._errorTracking.onRemoteConfig(response.errorTracking);_this._handleSurveysFromRemoteConfig(response);}})["catch"](function(error){_this._logger.error('Error loading remote config:',error);})["finally"](function(){_this._notifySurveysReady();});if((options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==false){void _this.captureAppLifecycleEvents();}void _this.persistAppVersion();void _this.startSessionReplay(options,cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:undefined);_this.onFeatureFlags(function(){var _a;if(_this._isEnableSessionReplay()||((_a=_this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.pending)){void _this._evaluateAndStartSessionReplay();}_this._refreshNativeSessionReplayDebugProperties();});if((options===null||options===void 0?void 0:options.addTracingHeaders)&&options.addTracingHeaders.length>0){(0,_core.patchFetchForTracingHeaders)(_this,options.addTracingHeaders);}};if(storagePromise){_this._initPromise=storagePromise.then(initAfterStorage);}else{_this._initPromise=Promise.resolve();initAfterStorage();}return _this;}(0,_inherits2["default"])(PostHog,_PostHogCore);return(0,_createClass2["default"])(PostHog,[{key:"ready",value:(function(){var _ready=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(){return _regenerator["default"].wrap(function(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.next=1;return this._initPromise;case 1:case"end":return _context5.stop();}},_callee5,this);}));function ready(){return _ready.apply(this,arguments);}return ready;}())},{key:"onRemoteConfig",value:function onRemoteConfig(response){this._errorTracking.onRemoteConfig(response.errorTracking);}},{key:"_storageForKey",value:function _storageForKey(key){return key===_core.PostHogPersistedProperty.LogsQueue?this._logsStorage:this._eventsStorage;}},{key:"getPersistedProperty",value:function getPersistedProperty(key){return this._storageForKey(key).getItem(key);}},{key:"setPersistedProperty",value:function setPersistedProperty(key,value){var storage=this._storageForKey(key);if(key===_core.PostHogPersistedProperty.SurveysInProgress&&value===null){var otherProjects=(0,_surveyProgress.getOtherProjectSurveyProgress)(this);otherProjects.length?storage.setItem(key,otherProjects):storage.removeItem(key);this._events.emit('surveysReset',undefined);}else{value!==null?storage.setItem(key,value):storage.removeItem(key);}if(key===_core.PostHogPersistedProperty.PersonProperties){this._events.emit('personProperties',value);}}},{key:"flushStorage",value:(function(){var _flushStorage=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(){return _regenerator["default"].wrap(function(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=1;return this._eventsStorage.waitForPersist();case 1:case"end":return _context6.stop();}},_callee6,this);}));function flushStorage(){return _flushStorage.apply(this,arguments);}return flushStorage;}())},{key:"_shutdown",value:(function(){var _shutdown2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(){var shutdownTimeoutMs,start,remainingMs,logsBudgetMs,_remainingMs,drain,_args7=arguments;return _regenerator["default"].wrap(function(_context7){while(1)switch(_context7.prev=_context7.next){case 0:shutdownTimeoutMs=_args7.length>0&&_args7[0]!==undefined?_args7[0]:30000;this._cancelManualRecordingStart();if(nativeSessionOwner===this){nativeSessionOwner=undefined;}start=Date.now();_context7.prev=1;remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));logsBudgetMs=Math.min(remainingMs,this._resolvedLogsConfig.terminationFlushBudgetMs);_context7.next=2;return Promise.all([this._logs.shutdown(logsBudgetMs),_superPropGet(PostHog,"_shutdown",this,3)([remainingMs])]);case 2:_context7.prev=2;this._replayDebugBundleAcceptedAt=undefined;this._replayDebugBundleClaimed=false;this._errorTracking.shutdown();_remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));drain=Promise.all([this._eventsStorage.waitForPersist(),this._logsStorage.waitForPersist()]);_context7.next=3;return(0,_core.raceWithTimeout)(drain,_remainingMs);case 3:return _context7.finish(2);case 4:case"end":return _context7.stop();}},_callee7,this,[[1,,2,4]]);}));function _shutdown(){return _shutdown2.apply(this,arguments);}return _shutdown;}())},{key:"fetch",value:function(_fetch){function fetch(_x,_x2){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(url,options){return fetch(url,options);})},{key:"getLibraryId",value:function getLibraryId(){return'posthog-react-native';}},{key:"getLibraryVersion",value:function getLibraryVersion(){return _version.version;}},{key:"getCustomUserAgent",value:function getCustomUserAgent(){if(_reactNative.Platform.OS==='web'){return'';}return"".concat(this.getLibraryId(),"/").concat(this.getLibraryVersion());}},{key:"getCustomHeaders",value:function getCustomHeaders(){return _objectSpread(_objectSpread({},_superPropGet(PostHog,"getCustomHeaders",this,3)([])),this._requestHeaders);}},{key:"getCommonEventProperties",value:function getCommonEventProperties(){var _Dimensions$get=_reactNative.Dimensions.get(_reactNative.Platform.OS==='ios'?'window':'screen'),width=_Dimensions$get.width,height=_Dimensions$get.height;return _objectSpread(_objectSpread(_objectSpread({},_superPropGet(PostHog,"getCommonEventProperties",this,3)([])),this._appProperties),{},{$screen_height:height,$screen_width:width});}},{key:"_stampReplayDebugProperties",value:function _stampReplayDebugProperties(message){var _a;var properties=(_a=message.properties)!==null&&_a!==void 0?_a:{};if(message.event==='$feature_flag_called'&&properties.$feature_flag_has_experiment===false&&this.isMinimalFlagCalledEventsEnabled()){return;}message.properties=_objectSpread(_objectSpread({},properties),this._sessionReplayDebugProperties());}},{key:"_sessionReplayDebugProperties",value:function _sessionReplayDebugProperties(){var _a,_b,_c;try{var sessionStart=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp);var hasSessionStart=typeof sessionStart==='number'&&sessionStart>0;var platformOS=(0,_utils.getPlatformOS)();var hasNativeReplay=!!_OptionalPlugin.OptionalReactNativePlugin&&(platformOS==='ios'||platformOS==='android');var replayEnabled=this._isEnableSessionReplay()||this._sessionReplayNativeInitialized;var cached=this._nativeSessionReplayDebugProperties;var _native=typeof(cached===null||cached===void 0?void 0:cached['$recording_status'])==='string'?cached:undefined;var nativeHoldReason=_native===null||_native===void 0?void 0:_native['$sdk_debug_replay_flush_hold_reason'];var nativeBufferLength=_native===null||_native===void 0?void 0:_native['$sdk_debug_replay_internal_buffer_length'];var eventTriggerStatus;var linkedFlagTriggerStatus;var pendingTriggerConditions;if(replayEnabled&&hasNativeReplay){var sessionId=(_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionId))!==null&&_a!==void 0?_a:'';eventTriggerStatus=this._sessionReplayEventTriggers.length===0?'trigger_disabled':this._isEventTriggerActivatedForSession(sessionId)?'trigger_activated':'trigger_pending';var sessionReplay=(_b=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_b!==void 0?_b:{};linkedFlagTriggerStatus=this._linkedFlagTriggerStatus(sessionReplay['linkedFlag'],(_c=this.getKnownFeatureFlags())!==null&&_c!==void 0?_c:{}).status;var pending=[eventTriggerStatus==='trigger_pending'?'event_trigger':undefined,linkedFlagTriggerStatus==='trigger_pending'?'linked_flag':undefined].filter(function(condition){return condition!==undefined;});pendingTriggerConditions=pending.length>0?pending:undefined;}return _objectSpread(_objectSpread({},EMPTY_SESSION_REPLAY_DEBUG_PROPERTIES),{},{$recording_status:_native?_native['$recording_status']:this._sessionReplayRecordingActive===true?'active':'disabled',$sdk_debug_session_start:hasSessionStart?sessionStart:undefined,$sdk_debug_pending_queue_size:this._pendingQueueSize(),$sdk_debug_replay_capture_mode:hasNativeReplay?'screenshot':undefined,$sdk_debug_replay_event_trigger_status:eventTriggerStatus,$sdk_debug_replay_linked_flag_trigger_status:linkedFlagTriggerStatus,$sdk_debug_replay_pending_trigger_conditions:pendingTriggerConditions,$sdk_debug_replay_flush_hold_reason:typeof nativeHoldReason==='string'?nativeHoldReason:undefined,$sdk_debug_replay_internal_buffer_length:typeof nativeBufferLength==='number'?nativeBufferLength:undefined});}catch(e){return _objectSpread(_objectSpread({},EMPTY_SESSION_REPLAY_DEBUG_PROPERTIES),{},{$sdk_debug_pending_queue_size:this._pendingQueueSize(),$sdk_debug_error_capturing_properties:String(e)});}}},{key:"_pendingQueueSize",value:function _pendingQueueSize(){try{var queue=this.getPersistedProperty(_core.PostHogPersistedProperty.Queue);return Array.isArray(queue)?queue.length:0;}catch(_a){return undefined;}}},{key:"_refreshNativeSessionReplayDebugProperties",value:function _refreshNativeSessionReplayDebugProperties(){var _this2=this;if(!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.getSessionReplayDebugProperties)||this._nativeSessionReplayDebugRefreshQueued){return;}this._nativeSessionReplayDebugRefreshQueued=true;var started=false;void this._enqueueNative('getSessionReplayDebugProperties',function(){var _ref5=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8(plugin){var _a,generation,map;return _regenerator["default"].wrap(function(_context8){while(1)switch(_context8.prev=_context8.next){case 0:started=true;_this2._nativeSessionReplayDebugRefreshQueued=false;generation=_this2._nativeSessionReplayDebugGeneration;_context8.prev=1;_context8.next=2;return(_a=plugin.getSessionReplayDebugProperties)===null||_a===void 0?void 0:_a.call(plugin);case 2:map=_context8.sent;if(generation===_this2._nativeSessionReplayDebugGeneration&&(0,_core.isObject)(map)&&typeof map['$recording_status']==='string'){_this2._nativeSessionReplayDebugProperties=map;}case 3:_context8.prev=3;if(generation===_this2._nativeSessionReplayDebugGeneration){_this2._nativeSessionReplayDebugRefreshedAt=Date.now();}return _context8.finish(3);case 4:case"end":return _context8.stop();}},_callee8,null,[[1,,3,4]]);}));return function(_x5){return _ref5.apply(this,arguments);};}(),false)["finally"](function(){if(!started){_this2._nativeSessionReplayDebugRefreshQueued=false;}});}},{key:"_refreshStaleNativeStatus",value:function _refreshStaleNativeStatus(){var _a;var status=(_a=this._nativeSessionReplayDebugProperties)===null||_a===void 0?void 0:_a['$recording_status'];var replayOn=this._isEnableSessionReplay()&&this._sessionReplayNativeInitialized;var stale=status==='buffering'||status==='active'||replayOn;if(stale&&Date.now()-this._nativeSessionReplayDebugRefreshedAt>=NATIVE_REPLAY_STATUS_REFRESH_INTERVAL_MS){this._refreshNativeSessionReplayDebugProperties();}}},{key:"_invalidateNativeSessionReplayDebugProperties",value:function _invalidateNativeSessionReplayDebugProperties(provisional){this._nativeSessionReplayDebugProperties=provisional;this._nativeSessionReplayDebugGeneration++;this._refreshNativeSessionReplayDebugProperties();}},{key:"_linkedFlagTriggerStatus",value:function _linkedFlagTriggerStatus(linkedFlag,featureFlags){if(typeof linkedFlag==='string'){var value=featureFlags[linkedFlag];var matched;if(typeof value==='boolean'){matched=value;}else if(typeof value==='string'){matched=true;}else{matched=false;}return{status:matched?'trigger_activated':'trigger_pending',message:"Session replay '".concat(linkedFlag,"' linked flag value: '").concat(value,"'")};}if(linkedFlag&&(0,_typeof2["default"])(linkedFlag)==='object'){var linked=linkedFlag;var flag=linked['flag'];var variant=linked['variant'];if(flag&&variant){var _value=featureFlags[flag];return{status:_value===variant?'trigger_activated':'trigger_pending',message:"Session replay '".concat(flag,"' linked flag variant '").concat(variant,"' and value '").concat(_value,"'")};}return{status:'trigger_pending',message:"Session replay '".concat(flag,"' linked flag variant: '").concat(variant,"' does not exist/quota limited.")};}return{status:'trigger_disabled',message:'Session replay has no cached linkedFlag.'};}},{key:"getSurveyDisplayLanguageOverride",value:function getSurveyDisplayLanguageOverride(){return this._overrideDisplayLanguage;}},{key:"register",value:function register(properties){return _superPropGet(PostHog,"register",this,3)([properties]);}},{key:"unregister",value:function unregister(property){return _superPropGet(PostHog,"unregister",this,3)([property]);}},{key:"reset",value:function reset(propertiesToKeep){var _this3=this;var effectivePropertiesToKeep=propertiesToKeep!==null&&propertiesToKeep!==void 0?propertiesToKeep:[_core.PostHogPersistedProperty.InstalledAppBuild,_core.PostHogPersistedProperty.InstalledAppVersion,_core.PostHogPersistedProperty.DeviceId];this._cancelManualRecordingStart();var wasOptedOut=this.optedOut;_superPropGet(PostHog,"reset",this,3)([[_core.PostHogPersistedProperty.RemoteConfig,_core.PostHogPersistedProperty.SessionReplay,_core.PostHogPersistedProperty.Surveys,_core.PostHogPersistedProperty.PushRegistered].concat((0,_toConsumableArray2["default"])(effectivePropertiesToKeep))]);if(this._setDefaultPersonProperties){this._setDefaultPersonPropertiesForFlags(false);}if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.reset){void this._enqueueNative('reset',function(plugin){var _a;return(_a=plugin.reset)===null||_a===void 0?void 0:_a.call(plugin,String(_this3.getDistinctId()),String(_this3.getAnonymousId()));},this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true);}if(this._isInitialized&&wasOptedOut&&!this.optedOut&&this._sessionReplayWanted){try{this._rotateReplaySession();}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}var nativeOptIn=this._propagateNativeOptOut();if(this._isInitialized&&wasOptedOut&&!this.optedOut){void nativeOptIn.then(function(){return _this3._evaluateAndStartSessionReplay(undefined,true);})["catch"](function(){});}void this._eventsStorage.waitForPersist();}},{key:"_setDefaultPersonPropertiesForFlags",value:function _setDefaultPersonPropertiesForFlags(){var _this4=this;var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var defaultProps={};var relevantKeys=['$app_version','$app_build','$app_namespace','$os_name','$os_version','$device_type'];relevantKeys.forEach(function(key){var value=_this4._appProperties[key];if(value!==null&&value!==undefined){defaultProps[key]=value;}});var commonProps=this.getCommonEventProperties();if(commonProps.$lib){defaultProps.$lib=commonProps.$lib;}if(commonProps.$lib_version){defaultProps.$lib_version=commonProps.$lib_version;}if(Object.keys(defaultProps).length>0){this.setPersonPropertiesForFlags(defaultProps,reloadFeatureFlags);}}},{key:"flush",value:function flush(){return _superPropGet(PostHog,"flush",this,3)([]);}},{key:"captureLog",value:function captureLog(options){this._logs.captureLog(options);}},{key:"flushLogs",value:function flushLogs(){return this._logs.flush();}},{key:"logger",get:function get(){var _this5=this;if(!this._captureLogger){this._captureLogger={trace:function trace(body,attributes){return _this5.captureLog({body:body,level:'trace',attributes:attributes});},debug:function debug(body,attributes){return _this5.captureLog({body:body,level:'debug',attributes:attributes});},info:function info(body,attributes){return _this5.captureLog({body:body,level:'info',attributes:attributes});},warn:function warn(body,attributes){return _this5.captureLog({body:body,level:'warn',attributes:attributes});},error:function error(body,attributes){return _this5.captureLog({body:body,level:'error',attributes:attributes});},fatal:function fatal(body,attributes){return _this5.captureLog({body:body,level:'fatal',attributes:attributes});}};}return this._captureLogger;}},{key:"optIn",value:function optIn(){var _this6=this;var wasOptedOut=this.optedOut;var result=_superPropGet(PostHog,"optIn",this,3)([]);void this._eventsStorage.waitForPersist();if(this._isInitialized&&wasOptedOut&&!this.optedOut&&this._sessionReplayWanted){try{this._rotateReplaySession();}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}var nativeOptIn=this._propagateNativeOptOut();if(this._isInitialized&&wasOptedOut){var replay=Promise.all([result,nativeOptIn]).then(function(){return _this6._evaluateAndStartSessionReplay(undefined,true);})["catch"](function(){});return Promise.all([result,replay]).then(function(){return undefined;});}return result;}},{key:"optOut",value:function optOut(){var _this7=this;this._cancelManualRecordingStart();var coreOptOut=_superPropGet(PostHog,"optOut",this,3)([]);this._sessionReplayStartedByApp=false;var replayStop=this._isInitialized?coreOptOut.then(function(){return _this7._evaluateAndStartSessionReplay();})["catch"](function(){}):Promise.resolve();var persistOptOut=function persistOptOut(){_this7.setPersistedProperty(_core.PostHogPersistedProperty.SurveysInProgress,null);return _this7._eventsStorage.waitForPersist();};var result=Promise.all([coreOptOut,replayStop,this._isInitialized?persistOptOut():this._initPromise.then(persistOptOut)]).then(function(){return undefined;});if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.unregisterPushNotificationToken){void this.unregisterPushNotificationToken();}this._propagateNativeOptOut();return result;}},{key:"_propagateNativeOptOut",value:function _propagateNativeOptOut(){var _this8=this;if(!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.setOptOut)){return Promise.resolve();}var sent=this._enqueueNative('setOptOut',function(plugin){var _a;return(_a=plugin.setOptOut)===null||_a===void 0?void 0:_a.call(plugin,_this8.optedOut);});if(this._isPushNativeEnabled(this._sessionReplayOptions)){void this._ensureNativeInitialized();}return sent;}},{key:"isFeatureEnabled",value:function isFeatureEnabled(key,options){return _superPropGet(PostHog,"isFeatureEnabled",this,3)([key,options]);}},{key:"getFeatureFlag",value:function getFeatureFlag(key,options){return _superPropGet(PostHog,"getFeatureFlag",this,3)([key,options]);}},{key:"getFeatureFlagPayload",value:function getFeatureFlagPayload(key){return _superPropGet(PostHog,"getFeatureFlagPayload",this,3)([key]);}},{key:"reloadFeatureFlags",value:function reloadFeatureFlags(){_superPropGet(PostHog,"reloadFeatureFlags",this,3)([]);}},{key:"reloadFeatureFlagsAsync",value:function reloadFeatureFlagsAsync(){return _superPropGet(PostHog,"reloadFeatureFlagsAsync",this,3)([]);}},{key:"updateFlags",value:function updateFlags(flags,payloads,options){_superPropGet(PostHog,"updateFlags",this,3)([flags,payloads,options]);}},{key:"group",value:function group(groupType,groupKey,properties){_superPropGet(PostHog,"group",this,3)([groupType,groupKey,properties]);if(properties&&Object.keys(properties).length>0){var propsToCache={};Object.keys(properties).forEach(function(key){var value=properties[key];if(value!==null&&value!==undefined){propsToCache[key]=value;}});if(Object.keys(propsToCache).length>0){this.setGroupPropertiesForFlags((0,_defineProperty2["default"])({},groupType,propsToCache));}}}},{key:"alias",value:function alias(_alias){_superPropGet(PostHog,"alias",this,3)([_alias]);}},{key:"getDistinctId",value:function getDistinctId(){return _superPropGet(PostHog,"getDistinctId",this,3)([]);}},{key:"getDeviceId",value:function getDeviceId(){var deviceId=this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId);if(!deviceId){var anonId=this.getAnonymousId();if(anonId){this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);return anonId;}return'';}return deviceId;}},{key:"setPersonPropertiesForFlags",value:function setPersonPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setPersonPropertiesForFlags",this,3)([properties,reloadFeatureFlags]);}},{key:"resetPersonPropertiesForFlags",value:function resetPersonPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetPersonPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"setGroupPropertiesForFlags",value:function setGroupPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setGroupPropertiesForFlags",this,3)([properties]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"resetGroupPropertiesForFlags",value:function resetGroupPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetGroupPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"screen",value:(function(){var _screen=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(name,properties,options){return _regenerator["default"].wrap(function(_context9){while(1)switch(_context9.prev=_context9.next){case 0:if(this._isInitialized){_context9.next=1;break;}_context9.next=1;return this._initPromise;case 1:this.registerForSession({$screen_name:name});return _context9.abrupt("return",this.capture('$screen',_objectSpread(_objectSpread({},properties),{},{$screen_name:name}),options));case 2:case"end":return _context9.stop();}},_callee9,this);}));function screen(_x6,_x7,_x8){return _screen.apply(this,arguments);}return screen;}())},{key:"_isEnableSessionReplay",value:function _isEnableSessionReplay(){var _a;return!this.isDisabled&&!(0,_utils.isMacOS)()&&((_a=this._enableSessionReplay)!==null&&_a!==void 0?_a:false);}},{key:"_isNativeSessionOwner",value:function _isNativeSessionOwner(){return nativeSessionOwner===undefined||nativeSessionOwner===this;}},{key:"_isSameProjectAs",value:function _isSameProjectAs(other){return other.apiKey===this.apiKey&&other.host===this.host;}},{key:"_canTakeOverNativeSession",value:function _canTakeOverNativeSession(owner){return!this._isNativePluginInitialized()&&this._isSameProjectAs(owner);}},{key:"_resetSessionId",value:function _resetSessionId(reactNativeSessionReplay,sessionId){if(reactNativeSessionReplay&&this._isNativeSessionOwner()){reactNativeSessionReplay.endSession();reactNativeSessionReplay.startSession(sessionId);}}},{key:"getSessionId",value:function getSessionId(){var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!this._isEnableSessionReplay()&&!this._isNativePluginInitialized()){return sessionId;}if(sessionId.length>0&&this._currentSessionId&&sessionId!==this._currentSessionId){if(_OptionalPlugin.OptionalReactNativePlugin){try{this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));this._refreshNativeSessionReplayDebugProperties();this._logger.info("sessionId rotated from ".concat(this._currentSessionId," to ").concat(sessionId,"."));}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}this._currentSessionId=sessionId;if(this._sessionReplayEventTriggers.length>0){void this._evaluateAndStartSessionReplay();}}else{this._logger.info("sessionId not rotated, sessionId ".concat(sessionId," and currentSessionId ").concat(this._currentSessionId,"."));}return sessionId;}},{key:"resetSessionId",value:function resetSessionId(){_superPropGet(PostHog,"resetSessionId",this,3)([]);if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin&&this._isNativeSessionOwner()){try{_OptionalPlugin.OptionalReactNativePlugin.endSession();this._refreshNativeSessionReplayDebugProperties();this._logger.info("Native PostHog session ended.");}catch(e){this._logger.error("Native PostHog session failed to end: ".concat(e,"."));}}}},{key:"startSessionRecording",value:(function(){var _startSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee1(){var _this9=this;var resumeCurrent,request,_args1=arguments;return _regenerator["default"].wrap(function(_context1){while(1)switch(_context1.prev=_context1.next){case 0:resumeCurrent=_args1.length>0&&_args1[0]!==undefined?_args1[0]:true;this._cancelManualRecordingStart();if(!this.optedOut&&!(0,_utils.isMacOS)()){this._sessionReplayWanted=true;}request={pending:false,retryCount:0};this._manualRecordingStartRequest=request;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee0(){return _regenerator["default"].wrap(function(_context0){while(1)switch(_context0.prev=_context0.next){case 0:_context0.next=1;return _this9._attemptManualRecordingStart(request,resumeCurrent);case 1:case"end":return _context0.stop();}},_callee0);})));_context1.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context1.stop();}},_callee1,this);}));function startSessionRecording(){return _startSessionRecording2.apply(this,arguments);}return startSessionRecording;}())},{key:"_cancelManualRecordingStart",value:function _cancelManualRecordingStart(){var _a;clearTimeout((_a=this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.timer);this._manualRecordingStartRequest=undefined;}},{key:"_attemptManualRecordingStart",value:function(){var _attemptManualRecordingStart2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(request,resumeCurrent){var started;return _regenerator["default"].wrap(function(_context10){while(1)switch(_context10.prev=_context10.next){case 0:if(!(this._manualRecordingStartRequest!==request)){_context10.next=1;break;}return _context10.abrupt("return",false);case 1:if(!(this.isDisabled||this.optedOut)){_context10.next=2;break;}this._cancelManualRecordingStart();return _context10.abrupt("return",false);case 2:if(!(request.awaitEventTrigger&&this._sessionReplayEventTriggers.length>0&&!this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([])))){_context10.next=4;break;}request.pending=true;if(!this._sessionReplayNativeInitialized){_context10.next=3;break;}_context10.next=3;return this._stopSessionRecording();case 3:return _context10.abrupt("return",false);case 4:this._sessionReplayStartedByApp=true;_context10.next=5;return this._startSessionRecording(resumeCurrent);case 5:started=_context10.sent;if(!(this._manualRecordingStartRequest!==request)){_context10.next=7;break;}if(!started){_context10.next=6;break;}_context10.next=6;return this._stopSessionRecording();case 6:return _context10.abrupt("return",false);case 7:if(started){this._cancelManualRecordingStart();}else{request.pending=true;this._scheduleManualRecordingStartRetry(request);}return _context10.abrupt("return",started);case 8:case"end":return _context10.stop();}},_callee10,this);}));function _attemptManualRecordingStart(_x9,_x0){return _attemptManualRecordingStart2.apply(this,arguments);}return _attemptManualRecordingStart;}()},{key:"_scheduleManualRecordingStartRetry",value:function _scheduleManualRecordingStartRetry(request){var _this0=this;var delay=MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount];if(request.timer!==undefined||delay===undefined||!this._sessionReplayNativeInitialized||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.startRecording)){return;}request.retryCount++;request.timer=(0,_core.safeSetTimeout)(function(){request.timer=undefined;_this0._sessionReplayEvalChain=_this0._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(){return _regenerator["default"].wrap(function(_context11){while(1)switch(_context11.prev=_context11.next){case 0:_context11.next=1;return _this0._attemptManualRecordingStart(request,true);case 1:case"end":return _context11.stop();}},_callee11);})));},delay);}},{key:"_rotateReplaySession",value:function _rotateReplaySession(){if(!_OptionalPlugin.OptionalReactNativePlugin){return;}_superPropGet(PostHog,"resetSessionId",this,3)([]);var newSessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(newSessionId));this._currentSessionId=newSessionId;}},{key:"_startSessionRecording",value:function(){var _startSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(resumeCurrent){var _this1=this;var initialized,started,_t;return _regenerator["default"].wrap(function(_context12){while(1)switch(_context12.prev=_context12.next){case 0:_context12.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context12.next=2;break;}return _context12.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context12.next=3;break;}return _context12.abrupt("return",false);case 3:_context12.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.startRecording){_context12.next=4;break;}this._logger.warn('startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context12.abrupt("return",false);case 4:if(this._sessionReplayNativeInitialized){_context12.next=6;break;}this._logger.info('Native session replay SDK not initialized, initializing now...');_context12.next=5;return this.initializeNativePlugin(this._sessionReplayOptions,undefined,true);case 5:initialized=_context12.sent;if(initialized){_context12.next=6;break;}this._logger.error('Failed to initialize native session replay SDK.');return _context12.abrupt("return",false);case 6:if(!resumeCurrent){this._rotateReplaySession();}_context12.next=7;return _OptionalPlugin.OptionalReactNativePlugin.startRecording(resumeCurrent);case 7:_context12.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(e){_this1._logger.warn("Failed to confirm the session recording started: ".concat(e));return true;});case 8:started=_context12.sent;this._invalidateNativeSessionReplayDebugProperties({$recording_status:started?'active':'disabled'});if(started){_context12.next=9;break;}this._logger.warn('The native SDK refused to start session recording, usually because its remote config is not loaded yet. '+'PostHog retries on the next feature flags load.');return _context12.abrupt("return",false);case 9:this._logger.info("Session recording ".concat(resumeCurrent?'resumed':'started',"."));return _context12.abrupt("return",true);case 10:_context12.prev=10;_t=_context12["catch"](3);this._logger.error("Failed to start session recording: ".concat(_t));return _context12.abrupt("return",false);case 11:case"end":return _context12.stop();}},_callee12,this,[[3,10]]);}));function _startSessionRecording(_x1){return _startSessionRecording3.apply(this,arguments);}return _startSessionRecording;}()},{key:"stopSessionRecording",value:(function(){var _stopSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(){var _this10=this;return _regenerator["default"].wrap(function(_context14){while(1)switch(_context14.prev=_context14.next){case 0:this._cancelManualRecordingStart();this._sessionReplayStartedByApp=false;if(!this.optedOut){this._sessionReplayWanted=false;}this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(){return _regenerator["default"].wrap(function(_context13){while(1)switch(_context13.prev=_context13.next){case 0:_context13.next=1;return _this10._stopSessionRecording(true);case 1:case"end":return _context13.stop();}},_callee13);})));_context14.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context14.stop();}},_callee14,this);}));function stopSessionRecording(){return _stopSessionRecording2.apply(this,arguments);}return stopSessionRecording;}())},{key:"_stopSessionRecording",value:function(){var _stopSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(){var byApp,_args15=arguments,_t2;return _regenerator["default"].wrap(function(_context15){while(1)switch(_context15.prev=_context15.next){case 0:byApp=_args15.length>0&&_args15[0]!==undefined?_args15[0]:false;_context15.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context15.next=2;break;}return _context15.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context15.next=3;break;}return _context15.abrupt("return",false);case 3:_context15.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.stopRecording){_context15.next=4;break;}this._logger.warn('stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context15.abrupt("return",false);case 4:if(!(!this._isNativeSessionOwner()&&!(byApp&&nativeSessionOwner&&this._isSameProjectAs(nativeSessionOwner)))){_context15.next=5;break;}this._logger.info('Session recording belongs to another PostHog client.');return _context15.abrupt("return",false);case 5:_context15.next=6;return _OptionalPlugin.OptionalReactNativePlugin.stopRecording();case 6:this._invalidateNativeSessionReplayDebugProperties({$recording_status:'disabled'});this._logger.info('Session recording stopped.');return _context15.abrupt("return",true);case 7:_context15.prev=7;_t2=_context15["catch"](3);this._logger.error("Failed to stop session recording: ".concat(_t2));return _context15.abrupt("return",false);case 8:case"end":return _context15.stop();}},_callee15,this,[[3,7]]);}));function _stopSessionRecording(){return _stopSessionRecording3.apply(this,arguments);}return _stopSessionRecording;}()},{key:"isSessionReplayActive",value:(function(){var _isSessionReplayActive=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16(){var _t3;return _regenerator["default"].wrap(function(_context16){while(1)switch(_context16.prev=_context16.next){case 0:_context16.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context16.next=2;break;}return _context16.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context16.next=3;break;}return _context16.abrupt("return",false);case 3:if(!(nativeSessionOwner&&nativeSessionOwner!==this&&!this._isSameProjectAs(nativeSessionOwner))){_context16.next=4;break;}return _context16.abrupt("return",false);case 4:_context16.prev=4;_context16.next=5;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 5:return _context16.abrupt("return",_context16.sent);case 6:_context16.prev=6;_t3=_context16["catch"](4);this._logger.error("Failed to check session replay status: ".concat(_t3));return _context16.abrupt("return",false);case 7:case"end":return _context16.stop();}},_callee16,this,[[4,6]]);}));function isSessionReplayActive(){return _isSessionReplayActive.apply(this,arguments);}return isSessionReplayActive;}())},{key:"identify",value:function identify(distinctId,properties,options){var _this11=this;var previousDistinctId=this.getDistinctId();var userProps=(properties===null||properties===void 0?void 0:properties.$set)||properties;var userPropsOnce=properties===null||properties===void 0?void 0:properties.$set_once;_superPropGet(PostHog,"identify",this,3)([distinctId,properties,options]);var propsToCache={};if(userProps&&(0,_typeof2["default"])(userProps)==='object'&&!Array.isArray(userProps)){Object.entries(userProps).forEach(function(_ref9){var _ref0=(0,_slicedToArray2["default"])(_ref9,2),key=_ref0[0],value=_ref0[1];if(value!==null&&value!==undefined){propsToCache[key]=value;}});}var propsOnceToCache={};if(userPropsOnce&&(0,_typeof2["default"])(userPropsOnce)==='object'&&!Array.isArray(userPropsOnce)){Object.entries(userPropsOnce).forEach(function(_ref1){var _ref10=(0,_slicedToArray2["default"])(_ref1,2),key=_ref10[0],value=_ref10[1];if(value!==null&&value!==undefined){propsOnceToCache[key]=value;}});}if(Object.keys(propsToCache).length>0||Object.keys(propsOnceToCache).length>0){this.setPersonPropertiesForFlags(_objectSpread({$set:propsToCache},Object.keys(propsOnceToCache).length>0?{$set_once:propsOnceToCache}:{}),false);}if(_OptionalPlugin.OptionalReactNativePlugin){void this._enqueueNative('identify',function(plugin){var nativeDistinctId=String(_this11.getDistinctId()||previousDistinctId);var anonymousId=String(_this11.getAnonymousId());var identified=plugin.identify(nativeDistinctId,anonymousId);_this11._logger.info("Native PostHog identified with distinctId ".concat(nativeDistinctId," and anonymousId ").concat(anonymousId,"."));return identified;});}void this._eventsStorage.waitForPersist();}},{key:"captureException",value:function captureException(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var _a;try{var result=this.captureExceptionInternal(error,additionalProperties,hint);if(((_a=result===null||result===void 0?void 0:result.additionalProperties)===null||_a===void 0?void 0:_a.$exception_level)==='fatal'){void this._eventsStorage.waitForPersist();void this._logsStorage.waitForPersist();}}catch(e){this._logger.error('Error while capturing $exception:',e);}}},{key:"captureExceptionInternal",value:function captureExceptionInternal(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var options=arguments.length>3?arguments[3]:undefined;var _a,_b;var resolvedHint=hint!==null&&hint!==void 0?hint:{mechanism:{handled:true,type:'generic'},syntheticException:new Error('Synthetic Error')};var merged=_objectSpread(_objectSpread({},(0,_exceptionContext.getExceptionContext)()),additionalProperties);var finalAdditional=this._errorTracking.attachExceptionSteps(merged);var captureOptions=_objectSpread(_objectSpread({},options||{}),{},{_originatedFromCaptureException:true});this.capture('$exception',_objectSpread(_objectSpread({},this.buildExceptionProperties(error,resolvedHint)),finalAdditional),captureOptions);var eventUuid=(_a=captureOptions.uuid)!==null&&_a!==void 0?_a:'';var timestamp=((_b=captureOptions.timestamp)!==null&&_b!==void 0?_b:new Date()).toISOString();return{eventUuid:eventUuid,timestamp:timestamp,additionalProperties:finalAdditional};}},{key:"buildExceptionProperties",value:function buildExceptionProperties(error,hint){try{var builder=this.getErrorPropertiesBuilder();var exceptionProperties=builder.buildFromUnknown(error,hint);return exceptionProperties;}catch(e){this._logger.error('Error while building exception properties:',e);return{};}}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){this._errorTracking.addExceptionStep(message,properties);}},{key:"createErrorPropertiesBuilder",value:function createErrorPropertiesBuilder(){return new _core.ErrorTracking.ErrorPropertiesBuilder([new _core.ErrorTracking.PromiseRejectionEventCoercer(),new _core.ErrorTracking.ErrorCoercer(),new _core.ErrorTracking.ErrorEventCoercer(),new _core.ErrorTracking.ObjectCoercer(),new _core.ErrorTracking.StringCoercer(),new _core.ErrorTracking.PrimitiveCoercer()],_core.ErrorTracking.createStackParser((0,_utils.isHermes)()?'hermes':'web:javascript',_core.ErrorTracking.chromeStackLineParser,_core.ErrorTracking.geckoStackLineParser));}},{key:"initReactNativeNavigation",value:function initReactNativeNavigation(options){return(0,_wixNavigation.withReactNativeNavigation)(this,options);}},{key:"createPersonProfile",value:function createPersonProfile(){_superPropGet(PostHog,"createPersonProfile",this,3)([]);}},{key:"setPersonProperties",value:function setPersonProperties(userPropertiesToSet,userPropertiesToSetOnce){var reloadFeatureFlags=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;_superPropGet(PostHog,"setPersonProperties",this,3)([userPropertiesToSet,userPropertiesToSetOnce,reloadFeatureFlags]);}},{key:"unsetPersonProperties",value:function unsetPersonProperties(propertyNames){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"unsetPersonProperties",this,3)([propertyNames,reloadFeatureFlags]);}},{key:"getSurveys",value:function(){var _getSurveys=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee17(){var surveys;return _regenerator["default"].wrap(function(_context17){while(1)switch(_context17.prev=_context17.next){case 0:if(!(this._disableSurveys===true)){_context17.next=1;break;}this._logger.info('Loading surveys is disabled.');this._cacheSurveys(null,'disabled in config');return _context17.abrupt("return",[]);case 1:surveys=this.getPersistedProperty(_core.PostHogPersistedProperty.Surveys);if(!(surveys&&surveys.length>0)){_context17.next=2;break;}this._logger.info('Surveys fetched from storage: ',JSON.stringify(surveys));return _context17.abrupt("return",surveys);case 2:this._logger.info('No surveys found in storage');return _context17.abrupt("return",[]);case 3:case"end":return _context17.stop();}},_callee17,this);}));function getSurveys(){return _getSurveys.apply(this,arguments);}return getSurveys;}()},{key:"_onSurveysReady",value:function _onSurveysReady(){var _this12=this;if(this._surveysReady){return Promise.resolve();}if(!this._surveysReadyPromise){this._surveysReadyPromise=new Promise(function(resolve){_this12._surveysReadyResolve=resolve;});}return this._surveysReadyPromise;}},{key:"_cacheSurveys",value:function _cacheSurveys(surveys,source){this.setPersistedProperty(_core.PostHogPersistedProperty.Surveys,surveys);if(surveys&&surveys.length>0){this._logger.info("Surveys cached from ".concat(source,":"),JSON.stringify(surveys));}else if(surveys===null){this._logger.info("Surveys cleared (".concat(source,")"));}else{this._logger.info("No surveys to cache from ".concat(source,")"));}}},{key:"_notifySurveysReady",value:function _notifySurveysReady(){this._surveysReady=true;if(this._surveysReadyResolve){this._surveysReadyResolve();this._surveysReadyResolve=null;this._surveysReadyPromise=null;}}},{key:"_handleSurveysFromRemoteConfig",value:function _handleSurveysFromRemoteConfig(response){if(this._disableSurveys===true){this._logger.info('Loading surveys skipped, disabled.');this._cacheSurveys(null,'remote config (disabled)');return;}var surveys=response.surveys;if(Array.isArray(surveys)){this._cacheSurveys(surveys,'remote config');}else{this._cacheSurveys(null,'remote config');}}},{key:"registerPushNotificationToken",value:(function(){var _registerPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee18(deviceToken,options){var _this13=this;return _regenerator["default"].wrap(function(_context18){while(1)switch(_context18.prev=_context18.next){case 0:return _context18.abrupt("return",this._callPushPlugin('registerPushNotificationToken',{allowMacOS:false,requireInit:true,noop:'token not registered'},function(plugin){var _a;var _b;_this13.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,true);return(_a=plugin.registerPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin,deviceToken,(_b=options===null||options===void 0?void 0:options.appId)!==null&&_b!==void 0?_b:null);}));case 1:case"end":return _context18.stop();}},_callee18,this);}));function registerPushNotificationToken(_x10,_x11){return _registerPushNotificationToken.apply(this,arguments);}return registerPushNotificationToken;}())},{key:"unregisterPushNotificationToken",value:(function(){var _unregisterPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee19(){var _this14=this;return _regenerator["default"].wrap(function(_context19){while(1)switch(_context19.prev=_context19.next){case 0:return _context19.abrupt("return",this._callPushPlugin('unregisterPushNotificationToken',{allowMacOS:false,allowWhenOptedOut:true,requireInit:this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true,noop:'nothing to unregister'},function(plugin){var _a;_this14.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,null);return(_a=plugin.unregisterPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin);}));case 1:case"end":return _context19.stop();}},_callee19,this);}));function unregisterPushNotificationToken(){return _unregisterPushNotificationToken.apply(this,arguments);}return unregisterPushNotificationToken;}())},{key:"capturePushNotificationOpened",value:(function(){var _capturePushNotificationOpened=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee20(options){var properties,_i2,_arr,key;return _regenerator["default"].wrap(function(_context20){while(1)switch(_context20.prev=_context20.next){case 0:properties={};for(_i2=0,_arr=['title','subtitle','body','payload','action'];_i2<_arr.length;_i2++){key=_arr[_i2];if(options[key]!==undefined){properties[key]=options[key];}}return _context20.abrupt("return",this._callPushPlugin('capturePushNotificationOpened',{allowMacOS:true,requireInit:true,noop:'event not captured'},function(plugin){var _a;return(_a=plugin.capturePushNotificationOpened)===null||_a===void 0?void 0:_a.call(plugin,properties);}));case 1:case"end":return _context20.stop();}},_callee20,this);}));function capturePushNotificationOpened(_x12){return _capturePushNotificationOpened.apply(this,arguments);}return capturePushNotificationOpened;}())},{key:"_callPushPlugin",value:function(){var _callPushPlugin2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee21(method,behavior,invoke){var _this15=this;return _regenerator["default"].wrap(function(_context21){while(1)switch(_context21.prev=_context21.next){case 0:if(!this.isDisabled){_context21.next=1;break;}return _context21.abrupt("return");case 1:if(!(this.optedOut&&!behavior.allowWhenOptedOut)){_context21.next=2;break;}this._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return _context21.abrupt("return");case 2:if(!((0,_utils.isWeb)()||!behavior.allowMacOS&&(0,_utils.isMacOS)())){_context21.next=3;break;}this._logger.warn("".concat(method," is not supported on ").concat((0,_utils.isWeb)()?'web':'macOS',"; ").concat(behavior.noop,"."));return _context21.abrupt("return");case 3:if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin[method]){_context21.next=4;break;}this._logger.warn("".concat(method," requires @posthog/react-native-plugin; install or update it."));return _context21.abrupt("return");case 4:return _context21.abrupt("return",this._enqueueNative(method,function(plugin){if(_this15.optedOut&&!behavior.allowWhenOptedOut){_this15._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return;}return invoke(plugin);},behavior.requireInit));case 5:case"end":return _context21.stop();}},_callee21,this);}));function _callPushPlugin(_x13,_x14,_x15){return _callPushPlugin2.apply(this,arguments);}return _callPushPlugin;}()},{key:"_enqueueNative",value:function _enqueueNative(label,run){var _this16=this;var requireInit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var next=this._nativeChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee22(){return _regenerator["default"].wrap(function(_context22){while(1)switch(_context22.prev=_context22.next){case 0:if(!(_this16.isDisabled||(0,_utils.isWeb)()||!_OptionalPlugin.OptionalReactNativePlugin)){_context22.next=1;break;}return _context22.abrupt("return");case 1:_context22.next=2;return _this16._initPromise["catch"](function(){});case 2:_context22.next=3;return _this16._sessionReplayEvalChain["catch"](function(){});case 3:if(_this16._isNativePluginInitialized()){_context22.next=6;break;}if(requireInit){_context22.next=4;break;}return _context22.abrupt("return");case 4:_context22.next=5;return _this16._ensureNativeInitialized();case 5:if(_this16._isNativePluginInitialized()){_context22.next=6;break;}_this16._logger.warn("".concat(label," skipped: the native plugin is not initialized."));return _context22.abrupt("return");case 6:_context22.next=7;return(0,_core.raceWithTimeout)(Promise.resolve(run(_OptionalPlugin.OptionalReactNativePlugin)),NATIVE_CALL_TIMEOUT_MS,function(){return _this16._logger.warn("Native PostHog ".concat(label," timed out after ").concat(NATIVE_CALL_TIMEOUT_MS,"ms; continuing."));});case 7:case"end":return _context22.stop();}},_callee22);})))["catch"](function(e){return _this16._logger.warn("Native PostHog ".concat(label," failed: ").concat(e,"."));});this._nativeChain=next;return next;}},{key:"_ensureNativeInitialized",value:function _ensureNativeInitialized(){var _this17=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee23(){return _regenerator["default"].wrap(function(_context23){while(1)switch(_context23.prev=_context23.next){case 0:if(_this17._isNativePluginInitialized()){_context23.next=1;break;}_context23.next=1;return _this17.initializeNativePlugin(_this17._sessionReplayOptions,undefined,false,true);case 1:case"end":return _context23.stop();}},_callee23);})));return this._sessionReplayEvalChain;}},{key:"_pluginVersionAtLeast",value:function _pluginVersionAtLeast(major,minor){var version=_OptionalPlugin.OptionalReactNativePluginVersion===null||_OptionalPlugin.OptionalReactNativePluginVersion===void 0?void 0:_OptionalPlugin.OptionalReactNativePluginVersion.match(/^(\d+)\.(\d+)\.\d+(?:\+[\w.-]+)?$/);if(!version){return false;}var _ref13=[Number(version[1]),Number(version[2])],installedMajor=_ref13[0],installedMinor=_ref13[1];return installedMajor>major||installedMajor===major&&installedMinor>=minor;}},{key:"_nativeErrorAutocapture",value:function _nativeErrorAutocapture(options){var _a;var autocapture=(_a=options===null||options===void 0?void 0:options.errorTracking)===null||_a===void 0?void 0:_a.autocapture;if(this.isDisabled||(0,_typeof2["default"])(autocapture)!=='object'){return{nativeCrashes:false,androidNdkCrashes:false};}var androidNdkCrashes=_reactNative.Platform.OS==='android'&&autocapture.androidNdkCrashes===true;if(androidNdkCrashes&&!this._pluginVersionAtLeast(2,12)){if(!this._androidNdkCrashesUnsupportedWarned){this._androidNdkCrashesUnsupportedWarned=true;this._logger.warn("errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later "+"(installed: ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',"); ignoring."));}androidNdkCrashes=false;}return{nativeCrashes:autocapture.nativeCrashes===true,androidNdkCrashes:androidNdkCrashes};}},{key:"_isAutocaptureNativeErrors",value:function _isAutocaptureNativeErrors(options){var _this$_nativeErrorAut=this._nativeErrorAutocapture(options),nativeCrashes=_this$_nativeErrorAut.nativeCrashes,androidNdkCrashes=_this$_nativeErrorAut.androidNdkCrashes;return nativeCrashes||androidNdkCrashes;}},{key:"_isFatalJsCaptureNativeEnabled",value:function _isFatalJsCaptureNativeEnabled(){if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._persistence==='memory'){return false;}return this._errorTracking.isUncaughtExceptionAutocaptureEnabled();}},{key:"_isNativePluginInitialized",value:function _isNativePluginInitialized(){return this._sessionReplayNativeInitialized||this._nativeErrorTrackingInitialized||this._pushNativeInitialized||this._fatalJsCaptureNativeInitialized;}},{key:"_isPushNativeEnabled",value:function _isPushNativeEnabled(options){var force=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._pushNativeUnsupported){return false;}return force||(options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==false||(options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==false||!!(options===null||options===void 0?void 0:options.pushIdentityProvider);}},{key:"initializeSessionReplayNative",value:(function(){var _initializeSessionReplayNative=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee24(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context24){while(1)switch(_context24.prev=_context24.next){case 0:return _context24.abrupt("return",this.initializeNativePlugin(options,cachedRemoteConfig,true));case 1:case"end":return _context24.stop();}},_callee24,this);}));function initializeSessionReplayNative(_x16,_x17){return _initializeSessionReplayNative.apply(this,arguments);}return initializeSessionReplayNative;}())},{key:"initializeNativePlugin",value:function(){var _initializeNativePlugin=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee25(options,cachedRemoteConfig){var enableSessionReplay,forcePush,_a,_b,_c,_d,_e,_f,_g,_h,_j,nativeErrorAutocapture,enableNativeErrorTracking,enablePush,enableFatalJsCapture,sessionId,defaultThrottleDelayMs,_ref14,_ref14$maskAllTextInp,maskAllTextInputs,_ref14$maskAllImages,maskAllImages,_ref14$maskAllSandbox,maskAllSandboxedViews,_ref14$captureTouches,captureTouches,_ref14$captureLog,localCaptureLog,_ref14$captureNetwork,localCaptureNetworkTelemetry,_ref14$verifyScreensh,verifyScreenshotMaskAlignment,screenshotScale,screenshotCompressionQuality,screenshotColorMode,_ref14$screenshotMode,screenshotModeBackgroundCapture,localSampleRate,_ref14$iOSdebouncerDe,iOSdebouncerDelayMs,_ref14$androidDebounc,androidDebouncerDelayMs,throttleDelayMs,remoteConsoleLogEnabled,remoteNetworkTimingEnabled,remoteSampleRateRaw,captureLog,captureNetworkTelemetry,localSampleRateValid,remoteSampleRateValid,sampleRate,source,sdkReplayConfig,sessionReplay,cachedSessionReplayConfig,pushOnlyInit,sdkOptions,loggableSdkOptions,wasSessionReplayEnabled,pushIdentityProviderEnabled,pluginConfig,_args25=arguments,_t4,_t5;return _regenerator["default"].wrap(function(_context25){while(1)switch(_context25.prev=_context25.next){case 0:enableSessionReplay=_args25.length>2&&_args25[2]!==undefined?_args25[2]:this._isEnableSessionReplay();forcePush=_args25.length>3&&_args25[3]!==undefined?_args25[3]:false;nativeErrorAutocapture=this._nativeErrorAutocapture(options);enableNativeErrorTracking=nativeErrorAutocapture.nativeCrashes||nativeErrorAutocapture.androidNdkCrashes;enablePush=this._isPushNativeEnabled(options,forcePush);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();if(enableSessionReplay&&(0,_utils.isMacOS)()){if(!this._sessionReplayMacOSWarned){this._sessionReplayMacOSWarned=true;this._logger.warn('Session replay is not supported on macOS; ignoring.');}enableSessionReplay=false;}if(!(!enableSessionReplay&&!enableNativeErrorTracking&&!enablePush&&!enableFatalJsCapture)){_context25.next=1;break;}return _context25.abrupt("return",true);case 1:if(_OptionalPlugin.OptionalReactNativePlugin){_context25.next=2;break;}if(enableSessionReplay||enableNativeErrorTracking){this._logger.warn(enableSessionReplay?'Session replay enabled but not installed.':'Native error tracking enabled but not installed.');}this._pushNativeUnsupported=true;return _context25.abrupt("return",false);case 2:if(!((!enableSessionReplay||this._sessionReplayNativeInitialized)&&(!enableNativeErrorTracking||this._nativeErrorTrackingInitialized)&&(!enablePush||this._pushNativeInitialized)&&(!enableFatalJsCapture||this._fatalJsCaptureNativeInitialized))){_context25.next=3;break;}return _context25.abrupt("return",true);case 3:if(!(this._isNativePluginInitialized()&&enableSessionReplay&&!this._sessionReplayNativeInitialized)){_context25.next=5;break;}this._sessionReplayNativeInitialized=true;_context25.next=4;return(_a=_OptionalPlugin.OptionalReactNativePlugin.startRecording)===null||_a===void 0?void 0:_a.call(_OptionalPlugin.OptionalReactNativePlugin,true);case 4:this._refreshNativeSessionReplayDebugProperties();return _context25.abrupt("return",true);case 5:sessionId=this.getSessionId();if(!(sessionId.length===0)){_context25.next=6;break;}this._logger.warn("Native PostHog plugin enabled but no sessionId found.");return _context25.abrupt("return",false);case 6:defaultThrottleDelayMs=1000;_ref14=(_d=options===null||options===void 0?void 0:options.sessionReplayConfig)!==null&&_d!==void 0?_d:{},_ref14$maskAllTextInp=_ref14.maskAllTextInputs,maskAllTextInputs=_ref14$maskAllTextInp===void 0?true:_ref14$maskAllTextInp,_ref14$maskAllImages=_ref14.maskAllImages,maskAllImages=_ref14$maskAllImages===void 0?true:_ref14$maskAllImages,_ref14$maskAllSandbox=_ref14.maskAllSandboxedViews,maskAllSandboxedViews=_ref14$maskAllSandbox===void 0?true:_ref14$maskAllSandbox,_ref14$captureTouches=_ref14.captureTouches,captureTouches=_ref14$captureTouches===void 0?true:_ref14$captureTouches,_ref14$captureLog=_ref14.captureLog,localCaptureLog=_ref14$captureLog===void 0?true:_ref14$captureLog,_ref14$captureNetwork=_ref14.captureNetworkTelemetry,localCaptureNetworkTelemetry=_ref14$captureNetwork===void 0?true:_ref14$captureNetwork,_ref14$verifyScreensh=_ref14.verifyScreenshotMaskAlignment,verifyScreenshotMaskAlignment=_ref14$verifyScreensh===void 0?false:_ref14$verifyScreensh,screenshotScale=_ref14.screenshotScale,screenshotCompressionQuality=_ref14.screenshotCompressionQuality,screenshotColorMode=_ref14.screenshotColorMode,_ref14$screenshotMode=_ref14.screenshotModeBackgroundCapture,screenshotModeBackgroundCapture=_ref14$screenshotMode===void 0?false:_ref14$screenshotMode,localSampleRate=_ref14.sampleRate,_ref14$iOSdebouncerDe=_ref14.iOSdebouncerDelayMs,iOSdebouncerDelayMs=_ref14$iOSdebouncerDe===void 0?defaultThrottleDelayMs:_ref14$iOSdebouncerDe,_ref14$androidDebounc=_ref14.androidDebouncerDelayMs,androidDebouncerDelayMs=_ref14$androidDebounc===void 0?defaultThrottleDelayMs:_ref14$androidDebounc;if(captureTouches===false&&!(0,_utils.isMacOS)()){if(!this._pluginVersionAtLeast(2,9)){this._logger.warn("sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. "+"The installed plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") may still record touch coordinates. ")+"Upgrade the plugin and rebuild your app before relying on this setting.");}}throttleDelayMs=(_e=(_b=options===null||options===void 0?void 0:options.sessionReplayConfig)===null||_b===void 0?void 0:_b.throttleDelayMs)!==null&&_e!==void 0?_e:defaultThrottleDelayMs;if(throttleDelayMs===defaultThrottleDelayMs&&(iOSdebouncerDelayMs!==defaultThrottleDelayMs||androidDebouncerDelayMs!==defaultThrottleDelayMs)){throttleDelayMs=Math.max(iOSdebouncerDelayMs,androidDebouncerDelayMs);}remoteConsoleLogEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'consoleLogRecordingEnabled',true);remoteNetworkTimingEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.capturePerformance,'network_timing',true);remoteSampleRateRaw=(0,_utils.getRemoteConfigNumber)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'sampleRate');captureLog=localCaptureLog&&remoteConsoleLogEnabled;captureNetworkTelemetry=localCaptureNetworkTelemetry&&remoteNetworkTimingEnabled;localSampleRateValid=localSampleRate===undefined?undefined:(0,_utils.isValidSampleRate)(localSampleRate)?localSampleRate:undefined;remoteSampleRateValid=remoteSampleRateRaw===undefined?undefined:(0,_utils.isValidSampleRate)(remoteSampleRateRaw)?remoteSampleRateRaw:undefined;sampleRate=localSampleRateValid!==null&&localSampleRateValid!==void 0?localSampleRateValid:remoteSampleRateValid;if(localCaptureLog&&!remoteConsoleLogEnabled){this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).');}if(localCaptureNetworkTelemetry&&!remoteNetworkTimingEnabled){this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).');}if(localSampleRate!==undefined&&localSampleRateValid===undefined){this._logger.warn("Ignoring invalid sessionReplayConfig.sampleRate '".concat(localSampleRate,"'. Expected a number between 0 and 1."));}if(remoteSampleRateRaw!==undefined&&remoteSampleRateValid===undefined){this._logger.warn("Ignoring invalid remote config sessionRecording.sampleRate '".concat(remoteSampleRateRaw,"'. Expected a number between 0 and 1."));}if(localSampleRateValid!==undefined&&remoteSampleRateValid!==undefined){this._logger.warn("Local sessionReplayConfig.sampleRate (".concat(localSampleRateValid,") overrides the remote sampleRate ")+"(".concat(remoteSampleRateValid,"). The project setting is ignored while the local option is set. ")+"Remove sessionReplayConfig.sampleRate to follow the project setting.");}else if(typeof sampleRate==='number'){source=localSampleRateValid!==undefined?'local config':'remote config';this._logger.info("sampleRate set from ".concat(source," (").concat(sampleRate,")."));}else if(cachedRemoteConfig===undefined){this._logger.warn('Session replay starts with no sampleRate because no remote config is cached yet. '+'Any project sample rate applies from the next launch.');}sdkReplayConfig=_objectSpread(_objectSpread(_objectSpread(_objectSpread({maskAllTextInputs:maskAllTextInputs,maskAllImages:maskAllImages,maskAllSandboxedViews:maskAllSandboxedViews,captureTouches:captureTouches,captureLog:captureLog,captureNetworkTelemetry:captureNetworkTelemetry,verifyScreenshotMaskAlignment:verifyScreenshotMaskAlignment},Number.isFinite(screenshotScale)?{screenshotScale:screenshotScale}:{}),Number.isFinite(screenshotCompressionQuality)?{screenshotCompressionQuality:screenshotCompressionQuality}:{}),screenshotColorMode!==undefined?{screenshotColorMode:screenshotColorMode}:{}),{},{screenshotModeBackgroundCapture:screenshotModeBackgroundCapture,sampleRate:sampleRate,iOSdebouncerDelayMs:iOSdebouncerDelayMs,androidDebouncerDelayMs:androidDebouncerDelayMs,throttleDelayMs:throttleDelayMs});this._logger.info("Native PostHog plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") replay config: ").concat(JSON.stringify(sdkReplayConfig)));sessionReplay=(_f=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_f!==void 0?_f:{};cachedSessionReplayConfig=(_g=sessionReplay)!==null&&_g!==void 0?_g:{};this._logger.info("Session replay session recording from flags cached config: ".concat(JSON.stringify(cachedSessionReplayConfig)));pushOnlyInit=(enablePush||enableFatalJsCapture)&&!enableSessionReplay&&!enableNativeErrorTracking;sdkOptions={apiKey:this.apiKey,host:this.host,debug:this.isDebug,distinctId:this.getDistinctId(),anonymousId:this.getAnonymousId(),sdkVersion:this.getLibraryVersion(),flushAt:this.flushAt,optOut:this.optedOut,preloadFeatureFlags:!pushOnlyInit,requestHeaders:this._requestHeaders};loggableSdkOptions=_objectSpread(_objectSpread({},sdkOptions),{},{requestHeaders:Object.keys(this._requestHeaders)});this._logger.info("Native PostHog plugin sdk options: ".concat(JSON.stringify(loggableSdkOptions)));_context25.prev=7;if(!enableSessionReplay){_context25.next=9;break;}_context25.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(){return false;});case 8:_t4=_context25.sent;_context25.next=10;break;case 9:_t4=false;case 10:wasSessionReplayEnabled=_t4;if(!(nativeSessionOwner&&nativeSessionOwner!==this&&!this._canTakeOverNativeSession(nativeSessionOwner))){_context25.next=11;break;}this._logger.info('Native PostHog plugin already set up by another PostHog client.');return _context25.abrupt("return",false);case 11:if(!_OptionalPlugin.OptionalReactNativePlugin.setup){_context25.next=14;break;}pushIdentityProviderEnabled=false;if(options===null||options===void 0?void 0:options.pushIdentityProvider){if(_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider){_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider);pushIdentityProviderEnabled=true;}else{this._logger.warn('pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.');}}pluginConfig=_objectSpread({sessionReplay:{enabled:enableSessionReplay,sdkReplayConfig:sdkReplayConfig,decideReplayConfig:cachedSessionReplayConfig},errorTracking:{nativeAutocapture:nativeErrorAutocapture.nativeCrashes,androidNdkCrashes:nativeErrorAutocapture.androidNdkCrashes,exceptionSteps:this._errorTracking.getNativePluginExceptionStepsConfig(),fatalExceptionMarker:true},push:{capturePushNotificationSubscriptions:(_h=options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==null&&_h!==void 0?_h:true,capturePushNotificationOpened:(_j=options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==null&&_j!==void 0?_j:true,pushIdentityProviderEnabled:pushIdentityProviderEnabled}},(options===null||options===void 0?void 0:options.rageClickConfig)&&{rageClick:options.rageClickConfig});nativeSessionOwner=this;_context25.next=12;return _OptionalPlugin.OptionalReactNativePlugin.setup(String(sessionId),sdkOptions,pluginConfig);case 12:_context25.next=13;return(_c=_OptionalPlugin.OptionalReactNativePlugin.setOptOut)===null||_c===void 0?void 0:_c.call(_OptionalPlugin.OptionalReactNativePlugin,this.optedOut);case 13:if(wasSessionReplayEnabled){this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));}_context25.next=19;break;case 14:if(enableNativeErrorTracking){this._logger.warn('Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');enableNativeErrorTracking=false;}if(enablePush){this._logger.warn('Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.');}enablePush=false;this._pushNativeUnsupported=true;if(enableSessionReplay){_context25.next=15;break;}return _context25.abrupt("return",false);case 15:nativeSessionOwner=this;_context25.next=16;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 16:if(_context25.sent){_context25.next=18;break;}_context25.next=17;return _OptionalPlugin.OptionalReactNativePlugin.start(String(sessionId),sdkOptions,sdkReplayConfig,cachedSessionReplayConfig);case 17:_context25.next=19;break;case 18:this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));case 19:this._currentSessionId=sessionId;if(enableSessionReplay){this._sessionReplayNativeInitialized=true;this._refreshNativeSessionReplayDebugProperties();this._logger.info("Session replay started with sessionId ".concat(sessionId,"."));this.getSessionId();}if(enableNativeErrorTracking){this._nativeErrorTrackingInitialized=true;this._errorTracking.onNativeErrorTrackingReady();this._logger.info('Native error tracking started.');}if(enablePush){this._pushNativeInitialized=true;this._logger.info('Push notification native support started.');}if(enableFatalJsCapture){this._fatalJsCaptureNativeInitialized=true;this._logger.info('Native durable capture for fatal JavaScript exceptions started.');}return _context25.abrupt("return",true);case 20:_context25.prev=20;_t5=_context25["catch"](7);if(nativeSessionOwner===this&&!this._isNativePluginInitialized()){nativeSessionOwner=undefined;}this._logger.error("Native PostHog plugin failed to start: ".concat(_t5,"."));return _context25.abrupt("return",false);case 21:case"end":return _context25.stop();}},_callee25,this,[[7,20]]);}));function initializeNativePlugin(_x18,_x19){return _initializeNativePlugin.apply(this,arguments);}return initializeNativePlugin;}()},{key:"startSessionReplay",value:function(){var _startSessionReplay=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee26(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context26){while(1)switch(_context26.prev=_context26.next){case 0:this._enableSessionReplay=options===null||options===void 0?void 0:options.enableSessionReplay;this._sessionReplayOptions=options;_context26.next=1;return this._evaluateAndStartSessionReplay(cachedRemoteConfig);case 1:case"end":return _context26.stop();}},_callee26,this);}));function startSessionReplay(_x20,_x21){return _startSessionReplay.apply(this,arguments);}return startSessionReplay;}()},{key:"_evaluateAndStartSessionReplay",value:function _evaluateAndStartSessionReplay(cachedRemoteConfig){var _this18=this;var freshSession=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then(function(){return _this18._evaluateAndStartSessionReplayInternal(cachedRemoteConfig,freshSession);});return this._sessionReplayEvalChain;}},{key:"_evaluateAndStartSessionReplayInternal",value:function(){var _evaluateAndStartSessionReplayInternal2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee27(cachedRemoteConfig){var freshSession,_a,_b,options,enableNativeErrorTracking,enablePush,enableFatalJsCapture,remoteConfig,restoreAppRecording,request,cachedSessionReplayConfig,recordingActive,eventTriggers,activated,_args27=arguments,_t6;return _regenerator["default"].wrap(function(_context27){while(1)switch(_context27.prev=_context27.next){case 0:freshSession=_args27.length>1&&_args27[1]!==undefined?_args27[1]:false;options=this._sessionReplayOptions;enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);enablePush=this._isPushNativeEnabled(options);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();remoteConfig=cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(this._isEnableSessionReplay()){_context27.next=6;break;}restoreAppRecording=freshSession&&!this.optedOut&&this._sessionReplayWanted&&!this._sessionReplayStartedByApp;this._logger.info('Session replay is not enabled.');this._sessionReplayEventTriggers=this._sessionReplayWanted?this._parseEventTriggers(((_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_a!==void 0?_a:{})['eventTriggers']):[];if(!restoreAppRecording){_context27.next=2;break;}_context27.next=1;return this._restoreAppRecording();case 1:_context27.next=3;break;case 2:if(!(this._sessionReplayNativeInitialized&&(this.optedOut||freshSession&&!this._sessionReplayStartedByApp))){_context27.next=3;break;}_context27.next=3;return this._stopSessionRecording(this.optedOut);case 3:if(!(enableNativeErrorTracking||enablePush||enableFatalJsCapture)){_context27.next=4;break;}_context27.next=4;return this.initializeNativePlugin(options,remoteConfig,false);case 4:request=this._manualRecordingStartRequest;if(!((request===null||request===void 0?void 0:request.pending)&&!restoreAppRecording)){_context27.next=5;break;}_context27.next=5;return this._attemptManualRecordingStart(request,true);case 5:return _context27.abrupt("return");case 6:cachedSessionReplayConfig=(_b=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_b!==void 0?_b:{};recordingActive=this._isSessionReplayLinkedFlagActive(cachedSessionReplayConfig);eventTriggers=this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers']);this._sessionReplayEventTriggers=eventTriggers;if(eventTriggers.length>0){activated=this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([]));if(!activated){recordingActive=false;}this._logger.info("Session replay event triggers configured (".concat(eventTriggers.length,"); activated: ").concat(activated,"."));}if(!this.optedOut){_context27.next=9;break;}if(this._sessionReplayNativeInitialized){_context27.next=7;break;}_context27.next=7;return this.initializeNativePlugin(options,remoteConfig,true);case 7:if(!this._sessionReplayNativeInitialized){_context27.next=8;break;}_context27.next=8;return this._stopSessionRecording(true);case 8:if(this._sessionReplayWanted){this._sessionReplayRecordingActive=false;}return _context27.abrupt("return");case 9:if(!(freshSession&&!this._sessionReplayWanted&&!this._sessionReplayStartedByApp)){_context27.next=11;break;}if(!this._sessionReplayNativeInitialized){_context27.next=10;break;}_context27.next=10;return this._stopSessionRecording(true);case 10:this._sessionReplayRecordingActive=true;return _context27.abrupt("return");case 11:if(!recordingActive){_context27.next=17;break;}if(!(this._sessionReplayRecordingActive===true)){_context27.next=12;break;}return _context27.abrupt("return");case 12:if(!this._sessionReplayNativeInitialized){_context27.next=14;break;}_context27.next=13;return this._startSessionRecording(true);case 13:_t6=_context27.sent;_context27.next=16;break;case 14:_context27.next=15;return this.initializeNativePlugin(options,remoteConfig,true);case 15:_t6=_context27.sent;case 16:this._sessionReplayRecordingActive=_t6;_context27.next=22;break;case 17:this._logger.info('Session replay disabled.');if(!(this._sessionReplayRecordingActive===true)){_context27.next=19;break;}_context27.next=18;return this._stopSessionRecording();case 18:this._sessionReplayRecordingActive=!_context27.sent;_context27.next=21;break;case 19:if(!(freshSession&&!this._sessionReplayStartedByApp&&this._sessionReplayNativeInitialized)){_context27.next=20;break;}_context27.next=20;return this._stopSessionRecording();case 20:this._sessionReplayRecordingActive=false;case 21:if(!(enableNativeErrorTracking||enablePush)){_context27.next=22;break;}_context27.next=22;return this.initializeNativePlugin(options,remoteConfig,false);case 22:case"end":return _context27.stop();}},_callee27,this);}));function _evaluateAndStartSessionReplayInternal(_x22){return _evaluateAndStartSessionReplayInternal2.apply(this,arguments);}return _evaluateAndStartSessionReplayInternal;}()},{key:"_restoreAppRecording",value:function _restoreAppRecording(){this._cancelManualRecordingStart();var request={pending:false,retryCount:0,awaitEventTrigger:true};this._manualRecordingStartRequest=request;return this._attemptManualRecordingStart(request,true);}},{key:"_isSessionReplayLinkedFlagActive",value:function _isSessionReplayLinkedFlagActive(cachedSessionReplayConfig){var _a,_b;var featureFlags=(_a=this.getKnownFeatureFlags())!==null&&_a!==void 0?_a:{};var cachedFeatureFlags=(_b=featureFlags)!==null&&_b!==void 0?_b:{};this._logger.info('Session replay feature flags from flags cached config:',JSON.stringify(cachedFeatureFlags));var linkedFlagTrigger=this._linkedFlagTriggerStatus(cachedSessionReplayConfig['linkedFlag'],cachedFeatureFlags);this._logger.info(linkedFlagTrigger.message);var recordingActive=linkedFlagTrigger.status!=='trigger_pending';return recordingActive;}},{key:"processBeforeEnqueue",value:function processBeforeEnqueue(message){this._stampReplayDebugProperties(message);var claimedBundle=this._claimReplayDebugBundle(message);var accepted=false;try{var observation=this._fatalCaptureObservation;var isObservedFatal=observation!==undefined&&message.uuid===observation.eventUuid&&message.event==='$exception';var processed=_superPropGet(PostHog,"processBeforeEnqueue",this,3)([message]);var backdated=false;if(processed){try{backdated=this._stripDebugPropertiesIfBackdated(processed);}catch(e){this._logger.error("Session replay debug property strip failed: ".concat(e,"."));}}var suppress=false;if(isObservedFatal&&processed&&observation){try{observation.nativeCapture=observation.prepareNativeCapture(_objectSpread(_objectSpread({},processed),{},{properties:withoutDebugProperties(processed.properties)}));}catch(e){this._logger.warn("Fatal exception payload could not be prepared for native capture: ".concat(e));observation.nativeCapture=undefined;}suppress=observation.nativeCapture!==undefined;observation.queued=!suppress;}try{this._maybeActivateEventTrigger(processed===null||processed===void 0?void 0:processed['event']);this._refreshStaleNativeStatus();}catch(e){this._logger.error("Session replay event trigger check failed: ".concat(e,"."));}accepted=processed!==null&&!suppress&&!backdated;return suppress?null:processed;}finally{this._settleReplayDebugBundleClaim(claimedBundle,accepted);}}},{key:"_claimReplayDebugBundle",value:function _claimReplayDebugBundle(message){var claimed=isReplayDebugEvent(message.event)&&!this._replayDebugBundleClaimed&&(this._replayDebugBundleAcceptedAt===undefined||Date.now()-this._replayDebugBundleAcceptedAt>=REPLAY_DEBUG_PROPERTIES_INTERVAL_MS)&&!this._isBackdatedBeforeSession(message);if(claimed){this._replayDebugBundleClaimed=true;}else if(message.event==='$snapshot'){message.properties=withoutDebugProperties(message.properties);}else{message.properties=withoutOptionalReplayDebugProperties(message.properties);}return claimed;}},{key:"_settleReplayDebugBundleClaim",value:function _settleReplayDebugBundleClaim(claimed,accepted){if(!claimed){return;}this._replayDebugBundleClaimed=false;if(accepted){this._replayDebugBundleAcceptedAt=Date.now();}}},{key:"_captureFatalAndChooseOwner",value:function _captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,capture){var observation={eventUuid:eventUuid,prepareNativeCapture:prepareNativeCapture,queued:false};var previousObservation=this._fatalCaptureObservation;this._fatalCaptureObservation=observation;try{capture();}finally{this._fatalCaptureObservation=previousObservation;}return{queued:observation.queued,nativeCapture:observation.nativeCapture};}},{key:"_isBackdatedBeforeSession",value:function _isBackdatedBeforeSession(message){var sessionStart=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp);if(typeof sessionStart!=='number'||sessionStart<=0){return false;}var timestamp=message.timestamp;var eventTime=timestamp instanceof Date?timestamp.getTime():typeof timestamp==='string'?Date.parse(timestamp):NaN;return!Number.isNaN(eventTime)&&eventTime<sessionStart;}},{key:"_stripDebugPropertiesIfBackdated",value:function _stripDebugPropertiesIfBackdated(message){if(!this._isBackdatedBeforeSession(message)){return false;}message.properties=withoutDebugProperties(message.properties);return true;}},{key:"_maybeActivateEventTrigger",value:function _maybeActivateEventTrigger(eventName){if(this._sessionReplayEventTriggers.length===0||typeof eventName!=='string'){return;}if(!this._sessionReplayEventTriggers.includes(eventName)){return;}var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!sessionId){return;}if(this._isEventTriggerActivatedForSession(sessionId)&&this._sessionReplayRecordingActive===true){return;}if(!this._isEventTriggerActivatedForSession(sessionId)){this.setPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession,sessionId);this._logger.info("Session replay event trigger '".concat(eventName,"' activated for session ").concat(sessionId,"."));}void this._evaluateAndStartSessionReplay();this._refreshNativeSessionReplayDebugProperties();}},{key:"_parseEventTriggers",value:function _parseEventTriggers(value){if(!Array.isArray(value)){return[];}return value.filter(function(entry){return typeof entry==='string';});}},{key:"_isEventTriggerActivatedForSession",value:function _isEventTriggerActivatedForSession(sessionId){return this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession)===sessionId;}},{key:"captureAppLifecycleEvents",value:function(){var _captureAppLifecycleEvents=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee28(){var _this19=this;var _a,appBuild,appVersion,isMemoryPersistence,properties,prevAppBuild,prevAppVersion,installProperties,initialUrl,_t7,_t8,_t9;return _regenerator["default"].wrap(function(_context28){while(1)switch(_context28.prev=_context28.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;isMemoryPersistence=this._persistence==='memory';properties={};if(!isMemoryPersistence){prevAppBuild=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild);prevAppVersion=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion);if(!appBuild||!appVersion){this._logger.warn('PostHog could not track installation/update/open, as the build and version were not set. '+'This can happen if some dependencies are not installed correctly, or if you have provided'+'customAppProperties but not included $app_build or $app_version.');}if(appBuild){installProperties=_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('$react_native_version',(0,_utils.getReactNativeVersion)()));if(!prevAppBuild){this.capture('Application Installed',installProperties);}else if(prevAppBuild!==appBuild){this.capture('Application Updated',_objectSpread(_objectSpread(_objectSpread({},(0,_core.maybeAdd)('previous_version',prevAppVersion)),(0,_core.maybeAdd)('previous_build',prevAppBuild)),installProperties));}}}else{this._logger.warn('PostHog was initialised with persistence set to "memory", capturing native app events (Application Installed and Application Updated) is not supported.');}_context28.next=1;return _reactNative.Linking.getInitialURL();case 1:_t8=_a=_context28.sent;_t7=_t8!==null;if(!_t7){_context28.next=2;break;}_t7=_a!==void 0;case 2:if(!_t7){_context28.next=3;break;}_t9=_a;_context28.next=4;break;case 3:_t9=undefined;case 4:initialUrl=_t9;this.capture('Application Opened',_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('url',initialUrl)));_reactNative.AppState.addEventListener('change',function(state){if(state==='active'){_this19.capture('Application Became Active');}else if(state==='background'){_this19.capture('Application Backgrounded');}});case 5:case"end":return _context28.stop();}},_callee28,this);}));function captureAppLifecycleEvents(){return _captureAppLifecycleEvents.apply(this,arguments);}return captureAppLifecycleEvents;}()},{key:"persistAppVersion",value:function(){var _persistAppVersion=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee29(){var appBuild,appVersion;return _regenerator["default"].wrap(function(_context29){while(1)switch(_context29.prev=_context29.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild,appBuild);this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion,appVersion);case 1:case"end":return _context29.stop();}},_callee29,this);}));function persistAppVersion(){return _persistAppVersion.apply(this,arguments);}return persistAppVersion;}()}]);}(_core.PostHogCore);
2
2
  //# sourceMappingURL=posthog-rn.js.map