@oneuptime/react-native-replay 17.0.0 → 17.2.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/ReplayProvider.tsx", "../src/MobileReplayRecorder.ts", "../src/Contract.ts", "../src/Sanitize.ts", "../src/ChunkBuffer.ts", "../src/CustomSignals.ts", "../src/ProductAnalyticsContract.ts", "../src/Config.ts", "../src/ViewTreeSerializer.ts", "../src/Events.ts", "../src/NativeViewTree.ts", "../node_modules/fflate/esm/browser.js", "../src/Base64.ts", "../src/Outbox.ts", "../src/RetryAfter.ts", "../src/Storage.ts", "../src/ProductAnalytics.ts", "../src/Transport.ts", "../src/TouchPrivacy.ts"],
4
- "sourcesContent": ["import MobileReplayRecorder from \"./MobileReplayRecorder\";\nimport { defaultMobileReplayRecorder } from \"./ReplayProvider\";\n\nexport { default as MobileReplayRecorder } from \"./MobileReplayRecorder\";\nexport type {\n MobileReplayDiagnosticEvent,\n MobileReplayDiagnostics,\n MobileReplayRecorderDependencies,\n MobileReplaySessionChangeListener,\n MobileReplayStatus,\n} from \"./MobileReplayRecorder\";\nexport type {\n MobileReplayStartOptions,\n ReplayFetch,\n ReplayFetchResponse,\n} from \"./Config\";\nexport type {\n ProductAnalyticsDiagnostics,\n ProductAnalyticsStopReason,\n} from \"./ProductAnalytics\";\nexport {\n OneUptimeReplayProvider,\n ReplayMask,\n ReplayProvider,\n useOneUptimeReplay,\n} from \"./ReplayProvider\";\nexport type {\n OneUptimeReplayProviderProps,\n ReplayMaskProps,\n} from \"./ReplayProvider\";\nexport type { RecordedTouch, TouchPhase } from \"./Events\";\nexport {\n MOBILE_RECORDER_KIND,\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n SessionReplayCaptureTrigger,\n SessionReplayConsentMode,\n SessionReplayFidelityNotice,\n SessionReplayMaskingMode,\n SessionReplayTriggerReason,\n} from \"./Contract\";\n\n/** Process-wide convenience client used by ReplayProvider by default. */\nexport const OneUptimeReplay: MobileReplayRecorder =\n defaultMobileReplayRecorder;\n\nexport default OneUptimeReplay;\n", "import React, {\n createContext,\n ReactElement,\n ReactNode,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport {\n findNodeHandle,\n GestureResponderEvent,\n StyleProp,\n View,\n ViewStyle,\n} from \"react-native\";\nimport { MobileReplayStartOptions } from \"./Config\";\nimport { RecordedTouch } from \"./Events\";\nimport MobileReplayRecorder from \"./MobileReplayRecorder\";\n\nexport const defaultMobileReplayRecorder: MobileReplayRecorder =\n new MobileReplayRecorder();\n\nconst ReplayContext: React.Context<MobileReplayRecorder> =\n createContext<MobileReplayRecorder>(defaultMobileReplayRecorder);\n\nexport interface OneUptimeReplayProviderProps {\n children: ReactNode;\n recorder?: MobileReplayRecorder;\n /** Optional convenience start; callers may instead call recorder.start(). */\n options?: MobileReplayStartOptions;\n stopOnUnmount?: boolean;\n style?: StyleProp<ViewStyle>;\n}\n\nexport interface GestureTouchPoint {\n x: number;\n y: number;\n}\n\nexport function touchPointFromEvent(\n event: GestureResponderEvent,\n): GestureTouchPoint {\n const nativeEvent: GestureResponderEvent[\"nativeEvent\"] = event.nativeEvent;\n const x: number =\n typeof nativeEvent.pageX === \"number\"\n ? nativeEvent.pageX\n : typeof nativeEvent.locationX === \"number\"\n ? nativeEvent.locationX\n : 0;\n const y: number =\n typeof nativeEvent.pageY === \"number\"\n ? nativeEvent.pageY\n : typeof nativeEvent.locationY === \"number\"\n ? nativeEvent.locationY\n : 0;\n return {\n x: Number.isFinite(x) ? x : 0,\n y: Number.isFinite(y) ? y : 0,\n };\n}\n\nexport function OneUptimeReplayProvider(\n props: OneUptimeReplayProviderProps,\n): ReactElement {\n const recorder: MobileReplayRecorder =\n props.recorder ?? defaultMobileReplayRecorder;\n const rootRef: React.RefObject<View | null> = useRef<View>(null);\n const initialOptions: React.MutableRefObject<\n MobileReplayStartOptions | undefined\n > = useRef(props.options);\n\n useEffect((): (() => void) => {\n const tag: number | null = findNodeHandle(rootRef.current);\n recorder.setRootTag(tag);\n if (initialOptions.current) {\n void recorder.start(initialOptions.current);\n }\n\n return (): void => {\n recorder.setRootTag(null);\n if (initialOptions.current && props.stopOnUnmount !== false) {\n void recorder.stop();\n }\n };\n }, [props.stopOnUnmount, recorder]);\n\n const record: (\n phase: \"start\" | \"move\" | \"end\",\n event: GestureResponderEvent,\n ) => void = (\n phase: \"start\" | \"move\" | \"end\",\n event: GestureResponderEvent,\n ): void => {\n const point: GestureTouchPoint = touchPointFromEvent(event);\n const targetTag: unknown = event.nativeEvent.target;\n const pointerId: unknown = (\n event.nativeEvent as unknown as Record<string, unknown>\n )[\"identifier\"];\n const touch: RecordedTouch = {\n phase,\n x: point.x,\n y: point.y,\n timestamp: Date.now(),\n };\n if (typeof targetTag === \"number\" && Number.isSafeInteger(targetTag)) {\n touch.targetTag = targetTag;\n }\n if (\n (typeof pointerId === \"number\" && Number.isSafeInteger(pointerId)) ||\n typeof pointerId === \"string\"\n ) {\n touch.pointerId = pointerId;\n }\n recorder.recordTouch(touch);\n };\n\n return (\n <ReplayContext.Provider value={recorder}>\n <View\n ref={rootRef}\n collapsable={false}\n style={[{ flex: 1 }, props.style]}\n onTouchStart={(event: GestureResponderEvent): void => {\n record(\"start\", event);\n }}\n onTouchMove={(event: GestureResponderEvent): void => {\n record(\"move\", event);\n }}\n onTouchEnd={(event: GestureResponderEvent): void => {\n record(\"end\", event);\n }}\n >\n {props.children}\n </View>\n </ReplayContext.Provider>\n );\n}\n\nexport function useOneUptimeReplay(): MobileReplayRecorder {\n return useContext(ReplayContext);\n}\n\nexport interface ReplayMaskProps {\n children: ReactNode;\n style?: StyleProp<ViewStyle>;\n}\n\n/** A hard native traversal boundary; descendants are never serialized. */\nexport function ReplayMask(props: ReplayMaskProps): ReactElement {\n return (\n <View\n collapsable={false}\n nativeID=\"oneuptime-replay-mask\"\n testID=\"oneuptime-replay-mask\"\n style={props.style}\n >\n {props.children}\n </View>\n );\n}\n\nexport const ReplayProvider: typeof OneUptimeReplayProvider =\n OneUptimeReplayProvider;\n", "import { AppState, Keyboard } from \"react-native\";\nimport ReplayChunkBuffer, {\n BufferedReplaySegment,\n RollingReplayBuffer,\n} from \"./ChunkBuffer\";\nimport {\n CUSTOM_EVENT_TAG,\n CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,\n ERROR_CUSTOM_EVENT_TAG,\n IDENTIFY_CUSTOM_EVENT_TAG,\n IDLE_PAUSED_CUSTOM_EVENT_TAG,\n IDLE_RESUMED_CUSTOM_EVENT_TAG,\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION,\n MOBILE_CAPTURE_INTERVAL_MS,\n MOBILE_RECORDER_KIND,\n RECORDER_VERSION,\n ROUTE_CUSTOM_EVENT_TAG,\n SESSION_REPLAY_CHECKOUT_INTERVAL_MS,\n SESSION_REPLAY_FLUSH_INTERVAL_MS,\n SESSION_REPLAY_IDLE_PAUSE_MS,\n SESSION_REPLAY_IDLE_ROLLOVER_MS,\n SESSION_REPLAY_MAX_SESSION_MS,\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n SESSION_REPLAY_SCHEMA_VERSION,\n SESSION_REPLAY_WIRE_VERSION,\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n SYNTHETIC_RRWEB_VERSION,\n TAGS_CUSTOM_EVENT_TAG,\n TOUCH_CUSTOM_EVENT_TAG,\n VISIBILITY_CUSTOM_EVENT_TAG,\n RrwebEvent,\n SessionReplayCaptureTrigger,\n SessionReplayChunkEnvelope,\n SessionReplayChunkMeta,\n SessionReplayConsentMode,\n SessionReplayConsentState,\n SessionReplayCustomSignalConfig,\n SessionReplayCustomSignalPayload,\n SessionReplayDirective,\n SessionReplayIdlePausedPayload,\n SessionReplayIdleResumedPayload,\n SessionReplayTriggerReason,\n} from \"./Contract\";\nimport {\n fetchReplayConfig,\n forgetReplayConfig,\n loadCachedReplayConfig,\n MobileReplayStartOptions,\n mobileRequestHeaders,\n ResolvedReplayConfig,\n saveReplayConfig,\n ValidatedStartOptions,\n validateStartOptions,\n} from \"./Config\";\nimport { CustomSignalMatcher, MobileCustomSignalHit } from \"./CustomSignals\";\nimport {\n createCustomEvent,\n createTouchEvent,\n RecordedTouch,\n sanitizeRecordedTouch,\n} from \"./Events\";\nimport {\n defaultNativeViewTreeAdapter,\n getViewport,\n NativeAppMetadata,\n NativeViewTreeAdapter,\n NativeViewTreeNode,\n} from \"./NativeViewTree\";\nimport ReplayOutbox from \"./Outbox\";\nimport MobileProductAnalytics, {\n ProductAnalyticsDiagnostics,\n ProductAnalyticsIdentity,\n} from \"./ProductAnalytics\";\nimport {\n PRODUCT_ANALYTICS_EVENTS_PATH,\n PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH,\n PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE,\n ProductAnalyticsWireContext,\n toProductAnalyticsAppVersion,\n} from \"./ProductAnalyticsContract\";\nimport {\n MAX_CAPTURE_REASON_LENGTH,\n MAX_CUSTOM_EVENT_NAME_LENGTH,\n MAX_TAG_KEY_LENGTH,\n MAX_TAG_VALUE_LENGTH,\n MAX_USER_REFERENCE_LENGTH,\n maskStringMapValues,\n maskTextValue,\n sanitizeEventProperties,\n sanitizeRoute,\n sanitizeTags,\n sanitizeTraits,\n toAppUrl,\n truncate,\n} from \"./Sanitize\";\nimport ReplaySessionStore, {\n defaultReplayStorage,\n generateReplayId,\n ReplaySessionIdentity,\n ReplayStorage,\n} from \"./Storage\";\nimport ReplayTransport from \"./Transport\";\nimport {\n CONSERVATIVE_TOUCH_PRIVACY_MAP,\n deriveTouchPrivacyMap,\n isTouchPrivate,\n TouchPrivacyMap,\n} from \"./TouchPrivacy\";\nimport ViewTreeSerializer, { SerializedCapture } from \"./ViewTreeSerializer\";\n\n/*\n * \"paused\" is a recording recorder that nobody has touched for\n * SESSION_REPLAY_IDLE_PAUSE_MS: it captures nothing until the next touch or\n * the app's return to the foreground (see idlePause).\n */\nexport type MobileReplayStatus =\n | \"idle\"\n | \"starting\"\n | \"recording\"\n | \"paused\"\n | \"background\"\n | \"consent-required\"\n | \"disabled\"\n | \"stopped\"\n | \"consent-revoked\";\n\nexport interface MobileReplayDiagnosticEvent {\n code: string;\n atUnixMs: number;\n details?: Record<string, unknown>;\n}\n\nexport interface MobileReplayDiagnostics {\n status: MobileReplayStatus;\n sessionId: string | null;\n recorderKind: \"rn-view-tree\";\n configEpoch: number;\n sampled: boolean;\n triggered: boolean;\n consentState: SessionReplayConsentState;\n pendingEvents: number;\n /*\n * Product analytics events (issue #6629): \"off\" when the application has\n * them off or nothing runs, \"on\" while they are sent, else why they\n * stopped; how many items are held to be sent, and how many events were\n * dropped because too many were held.\n */\n productAnalytics: ProductAnalyticsDiagnostics;\n events: Array<MobileReplayDiagnosticEvent>;\n}\n\nexport type MobileReplaySessionChangeListener = (\n sessionId: string | null,\n) => void;\n\ninterface AppStateSubscription {\n remove(): void;\n}\n\nexport interface ReplayAppState {\n currentState: string | null;\n addEventListener(\n type: \"change\",\n listener: (state: string) => void,\n ): AppStateSubscription;\n}\n\ninterface KeyboardSubscription {\n remove(): void;\n}\n\n/*\n * The soft keyboard, as React Native's Keyboard module reports it. Typing\n * on it never reaches the replay root as a touch - the keyboard is a window\n * of its own - so its showing and hiding are what say someone is typing.\n * The Did events, because Android reports no Will events. isVisible() (React\n * Native 0.71+) says whether it was already up when recording started.\n */\nexport interface ReplayKeyboard {\n addListener(\n eventName: \"keyboardDidShow\" | \"keyboardDidHide\",\n listener: () => void,\n ): KeyboardSubscription;\n isVisible?(): boolean;\n}\n\nexport interface MobileReplayRecorderDependencies {\n storage?: ReplayStorage;\n nativeViewTree?: NativeViewTreeAdapter;\n appState?: ReplayAppState;\n keyboard?: ReplayKeyboard;\n now?: () => number;\n}\n\ntype GlobalErrorHandler = (error: Error, isFatal?: boolean) => void;\n\ninterface GlobalErrorUtils {\n getGlobalHandler?(): GlobalErrorHandler | undefined;\n setGlobalHandler?(handler: GlobalErrorHandler): void;\n}\n\nconst MAX_DIAGNOSTIC_EVENTS: number = 100;\nconst TOUCH_MOVE_SAMPLE_MS: number = 50;\nexport const MOBILE_POLICY_REFRESH_INTERVAL_MS: number = 5 * 60_000;\ntype SessionRotationReason = \"duration\" | \"idle\" | \"chunk-cap\" | \"identity\";\ntype PolicyRefreshReason = \"consent\" | \"foreground\" | \"identity\" | \"periodic\";\ntype ChunkAppendOptions = NonNullable<\n Parameters<ReplayChunkBuffer[\"append\"]>[1]\n>;\n\n/*\n * Capture stopped because nobody touched the app for\n * SESSION_REPLAY_IDLE_PAUSE_MS. Kept from the pause until the snapshot\n * that resumes it is in the buffer, or until the session ends (sealForIdle,\n * or any rotation).\n */\ninterface IdlePause {\n /*\n * The stream the pause belongs to. Only that session and tab are owed\n * the matching idle-resumed marker, and only its stop is dated at the\n * pause: an identity swapped underneath (a consent decision) never had\n * the pause in its stream.\n */\n sessionId: string;\n tabId: string;\n idleSinceUnixMs: number;\n pausedAtUnixMs: number;\n /*\n * The idle-paused marker went out in an uploading stream. A recorder\n * holding its pre-roll in memory marks nothing and drops the pre-roll\n * instead (see pauseForIdle), so its resume owes no marker and its stop\n * sends nothing.\n */\n marked: boolean;\n}\n\n/* An event recorded between an input that ended a pause and its snapshot. */\ninterface HeldReplayEvent {\n event: RrwebEvent;\n options: ChunkAppendOptions;\n}\n\n/*\n * The resuming snapshot normally follows its input within one native\n * capture. This bounds what can pile up when it cannot - a replay root\n * unmounted during the pause leaves nothing to capture until it is back.\n */\nconst MAX_EVENTS_HELD_FOR_RESUME: number = 500;\n\n/*\n * What a touch or a return to the foreground did to an idle pause:\n * nothing (there was none), resumed the paused session, or found that the\n * paused session has ended, so the input starts the next one.\n */\ntype IdleInputOutcome = \"none\" | \"resumed\" | \"session-ended\";\n\nconst SAFE_ERROR_NAMES: ReadonlySet<string> = new Set<string>([\n \"AggregateError\",\n \"Error\",\n \"EvalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/*\n * The text an error's signals are matched on: its message as thrown. Only\n * ever compared on the device; never recorded or sent.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") {\n return error;\n }\n if (error && typeof error === \"object\") {\n const message: unknown = (error as { message?: unknown }).message;\n if (typeof message === \"string\") {\n return message;\n }\n }\n return \"\";\n}\n\nfunction defaultNow(): number {\n return Date.now();\n}\n\nfunction deterministicSample(sessionId: string, percentage: number): boolean {\n if (percentage >= 100) {\n return true;\n }\n if (percentage <= 0) {\n return false;\n }\n\n let hash: number = 2_166_136_261;\n for (let index: number = 0; index < sessionId.length; index += 1) {\n hash ^= sessionId.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n\n return (hash >>> 0) % 10_000 < Math.round(percentage * 100);\n}\n\nfunction hashNamespaceSecret(value: string): string {\n const seeds: Array<number> = [\n 2_166_136_261, 2_654_435_761, 1_013_904_223, 3_747_611_933,\n ];\n return seeds\n .map((seed: number): string => {\n let hash: number = seed;\n for (let index: number = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n })\n .join(\"\");\n}\n\nexport function getReplayStorageNamespace(\n options: Pick<\n ValidatedStartOptions,\n \"host\" | \"token\" | \"appIdentifier\" | \"mobileAppIdentifier\"\n >,\n): string {\n const scope: string = [\n options.host,\n options.appIdentifier,\n options.mobileAppIdentifier,\n hashNamespaceSecret(options.token),\n ].join(\"\\u0000\");\n return `v1-${hashNamespaceSecret(scope)}`;\n}\n\nfunction safeMetadataValue(\n value: unknown,\n fallback: string,\n maximumLength: number = 100,\n): string {\n return typeof value === \"string\" && value.trim()\n ? truncate(value.trim(), maximumLength)\n : fallback;\n}\n\nfunction isRetryablePolicyFailure(config: ResolvedReplayConfig): boolean {\n if (config.disabledReason === \"config-fetch-failed\") {\n return true;\n }\n const match: RegExpMatchArray | null =\n config.disabledReason?.match(/^config-http-(\\d{3})$/u) ?? null;\n if (!match) {\n return false;\n }\n const status: number = Number(match[1]);\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nexport default class MobileReplayRecorder {\n private readonly storage: ReplayStorage;\n private readonly nativeViewTree: NativeViewTreeAdapter;\n private readonly appState: ReplayAppState;\n private readonly keyboard: ReplayKeyboard | null;\n private readonly now: () => number;\n private readonly serializer: ViewTreeSerializer = new ViewTreeSerializer();\n private readonly chunkBuffer: ReplayChunkBuffer = new ReplayChunkBuffer();\n /* The application's own page, event and error signals (issue #6443). */\n private readonly customSignalMatcher: CustomSignalMatcher =\n new CustomSignalMatcher();\n private readonly rollingBuffer: RollingReplayBuffer =\n new RollingReplayBuffer();\n private diagnosticsStatus: MobileReplayStatus = \"idle\";\n private diagnosticsEvents: Array<MobileReplayDiagnosticEvent> = [];\n private options: ValidatedStartOptions | null = null;\n private config: ResolvedReplayConfig | null = null;\n private sessionStore: ReplaySessionStore | null = null;\n private identity: ReplaySessionIdentity | null = null;\n private outbox: ReplayOutbox | null = null;\n private transport: ReplayTransport | null = null;\n private metadata: NativeAppMetadata = {\n appName: \"React Native\",\n appVersion: \"unknown\",\n osName: \"unknown\",\n osVersion: \"unknown\",\n };\n private rootTag: number | null = null;\n private route: string = \"/\";\n private entryUrl: string = \"\";\n private captureTimer: ReturnType<typeof setInterval> | null = null;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private appStateSubscription: AppStateSubscription | null = null;\n\n /*\n * Offline mode: the host app's connectivity source (start option\n * `connectivity`), and what it last said, which a transport created later\n * - after a consent or identity change - starts from.\n */\n private unsubscribeConnectivity: (() => void) | null = null;\n private lastConnectivity: boolean | null = null;\n\n /*\n * The policy in force is the cached one an offline launch started with,\n * or the last refresh could not reach the server. Refreshed the moment the\n * connection is back rather than on the five-minute schedule, so a policy\n * changed while the device was offline takes effect before its backlog\n * has finished uploading.\n */\n private policyStale: boolean = false;\n private captureGeneration: number | null = null;\n private running: boolean = false;\n private foreground: boolean = true;\n private forceFullSnapshot: boolean = true;\n private lastFullSnapshotAtUnixMs: number = 0;\n private sampled: boolean = false;\n private triggered: boolean = false;\n private uploadActive: boolean = false;\n private consentGranted: boolean = false;\n private triggerReason: SessionReplayTriggerReason =\n SessionReplayTriggerReason.Sampled;\n private userRef: string | null = null;\n private traits: Record<string, string> = {};\n private tags: Record<string, string> = {};\n private metaDirty: boolean = true;\n private droppedEvents: number = 0;\n private closeQueue: Promise<void> = Promise.resolve();\n private lastTouchMoveAtUnixMs: number = 0;\n private previousGlobalErrorHandler: GlobalErrorHandler | null = null;\n private installedGlobalErrorHandler: GlobalErrorHandler | null = null;\n private globalErrorUtils: GlobalErrorUtils | null = null;\n private lifecycleGeneration: number = 0;\n private lifecycleCancellationEpoch: number = 0;\n private lifecycleQueue: Promise<void> = Promise.resolve();\n private pendingStart: {\n generation: number;\n promise: Promise<boolean>;\n } | null = null;\n private pendingStartCancellation: {\n generation: number;\n cancel: () => void;\n } | null = null;\n private identityPersisted: boolean = false;\n private sessionLastActivityUnixMs: number = 0;\n\n /*\n * The session went the idle window without activity, was sealed where it\n * ended, and nobody has come back since.\n *\n * Rotating on the spot instead (the old behaviour) started a session\n * nobody was in: an app left open in the foreground with the screen on\n * re-snapshots every minute, so it filed a new session every half hour\n * for as long as it stayed open. Now nothing is captured, uploaded or\n * handed to the host as a session id until the user is back - a touch,\n * the soft keyboard, the app returning to the foreground, or an explicit\n * captureSession() - and that starts the next session (see\n * maybeRotateSession). In the foreground the session was almost always\n * paused for idle first (idlePause), so its footage already ended there.\n */\n private sealedForIdle: boolean = false;\n private rotatingSession: boolean = false;\n private rotationPromise: Promise<void> | null = null;\n private appStateQueue: Promise<void> = Promise.resolve();\n private acceptingEvents: boolean = false;\n private lastPolicyRefreshAtUnixMs: number = 0;\n private policyRefreshPromise: Promise<boolean> | null = null;\n private identityQueue: Promise<void> = Promise.resolve();\n private identityCancellationEpoch: number = 0;\n private pendingIdentityOperations: number = 0;\n private readonly sessionChangeListeners: Set<MobileReplaySessionChangeListener> =\n new Set<MobileReplaySessionChangeListener>();\n private lastNotifiedSessionId: string | null = null;\n private touchPrivacyMap: TouchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n private touchQueue: Promise<void> = Promise.resolve();\n private readonly suppressedTouchPointers: Set<string> = new Set<string>();\n private unidentifiedTouchCount: number = 0;\n private unidentifiedTouchPrivate: boolean = false;\n\n /*\n * When the person last did something: a touch (any touch - one inside a\n * ReplayMask is still someone using the app, even though it is never\n * recorded), the app coming back to the foreground, or the app starting.\n * Not sessionLastActivityUnixMs, which every recorded event moves: a\n * route change, a track() call or a JS error the app raises by itself is\n * the app, not the person, and a polling screen would otherwise never\n * look idle.\n */\n private lastInputUnixMs: number = 0;\n\n /*\n * The idle pause (SESSION_REPLAY_IDLE_PAUSE_MS, #4208). Set when the\n * capture tick finds nobody has touched the app for that long: the open\n * chunk closes with an idle-paused marker as its last event, the capture\n * timer stops, and from then on nothing is recorded - no view-tree\n * sample, no checkout, no chunk, and every event the app emits is\n * dropped rather than queued. The 15-second flush timer is the only one\n * left, and all it does is end the session (sealForIdle, #4207) if nobody\n * comes back inside SESSION_REPLAY_IDLE_ROLLOVER_MS.\n *\n * It exists because the recorder used to go on sampling the view tree\n * every 500 ms, with a full checkout every minute, for the whole half\n * hour before the idle rollover - the phone's CPU and battery and the\n * customer's upload and storage, all spent on footage of nobody.\n *\n * Input inside that window - a touch, the soft keyboard, the app\n * returning to the foreground - resumes the same session and tab on a\n * fresh full snapshot with an idle-resumed marker directly behind it\n * (idleResumeBacklog), at the next chunk index.\n */\n private idlePause: IdlePause | null = null;\n\n /*\n * Non-null from the input that ends an idle pause until the snapshot it\n * resumes on is in the buffer. What is recorded meanwhile - the touch\n * that woke the recorder, the screen it opened, a track() it caused - is\n * held here and appended behind that snapshot and the idle-resumed\n * marker, so the chunk after a pause always opens on its snapshot.\n */\n private idleResumeBacklog: Array<HeldReplayEvent> | null = null;\n\n /*\n * The soft keyboard is up. Keystrokes reach no view the recorder can see,\n * so someone writing a long message - a chat, a form, a review - would\n * otherwise look exactly like nobody touching the app. While it is up the\n * idle pause waits, and its showing and hiding are input\n * (onKeyboardChange). The 30-minute rollover does not look at it.\n */\n private softKeyboardVisible: boolean = false;\n private keyboardSubscriptions: Array<KeyboardSubscription> = [];\n\n /*\n * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside\n * the recording, from every session the policy lets the recorder run in,\n * recorded or not. Null while the application has them off.\n */\n private analytics: MobileProductAnalytics | null = null;\n\n /*\n * The replay sample left the session out under \"Always\": nothing of it\n * is recorded, but its product analytics events are still sent - and,\n * nothing else moving the session, they are what keeps it alive\n * (ReplaySessionStore.continueSession), as the browser recorder does.\n */\n private analyticsOnly: boolean = false;\n\n public constructor(dependencies: MobileReplayRecorderDependencies = {}) {\n this.storage = dependencies.storage ?? defaultReplayStorage;\n this.nativeViewTree =\n dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;\n this.appState =\n dependencies.appState ?? (AppState as unknown as ReplayAppState);\n /* Absent where React Native has no Keyboard module: no typing signal. */\n this.keyboard =\n dependencies.keyboard ??\n (Keyboard as unknown as ReplayKeyboard | undefined) ??\n null;\n this.now = dependencies.now ?? defaultNow;\n }\n\n public start(options: MobileReplayStartOptions): Promise<boolean> {\n if (\n this.pendingStart &&\n this.pendingStart.generation === this.lifecycleCancellationEpoch\n ) {\n return this.pendingStart.promise;\n }\n\n const requestGeneration: number = this.lifecycleCancellationEpoch;\n const identityBarrier: Promise<void> = this.identityQueue;\n const promise: Promise<boolean> = this.enqueueLifecycleOperation(\n async (): Promise<boolean> => {\n await identityBarrier;\n if (requestGeneration !== this.lifecycleCancellationEpoch) {\n return false;\n }\n return await this.startNow(options);\n },\n );\n this.pendingStart = { generation: requestGeneration, promise };\n void promise.then(\n (): void => {\n if (this.pendingStart?.promise === promise) {\n this.pendingStart = null;\n }\n },\n (): void => {\n if (this.pendingStart?.promise === promise) {\n this.pendingStart = null;\n }\n },\n );\n return promise;\n }\n\n private async startNow(options: MobileReplayStartOptions): Promise<boolean> {\n if (this.running) {\n return true;\n }\n const generation: number = this.lifecycleGeneration + 1;\n this.lifecycleGeneration = generation;\n let cancelStart: () => void = (): void => {\n return undefined;\n };\n const cancellation: Promise<boolean> = new Promise<boolean>(\n (resolve: (value: boolean | PromiseLike<boolean>) => void): void => {\n cancelStart = (): void => {\n resolve(false);\n };\n },\n );\n this.pendingStartCancellation = { generation, cancel: cancelStart };\n const work: Promise<boolean> = this.startInternal(options, generation);\n try {\n return await Promise.race([work, cancellation]);\n } finally {\n if (this.pendingStartCancellation?.generation === generation) {\n this.pendingStartCancellation = null;\n }\n }\n }\n\n private async startInternal(\n options: MobileReplayStartOptions,\n generation: number,\n ): Promise<boolean> {\n this.acceptingEvents = false;\n this.diagnosticsStatus = \"starting\";\n this.serializer.reset();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.closeQueue = Promise.resolve();\n this.appStateQueue = Promise.resolve();\n this.rotationPromise = null;\n this.rotatingSession = false;\n this.sealedForIdle = false;\n this.policyRefreshPromise = null;\n this.lastPolicyRefreshAtUnixMs = 0;\n this.forceFullSnapshot = true;\n this.lastFullSnapshotAtUnixMs = 0;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.touchQueue = Promise.resolve();\n this.resetTouchSequences();\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.customSignalMatcher.reset();\n /* A run before this one (an unsampled session's events) ends here. */\n this.stopProductAnalytics();\n const validated: ValidatedStartOptions | null =\n validateStartOptions(options);\n if (!validated) {\n this.disable(\"invalid-start-options\");\n return false;\n }\n\n if (validated.userRef) {\n this.userRef = truncate(validated.userRef, MAX_USER_REFERENCE_LENGTH);\n }\n this.options = this.userRef\n ? { ...validated, userRef: this.userRef }\n : validated;\n if (this.nativeViewTree.isAvailable?.() === false) {\n this.disable(\"native-module-unavailable\", {\n expoGoUnsupported: true,\n });\n return false;\n }\n\n const namespace: string = getReplayStorageNamespace(validated);\n let config: ResolvedReplayConfig = await fetchReplayConfig(this.options);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n\n /*\n * Offline mode. An app launched without a connection cannot fetch its\n * policy; failing closed there meant nothing was recorded on exactly the\n * launches offline mode exists for. The last policy the server gave is\n * used instead - only when the request got no usable answer, never when\n * the server answered that replay is off - and the periodic refresh\n * replaces it the moment the server can be reached.\n */\n let configFromCache: boolean = false;\n if (isRetryablePolicyFailure(config)) {\n const cached: ResolvedReplayConfig | null = await loadCachedReplayConfig(\n this.storage,\n namespace,\n this.now(),\n );\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n if (cached) {\n this.diagnostic(\"config-from-cache\", {\n reason: config.disabledReason ?? \"not-reported\",\n });\n config = cached;\n configFromCache = true;\n }\n } else if (this.mayPersistUnder(config)) {\n await saveReplayConfig(this.storage, namespace, config, this.now());\n }\n\n if (\n !configFromCache &&\n config.enabled &&\n this.userRef &&\n (config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted)\n ) {\n config = await this.refreshTargetingConfig(config);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n this.config = config;\n if (!config.enabled) {\n this.disable(\"config-disabled\", {\n reason: config.disabledReason ?? \"not-reported\",\n });\n return false;\n }\n /* A cached policy is refreshed at the first chance, not in five minutes. */\n this.lastPolicyRefreshAtUnixMs = configFromCache ? 0 : this.now();\n this.policyStale = configFromCache;\n\n const sessionStore: ReplaySessionStore = new ReplaySessionStore(\n this.storage,\n namespace,\n );\n this.sessionStore = sessionStore;\n const nowUnixMs: number = this.now();\n const awaitingConsent: boolean =\n config.consentMode === SessionReplayConsentMode.RequireExplicit &&\n !this.consentGranted;\n if (awaitingConsent) {\n this.identity = this.ephemeralIdentity(nowUnixMs);\n this.identityPersisted = false;\n this.sampled = false;\n } else {\n const identity: ReplaySessionIdentity =\n await sessionStore.resolve(nowUnixMs);\n if (\n !this.isCurrentGeneration(generation) ||\n this.sessionStore !== sessionStore\n ) {\n return false;\n }\n this.identity = identity;\n this.identityPersisted = true;\n this.sampled = deterministicSample(\n this.identity.sessionId,\n config.samplePercentage,\n );\n }\n this.sessionLastActivityUnixMs = nowUnixMs;\n /*\n * Starting is itself the person: the app was just opened. Without this\n * an app nobody touches after launch would be judged idle from epoch 0\n * and pause on its very first capture.\n */\n this.lastInputUnixMs = nowUnixMs;\n\n /*\n * Product analytics (issue #6629) start before the replay sample is\n * read: a session it leaves out records nothing, but its events still\n * count. Their context needs the app's metadata, read first.\n */\n let metadataRead: boolean = false;\n if (config.productAnalytics.enabled) {\n if (!(await this.readAppMetadata(validated, generation))) {\n return false;\n }\n metadataRead = true;\n await this.startProductAnalytics(validated, config, namespace);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n\n if (\n !awaitingConsent &&\n config.captureTrigger === SessionReplayCaptureTrigger.Always &&\n !this.sampled &&\n !config.isTargeted\n ) {\n this.analyticsOnly = this.analytics !== null;\n this.disable(\"not-sampled\");\n return false;\n }\n\n this.outbox = new ReplayOutbox(this.storage, namespace, this.now);\n this.transport = this.createTransport(validated, this.outbox);\n this.subscribeConnectivity(validated);\n\n if (!metadataRead && !(await this.readAppMetadata(validated, generation))) {\n return false;\n }\n\n this.route = \"/\";\n this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);\n this.running = true;\n this.acceptingEvents = true;\n this.triggered = config.isTargeted;\n this.triggerReason = config.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n const hasConsent: boolean =\n config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted;\n this.uploadActive =\n hasConsent && (this.sampled || config.isTargeted || this.triggered);\n this.foreground = this.appState.currentState === \"active\";\n this.diagnosticsStatus = hasConsent\n ? this.foreground\n ? \"recording\"\n : \"background\"\n : \"consent-required\";\n this.notifySessionChange();\n this.installLifecycle();\n this.installGlobalErrorHandler();\n if (this.foreground) {\n this.startTimers();\n await this.captureTick(true);\n }\n if (!this.running) {\n return false;\n }\n if (this.uploadActive) {\n await this.transport.restore();\n }\n if (!this.isCurrentGeneration(generation) || !this.running) {\n return false;\n }\n this.diagnostic(\"recorder-started\", {\n sampled: this.sampled,\n consentState: this.consentState(),\n });\n return true;\n }\n\n public stop(): Promise<void> {\n const identityBarrier: Promise<void> = this.identityQueue;\n this.lifecycleGeneration += 1;\n this.lifecycleCancellationEpoch += 1;\n this.pendingStartCancellation?.cancel();\n this.acceptingEvents = false;\n /* What product analytics holds goes now, while it can (issue #6629). */\n this.stopProductAnalytics(true);\n this.quiesceCapture();\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n await identityBarrier;\n await this.stopInternal();\n });\n }\n\n private async stopInternal(): Promise<void> {\n if (!this.running) {\n this.diagnosticsStatus = \"stopped\";\n return;\n }\n\n if (this.rotationPromise) {\n await this.rotationPromise;\n }\n if (!this.running) {\n this.diagnosticsStatus = \"stopped\";\n return;\n }\n\n /*\n * Not on a session that has gone idle: it ended at its last activity,\n * and a marker dated now would stretch it by the whole absence. Any\n * footage it still buffers goes out below, dated by itself.\n */\n const endedIdle: boolean =\n this.sealedForIdle || this.rotationReason(this.now()) === \"idle\";\n const pause: IdlePause | null = this.idlePause;\n if (!endedIdle && pause === null) {\n this.appendCustom(\n VISIBILITY_CUSTOM_EVENT_TAG,\n { state: \"stopped\" },\n undefined,\n true,\n );\n } else if (!endedIdle && pause !== null && this.isPauseInStream(pause)) {\n /*\n * Stopped while paused for idle (#4208): the session's footage ended\n * at the pause, so its final chunk is dated there - dated now, it\n * would run on over the whole stretch nobody recorded. An input that\n * came back without its snapshot yet recorded nothing either.\n */\n this.idleResumeBacklog = null;\n this.appendMarker(\n VISIBILITY_CUSTOM_EVENT_TAG,\n { state: \"stopped\" },\n pause.pausedAtUnixMs,\n );\n }\n /* Quiesce first so no timer or AppState callback can append after final. */\n this.haltCapture();\n await this.closeCurrent(true);\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n this.rollingBuffer.clear();\n }\n this.transport?.destroy();\n this.diagnosticsStatus = \"stopped\";\n this.diagnostic(\"recorder-stopped\");\n }\n\n public grantConsent(): Promise<void> {\n const identityBarrier: Promise<void> = this.identityQueue;\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n await identityBarrier;\n await this.grantConsentInternal();\n });\n }\n\n private async grantConsentInternal(): Promise<void> {\n this.consentGranted = true;\n if (!this.running && this.options) {\n const options: ValidatedStartOptions = this.options;\n await this.startNow(options);\n return;\n }\n if (!this.running || !this.config) {\n return;\n }\n\n const generation: number = this.lifecycleGeneration;\n const refreshed: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"consent\",\n );\n if (\n !refreshed ||\n !this.running ||\n !this.consentGranted ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n this.diagnosticsStatus = this.foreground ? \"recording\" : \"background\";\n this.diagnostic(\"consent-granted\");\n /* Held events go now, under the session the grant opened (issue #6629). */\n this.analytics?.onConsentGranted();\n }\n\n public revokeConsent(): Promise<void> {\n this.lifecycleGeneration += 1;\n this.lifecycleCancellationEpoch += 1;\n this.identityCancellationEpoch += 1;\n this.pendingStartCancellation?.cancel();\n this.consentGranted = false;\n this.acceptingEvents = false;\n /*\n * Product analytics drops what it held, forgets the session it\n * announced, and holds nothing until a new grant (issue #6629).\n */\n this.analytics?.forget();\n this.haltCapture();\n this.transport?.destroy();\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n return this.revokeConsentInternal();\n });\n }\n\n private async revokeConsentInternal(): Promise<void> {\n this.haltCapture();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n await this.sessionStore?.clear();\n await this.forgetCachedConfig();\n this.identity = null;\n this.userRef = null;\n this.traits = {};\n this.tags = {};\n this.uploadActive = false;\n this.triggered = false;\n this.diagnosticsStatus = \"consent-revoked\";\n this.diagnostic(\"consent-revoked\");\n }\n\n public identify(userRef: string, traits?: Record<string, unknown>): void {\n const trimmedRef: string =\n typeof userRef === \"string\" ? userRef.trim() : \"\";\n const ref: string | null = trimmedRef\n ? truncate(trimmedRef, MAX_USER_REFERENCE_LENGTH)\n : null;\n const sanitizedTraits: Record<string, string> | null =\n traits === undefined ? null : maskStringMapValues(sanitizeTraits(traits));\n const identityEpoch: number = this.identityCancellationEpoch;\n const lifecycleBarrier: Promise<void> = this.lifecycleQueue;\n this.pendingIdentityOperations += 1;\n const operation: Promise<void> = this.identityQueue.then(\n async (): Promise<void> => {\n await lifecycleBarrier;\n await this.applyIdentityChange(ref, sanitizedTraits, identityEpoch);\n },\n );\n this.identityQueue = operation.then(\n (): void => {\n this.pendingIdentityOperations = Math.max(\n 0,\n this.pendingIdentityOperations - 1,\n );\n },\n (): void => {\n this.pendingIdentityOperations = Math.max(\n 0,\n this.pendingIdentityOperations - 1,\n );\n this.diagnostic(\"identity-change-failed\");\n },\n );\n }\n\n public setTags(tags: Record<string, unknown>): void {\n const sanitizedTags: Record<string, string> = sanitizeTags(tags);\n this.runExternalActivity(this.now(), (): void => {\n this.tags = sanitizedTags;\n this.metaDirty = true;\n this.appendCustom(TAGS_CUSTOM_EVENT_TAG, { ...this.tags });\n });\n }\n\n public addTag(key: string, value: string | number | boolean): void {\n if (typeof key !== \"string\") {\n return;\n }\n const safeKey: string = truncate(key.trim(), MAX_TAG_KEY_LENGTH);\n if (!safeKey) {\n return;\n }\n const safeValue: string = truncate(String(value), MAX_TAG_VALUE_LENGTH);\n this.runExternalActivity(this.now(), (): void => {\n this.tags = sanitizeTags({\n ...this.tags,\n [safeKey]: safeValue,\n });\n this.metaDirty = true;\n this.appendCustom(TAGS_CUSTOM_EVENT_TAG, { ...this.tags });\n });\n }\n\n public track(name: string, properties?: Record<string, unknown>): void {\n const eventName: string =\n typeof name === \"string\"\n ? truncate(name.trim(), MAX_CUSTOM_EVENT_NAME_LENGTH)\n : \"\";\n if (!eventName) {\n return;\n }\n\n /*\n * With product analytics on, also an event the application's Events,\n * Funnels and User Retention pages count, from every session, recorded\n * or not (issue #6629). Not held back by the recording's own state - a\n * session paused or left out by the sample still counts what is done\n * in it - only by an identify() still being applied, as the recording\n * is: a track() right after a sign-in is the signed-in user's.\n */\n this.afterIdentity((): void => {\n this.analytics?.track(name, properties);\n });\n\n const sanitizedProperties: Record<string, string> = maskStringMapValues(\n sanitizeEventProperties(properties),\n );\n this.runExternalActivity(this.now(), (): void => {\n this.appendCustom(\n CUSTOM_EVENT_TAG,\n { name: eventName, properties: sanitizedProperties },\n \"customEventCount\",\n );\n if (\n this.recordCustomSignals(\n this.customSignalMatcher.matchEvent(\n this.customSignals(),\n eventName,\n this.now(),\n ),\n )\n ) {\n void this.trigger(SessionReplayTriggerReason.Frustration);\n }\n });\n }\n\n /*\n * A number the app measured (\"cart.value\", 42.5), with optional\n * attributes: a point in the metric store under the RUM application, for\n * charts, dashboards and Metrics monitors (issue #6629). It needs product\n * analytics on for the application; its attribute values are masked, as\n * track()'s property values are.\n */\n public metric(\n name: string,\n value: number,\n attributes?: Record<string, unknown>,\n ): void {\n if (!this.analytics || !this.analytics.isStarted()) {\n this.diagnostic(\"metric-analytics-off\");\n return;\n }\n\n this.afterIdentity((): void => {\n this.analytics?.metric(name, value, attributes);\n });\n }\n\n /*\n * Runs a product analytics call once every identify() made before it has\n * been applied - a change of user starts the next session first - or\n * now, when none is pending. Dropped when consent is withdrawn meanwhile.\n */\n private afterIdentity(action: () => void): void {\n if (this.pendingIdentityOperations === 0) {\n action();\n return;\n }\n const identityEpoch: number = this.identityCancellationEpoch;\n void this.identityQueue.then((): void => {\n if (identityEpoch === this.identityCancellationEpoch) {\n action();\n }\n });\n }\n\n public async setRoute(route: string): Promise<void> {\n await this.identityQueue;\n /*\n * A page view for product analytics (issue #6629), named by the route\n * as the recording keeps it, whatever the recording does with it.\n */\n this.analytics?.page(sanitizeRoute(route));\n /*\n * Paused for idle, the route the app moves to on its own is not\n * recorded (nor counted) - only remembered, so the snapshot the resume\n * takes is on the screen the app is actually showing.\n */\n if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {\n this.route = sanitizeRoute(route);\n return;\n }\n await this.maybeRotateSession(this.now());\n if (!this.options) {\n this.route = sanitizeRoute(route);\n return;\n }\n\n const previous: string = this.route;\n const next: string = sanitizeRoute(route);\n if (previous === next) {\n return;\n }\n\n this.route = next;\n\n /*\n * A navigation on an app whose session ended idle is not the user\n * coming back - it can be a timer, or an inactivity logout - so it\n * starts nothing. The next session opens on this route when they do.\n */\n if (this.sealedForIdle) {\n return;\n }\n\n this.appendCustom(\n ROUTE_CUSTOM_EVENT_TAG,\n {\n from: toAppUrl(this.options.mobileAppIdentifier, previous),\n to: toAppUrl(this.options.mobileAppIdentifier, next),\n kind: \"manual\",\n },\n \"routeCount\",\n );\n /*\n * Matched on the route as the app passed it, not the recorded copy\n * whose ids are redacted: a pattern names the app's own screens, and\n * only the signal's name is recorded.\n */\n const frustrated: boolean = this.recordCustomSignals(\n this.customSignalMatcher.matchPage(\n this.customSignals(),\n route,\n this.now(),\n ),\n );\n await this.closeCurrent(false);\n this.forceFullSnapshot = true;\n await this.captureTick(true);\n if (frustrated) {\n await this.trigger(SessionReplayTriggerReason.Frustration);\n }\n }\n\n public async captureSession(reason: string = \"manual\"): Promise<void> {\n await this.identityQueue;\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n /*\n * The app asked for this moment to be recorded.\n *\n * An explicit ask for a recording starts the next session on an app\n * whose last one ended idle, so the marker lands in it rather than\n * nowhere: the new session's snapshot, the rotation marker, then this\n * marker.\n *\n * Paused for idle inside the session's window (#4208), capture resumes\n * at once in the same session, on a snapshot of what is on screen now,\n * with the idle-resumed marker and then this marker behind it.\n *\n * Either way it is not input: lastInputUnixMs stays where the person\n * left it, so the next pause check pauses again unless someone is\n * actually there - as the browser recorder does. In the background\n * nothing can be captured, so a pause stands.\n */\n const resume: IdleInputOutcome = this.foreground\n ? this.endIdlePause(this.now())\n : \"none\";\n await this.maybeRotateForUser(this.now());\n if (resume === \"resumed\") {\n this.startTimers();\n /*\n * The snapshot first, and without the pause check that follows a\n * sample, which would pause again before this marker is in. Under an\n * error trigger the upload below then opens on that snapshot.\n */\n await this.captureTick(true, false);\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n }\n const safeReason: string = truncate(\n (typeof reason === \"string\" ? reason.trim() : \"\") || \"manual\",\n MAX_CAPTURE_REASON_LENGTH,\n );\n this.appendCustom(CUSTOM_EVENT_TAG, {\n name: \"oneuptime.capture\",\n properties: { reason: maskTextValue(safeReason) },\n });\n await this.trigger(SessionReplayTriggerReason.Manual);\n }\n\n public async captureError(error: unknown): Promise<void> {\n await this.identityQueue;\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n /*\n * Nobody is using the app. A background poll's failure says nothing\n * about what the user went through: it is neither recorded (nothing is,\n * while paused) nor allowed to trigger an upload of a session whose\n * footage ended minutes before it.\n */\n if (this.isIdlePaused()) {\n return;\n }\n await this.maybeRotateSession(this.now());\n /*\n * The session ended idle and nobody is back: an error a background\n * poll threw belongs to no recording, and triggers nothing.\n */\n if (this.sealedForIdle) {\n return;\n }\n const rawName: string =\n error instanceof Error && typeof error.name === \"string\"\n ? error.name.trim()\n : \"\";\n const name: string = SAFE_ERROR_NAMES.has(rawName) ? rawName : \"Error\";\n /* Error text and stacks can quote end-user data; mobile v1 never sends them. */\n this.appendCustom(\n ERROR_CUSTOM_EVENT_TAG,\n { kind: \"error\", name, message: \"[masked]\" },\n \"errorCount\",\n );\n /*\n * The application's error signals are matched on the text the app\n * threw - compared here, on the device, and never sent: the marker\n * carries the signal's name.\n */\n this.recordCustomSignals(\n this.customSignalMatcher.matchErrorText(\n this.customSignals(),\n errorText(error),\n this.now(),\n ),\n );\n await this.trigger(SessionReplayTriggerReason.Error);\n }\n\n public recordTouch(touch: RecordedTouch): void {\n const sanitizedTouch: RecordedTouch | null = sanitizeRecordedTouch(\n touch,\n this.now(),\n );\n if (!sanitizedTouch) {\n this.diagnostic(\"invalid-touch-event\");\n return;\n }\n if (!this.running || !this.acceptingEvents || !this.foreground) {\n return;\n }\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n let resumeCapture: Promise<void> | null = null;\n if (input === \"resumed\") {\n /*\n * The capture that resumes the session starts now, and this touch\n * waits for it: recorded behind the snapshot and the idle-resumed\n * marker, and checked against the privacy map that snapshot derives\n * rather than the one from before the pause, which may describe a\n * screen the app has since left. A touch that finds the session\n * ended starts the next one and is dropped, as on any idle session\n * (recordTouchAfterPrivacyCheck).\n */\n this.startTimers();\n resumeCapture = this.captureTick(true);\n }\n const generation: number = this.lifecycleGeneration;\n const operation: Promise<void> = this.touchQueue.then(\n async (): Promise<void> => {\n if (resumeCapture) {\n await resumeCapture;\n }\n await this.recordTouchAfterPrivacyCheck(sanitizedTouch, generation);\n },\n );\n this.touchQueue = operation.catch((): void => {\n this.diagnostic(\"touch-privacy-check-failed\");\n });\n }\n\n private async recordTouchAfterPrivacyCheck(\n touch: RecordedTouch,\n generation: number,\n ): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n const pointIsPrivate: boolean = await this.isCurrentTouchPrivate(touch);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n if (this.updateTouchSuppression(touch, pointIsPrivate)) {\n this.diagnostic(\"touch-suppressed-private-region\");\n return;\n }\n if (\n touch.phase === \"move\" &&\n touch.timestamp - this.lastTouchMoveAtUnixMs < TOUCH_MOVE_SAMPLE_MS\n ) {\n return;\n }\n if (touch.phase === \"move\") {\n this.lastTouchMoveAtUnixMs = touch.timestamp;\n }\n\n /*\n * A touch is the user, so on an idle session it starts the next one.\n * The touch itself is dropped: it lands before that session's first\n * snapshot, which shows its result anyway.\n */\n const nowUnixMs: number = this.now();\n if (\n this.rotatingSession ||\n this.sealedForIdle ||\n this.rotationReason(nowUnixMs)\n ) {\n this.diagnostic(\"touch-dropped-session-rotation\");\n void this.maybeRotateForUser(nowUnixMs);\n return;\n }\n\n this.appendEvent(\n createTouchEvent(touch),\n touch.phase === \"start\" ? \"clickCount\" : undefined,\n );\n if (touch.phase === \"start\") {\n this.appendCustom(TOUCH_CUSTOM_EVENT_TAG, {\n phase: \"start\",\n x: touch.x,\n y: touch.y,\n });\n }\n }\n\n public setRootTag(rootTag: number | null): void {\n this.rootTag =\n typeof rootTag === \"number\" &&\n Number.isSafeInteger(rootTag) &&\n rootTag > 0\n ? rootTag\n : null;\n this.forceFullSnapshot = true;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n if (\n this.rootTag &&\n this.running &&\n this.acceptingEvents &&\n this.foreground\n ) {\n void this.captureTick(true);\n }\n }\n\n public getDiagnostics(): MobileReplayDiagnostics {\n /*\n * Derived rather than stored: the policy, consent and identity paths\n * all write \"recording\" without knowing about the pause, and a paused\n * recorder that reported \"recording\" is exactly the question a support\n * ticket asks. A session that ended idle while nobody came back is\n * paused too - nothing is captured until someone is - as the browser\n * recorder reports it.\n */\n const status: MobileReplayStatus =\n this.diagnosticsStatus === \"recording\" &&\n this.running &&\n this.foreground &&\n (this.isIdlePaused() || this.sealedForIdle)\n ? \"paused\"\n : this.diagnosticsStatus;\n return {\n status,\n sessionId: this.identity?.sessionId ?? null,\n recorderKind: MOBILE_RECORDER_KIND,\n configEpoch: this.config?.configEpoch ?? 0,\n sampled: this.sampled,\n triggered: this.triggered,\n consentState: this.consentState(),\n pendingEvents:\n this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),\n productAnalytics: this.analytics\n ? this.analytics.getDiagnostics()\n : { state: \"off\", pending: 0, dropped: 0 },\n events: this.diagnosticsEvents.map(\n (event: MobileReplayDiagnosticEvent): MobileReplayDiagnosticEvent => {\n const copied: MobileReplayDiagnosticEvent = {\n code: event.code,\n atUnixMs: event.atUnixMs,\n };\n if (event.details) {\n copied.details = { ...event.details };\n }\n return copied;\n },\n ),\n };\n }\n\n /**\n * Current consented replay session for host trace/log correlation. None\n * while the session has ended idle and nobody is back: a background poll\n * on an idle app is no part of a recording that ended at the user's last\n * activity.\n */\n public getSessionId(): string | null {\n return this.running && this.identityPersisted && !this.sealedForIdle\n ? this.identity?.sessionId ?? null\n : null;\n }\n\n /** Fires immediately when a session exists and again on rotate/clear. */\n public onSessionChange(\n listener: MobileReplaySessionChangeListener,\n ): () => void {\n if (typeof listener !== \"function\") {\n return (): void => {\n return undefined;\n };\n }\n this.sessionChangeListeners.add(listener);\n const sessionId: string | null = this.getSessionId();\n if (sessionId) {\n try {\n listener(sessionId);\n } catch {\n /* Host observers cannot interrupt capture. */\n }\n }\n return (): void => {\n this.sessionChangeListeners.delete(listener);\n };\n }\n\n private async trigger(reason: SessionReplayTriggerReason): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n this.triggered ||\n this.uploadActive ||\n this.sampled ||\n this.config?.isTargeted\n ) {\n return;\n }\n\n this.triggered = true;\n this.triggerReason = reason;\n this.diagnostic(\"capture-triggered\", { reason });\n if (this.consentState() !== \"Unknown\") {\n await this.activateUpload(this.lifecycleGeneration);\n }\n }\n\n private async activateUpload(generation: number): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n this.uploadActive ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n\n await this.closeCurrent(false);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n this.uploadActive = true;\n const buffered: Array<BufferedReplaySegment> = this.rollingBuffer.drain();\n for (const segment of buffered) {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n await this.uploadSegment(segment, false);\n }\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n await this.transport?.restore();\n }\n\n /*\n * mayPauseForIdle is false only for the snapshot captureSession() takes\n * while paused, whose marker must be in before the pause check runs.\n */\n private async captureTick(\n force: boolean = false,\n mayPauseForIdle: boolean = true,\n ): Promise<void> {\n const generation: number = this.lifecycleGeneration;\n /*\n * Nothing is captured while the session has ended idle: there is no\n * session to put it in until the user is back (see sealedForIdle), and\n * an idle app left in the foreground is not walking the view tree\n * twice a second for nobody.\n */\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.rootTag ||\n this.sealedForIdle ||\n this.captureGeneration === generation ||\n !this.options\n ) {\n return;\n }\n /*\n * Paused for idle: no sample, no checkout, and not the periodic policy\n * refresh either. Nothing happens on a tick until input resumes it.\n */\n if (this.isIdlePaused()) {\n return;\n }\n\n this.captureGeneration = generation;\n try {\n const nowUnixMs: number = this.now();\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n false,\n \"periodic\",\n );\n if (!policyReady) {\n return;\n }\n await this.maybeRotateSession(nowUnixMs);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.sealedForIdle\n ) {\n return;\n }\n /*\n * Paused again meanwhile, or the person came back to a session whose\n * window has run out while its successor is not in place yet (another\n * rotation was still finishing): the next tick starts that one.\n * Nothing is captured into a session that is over.\n */\n if (\n this.isIdlePaused() ||\n (this.idlePause !== null && this.rotationReason(nowUnixMs) !== null)\n ) {\n return;\n }\n const capturedSessionId: string | undefined = this.identity?.sessionId;\n const tree: NativeViewTreeNode =\n await this.nativeViewTree.captureViewTree(this.rootTag);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.rotatingSession ||\n !capturedSessionId ||\n this.identity?.sessionId !== capturedSessionId\n ) {\n return;\n }\n this.touchPrivacyMap = deriveTouchPrivacyMap(tree);\n const shouldForce: boolean =\n force ||\n this.forceFullSnapshot ||\n nowUnixMs - this.lastFullSnapshotAtUnixMs >=\n SESSION_REPLAY_CHECKOUT_INTERVAL_MS;\n if (shouldForce && !this.chunkBuffer.isEmpty()) {\n await this.closeCurrent(false);\n }\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.identity?.sessionId !== capturedSessionId\n ) {\n return;\n }\n\n this.appendCapture(tree, this.options, nowUnixMs, shouldForce);\n if (this.chunkBuffer.shouldFlush()) {\n await this.closeCurrent(false);\n }\n /*\n * Nobody has touched the app for the pause window: stop capturing.\n * Checked after this tick's sample, so the chunk the pause closes ends\n * on the screen as it was when capture stopped. Never while the soft\n * keyboard is up: someone typing touches nothing the recorder sees,\n * so the check waits until it goes away (which is input itself).\n */\n if (\n mayPauseForIdle &&\n !this.softKeyboardVisible &&\n nowUnixMs - this.lastInputUnixMs >= SESSION_REPLAY_IDLE_PAUSE_MS\n ) {\n await this.pauseForIdle(nowUnixMs, generation);\n }\n } catch (error) {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.disable(\"native-capture-failed\", {\n name: error instanceof Error ? error.name : \"Error\",\n });\n this.haltCapture();\n }\n } finally {\n if (this.captureGeneration === generation) {\n this.captureGeneration = null;\n }\n }\n }\n\n private appendCapture(\n tree: NativeViewTreeNode,\n options: ValidatedStartOptions,\n nowUnixMs: number,\n forceFullSnapshot: boolean,\n ): void {\n const size: { width: number; height: number } = getViewport();\n const url: string = toAppUrl(options.mobileAppIdentifier, this.route);\n const capture: SerializedCapture = this.serializer.capture(tree, {\n timestamp: nowUnixMs,\n url,\n viewportWidth: size.width,\n viewportHeight: size.height,\n forceFullSnapshot,\n });\n this.droppedEvents += capture.droppedNodes;\n this.chunkBuffer.appendMany(capture.events, {\n route: url,\n fidelityNotices: capture.fidelityNotices,\n });\n if (capture.hasFullSnapshot) {\n this.lastFullSnapshotAtUnixMs = nowUnixMs;\n this.forceFullSnapshot = false;\n this.completeIdleResume(nowUnixMs);\n }\n }\n\n /*\n * The person did something: a touch, the soft keyboard showing or\n * hiding, or the app coming back to the foreground. It ends an idle\n * pause (see endIdlePause).\n */\n private noteUserInput(nowUnixMs: number): IdleInputOutcome {\n this.lastInputUnixMs = Math.max(this.lastInputUnixMs, nowUnixMs);\n return this.endIdlePause(nowUnixMs);\n }\n\n /*\n * What someone being back does to an idle pause, on its own for\n * captureSession(), which acts on the pause without being input.\n *\n * Inside the session's idle window the same session resumes, on the\n * snapshot of the next capture; the caller starts that capture. Once\n * the window has run out - or the session already ended idle - the\n * session is over, and the caller starts the next one through\n * maybeRotateForUser, as on any idle session; nothing changes here.\n */\n private endIdlePause(nowUnixMs: number): IdleInputOutcome {\n if (this.sealedForIdle) {\n return \"session-ended\";\n }\n if (!this.isIdlePaused()) {\n return \"none\";\n }\n if (this.rotationReason(nowUnixMs) !== null) {\n return \"session-ended\";\n }\n this.idleResumeBacklog = [];\n this.forceFullSnapshot = true;\n /* The return is activity: the session's idle window starts over. */\n this.sessionLastActivityUnixMs = Math.max(\n this.sessionLastActivityUnixMs,\n nowUnixMs,\n );\n return \"resumed\";\n }\n\n /* Paused for idle with nobody back yet: nothing is captured or recorded. */\n private isIdlePaused(): boolean {\n return this.idlePause !== null && this.idleResumeBacklog === null;\n }\n\n /*\n * Whether the pause's marker is in the stream being recorded now, which\n * is what owes it the idle-resumed marker and dates a stop at it.\n */\n private isPauseInStream(pause: IdlePause): boolean {\n return (\n pause.marked &&\n this.identity?.sessionId === pause.sessionId &&\n this.identity?.tabId === pause.tabId\n );\n }\n\n /*\n * Stop capturing: nobody has touched the app for the pause window.\n *\n * In this order: the idle-paused marker goes in as the last event of the\n * open chunk, that chunk goes out through the ordinary path, and the\n * sampler stops. So the last thing the recording holds before the\n * stretch nobody recorded says so - and a session the person never comes\n * back to has already ended there when its idle window runs out, so the\n * idle seal (sealForIdle) has nothing left to send.\n *\n * A recorder holding its pre-roll in memory (error-triggered, or waiting\n * for consent) has nothing to mark and nothing to send. Its pre-roll is\n * dropped instead: a trigger once the person is back must not upload a\n * minute of nobody in front of a snapshot taken after an unrecorded gap.\n */\n private async pauseForIdle(\n nowUnixMs: number,\n generation: number,\n ): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.idlePause !== null ||\n this.sealedForIdle ||\n !this.identity\n ) {\n return;\n }\n\n const paused: SessionReplayIdlePausedPayload = {\n /*\n * Never before the session began: one that started with nobody there\n * (the chunk cap rolled it over) was not idle before it existed.\n */\n idleSinceUnixMs: Math.min(\n nowUnixMs,\n Math.max(this.lastInputUnixMs, this.identity.sessionStartUnixMs),\n ),\n pausedAtUnixMs: nowUnixMs,\n };\n const marked: boolean = this.uploadActive;\n this.idlePause = {\n sessionId: this.identity.sessionId,\n tabId: this.identity.tabId,\n idleSinceUnixMs: paused.idleSinceUnixMs,\n pausedAtUnixMs: paused.pausedAtUnixMs,\n marked,\n };\n this.stopCaptureTimer();\n this.diagnostic(\"idle-paused\", {\n idleForMs: nowUnixMs - paused.idleSinceUnixMs,\n });\n\n if (!marked) {\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n return;\n }\n this.appendMarker(IDLE_PAUSED_CUSTOM_EVENT_TAG, paused, nowUnixMs);\n await this.closeCurrent(false);\n }\n\n /*\n * The snapshot the session resumes on is in the buffer: the idle-resumed\n * marker goes directly behind it, then whatever was recorded since the\n * input that woke the recorder. Same session, same tab and - the pause\n * having closed its chunk - the next chunk index.\n */\n private completeIdleResume(nowUnixMs: number): void {\n const pause: IdlePause | null = this.idlePause;\n const held: Array<HeldReplayEvent> | null = this.idleResumeBacklog;\n if (pause === null || held === null) {\n return;\n }\n this.idlePause = null;\n this.idleResumeBacklog = null;\n\n const resumedAtUnixMs: number = Math.max(pause.pausedAtUnixMs, nowUnixMs);\n if (this.isPauseInStream(pause)) {\n const resumed: SessionReplayIdleResumedPayload = {\n pausedAtUnixMs: pause.pausedAtUnixMs,\n resumedAtUnixMs,\n };\n this.appendMarker(\n IDLE_RESUMED_CUSTOM_EVENT_TAG,\n resumed,\n resumedAtUnixMs,\n );\n }\n this.releaseHeldEvents(held);\n this.diagnostic(\"idle-resumed\", {\n pausedForMs: resumedAtUnixMs - pause.pausedAtUnixMs,\n });\n }\n\n /*\n * A marker the recorder writes about itself - the idle pause and resume,\n * and a stop while paused - straight into the open chunk, stamped with\n * the moment it stands for. None of them is activity (the idle rollover\n * must not move for them), and none is \"now\": a stop while paused is\n * dated at the pause.\n */\n private appendMarker(tag: string, payload: unknown, timestamp: number): void {\n const options: ChunkAppendOptions = {};\n if (this.options) {\n options.route = toAppUrl(this.options.mobileAppIdentifier, this.route);\n }\n if (\n !this.chunkBuffer.append(\n createCustomEvent(tag, payload, timestamp),\n options,\n )\n ) {\n this.droppedEvents += 1;\n }\n }\n\n /* What was held for a resume, in the order it was recorded. */\n private releaseHeldEvents(held: Array<HeldReplayEvent>): void {\n for (const entry of held) {\n if (!this.chunkBuffer.append(entry.event, entry.options)) {\n this.droppedEvents += 1;\n }\n }\n }\n\n /* The page, event and error signals the application's policy defines. */\n private customSignals(): ReadonlyArray<SessionReplayCustomSignalConfig> {\n return this.config?.frustrationSignals.customSignals ?? [];\n }\n\n /*\n * Marks each hit in the stream and counts it on the chunk, as the browser\n * recorder does. Returns whether one of them counts as frustration, which\n * starts an upload under \"On error or frustration\" like an error does.\n *\n * Nothing while the recorder records nothing: before start, while\n * waiting, paused for idle or after a session ended idle - a hit then\n * belongs to no recording, and must not start an upload of footage that\n * ended minutes before it.\n */\n private recordCustomSignals(hits: Array<MobileCustomSignalHit>): boolean {\n if (\n hits.length === 0 ||\n !this.running ||\n !this.acceptingEvents ||\n this.sealedForIdle ||\n this.isIdlePaused()\n ) {\n return false;\n }\n let frustrated: boolean = false;\n for (const hit of hits) {\n if (!this.chunkBuffer.hasRoomForCustomSignal()) {\n this.diagnostic(\"custom-signal-cap-reached\");\n break;\n }\n const payload: SessionReplayCustomSignalPayload = {\n name: hit.name,\n trigger: hit.trigger,\n isFrustration: hit.isFrustration,\n atUnixMs: hit.atUnixMs,\n };\n this.appendEvent(\n createCustomEvent(\n CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,\n payload,\n hit.atUnixMs,\n ),\n undefined,\n false,\n { name: hit.name, isFrustration: hit.isFrustration },\n );\n frustrated = frustrated || hit.isFrustration;\n }\n return frustrated;\n }\n\n private appendCustom(\n tag: string,\n payload: unknown,\n signal?: \"errorCount\" | \"routeCount\" | \"customEventCount\",\n allowWhenQuiesced: boolean = false,\n ): void {\n this.appendEvent(\n createCustomEvent(tag, payload, this.now()),\n signal,\n allowWhenQuiesced,\n );\n }\n\n private appendEvent(\n event: RrwebEvent,\n signal?: \"errorCount\" | \"routeCount\" | \"clickCount\" | \"customEventCount\",\n allowWhenQuiesced: boolean = false,\n customSignal?: { name: string; isFrustration: boolean },\n ): void {\n if (!this.running || (!this.acceptingEvents && !allowWhenQuiesced)) {\n return;\n }\n /*\n * Not counted as dropped: nothing is lost. The session ended idle, an\n * event dated after that is no part of it, and the next session opens\n * on a snapshot of its own.\n */\n if (this.sealedForIdle) {\n return;\n }\n if (!Number.isFinite(event.timestamp)) {\n this.droppedEvents += 1;\n this.diagnostic(\"invalid-event-timestamp\");\n return;\n }\n\n /*\n * Paused for idle: nothing is recorded. Dropped, not queued - held\n * until the resume, a route the app changed or a track() it fired\n * twenty minutes earlier would be stamped after the person came back -\n * and neither counted in the chunk's signals nor taken as activity, so\n * an app that keeps raising events cannot hold the idle rollover off.\n */\n if (this.isIdlePaused()) {\n return;\n }\n\n const appendOptions: ChunkAppendOptions = {};\n if (this.options) {\n appendOptions.route = toAppUrl(\n this.options.mobileAppIdentifier,\n this.route,\n );\n }\n if (signal) {\n appendOptions.signal = signal;\n }\n if (customSignal) {\n appendOptions.customSignal = customSignal;\n }\n\n /*\n * The person is back but the snapshot the session resumes on is not in\n * the buffer yet: held, to land behind it (completeIdleResume). Not\n * counted as activity here: the input that woke the recorder already\n * was.\n */\n if (this.idleResumeBacklog !== null) {\n if (this.idleResumeBacklog.length < MAX_EVENTS_HELD_FOR_RESUME) {\n this.idleResumeBacklog.push({ event, options: appendOptions });\n } else {\n this.droppedEvents += 1;\n }\n return;\n }\n\n this.sessionLastActivityUnixMs = Math.max(\n this.sessionLastActivityUnixMs,\n event.timestamp,\n );\n\n const accepted: boolean = this.chunkBuffer.append(event, appendOptions);\n if (!accepted) {\n this.droppedEvents += 1;\n }\n if (this.chunkBuffer.shouldFlush()) {\n void this.closeCurrent(false);\n }\n }\n\n private async closeCurrent(isFinal: boolean): Promise<void> {\n /*\n * Never on a session that ended idle: the cap's marker would be dated\n * now, long after its footage, and the rotation after it would start a\n * session nobody is in.\n */\n const closesFinalChunkSlot: boolean =\n !isFinal &&\n !this.rotatingSession &&\n !this.sealedForIdle &&\n this.uploadActive &&\n this.sessionStore?.getNextChunkIndex() ===\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION - 1;\n if (closesFinalChunkSlot) {\n this.rotatingSession = true;\n const rotationOptions: NonNullable<\n Parameters<ReplayChunkBuffer[\"append\"]>[1]\n > = {};\n if (this.options) {\n rotationOptions.route = toAppUrl(\n this.options.mobileAppIdentifier,\n this.route,\n );\n }\n this.chunkBuffer.append(\n createCustomEvent(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason: \"chunk-cap\" },\n this.now(),\n ),\n rotationOptions,\n );\n }\n const segment: BufferedReplaySegment | null = this.chunkBuffer.take();\n if (!segment) {\n if (closesFinalChunkSlot) {\n this.rotatingSession = false;\n }\n return;\n }\n\n const operation: Promise<void> = this.closeQueue.then(\n async (): Promise<void> => {\n return this.processSegment(segment, isFinal || closesFinalChunkSlot);\n },\n );\n if (closesFinalChunkSlot) {\n const rotation: Promise<void> = operation.then(\n async (): Promise<void> => {\n if (this.running) {\n await this.completeSessionIdentityRotation(this.now(), \"chunk-cap\");\n }\n },\n );\n this.rotationPromise = rotation;\n this.closeQueue = rotation.catch((): void => {\n this.diagnostic(\"chunk-close-failed\");\n });\n try {\n await rotation;\n } finally {\n if (this.rotationPromise === rotation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n return;\n }\n this.closeQueue = operation.catch((): void => {\n this.diagnostic(\"chunk-close-failed\");\n });\n return await operation;\n }\n\n private async processSegment(\n segment: BufferedReplaySegment,\n isFinal: boolean,\n ): Promise<void> {\n if (!this.uploadActive) {\n this.rollingBuffer.push(segment, this.now());\n return;\n }\n\n await this.uploadSegment(segment, isFinal);\n }\n\n private async uploadSegment(\n segment: BufferedReplaySegment,\n isFinal: boolean,\n ): Promise<void> {\n if (\n !this.options ||\n !this.config ||\n !this.identity ||\n !this.sessionStore ||\n !this.transport ||\n !this.identityPersisted\n ) {\n return;\n }\n\n const chunkIndex: number = await this.sessionStore.takeChunkIndex(\n this.now(),\n );\n if (chunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION) {\n this.diagnostic(\"session-chunk-cap-race\", { chunkIndex });\n if (this.running) {\n await this.completeSessionIdentityRotation(this.now(), \"chunk-cap\");\n await this.uploadSegment(segment, isFinal);\n }\n return;\n }\n\n const includeMeta: boolean = chunkIndex === 0 || isFinal || this.metaDirty;\n const envelope: SessionReplayChunkEnvelope = {\n v: SESSION_REPLAY_WIRE_VERSION,\n appIdentifier: this.options.appIdentifier,\n sessionId: this.identity.sessionId,\n tabId: this.identity.tabId,\n chunkIndex,\n sessionStartUnixMs: this.identity.sessionStartUnixMs,\n clientSendUnixMs: this.now(),\n chunkStartOffsetMs: Math.max(\n 0,\n segment.startUnixMs - this.identity.sessionStartUnixMs,\n ),\n chunkEndOffsetMs: Math.max(\n 0,\n segment.endUnixMs - this.identity.sessionStartUnixMs,\n ),\n eventCount: segment.eventCount,\n hasFullSnapshot: segment.hasFullSnapshot,\n isFinal,\n recorderKind: MOBILE_RECORDER_KIND,\n schemaVersion: SESSION_REPLAY_SCHEMA_VERSION,\n rrwebVersion: SYNTHETIC_RRWEB_VERSION,\n recorderVersion: RECORDER_VERSION,\n maskingMode: this.config.maskingMode,\n consentState: this.consentState(),\n triggerReason: this.triggerReason,\n payloadEncoding: \"gzip\",\n payloadBytes: 0,\n url: toAppUrl(this.options.mobileAppIdentifier, this.route),\n routes: segment.routes,\n signals: segment.signals,\n fidelityNotices: segment.fidelityNotices,\n droppedEvents: segment.droppedEvents + this.droppedEvents,\n flushFailures: this.transport.getFlushFailures(),\n };\n if (includeMeta) {\n envelope.meta = this.buildMeta();\n }\n if (chunkIndex === 0) {\n envelope.capabilities = Array.from(\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n );\n }\n this.metaDirty = false;\n this.droppedEvents = 0;\n await this.transport.enqueue(envelope, segment.payload);\n }\n\n private buildMeta(): SessionReplayChunkMeta {\n const size: { width: number; height: number } = getViewport();\n const captureIdentity: boolean = this.config?.captureUserIdentity === true;\n const meta: SessionReplayChunkMeta = {\n entryUrl: this.entryUrl,\n browserName: this.metadata.appName,\n browserVersion: this.metadata.appVersion,\n osName: `${this.metadata.osName} ${this.metadata.osVersion}`.trim(),\n deviceType: this.metadata.osName.toLowerCase().includes(\"ios\")\n ? \"ios\"\n : \"android\",\n viewportWidth: size.width,\n viewportHeight: size.height,\n };\n if (this.identity?.visitorId) {\n meta.visitorId = this.identity.visitorId;\n }\n if (captureIdentity && this.userRef) {\n meta.identifiedUserRef = this.userRef;\n }\n if (captureIdentity && Object.keys(this.traits).length > 0) {\n meta.identifiedUserTraits = { ...this.traits };\n }\n if (Object.keys(this.tags).length > 0) {\n meta.tags = { ...this.tags };\n }\n return meta;\n }\n\n private consentState(): SessionReplayConsentState {\n if (this.config?.consentMode === SessionReplayConsentMode.NotRequired) {\n return \"NotRequired\";\n }\n\n return this.consentGranted ? \"Granted\" : \"Unknown\";\n }\n\n private installLifecycle(): void {\n this.appStateSubscription?.remove();\n this.appStateSubscription = this.appState.addEventListener(\n \"change\",\n (state: string): void => {\n const generation: number = this.lifecycleGeneration;\n const operation: Promise<void> = this.appStateQueue.then(\n async (): Promise<void> => {\n await this.onAppStateChange(state, generation);\n },\n );\n this.appStateQueue = operation.catch((): void => {\n this.diagnostic(\"app-state-transition-failed\");\n });\n },\n );\n this.installKeyboardListeners();\n }\n\n private installKeyboardListeners(): void {\n this.removeKeyboardListeners();\n const keyboard: ReplayKeyboard | null = this.keyboard;\n this.softKeyboardVisible = false;\n if (!keyboard || typeof keyboard.addListener !== \"function\") {\n return;\n }\n try {\n /* Already up when recording started: someone is typing. */\n this.softKeyboardVisible = keyboard.isVisible?.() === true;\n } catch {\n this.softKeyboardVisible = false;\n }\n try {\n this.keyboardSubscriptions.push(\n keyboard.addListener(\"keyboardDidShow\", (): void => {\n this.onKeyboardChange(true);\n }),\n keyboard.addListener(\"keyboardDidHide\", (): void => {\n this.onKeyboardChange(false);\n }),\n );\n } catch {\n /* A keyboard module that cannot be observed costs only this signal. */\n this.removeKeyboardListeners();\n this.softKeyboardVisible = false;\n this.diagnostic(\"keyboard-subscribe-failed\");\n }\n }\n\n private removeKeyboardListeners(): void {\n const subscriptions: Array<KeyboardSubscription> =\n this.keyboardSubscriptions;\n this.keyboardSubscriptions = [];\n for (const subscription of subscriptions) {\n try {\n subscription.remove();\n } catch {\n /* The host's keyboard module must not break teardown. */\n }\n }\n }\n\n /*\n * The soft keyboard came up or went away. That is the person - a field\n * tapped, a message sent - so it counts as input and resumes a paused\n * recording the way a touch does; and while it is up the idle pause\n * waits, since what is typed on it reaches no view the recorder sees.\n */\n private onKeyboardChange(visible: boolean): void {\n this.softKeyboardVisible = visible;\n if (!this.running || !this.acceptingEvents || !this.foreground) {\n return;\n }\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n if (input === \"resumed\") {\n this.startTimers();\n void this.captureTick(true);\n } else if (input === \"session-ended\") {\n /* As a touch does on a session that ended idle: the next one starts. */\n void this.maybeRotateForUser(this.now());\n }\n }\n\n private async onAppStateChange(\n state: string,\n generation: number,\n ): Promise<void> {\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n\n const isActive: boolean = state === \"active\";\n if (!isActive && this.foreground) {\n this.foreground = false;\n this.clearTimers();\n this.diagnosticsStatus = \"background\";\n if (this.rotationPromise) {\n await this.rotationPromise;\n }\n if (this.policyRefreshPromise) {\n await this.policyRefreshPromise;\n }\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n if (this.idlePause !== null || this.sealedForIdle) {\n /*\n * Paused for idle - or a touch had just ended the pause and its\n * snapshot never came, which leaves the session paused where it\n * was - or ended idle. Nothing is recorded, not even this: the\n * stream still says \"visible\" from before the pause, and the return\n * will read as the idle-resumed marker (or open the next session).\n * What the outbox already holds - the pause's own chunk, if its\n * upload failed - is still worth one try before the OS suspends\n * the app.\n */\n this.idleResumeBacklog = null;\n if (this.uploadActive) {\n await this.transport?.drain();\n }\n return;\n }\n this.appendCustom(VISIBILITY_CUSTOM_EVENT_TAG, { state: \"hidden\" });\n await this.closeCurrent(false);\n if (this.uploadActive) {\n await this.transport?.drain();\n }\n return;\n }\n\n if (isActive && !this.foreground) {\n this.foreground = true;\n /*\n * Coming back to the app is the person coming back: like a touch, it\n * ends an idle pause (#4208), and the capture below takes the snapshot\n * the paused session resumes on.\n */\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"foreground\",\n );\n if (!policyReady) {\n return;\n }\n /* Coming back to the app is the user returning. */\n const sessionIdBeforeResume: string | undefined =\n this.identity?.sessionId;\n await this.maybeRotateSession(this.now(), true);\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n /*\n * A return that resumes the paused session records no visibility\n * change: none was recorded when the app left, and the idle-resumed\n * marker is what the return looks like. Any other return records it\n * as it always has.\n */\n const resumedPausedSession: boolean =\n input === \"resumed\" &&\n this.identity?.sessionId === sessionIdBeforeResume;\n if (!resumedPausedSession) {\n this.appendCustom(VISIBILITY_CUSTOM_EVENT_TAG, { state: \"visible\" });\n }\n /*\n * Any other return takes a fresh checkout, as the screen may have\n * changed while the app was away. A session the return just started\n * already leads with a snapshot of this screen; a second one would\n * only repeat it.\n */\n const openedOnSnapshot: boolean =\n this.identity?.sessionId !== sessionIdBeforeResume &&\n this.lastFullSnapshotAtUnixMs > 0;\n if (!openedOnSnapshot) {\n this.forceFullSnapshot = true;\n }\n this.startTimers();\n this.diagnosticsStatus =\n this.consentState() === \"Unknown\" ? \"consent-required\" : \"recording\";\n await this.captureTick(!openedOnSnapshot);\n\n /*\n * Offline mode: returning to the app is the most likely moment the\n * connection is back (the train left the tunnel while the phone was in\n * a pocket), so the backlog is tried now rather than on its timer.\n */\n if (this.uploadActive && this.running) {\n this.transport?.resume();\n }\n }\n }\n\n private startTimers(): void {\n this.clearTimers();\n const intervalMs: number = Math.max(\n 250,\n Math.min(\n 5_000,\n typeof this.options?.captureIntervalMs === \"number\" &&\n Number.isFinite(this.options.captureIntervalMs)\n ? this.options.captureIntervalMs\n : MOBILE_CAPTURE_INTERVAL_MS,\n ),\n );\n this.captureTimer = setInterval((): void => {\n void this.captureTick();\n }, intervalMs);\n this.flushTimer = setInterval((): void => {\n /*\n * Paused for idle, this is the only timer left running, and all it\n * does is end a session nobody came back to: maybeRotateSession seals\n * it once its idle window runs out (see sealForIdle).\n */\n if (this.isIdlePaused()) {\n if (this.acceptingEvents) {\n void this.maybeRotateSession(this.now());\n }\n return;\n }\n if (this.acceptingEvents) {\n void this.closeCurrent(false);\n }\n }, SESSION_REPLAY_FLUSH_INTERVAL_MS);\n }\n\n /*\n * The sampler alone. An idle pause stops it - every tick is a native\n * traversal of the whole view tree, which is what a pause is for not\n * paying - and keeps the 15-second flush timer as its heartbeat, rather\n * than waking the JS thread twice a second to find nothing to do.\n */\n private stopCaptureTimer(): void {\n if (this.captureTimer) {\n clearInterval(this.captureTimer);\n this.captureTimer = null;\n }\n }\n\n private clearTimers(): void {\n this.stopCaptureTimer();\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n private installGlobalErrorHandler(): void {\n const globals: Record<string, unknown> = globalThis as unknown as Record<\n string,\n unknown\n >;\n const errorUtils: GlobalErrorUtils | undefined = globals[\"ErrorUtils\"] as\n | GlobalErrorUtils\n | undefined;\n const previous: GlobalErrorHandler | undefined =\n errorUtils?.getGlobalHandler?.();\n if (!errorUtils?.setGlobalHandler || typeof previous !== \"function\") {\n return;\n }\n\n this.globalErrorUtils = errorUtils;\n this.previousGlobalErrorHandler = previous;\n const handlerGeneration: number = this.lifecycleGeneration;\n const installedHandler: GlobalErrorHandler = (\n error: Error,\n isFatal?: boolean,\n ): void => {\n if (\n this.installedGlobalErrorHandler === installedHandler &&\n this.lifecycleGeneration === handlerGeneration\n ) {\n void this.captureError(error);\n }\n try {\n previous?.(error, isFatal);\n } catch {\n /* A pre-existing handler remains isolated from the recorder. */\n }\n };\n this.installedGlobalErrorHandler = installedHandler;\n errorUtils.setGlobalHandler(installedHandler);\n }\n\n private restoreGlobalErrorHandler(): void {\n if (\n this.globalErrorUtils?.setGlobalHandler &&\n this.globalErrorUtils.getGlobalHandler?.() ===\n this.installedGlobalErrorHandler &&\n this.previousGlobalErrorHandler\n ) {\n this.globalErrorUtils.setGlobalHandler(this.previousGlobalErrorHandler);\n }\n this.globalErrorUtils = null;\n this.previousGlobalErrorHandler = null;\n this.installedGlobalErrorHandler = null;\n }\n\n private createTransport(\n startOptions: ValidatedStartOptions,\n outbox: ReplayOutbox,\n ): ReplayTransport {\n const transport: ReplayTransport = new ReplayTransport({\n startOptions,\n outbox,\n onDirective: (\n directive: SessionReplayDirective,\n reason: string | null,\n ): void => {\n this.onDirective(directive, reason);\n },\n onDiagnostic: (code: string, details?: Record<string, unknown>): void => {\n this.diagnostic(code, details);\n if (code === \"back-online\") {\n this.onBackOnline();\n }\n },\n });\n if (this.lastConnectivity !== null) {\n transport.setConnectivity(this.lastConnectivity);\n }\n return transport;\n }\n\n private onDirective(\n directive: SessionReplayDirective,\n reason: string | null,\n ): void {\n this.diagnostic(\"server-directive\", { directive, reason });\n if (directive === \"stop\") {\n this.disable(\"server-stopped\", { reason });\n this.haltCapture();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.uploadActive = false;\n this.transport?.destroy();\n }\n }\n\n private haltCapture(): void {\n this.running = false;\n this.acceptingEvents = false;\n this.quiesceCapture();\n this.notifySessionChange();\n }\n\n private notifySessionChange(): void {\n const sessionId: string | null = this.getSessionId();\n if (sessionId === this.lastNotifiedSessionId) {\n return;\n }\n this.lastNotifiedSessionId = sessionId;\n for (const listener of this.sessionChangeListeners) {\n try {\n listener(sessionId);\n } catch {\n /* Host observers cannot interrupt capture. */\n }\n }\n }\n\n private quiesceCapture(): void {\n this.clearTimers();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n this.removeKeyboardListeners();\n this.stopConnectivity();\n this.restoreGlobalErrorHandler();\n }\n\n /*\n * Whether this device may be written to under a policy. Nothing is stored\n * before an explicit consent the policy requires - the cached policy\n * included, even though it holds no user data - except a removal: a\n * policy that says replay is off always deletes the cached one.\n */\n /*\n * The cached policy goes with everything else when consent does: it holds\n * no user data, but \"nothing of the recorder stays on the device\" is the\n * promise, and the next consented policy fetch writes it again.\n */\n private async forgetCachedConfig(): Promise<void> {\n if (this.options) {\n await forgetReplayConfig(\n this.storage,\n getReplayStorageNamespace(this.options),\n );\n }\n }\n\n private mayPersistUnder(config: ResolvedReplayConfig): boolean {\n return (\n !config.enabled ||\n config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted\n );\n }\n\n private subscribeConnectivity(options: ValidatedStartOptions): void {\n this.stopConnectivity();\n this.lastConnectivity = null;\n if (!options.connectivity) {\n return;\n }\n\n try {\n const unsubscribe: unknown = options.connectivity.subscribe(\n (isConnected: boolean | null): void => {\n const connected: boolean | null =\n typeof isConnected === \"boolean\" ? isConnected : null;\n if (connected === this.lastConnectivity) {\n return;\n }\n this.lastConnectivity = connected;\n if (connected !== null) {\n this.diagnostic(connected ? \"network-online\" : \"network-offline\");\n }\n this.transport?.setConnectivity(connected);\n if (connected === true) {\n this.onBackOnline();\n /*\n * The backlog goes now - but only while uploading is allowed. A\n * consent this run has not been given does not become one\n * because the network came back.\n */\n if (this.uploadActive && this.running) {\n this.transport?.resume();\n }\n }\n },\n );\n this.unsubscribeConnectivity =\n typeof unsubscribe === \"function\" ? (unsubscribe as () => void) : null;\n } catch {\n /* A throwing connectivity source only costs the early drain. */\n this.diagnostic(\"connectivity-subscribe-failed\");\n }\n }\n\n /* The next capture tick refreshes a stale policy (see policyStale). */\n private onBackOnline(): void {\n if (this.policyStale) {\n this.lastPolicyRefreshAtUnixMs = 0;\n }\n }\n\n private stopConnectivity(): void {\n const unsubscribe: (() => void) | null = this.unsubscribeConnectivity;\n this.unsubscribeConnectivity = null;\n try {\n unsubscribe?.();\n } catch {\n /* The host's unsubscribe must not break teardown. */\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return generation === this.lifecycleGeneration;\n }\n\n private enqueueLifecycleOperation<T>(action: () => Promise<T>): Promise<T> {\n const operation: Promise<T> = this.lifecycleQueue.then(action, action);\n this.lifecycleQueue = operation.then(\n (): void => {\n return undefined;\n },\n (): void => {\n this.diagnostic(\"lifecycle-operation-failed\");\n },\n );\n return operation;\n }\n\n private async isCurrentTouchPrivate(touch: RecordedTouch): Promise<boolean> {\n if (\n !this.rootTag ||\n !touch.targetTag ||\n typeof this.nativeViewTree.isTouchTargetPrivate !== \"function\"\n ) {\n return true;\n }\n try {\n const privateAncestry: boolean =\n await this.nativeViewTree.isTouchTargetPrivate(\n touch.targetTag,\n this.rootTag,\n );\n if (privateAncestry) {\n return true;\n }\n return isTouchPrivate(this.touchPrivacyMap, touch.x, touch.y);\n } catch {\n return true;\n }\n }\n\n private updateTouchSuppression(\n touch: RecordedTouch,\n pointIsPrivate: boolean,\n ): boolean {\n if (touch.pointerId !== undefined) {\n const pointerKey: string = `${typeof touch.pointerId}:${String(\n touch.pointerId,\n )}`;\n if (pointIsPrivate) {\n this.suppressedTouchPointers.add(pointerKey);\n }\n const suppressed: boolean = this.suppressedTouchPointers.has(pointerKey);\n if (touch.phase === \"end\") {\n this.suppressedTouchPointers.delete(pointerKey);\n }\n return suppressed;\n }\n\n if (touch.phase === \"start\") {\n this.unidentifiedTouchCount += 1;\n }\n if (pointIsPrivate) {\n this.unidentifiedTouchPrivate = true;\n }\n const suppressed: boolean = this.unidentifiedTouchPrivate;\n if (touch.phase === \"end\") {\n this.unidentifiedTouchCount = Math.max(\n 0,\n this.unidentifiedTouchCount - 1,\n );\n if (this.unidentifiedTouchCount === 0) {\n this.unidentifiedTouchPrivate = false;\n }\n }\n return suppressed;\n }\n\n private resetTouchSequences(): void {\n this.suppressedTouchPointers.clear();\n this.unidentifiedTouchCount = 0;\n this.unidentifiedTouchPrivate = false;\n }\n\n private async applyIdentityChange(\n ref: string | null,\n traits: Record<string, string> | null,\n identityEpoch: number,\n ): Promise<void> {\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n if (!this.running) {\n /*\n * A session the replay sample left out still sends its events\n * (#6629), and like a recording it is one person's: another user, or\n * none, starts the next session, as a recording one does.\n */\n if (\n this.analyticsOnly &&\n ref !== this.userRef &&\n this.identityPersisted &&\n this.sessionStore\n ) {\n const identity: ReplaySessionIdentity = await this.sessionStore.rotate(\n this.now(),\n );\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n this.identity = identity;\n }\n this.applyIdentityValues(ref, traits, true);\n return;\n }\n\n if (ref === this.userRef) {\n this.applyIdentityValues(ref, traits, false);\n return;\n }\n\n const wasAcceptingEvents: boolean = this.acceptingEvents;\n this.acceptingEvents = false;\n try {\n if (this.policyRefreshPromise) {\n await this.policyRefreshPromise;\n }\n if (!this.running || identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n\n /*\n * A session that went idle before anything noticed (the app sat in\n * the background) ended at its last activity. It is sealed there:\n * closed by the identity marker instead, it was dated now and\n * stretched by the whole absence. A session paused for idle (#4208)\n * is sealed the same way, before its window runs out: nobody is in\n * it, and its footage ended at the pause.\n */\n if (!this.rotationPromise && !this.sealedForIdle) {\n if (this.isIdlePaused()) {\n await this.sealForIdleNow();\n } else if (this.rotationReason(this.now()) === \"idle\") {\n await this.maybeRotateSession(this.now());\n }\n }\n\n /*\n * A session that ended idle needs no rotation to keep two accounts\n * apart: it records nothing more, and the next one - minted when the\n * user is back - belongs to the new identity. Rotating here would\n * start a session nobody is in (an inactivity logout is the usual\n * case).\n */\n if (this.rotationPromise) {\n await this.rotationPromise;\n } else if (!this.sealedForIdle) {\n this.rotatingSession = true;\n const rotation: Promise<void> = this.performSessionRotation(\n this.now(),\n \"identity\",\n );\n this.rotationPromise = rotation;\n try {\n await rotation;\n } finally {\n if (this.rotationPromise === rotation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n this.acceptingEvents = this.running && wasAcceptingEvents;\n /* A trigger belongs to one user/session and cannot cross accounts. */\n this.triggered = false;\n this.triggerReason = SessionReplayTriggerReason.Sampled;\n this.uploadActive = this.consentState() !== \"Unknown\" && this.sampled;\n this.applyIdentityValues(ref, traits, true);\n const generation: number = this.lifecycleGeneration;\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"identity\",\n );\n if (\n !policyReady ||\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n identityEpoch !== this.identityCancellationEpoch\n ) {\n return;\n }\n if (this.running && this.foreground) {\n this.forceFullSnapshot = true;\n void this.captureTick(true);\n }\n } finally {\n if (this.running && identityEpoch === this.identityCancellationEpoch) {\n this.acceptingEvents = wasAcceptingEvents;\n }\n }\n }\n\n private applyIdentityValues(\n ref: string | null,\n traits: Record<string, string> | null,\n clearTraitsWhenMissing: boolean,\n ): void {\n const changed: boolean = ref !== this.userRef;\n this.userRef = ref;\n if (traits) {\n this.traits = traits;\n } else if (clearTraitsWhenMissing && changed) {\n this.traits = {};\n }\n if (this.options) {\n const currentOptions: ValidatedStartOptions = { ...this.options };\n if (ref) {\n currentOptions.userRef = ref;\n } else {\n delete currentOptions.userRef;\n }\n this.options = currentOptions;\n }\n this.metaDirty = true;\n this.appendCustom(IDENTIFY_CUSTOM_EVENT_TAG, {\n identified: ref !== null,\n traitKeys: Object.keys(this.traits),\n });\n }\n\n private async refreshTargetingConfig(\n baseConfig: ResolvedReplayConfig,\n forceRefresh: boolean = false,\n ): Promise<ResolvedReplayConfig> {\n if (!this.options || (!forceRefresh && !this.userRef)) {\n return baseConfig;\n }\n const currentOptions: ValidatedStartOptions = { ...this.options };\n if (this.userRef) {\n currentOptions.userRef = this.userRef;\n } else {\n delete currentOptions.userRef;\n }\n const targetedConfig: ResolvedReplayConfig = await fetchReplayConfig(\n currentOptions,\n Boolean(this.userRef),\n forceRefresh,\n );\n return targetedConfig;\n }\n\n private async refreshRuntimePolicy(\n generation: number,\n forceRefresh: boolean,\n reason: PolicyRefreshReason,\n ): Promise<boolean> {\n if (\n !this.running ||\n !this.config ||\n !this.options ||\n !this.isCurrentGeneration(generation)\n ) {\n return false;\n }\n\n if (this.policyRefreshPromise) {\n const existingResult: boolean = await this.policyRefreshPromise;\n if (!forceRefresh || !existingResult) {\n return existingResult;\n }\n }\n\n const nowUnixMs: number = this.now();\n if (\n !forceRefresh &&\n nowUnixMs - this.lastPolicyRefreshAtUnixMs <\n MOBILE_POLICY_REFRESH_INTERVAL_MS\n ) {\n return true;\n }\n\n const operation: Promise<boolean> = this.performRuntimePolicyRefresh(\n generation,\n reason,\n nowUnixMs,\n );\n this.policyRefreshPromise = operation;\n try {\n return await operation;\n } finally {\n if (this.policyRefreshPromise === operation) {\n this.policyRefreshPromise = null;\n }\n }\n }\n\n private async performRuntimePolicyRefresh(\n generation: number,\n reason: PolicyRefreshReason,\n nowUnixMs: number,\n ): Promise<boolean> {\n if (!this.options || !this.config) {\n return false;\n }\n const previousConfig: ResolvedReplayConfig = this.config;\n const previousConsentState: SessionReplayConsentState = this.consentState();\n const wasAcceptingEvents: boolean = this.acceptingEvents;\n this.acceptingEvents = false;\n try {\n let currentOptions: ValidatedStartOptions = this.currentStartOptions();\n const maySendUserRef: boolean =\n previousConsentState !== \"Unknown\" && Boolean(currentOptions.userRef);\n let freshConfig: ResolvedReplayConfig = await fetchReplayConfig(\n currentOptions,\n maySendUserRef,\n true,\n );\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n\n if (\n freshConfig.enabled &&\n !maySendUserRef &&\n freshConfig.consentMode === SessionReplayConsentMode.NotRequired &&\n this.userRef\n ) {\n currentOptions = this.currentStartOptions();\n freshConfig = await fetchReplayConfig(currentOptions, true, true);\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n\n this.lastPolicyRefreshAtUnixMs = nowUnixMs;\n if (\n !isRetryablePolicyFailure(freshConfig) &&\n this.mayPersistUnder(freshConfig)\n ) {\n /* What the next offline launch records under (see startInternal). */\n await saveReplayConfig(\n this.storage,\n getReplayStorageNamespace(currentOptions),\n freshConfig,\n nowUnixMs,\n );\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n if (!freshConfig.enabled) {\n if (reason !== \"consent\" && isRetryablePolicyFailure(freshConfig)) {\n this.diagnostic(\"policy-refresh-failed-using-last-config\", {\n reason,\n });\n this.policyStale = true;\n return true;\n }\n this.config = freshConfig;\n await this.discardForPolicyStop(\n reason === \"consent\"\n ? \"config-disabled-after-consent\"\n : \"config-disabled-after-refresh\",\n freshConfig.disabledReason ?? \"not-reported\",\n );\n return false;\n }\n\n this.policyStale = false;\n return await this.applyRuntimePolicy(\n previousConfig,\n freshConfig,\n previousConsentState,\n wasAcceptingEvents,\n generation,\n );\n } catch (error) {\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.lastPolicyRefreshAtUnixMs = nowUnixMs;\n if (reason !== \"consent\") {\n this.diagnostic(\"policy-refresh-failed-using-last-config\", {\n reason,\n name: error instanceof Error ? error.name : \"Error\",\n });\n return true;\n }\n await this.discardForPolicyStop(\n \"config-disabled-after-consent\",\n \"config-fetch-failed\",\n );\n return false;\n } finally {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.acceptingEvents = wasAcceptingEvents;\n }\n }\n }\n\n private async applyRuntimePolicy(\n _previousConfig: ResolvedReplayConfig,\n freshConfig: ResolvedReplayConfig,\n previousConsentState: SessionReplayConsentState,\n wasAcceptingEvents: boolean,\n generation: number,\n ): Promise<boolean> {\n this.config = freshConfig;\n this.metaDirty = true;\n const analyticsStart: Promise<void> | null =\n this.syncProductAnalytics(freshConfig);\n if (analyticsStart) {\n await analyticsStart;\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n const hasConsent: boolean =\n freshConfig.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted;\n\n if (!hasConsent) {\n const mustWithdrawPersistedState: boolean =\n this.identityPersisted ||\n this.uploadActive ||\n previousConsentState !== \"Unknown\";\n if (mustWithdrawPersistedState) {\n /*\n * Product analytics lets go of what it held and of the session it\n * announced, and holds what comes next for the grant (#6629).\n */\n this.analytics?.reset();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n await this.sessionStore?.clear();\n await this.forgetCachedConfig();\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n const nowUnixMs: number = this.now();\n this.identity = this.ephemeralIdentity(nowUnixMs);\n this.identityPersisted = false;\n this.notifySessionChange();\n this.sessionLastActivityUnixMs = nowUnixMs;\n this.sampled = false;\n this.uploadActive = false;\n this.forceFullSnapshot = true;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.recreateTransport();\n }\n this.triggered = freshConfig.isTargeted;\n this.triggerReason = freshConfig.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n this.diagnosticsStatus = \"consent-required\";\n this.acceptingEvents = wasAcceptingEvents;\n this.diagnostic(\"policy-now-requires-consent\");\n return true;\n }\n\n if (!this.identityPersisted && this.sessionStore) {\n const sessionStore: ReplaySessionStore = this.sessionStore;\n const identity: ReplaySessionIdentity = await sessionStore.resolve(\n this.now(),\n );\n if (\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n this.sessionStore !== sessionStore\n ) {\n return false;\n }\n this.identity = identity;\n this.identityPersisted = true;\n this.notifySessionChange();\n this.sessionLastActivityUnixMs = this.now();\n }\n\n if (!this.identity) {\n return false;\n }\n this.sampled = deterministicSample(\n this.identity.sessionId,\n freshConfig.samplePercentage,\n );\n if (freshConfig.isTargeted) {\n this.triggered = true;\n this.triggerReason = SessionReplayTriggerReason.Manual;\n } else if (!this.triggered) {\n this.triggerReason = SessionReplayTriggerReason.Sampled;\n }\n\n if (\n freshConfig.captureTrigger === SessionReplayCaptureTrigger.Always &&\n !this.sampled &&\n !freshConfig.isTargeted\n ) {\n await this.discardForPolicyStop(\n \"not-sampled-after-config-refresh\",\n \"not-sampled\",\n );\n return false;\n }\n\n const shouldUpload: boolean =\n this.sampled || this.triggered || freshConfig.isTargeted;\n if (!shouldUpload && this.uploadActive) {\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.uploadActive = false;\n this.recreateTransport();\n }\n\n this.acceptingEvents = wasAcceptingEvents;\n if (shouldUpload && !this.uploadActive) {\n await this.activateUpload(generation);\n }\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.diagnosticsStatus = this.foreground ? \"recording\" : \"background\";\n this.diagnostic(\"policy-refreshed\", {\n configEpoch: freshConfig.configEpoch,\n });\n /* A session named only now (after consent) takes what was held for it. */\n this.analytics?.refresh();\n return true;\n }\n\n private currentStartOptions(): ValidatedStartOptions {\n const currentOptions: ValidatedStartOptions = {\n ...(this.options as ValidatedStartOptions),\n };\n if (this.userRef) {\n currentOptions.userRef = this.userRef;\n } else {\n delete currentOptions.userRef;\n }\n return currentOptions;\n }\n\n private recreateTransport(): void {\n if (this.options && this.outbox) {\n this.transport = this.createTransport(this.options, this.outbox);\n }\n }\n\n private async discardForPolicyStop(\n code: string,\n reason: string,\n ): Promise<void> {\n if (reason === \"not-sampled\") {\n /* Nothing more is recorded, but the session's events still count. */\n this.analyticsOnly = this.analytics !== null;\n } else {\n /* Replay is off: so are the events its recorder sends. */\n this.stopProductAnalytics();\n }\n this.disable(code, { reason });\n this.haltCapture();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.uploadActive = false;\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n }\n\n private ephemeralIdentity(nowUnixMs: number): ReplaySessionIdentity {\n return {\n sessionId: generateReplayId(),\n tabId: generateReplayId(),\n visitorId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n chunkIndex: 0,\n };\n }\n\n /*\n * Idle before the duration cap, the order Common's SessionIdentity decides\n * them in. A session left for the idle window ended where it was left,\n * even when it has outlived the cap by the time anything notices, and\n * only an idle rotation dates its end there (see performSessionRotation):\n * called \"duration\", a session three hours old put in the background for\n * two more was sealed two hours after its footage.\n */\n private rotationReason(nowUnixMs: number): SessionRotationReason | null {\n if (!this.identity) {\n return null;\n }\n if (\n nowUnixMs - this.sessionLastActivityUnixMs >=\n SESSION_REPLAY_IDLE_ROLLOVER_MS\n ) {\n return \"idle\";\n }\n if (\n nowUnixMs - this.identity.sessionStartUnixMs >=\n SESSION_REPLAY_MAX_SESSION_MS\n ) {\n return \"duration\";\n }\n return null;\n }\n\n private runExternalActivity(nowUnixMs: number, action: () => void): void {\n if (this.pendingIdentityOperations > 0) {\n const identityBarrier: Promise<void> = this.identityQueue;\n const lifecycleEpoch: number = this.lifecycleCancellationEpoch;\n const identityEpoch: number = this.identityCancellationEpoch;\n const wasRunning: boolean = this.running;\n void identityBarrier.then((): void => {\n if (\n lifecycleEpoch !== this.lifecycleCancellationEpoch ||\n identityEpoch !== this.identityCancellationEpoch\n ) {\n return;\n }\n if (\n (this.running && this.acceptingEvents) ||\n (!wasRunning && this.diagnosticsStatus === \"idle\")\n ) {\n action();\n }\n });\n return;\n }\n if (!this.running) {\n action();\n return;\n }\n\n const shouldDefer: boolean =\n this.rotatingSession || this.rotationReason(nowUnixMs) !== null;\n if (!shouldDefer) {\n action();\n return;\n }\n\n const generation: number = this.lifecycleGeneration;\n void this.maybeRotateSession(nowUnixMs).then((): void => {\n if (this.running && this.isCurrentGeneration(generation)) {\n action();\n }\n });\n }\n\n /*\n * isUserBack: the caller knows the user is here - a touch, the app\n * returning to the foreground, an explicit captureSession(). An idle\n * session then rotates at once. Anything else (a capture tick, a route\n * change, a developer event) only finds out the session went idle, and\n * seals it to wait for them (see sealedForIdle).\n */\n private async maybeRotateSession(\n nowUnixMs: number,\n isUserBack: boolean = false,\n ): Promise<void> {\n while (this.rotationPromise) {\n await this.rotationPromise;\n /*\n * What was in flight may have been the idle seal; a returning user\n * still starts the next session after it.\n */\n if (!isUserBack || !this.sealedForIdle) {\n return;\n }\n }\n if (\n !this.running ||\n this.rotatingSession ||\n !this.identity ||\n !this.config ||\n !this.sessionStore ||\n !this.options\n ) {\n return;\n }\n\n let reason: SessionRotationReason | null;\n if (this.sealedForIdle) {\n if (!isUserBack) {\n return;\n }\n reason = \"idle\";\n } else {\n reason = this.rotationReason(nowUnixMs);\n /*\n * Paused for idle (#4208), nobody is in the session and its footage\n * already ended at the pause, so whatever ends it now - its idle\n * window, or the duration cap reached meanwhile - ends it there, as\n * idle: sealed to wait for the user, or followed at once by the next\n * session when they are back.\n */\n if (reason !== null && this.isIdlePaused()) {\n reason = \"idle\";\n }\n }\n if (!reason) {\n return;\n }\n\n this.rotatingSession = true;\n const operation: Promise<void> =\n reason === \"idle\" && !isUserBack\n ? this.sealForIdle()\n : this.performSessionRotation(nowUnixMs, reason);\n this.rotationPromise = operation;\n try {\n await operation;\n } finally {\n if (this.rotationPromise === operation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n\n /*\n * The idle seal on demand, under the lock every rotation takes: for an\n * identity change on a session paused for idle, which no clock has ended\n * yet but nobody is in.\n */\n private async sealForIdleNow(): Promise<void> {\n if (this.rotationPromise || this.rotatingSession || this.sealedForIdle) {\n return;\n }\n this.rotatingSession = true;\n const operation: Promise<void> = this.sealForIdle();\n this.rotationPromise = operation;\n try {\n await operation;\n } finally {\n if (this.rotationPromise === operation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n\n /*\n * maybeRotateSession for a user who is here. On an app whose session\n * ended idle - or was paused for idle, which stops the capture tick too\n * (#4208) - the policy is brought up to date first: no capture tick has\n * refreshed it while the app sat idle, and the next session must not open\n * under one that has since changed (or turned replay off).\n */\n private async maybeRotateForUser(nowUnixMs: number): Promise<void> {\n if (\n (this.sealedForIdle || this.idlePause !== null) &&\n !this.rotatingSession\n ) {\n const policyReady: boolean = await this.refreshRuntimePolicy(\n this.lifecycleGeneration,\n false,\n \"periodic\",\n );\n if (!policyReady) {\n return;\n }\n }\n await this.maybeRotateSession(nowUnixMs, true);\n }\n\n /*\n * End the session as idle, where it really ended, and wait for the user.\n *\n * Sealed with whatever footage is still buffered - dated by that footage,\n * never by now - and with no marker of its own: a marker stamped now\n * would date the session's end half an hour or more after anything the\n * player can show. With nothing buffered nothing is sent, and the server\n * ends the session at its last chunk - for a session paused for idle\n * (#4208), the chunk its idle-paused marker closed.\n */\n private async sealForIdle(): Promise<void> {\n /* First, so nothing appended while the seal uploads lands in it. */\n this.sealedForIdle = true;\n /*\n * An idle pause ends with its session, and nothing is left to wait for\n * on a timer: the next input starts the next session.\n */\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.clearTimers();\n this.diagnostic(\"session-ended-idle\", {\n idleForMs: Math.max(0, this.now() - this.sessionLastActivityUnixMs),\n });\n this.notifySessionChange();\n await this.closeCurrent(true);\n await this.closeQueue;\n if (!this.running) {\n return;\n }\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n /* Pre-roll of a session that ended; a later trigger is the next one's. */\n this.rollingBuffer.clear();\n }\n /*\n * Its record goes too: written by the session's last chunk, it looks\n * recent, and a relaunch before the user is back would otherwise carry\n * on a session that is over.\n */\n if (this.running && this.identityPersisted) {\n await this.sessionStore?.end();\n }\n }\n\n private async performSessionRotation(\n nowUnixMs: number,\n reason: SessionRotationReason,\n ): Promise<void> {\n /*\n * The marker closes the outgoing session for a rotation the user was\n * active through (the duration cap, an identity change): dated now, it\n * is where that session ended. Not for an idle one. That session ended\n * at its last activity - possibly hours ago, with the app in the\n * background since - and a marker dated now, as its final chunk,\n * stretched it by the whole absence. It opens the next session instead\n * (openSessionAfterIdle). A session paused for idle rotates as idle\n * (maybeRotateSession): its footage ended at the pause.\n */\n if (reason !== \"idle\") {\n this.appendCustom(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason },\n undefined,\n true,\n );\n }\n await this.closeCurrent(true);\n await this.closeQueue;\n if (!this.running) {\n return;\n }\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n this.rollingBuffer.clear();\n }\n if (!this.running) {\n return;\n }\n\n await this.completeSessionIdentityRotation(nowUnixMs, reason);\n if (reason === \"idle\" && this.running) {\n await this.openSessionAfterIdle();\n }\n }\n\n /*\n * The first things a session after an idle one records: a full snapshot\n * of the screen the user came back to, then the rotation marker - the\n * snapshot first, so chunk 0 is a seek anchor rather than a lone marker.\n *\n * Taken here, inside the rotation, rather than left to the next capture\n * tick: until the rotation settles, touches are dropped and every other\n * event waits for it (rotatingSession), so nothing can land ahead of the\n * snapshot. A user who has just come back is touching the screen, and\n * half a second of that was otherwise a chunk 0 with no screen in it.\n *\n * In the background or without a registered root there is no screen to\n * capture yet; the marker opens the session alone.\n */\n private async openSessionAfterIdle(): Promise<void> {\n const generation: number = this.lifecycleGeneration;\n const rootTag: number | null = this.rootTag;\n const options: ValidatedStartOptions | null = this.options;\n const sessionId: string | undefined = this.identity?.sessionId;\n if (this.foreground && rootTag && options && sessionId) {\n const capturedAtUnixMs: number = this.now();\n let tree: NativeViewTreeNode;\n try {\n tree = await this.nativeViewTree.captureViewTree(rootTag);\n } catch (error) {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.disable(\"native-capture-failed\", {\n name: error instanceof Error ? error.name : \"Error\",\n });\n this.haltCapture();\n }\n return;\n }\n if (\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n this.identity?.sessionId !== sessionId\n ) {\n return;\n }\n if (this.foreground) {\n this.touchPrivacyMap = deriveTouchPrivacyMap(tree);\n this.appendCapture(tree, options, capturedAtUnixMs, true);\n }\n }\n this.appendCustom(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason: \"idle\" },\n undefined,\n true,\n );\n }\n\n private async completeSessionIdentityRotation(\n nowUnixMs: number,\n reason: SessionRotationReason,\n ): Promise<void> {\n if (!this.sessionStore || !this.config || !this.options) {\n return;\n }\n this.identity = this.identityPersisted\n ? await this.sessionStore!.rotate(nowUnixMs)\n : this.ephemeralIdentity(nowUnixMs);\n /*\n * Before the notification, which hands the host the new id. An idle\n * pause, and whatever was held for its resume, belong to the session\n * that just ended (#4208): the new one opens on a snapshot of its own.\n */\n this.sealedForIdle = false;\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.notifySessionChange();\n this.sampled = this.identityPersisted\n ? deterministicSample(\n this.identity.sessionId,\n this.config.samplePercentage,\n )\n : false;\n this.triggered = this.config.isTargeted;\n this.triggerReason = this.config.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n this.uploadActive =\n this.consentState() !== \"Unknown\" &&\n (this.sampled || this.config.isTargeted);\n this.serializer.reset();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.forceFullSnapshot = true;\n this.lastFullSnapshotAtUnixMs = 0;\n this.sessionLastActivityUnixMs = nowUnixMs;\n this.metaDirty = true;\n this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);\n this.diagnostic(\"session-rotated\", { reason });\n\n if (\n this.config.captureTrigger === SessionReplayCaptureTrigger.Always &&\n this.identityPersisted &&\n !this.sampled &&\n !this.config.isTargeted\n ) {\n /* Nothing of it is recorded, but its events still count (#6629). */\n this.analyticsOnly = this.analytics !== null;\n this.disable(\"not-sampled\");\n this.haltCapture();\n return;\n }\n\n /*\n * An idle pause or seal had stopped the sampler. The new session\n * samples again - and, if nobody is there (a rotation nobody's input\n * caused, such as the chunk cap reached by the pause's own chunk),\n * pauses again on its own.\n */\n if (this.captureTimer === null && this.running && this.foreground) {\n this.startTimers();\n }\n }\n\n /*\n * The app's name, version and system, as the start options and then the\n * native module say them. False when a newer start or a stop took over\n * meanwhile.\n */\n private async readAppMetadata(\n validated: ValidatedStartOptions,\n generation: number,\n ): Promise<boolean> {\n try {\n const nativeMetadata: NativeAppMetadata =\n await this.nativeViewTree.getAppMetadata();\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n this.metadata = {\n appName: safeMetadataValue(\n validated.appName,\n safeMetadataValue(nativeMetadata?.appName, \"React Native\"),\n ),\n appVersion: safeMetadataValue(\n validated.appVersion,\n safeMetadataValue(nativeMetadata?.appVersion, \"unknown\"),\n ),\n osName: safeMetadataValue(nativeMetadata?.osName, \"unknown\"),\n osVersion: safeMetadataValue(nativeMetadata?.osVersion, \"unknown\"),\n };\n } catch {\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n this.diagnostic(\"native-metadata-unavailable\");\n }\n return true;\n }\n\n /*\n * Product analytics events (issue #6629, src/ProductAnalytics.ts), when\n * the application has them on: the channel asks this recorder for the\n * session, the visitor, consent and who is signed in, so an event and a\n * recording of the same visit carry the same ids.\n */\n private async startProductAnalytics(\n options: ValidatedStartOptions,\n config: ResolvedReplayConfig,\n namespace: string,\n ): Promise<void> {\n if (this.analytics || !config.productAnalytics.enabled) {\n return;\n }\n\n const analytics: MobileProductAnalytics = new MobileProductAnalytics(\n {\n url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,\n headers: mobileRequestHeaders(options),\n fetch: options.fetch,\n now: this.now,\n storage: this.storage,\n namespace,\n appState: this.appState,\n connectivity: options.connectivity,\n getSessionId: (nowUnixMs: number): string => {\n return this.analyticsSessionId(nowUnixMs, true);\n },\n peekSessionId: (): string => {\n return this.analyticsSessionId(this.now(), false);\n },\n getVisitorId: (): string => {\n return this.identityPersisted ? this.identity?.visitorId ?? \"\" : \"\";\n },\n getConsentState: (): SessionReplayConsentState => {\n return this.consentState();\n },\n requiresConsent: (): boolean => {\n return (\n this.config?.consentMode ===\n SessionReplayConsentMode.RequireExplicit\n );\n },\n getIdentity: (): ProductAnalyticsIdentity => {\n return this.analyticsIdentity();\n },\n toProperties: (value: unknown): Record<string, string> => {\n return maskStringMapValues(sanitizeEventProperties(value));\n },\n getContext: (): ProductAnalyticsWireContext => {\n return this.analyticsContext();\n },\n onDiagnostic: (\n code: string,\n details?: Record<string, unknown>,\n ): void => {\n this.diagnostic(code, details);\n },\n },\n config.productAnalytics,\n );\n this.analytics = analytics;\n await analytics.start();\n }\n\n /*\n * Ends the product analytics channel this recorder started; `flushFirst`\n * sends what it holds first (stop()).\n */\n private stopProductAnalytics(flushFirst: boolean = false): void {\n const analytics: MobileProductAnalytics | null = this.analytics;\n this.analytics = null;\n this.analyticsOnly = false;\n if (!analytics) {\n return;\n }\n if (flushFirst) {\n analytics.flush(true);\n }\n analytics.stop();\n }\n\n /*\n * A refreshed policy's product analytics: switched off, the channel\n * stops; switched on, it starts - again, too, after the server said they\n * were off - and its trait keys follow the policy. A promise only when a\n * channel has to start.\n */\n private syncProductAnalytics(\n config: ResolvedReplayConfig,\n ): Promise<void> | null {\n if (!config.productAnalytics.enabled) {\n this.stopProductAnalytics();\n return null;\n }\n if (this.analytics && this.analytics.getStopReason() !== \"not-enabled\") {\n this.analytics.setConfig(config.productAnalytics);\n return null;\n }\n if (!this.options) {\n return null;\n }\n const options: ValidatedStartOptions = this.currentStartOptions();\n this.stopProductAnalytics();\n return this.startProductAnalytics(\n options,\n config,\n getReplayStorageNamespace(options),\n );\n }\n\n /*\n * The session a product analytics event belongs to (issue #6629). The\n * recording's own while the recorder runs: it rotates its session\n * itself, and a session that ended idle keeps its id until the next one\n * starts. \"\" before consent, when the session the recorder holds is a\n * throwaway: the events wait for the one the grant opens. A session the\n * replay sample left out records nothing, so an event is its activity\n * (isActivity), and keeps it alive or rolls it over.\n */\n private analyticsSessionId(nowUnixMs: number, isActivity: boolean): string {\n if (!this.identity || !this.identityPersisted) {\n return \"\";\n }\n if (this.running) {\n return this.identity.sessionId;\n }\n if (this.analyticsOnly && this.sessionStore) {\n if (isActivity) {\n const continued: ReplaySessionIdentity | null =\n this.sessionStore.continueSession(nowUnixMs);\n if (continued) {\n this.identity = continued;\n }\n }\n return this.identity.sessionId;\n }\n return \"\";\n }\n\n /* Who is signed in, only while the application captures identity. */\n private analyticsIdentity(): ProductAnalyticsIdentity {\n if (this.config?.captureUserIdentity !== true || !this.userRef) {\n return { userRef: \"\", traits: null };\n }\n return { userRef: this.userRef, traits: { ...this.traits } };\n }\n\n /*\n * What the app runs on, as its recorded sessions are filed (Common's\n * RumProductAnalyticsSession): a phone, or a tablet from a shorter side\n * of 600 points; no browser; the system the native module names; and the\n * app's version, from the start options or the native module.\n */\n private analyticsContext(): ProductAnalyticsWireContext {\n const size: { width: number; height: number } = getViewport();\n const known: (value: string) => string = (value: string): string => {\n return value === \"unknown\" ? \"\" : value;\n };\n return {\n deviceType:\n Math.min(size.width, size.height) >=\n PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE\n ? \"tablet\"\n : \"mobile\",\n browserName: \"\",\n osName: known(this.metadata.osName)\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),\n appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion)),\n };\n }\n\n private disable(code: string, details?: Record<string, unknown>): void {\n this.diagnosticsStatus = \"disabled\";\n this.diagnostic(code, details);\n }\n\n private diagnostic(code: string, details?: Record<string, unknown>): void {\n const event: MobileReplayDiagnosticEvent = {\n code,\n atUnixMs: this.now(),\n };\n if (details) {\n event.details = details;\n }\n this.diagnosticsEvents.push(event);\n if (this.diagnosticsEvents.length > MAX_DIAGNOSTIC_EVENTS) {\n this.diagnosticsEvents.shift();\n }\n if (this.options?.debug) {\n // eslint-disable-next-line no-console\n console.info(`[OneUptime Replay] ${code}`, details ?? {});\n }\n }\n}\n\nexport { deterministicSample };\n", "/*\n * Build-time copy of the pure session-replay wire contract. This package is\n * installed in customer React Native applications and must not pull the\n * OneUptime monorepo's Common package into their bundle. Contract-parity\n * tests compare these additive constants with Common in the repository.\n */\n\nexport const SESSION_REPLAY_WIRE_VERSION: number = 1;\nexport const SESSION_REPLAY_SCHEMA_VERSION: number = 1;\n/*\n * octet-stream, not a vendor type: a web application firewall on the OWASP\n * Core Rule Set (Azure Front Door among them) refuses a Content-Type that\n * is not on its allowlist, and octet-stream is on it and never parsed. The\n * server accepts both. See Common/Types/Rum/SessionReplay.\n */\nexport const SESSION_REPLAY_CONTENT_TYPE: string = \"application/octet-stream\";\nexport const SESSION_REPLAY_LEGACY_CONTENT_TYPE: string =\n \"application/vnd.oneuptime.session-replay.v1\";\n\n/*\n * Copy of Common/Utils/Rum/SessionReplayWireEncoding, which explains why a\n * frame's envelope line has its `%`, `&` and `http/` escaped and a space\n * before its newline: a firewall's request-smuggling rule (CRS 921110)\n * would otherwise read a trait value or a URL plus that newline as an HTTP\n * request line.\n */\nexport const SESSION_REPLAY_ENVELOPE_TERMINATOR: string = \" \\n\";\n\nconst ESCAPED_SEQUENCES: RegExp = /[%&]|(http)\\//gi;\n\nexport function escapeSessionReplayJson(json: string): string {\n return json.replace(\n ESCAPED_SEQUENCES,\n (match: string, http: string | undefined): string => {\n if (http !== undefined) {\n return `${http}\\\\/`;\n }\n\n return match === \"%\" ? \"\\\\u0025\" : \"\\\\u0026\";\n },\n );\n}\n\nexport function encodeSessionReplayEnvelopeLine(envelope: unknown): string {\n return (\n escapeSessionReplayJson(JSON.stringify(envelope)) +\n SESSION_REPLAY_ENVELOPE_TERMINATOR\n );\n}\n\nexport const SESSION_REPLAY_APP_IDENTIFIER_HEADER: string =\n \"x-oneuptime-app-identifier\";\nexport const SESSION_REPLAY_RECORDER_KIND_HEADER: string =\n \"x-oneuptime-replay-recorder-kind\";\nexport const SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER: string =\n \"x-oneuptime-mobile-app-identifier\";\nexport const SESSION_REPLAY_USER_REF_HEADER: string = \"x-oneuptime-user-ref\";\nexport const SESSION_REPLAY_MAX_USER_REF_LENGTH: number = 512;\nexport const AUTH_TOKEN_HEADER: string = \"x-oneuptime-token\";\n\nexport const CONFIG_PATH: string = \"/telemetry/session-replay/v1/config\";\nexport const CHUNK_PATH: string = \"/telemetry/session-replay/v1/chunk\";\nexport const SESSION_REPLAY_FLUSH_INTERVAL_MS: number = 15_000;\nexport const SESSION_REPLAY_FLUSH_BYTES: number = 256 * 1024;\nexport const SESSION_REPLAY_CHECKOUT_INTERVAL_MS: number = 60_000;\nexport const SESSION_REPLAY_ROLLING_BUFFER_MS: number = 60_000;\nexport const SESSION_REPLAY_ROLLING_BUFFER_BYTES: number = 2 * 1024 * 1024;\nexport const SESSION_REPLAY_IDLE_ROLLOVER_MS: number = 30 * 60_000;\n/*\n * How long the recorder keeps capturing with nobody using the app (Common's\n * SESSION_REPLAY_IDLE_PAUSE_MS). After this long without a touch it stops\n * capturing altogether - no view-tree sample, no checkout, no chunk - and\n * the next touch, or the app coming back to the foreground, resumes the\n * same session on a fresh snapshot, as long as that comes inside\n * SESSION_REPLAY_IDLE_ROLLOVER_MS.\n */\nexport const SESSION_REPLAY_IDLE_PAUSE_MS: number = 5 * 60_000;\nexport const SESSION_REPLAY_MAX_SESSION_MS: number = 4 * 60 * 60_000;\nexport const SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES: number =\n 8 * 1024 * 1024;\nexport const MAX_SESSION_REPLAY_CHUNK_BYTES: number = 2 * 1024 * 1024;\nexport const MAX_SESSION_REPLAY_CHUNKS_PER_SESSION: number = 480;\n/*\n * Offline mode: how long a chunk may wait on the device for a connection.\n * The server allows exactly this much upload delay when it places a late\n * recording on its timeline (Common's SESSION_REPLAY_MAX_OFFLINE_DELAY_MS).\n */\nexport const SESSION_REPLAY_MAX_OFFLINE_DELAY_MS: number =\n 3 * 24 * 60 * 60 * 1000;\nexport const MOBILE_CAPTURE_INTERVAL_MS: number = 500;\ntype MobileRecorderKind = \"rn-view-tree\";\nexport const MOBILE_RECORDER_KIND: MobileRecorderKind = \"rn-view-tree\";\nexport const SYNTHETIC_RRWEB_VERSION: string = \"synthetic-1\";\n\ndeclare const __ONEUPTIME_MOBILE_RECORDER_VERSION__: string;\n\nexport const RECORDER_VERSION: string =\n typeof __ONEUPTIME_MOBILE_RECORDER_VERSION__ === \"string\"\n ? __ONEUPTIME_MOBILE_RECORDER_VERSION__\n : \"0.0.0-dev\";\n\nexport const SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES: ReadonlyArray<string> =\n [\n \"mobile-view-tree\",\n \"mobile-touch-events\",\n \"custom-events\",\n \"traits\",\n \"tags\",\n \"visibility\",\n \"visitor-id\",\n \"route-events\",\n \"js-errors\",\n ];\n\nexport enum SessionReplayMaskingMode {\n MaskSensitiveInputsOnly = \"MaskSensitiveInputsOnly\",\n MaskInputsOnly = \"MaskInputsOnly\",\n MaskAllText = \"MaskAllText\",\n}\n\nexport enum SessionReplayConsentMode {\n RequireExplicit = \"RequireExplicit\",\n NotRequired = \"NotRequired\",\n}\n\nexport enum SessionReplayCaptureTrigger {\n Always = \"Always\",\n OnErrorOrFrustration = \"OnErrorOrFrustration\",\n}\n\nexport enum SessionReplayTriggerReason {\n Error = \"error\",\n Frustration = \"frustration\",\n Sampled = \"sampled\",\n Manual = \"manual\",\n Performance = \"performance\",\n}\n\nexport enum SessionReplayFidelityNotice {\n MobileImagesOpaque = \"mobile-images-opaque\",\n MobileWebViewOpaque = \"mobile-webview-opaque\",\n MobileCanvasOpaque = \"mobile-canvas-opaque\",\n MobileAnimationSampled = \"mobile-animation-sampled\",\n BufferOverflow = \"buffer-overflow\",\n SnapshotTooLarge = \"snapshot-too-large\",\n}\n\n/*\n * Frustration signals (issue #6443), copied from Common's\n * Types/Rum/SessionReplayFrustrationSignals: what the config response\n * carries about the application's rules and its signals of its own, and\n * how a chunk counts the signals it saw. ContractParity holds every type\n * and number here identical to Common's.\n *\n * This recorder detects the application's own page, event and error\n * signals. The built-in rules (rage, dead and error clicks, refresh rage)\n * and click signals are about a mouse on a web page, and only the browser\n * recorder detects them.\n */\nexport type SessionReplayCustomSignalTrigger =\n | \"click\"\n | \"page\"\n | \"event\"\n | \"error\";\n\nexport interface SessionReplayRageClickRule {\n isEnabled: boolean;\n clickCount: number;\n windowMs: number;\n radiusPx: number;\n ignoreSelectors: Array<string>;\n}\n\nexport interface SessionReplayDeadClickRule {\n isEnabled: boolean;\n timeoutMs: number;\n ignoreSelectors: Array<string>;\n}\n\nexport interface SessionReplayErrorClickRule {\n isEnabled: boolean;\n windowMs: number;\n}\n\nexport interface SessionReplayRefreshRageRule {\n isEnabled: boolean;\n reloadCount: number;\n windowSeconds: number;\n}\n\nexport interface SessionReplayCustomSignalConfig {\n name: string;\n trigger: SessionReplayCustomSignalTrigger;\n match: string;\n isFrustration: boolean;\n}\n\nexport interface SessionReplayFrustrationSignalsConfig {\n rageClick: SessionReplayRageClickRule;\n deadClick: SessionReplayDeadClickRule;\n errorClick: SessionReplayErrorClickRule;\n refreshRage: SessionReplayRefreshRageRule;\n customSignals: Array<SessionReplayCustomSignalConfig>;\n}\n\nexport interface SessionReplayCustomSignalCount {\n name: string;\n count: number;\n frustrationCount: number;\n}\n\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNALS: number = 20;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH: number = 40;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH: number = 200;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH: number = 64;\n/* The same signal is not counted twice within a second. */\nexport const SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS: number = 1000;\n/* How many signal markers one chunk holds. */\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK: number = 50;\n\nexport type SessionReplayConsentState = \"Granted\" | \"NotRequired\" | \"Unknown\";\nexport type SessionReplayDirective = \"continue\" | \"stop\" | \"throttle\";\nexport type SessionReplayPayloadEncoding = \"gzip\" | \"identity\";\nexport type SessionReplayRecorderKind = \"dom\" | \"rn-view-tree\";\n\nexport interface SessionReplayConfigResponse {\n enabled: boolean;\n recorderVersion: string;\n maskingMode: SessionReplayMaskingMode;\n captureTrigger: string;\n consentMode: SessionReplayConsentMode;\n samplePercentage: number;\n maskSelectors: Array<string>;\n blockSelectors: Array<string>;\n urlAllowlist: Array<string>;\n recordCanvas: boolean;\n captureUserIdentity: boolean;\n ignoreErrorPatterns: Array<string>;\n respectDoNotTrack: boolean;\n configEpoch: number;\n directive: SessionReplayDirective;\n isTargeted?: boolean;\n disabledReason?: string;\n disabledDetail?: string;\n budgetResetsAt?: string;\n debug?: boolean;\n frustrationSignals?: SessionReplayFrustrationSignalsConfig;\n /*\n * Product analytics events (Common's SessionReplayConfigResponse\n * .productAnalytics, issue #6629): absent reads as off.\n */\n productAnalytics?: {\n enabled: boolean;\n userPropertyKeys: Array<string>;\n };\n}\n\nexport interface SessionReplaySignalCounts {\n errorCount: number;\n rageClickCount: number;\n deadClickCount: number;\n errorClickCount: number;\n refreshRageCount: number;\n routeCount: number;\n clickCount?: number;\n customEventCount?: number;\n customSignals?: Array<SessionReplayCustomSignalCount>;\n}\n\n/* The counts a chunk adds one to at a time. */\nexport type SessionReplayNumericSignalKey = Exclude<\n keyof SessionReplaySignalCounts,\n \"customSignals\"\n>;\n\nexport interface SessionReplayChunkMeta {\n entryUrl: string;\n browserName: string;\n browserVersion: string;\n osName: string;\n deviceType: string;\n viewportWidth: number;\n viewportHeight: number;\n identifiedUserRef?: string;\n visitorId?: string;\n identifiedUserTraits?: Record<string, string>;\n tags?: Record<string, string>;\n}\n\nexport interface SessionReplayChunkEnvelope {\n v: number;\n appIdentifier: string;\n sessionId: string;\n tabId: string;\n chunkIndex: number;\n sessionStartUnixMs: number;\n clientSendUnixMs: number;\n chunkStartOffsetMs: number;\n chunkEndOffsetMs: number;\n eventCount: number;\n hasFullSnapshot: boolean;\n isFinal: boolean;\n recorderKind: SessionReplayRecorderKind;\n schemaVersion: number;\n rrwebVersion: string;\n recorderVersion: string;\n maskingMode: SessionReplayMaskingMode;\n consentState: SessionReplayConsentState;\n triggerReason: SessionReplayTriggerReason;\n payloadEncoding: SessionReplayPayloadEncoding;\n payloadBytes: number;\n url: string;\n routes?: Array<string>;\n signals: SessionReplaySignalCounts;\n fidelityNotices: Array<string>;\n droppedEvents: number;\n flushFailures: number;\n meta?: SessionReplayChunkMeta;\n capabilities?: Array<string>;\n}\n\nexport interface SessionReplayChunkResponse {\n directive: SessionReplayDirective;\n configEpoch: number;\n retryAfterSeconds?: number;\n reason?: string;\n}\n\nexport enum RrwebEventType {\n DomContentLoaded = 0,\n Load = 1,\n FullSnapshot = 2,\n IncrementalSnapshot = 3,\n Meta = 4,\n Custom = 5,\n}\n\nexport enum RrwebIncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n}\n\nexport enum RrwebMouseInteractionType {\n TouchStart = 7,\n TouchEnd = 9,\n}\n\nexport interface RrwebEvent<TData = unknown> {\n type: RrwebEventType;\n data: TData;\n timestamp: number;\n}\n\nexport const ROUTE_CUSTOM_EVENT_TAG: string = \"oneuptime.route\";\nexport const ERROR_CUSTOM_EVENT_TAG: string = \"oneuptime.error\";\nexport const CUSTOM_EVENT_TAG: string = \"oneuptime.custom\";\nexport const IDENTIFY_CUSTOM_EVENT_TAG: string = \"oneuptime.identify\";\nexport const TAGS_CUSTOM_EVENT_TAG: string = \"oneuptime.tags\";\nexport const VISIBILITY_CUSTOM_EVENT_TAG: string = \"oneuptime.visibility\";\nexport const TOUCH_CUSTOM_EVENT_TAG: string = \"oneuptime.touch\";\nexport const SESSION_ROTATED_CUSTOM_EVENT_TAG: string =\n \"oneuptime.session-rotated\";\n\n/*\n * A signal of the application's own (Common's\n * SessionReplayCustomEventTag.CustomSignal and its payload). Carries the\n * signal's name, never what it matched: not the error's text, not the\n * route.\n */\nexport const CUSTOM_SIGNAL_CUSTOM_EVENT_TAG: string = \"oneuptime.signal\";\n\nexport interface SessionReplayCustomSignalPayload {\n name: string;\n trigger: SessionReplayCustomSignalTrigger;\n isFrustration: boolean;\n atUnixMs: number;\n /* Present for click signals. Viewport coordinates, never content. */\n x?: number;\n y?: number;\n}\n\n/*\n * The idle pause's two markers, copied from Common's\n * SessionReplayCustomEvents with their payloads. The player draws the\n * stretch between them as unrecorded rather than as footage of a screen\n * that sat still, so nothing at all is recorded between the two.\n */\nexport const IDLE_PAUSED_CUSTOM_EVENT_TAG: string = \"oneuptime.idle-paused\";\nexport const IDLE_RESUMED_CUSTOM_EVENT_TAG: string = \"oneuptime.idle-resumed\";\n\n/* The last thing in the stream before an idle pause. */\nexport interface SessionReplayIdlePausedPayload {\n /* The last input before the pause: where the user actually stopped. */\n idleSinceUnixMs: number;\n /* When capture stopped. */\n pausedAtUnixMs: number;\n /*\n * \"page\" when a web page paused recording itself (the browser recorder's\n * OneUptimeReplay.pause(), issue #6834). This recorder has no such call\n * and never sets it: every pause it marks is one nobody used the app for.\n */\n reason?: \"page\";\n}\n\n/*\n * The first marker after an idle pause, directly behind the fresh snapshot\n * that resumed capture. Carries the pause's start too, so the unrecorded\n * stretch can be drawn from this marker alone.\n */\nexport interface SessionReplayIdleResumedPayload {\n pausedAtUnixMs: number;\n resumedAtUnixMs: number;\n /*\n * The reason of the pause this ends, as its paused marker gave it\n * (issue #7498). Never set here, as reason is never set on a paused\n * marker of this recorder's.\n */\n reason?: \"page\";\n}\n", "import {\n SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES,\n SessionReplaySignalCounts,\n} from \"./Contract\";\n\nexport const MAX_TRAIT_KEYS: number = 20;\nexport const MAX_TRAIT_KEY_LENGTH: number = 40;\nexport const MAX_TRAIT_VALUE_LENGTH: number = 200;\nexport const MAX_TAG_KEYS: number = 20;\nexport const MAX_TAG_KEY_LENGTH: number = 32;\nexport const MAX_TAG_VALUE_LENGTH: number = 128;\nexport const MAX_CUSTOM_EVENT_NAME_LENGTH: number = 64;\nexport const MAX_CUSTOM_EVENT_PROPERTY_KEYS: number = 20;\nexport const MAX_CAPTURE_REASON_LENGTH: number = 80;\nexport const MAX_USER_REFERENCE_LENGTH: number = 200;\n\nconst SAFE_IDENTIFIER_PATTERN: RegExp = /^[A-Za-z0-9._:-]+$/;\nconst BLOCKED_KEYS: ReadonlySet<string> = new Set<string>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\nconst UUID_SEGMENT: RegExp =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;\nconst OBJECT_ID_SEGMENT: RegExp = /^[0-9a-f]{24}$/iu;\n/*\n * An email-shaped route segment. Each run is length-bounded (a local part, a\n * domain and a last label, at the sizes RFC 5321 allows) and anchored, so a\n * segment of any length is read once from end to end - the recorder runs\n * this on the device over whatever route the app was opened at.\n */\nconst EMAIL_SEGMENT: RegExp = /^[^@\\s/]{1,64}@[^@\\s/]{1,253}\\.[^@\\s/]{1,63}$/u;\nconst LONG_DIGIT_SEGMENT: RegExp = /^\\d{9,}$/u;\n/*\n * A token in base64url or standard base64, with up to two \"=\" of padding\n * (Common's UrlScrubber, #8489).\n */\nconst OPAQUE_TOKEN_SEGMENT: RegExp = /^[A-Za-z0-9_+/-]{32,}={0,2}$/u;\n/*\n * A JSON Web Token, signed, unsigned or encrypted: a header of base64url\n * JSON (\"eyJ\") and one to four more parts joined by dots, which kept it out\n * of the token rule (Common's UrlScrubber, #8385). Anchored at both ends of\n * one segment, and no part can hold a dot, so a segment is read once.\n */\nconst JWT_SEGMENT: RegExp = /^eyJ[A-Za-z0-9_-]{8,}(?:\\.[A-Za-z0-9_-]*){1,4}$/u;\nconst ABSOLUTE_URL_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTER_PATTERN: RegExp = /[\\u0000-\\u001F\\u007F]/gu;\n\nexport function truncate(value: string, length: number): string {\n return value.slice(0, Math.max(0, length));\n}\n\nexport function sanitizeIdentifier(\n value: unknown,\n maximumLength: number,\n): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed: string = value.trim();\n if (\n trimmed.length === 0 ||\n trimmed.length > maximumLength ||\n !SAFE_IDENTIFIER_PATTERN.test(trimmed)\n ) {\n return null;\n }\n\n return trimmed;\n}\n\nfunction stringifyPrimitive(value: unknown): string | null {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"number\":\n return Number.isFinite(value) ? String(value) : null;\n case \"boolean\":\n return value ? \"true\" : \"false\";\n default:\n return value === null ? \"null\" : null;\n }\n}\n\nexport function sanitizeStringMap(\n value: unknown,\n limits: {\n keys: number;\n keyLength: number;\n valueLength: number;\n },\n): Record<string, string> {\n const result: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return result;\n }\n\n for (const [rawKey, rawValue] of Object.entries(\n value as Record<string, unknown>,\n )) {\n if (Object.keys(result).length >= limits.keys) {\n break;\n }\n\n const key: string = truncate(rawKey.trim(), limits.keyLength);\n const stringValue: string | null = stringifyPrimitive(rawValue);\n\n if (!key || BLOCKED_KEYS.has(key) || stringValue === null) {\n continue;\n }\n\n result[key] = truncate(stringValue, limits.valueLength);\n }\n\n return result;\n}\n\nexport function sanitizeTraits(value: unknown): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_TRAIT_KEYS,\n keyLength: MAX_TRAIT_KEY_LENGTH,\n valueLength: MAX_TRAIT_VALUE_LENGTH,\n });\n}\n\nexport function sanitizeTags(value: unknown): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_TAG_KEYS,\n keyLength: MAX_TAG_KEY_LENGTH,\n valueLength: MAX_TAG_VALUE_LENGTH,\n });\n}\n\nexport function sanitizeEventProperties(\n value: unknown,\n): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_CUSTOM_EVENT_PROPERTY_KEYS,\n keyLength: MAX_TRAIT_KEY_LENGTH,\n valueLength: MAX_TRAIT_VALUE_LENGTH,\n });\n}\n\n/* Mirrors Common/Utils/Rum/Masking.maskText without a runtime dependency. */\nexport function maskTextValue(value: string): string {\n if (!value || value.trim().length === 0) {\n return value;\n }\n\n const length: number = value.trim().length;\n const maskedLength: number = length <= 8 ? 4 : length <= 32 ? 16 : 40;\n return \"\u2022\".repeat(maskedLength);\n}\n\nexport function maskStringMapValues(\n values: Record<string, string>,\n): Record<string, string> {\n const masked: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n for (const [key, value] of Object.entries(values)) {\n masked[key] = maskTextValue(value);\n }\n return masked;\n}\n\nexport function sanitizeRoute(route: unknown): string {\n if (typeof route !== \"string\") {\n return \"/\";\n }\n\n let path: string = route.trim();\n if (!path) {\n return \"/\";\n }\n\n try {\n if (ABSOLUTE_URL_PATTERN.test(path)) {\n path = new URL(path).pathname;\n }\n } catch {\n path = \"/\";\n }\n\n path = path.split(/[?#]/u, 1)[0] || \"/\";\n if (!path.startsWith(\"/\")) {\n path = `/${path}`;\n }\n\n path = path\n .split(\"/\")\n .map((segment: string): string => {\n let decoded: string = segment;\n /*\n * Decoded once, and once more for an address escaped twice\n * (\"someone%2540example.com\"), as Common's UrlScrubber reads it.\n */\n for (let pass: number = 0; pass < 2; pass++) {\n try {\n decoded = decodeURIComponent(decoded);\n } catch {\n // Matched as it is.\n }\n if (\n UUID_SEGMENT.test(decoded) ||\n OBJECT_ID_SEGMENT.test(decoded) ||\n EMAIL_SEGMENT.test(decoded) ||\n LONG_DIGIT_SEGMENT.test(decoded) ||\n OPAQUE_TOKEN_SEGMENT.test(decoded) ||\n JWT_SEGMENT.test(decoded)\n ) {\n return \"[redacted]\";\n }\n }\n return segment;\n })\n .join(\"/\");\n\n return truncate(path.replace(CONTROL_CHARACTER_PATTERN, \"\"), 2048);\n}\n\nexport function toAppUrl(mobileAppIdentifier: string, route: string): string {\n return `app://${mobileAppIdentifier}${sanitizeRoute(route)}`;\n}\n\nexport function emptySignalCounts(): SessionReplaySignalCounts {\n return {\n errorCount: 0,\n rageClickCount: 0,\n deadClickCount: 0,\n errorClickCount: 0,\n refreshRageCount: 0,\n routeCount: 0,\n clickCount: 0,\n customEventCount: 0,\n };\n}\n\nexport function byteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).byteLength;\n }\n\n return unescape(encodeURIComponent(value)).length;\n}\n\nexport function isPayloadWithinLimit(payload: string): boolean {\n return byteLength(payload) <= SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES;\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n SESSION_REPLAY_FLUSH_BYTES,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK,\n SESSION_REPLAY_MAX_CUSTOM_SIGNALS,\n SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES,\n SESSION_REPLAY_ROLLING_BUFFER_BYTES,\n SESSION_REPLAY_ROLLING_BUFFER_MS,\n SessionReplayCustomSignalCount,\n SessionReplayFidelityNotice,\n SessionReplayNumericSignalKey,\n SessionReplaySignalCounts,\n} from \"./Contract\";\nimport { byteLength, emptySignalCounts } from \"./Sanitize\";\n\n/*\n * Per-chunk caps on recorded routes, as the browser recorder's Chunker has.\n * The list rides the envelope, which the server refuses outright over 8 KB,\n * and it keeps a screen the user came back to, so nothing else bounds it. A\n * chunk with more route changes than this is an app rewriting its route\n * rather than a person moving through it; routeCount still counts them.\n */\nconst MAX_ROUTES_PER_CHUNK: number = 32;\nconst MAX_ROUTE_BYTES_PER_CHUNK: number = 2 * 1024;\n\nexport interface BufferedReplaySegment {\n payload: string;\n eventCount: number;\n startUnixMs: number;\n endUnixMs: number;\n hasFullSnapshot: boolean;\n routes: Array<string>;\n signals: SessionReplaySignalCounts;\n fidelityNotices: Array<SessionReplayFidelityNotice>;\n droppedEvents: number;\n}\n\nexport default class ReplayChunkBuffer {\n private events: Array<RrwebEvent> = [];\n private approximateBytes: number = 2;\n private startUnixMs: number = 0;\n private endUnixMs: number = 0;\n private hasFullSnapshot: boolean = false;\n /* In the order visited: a return to a screen is what a journey is read from. */\n private routes: Array<string> = [];\n private routeBytes: number = 0;\n private readonly fidelity: Set<SessionReplayFidelityNotice> =\n new Set<SessionReplayFidelityNotice>();\n private signals: SessionReplaySignalCounts = emptySignalCounts();\n private droppedEvents: number = 0;\n private customSignalEvents: number = 0;\n\n public append(\n event: RrwebEvent,\n options?: {\n route?: string;\n fidelityNotices?: Array<SessionReplayFidelityNotice>;\n signal?: SessionReplayNumericSignalKey;\n /*\n * The event marks a signal of the application's own: counted by name\n * on the envelope (signals.customSignals), as the browser's Chunker\n * counts it.\n */\n customSignal?: { name: string; isFrustration: boolean };\n },\n ): boolean {\n let serialized: string;\n try {\n serialized = JSON.stringify(event);\n } catch {\n this.droppedEvents += 1;\n return false;\n }\n\n const eventBytes: number = byteLength(serialized) + 1;\n if (eventBytes > SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES) {\n this.droppedEvents += 1;\n this.fidelity.add(SessionReplayFidelityNotice.SnapshotTooLarge);\n return false;\n }\n\n this.events.push(event);\n this.approximateBytes += eventBytes;\n this.startUnixMs =\n this.startUnixMs === 0 ? event.timestamp : this.startUnixMs;\n this.endUnixMs = Math.max(this.endUnixMs, event.timestamp);\n if (event.type === RrwebEventType.FullSnapshot) {\n this.hasFullSnapshot = true;\n }\n\n if (options?.route) {\n this.addRoute(options.route);\n }\n for (const notice of options?.fidelityNotices ?? []) {\n this.fidelity.add(notice);\n }\n if (options?.signal) {\n const current: number = this.signals[options.signal] ?? 0;\n this.signals[options.signal] = current + 1;\n }\n if (options?.customSignal) {\n this.countCustomSignal(\n options.customSignal.name,\n options.customSignal.isFrustration,\n );\n }\n\n return true;\n }\n\n /*\n * Whether this chunk takes another signal marker. Capped like the\n * browser's: a signal that fires in a loop is one moment a second (the\n * matcher's cooldown), and fifty of them a chunk is plenty to see it.\n */\n public hasRoomForCustomSignal(): boolean {\n return (\n this.customSignalEvents <\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK\n );\n }\n\n private countCustomSignal(name: string, isFrustration: boolean): void {\n this.customSignalEvents += 1;\n const counts: Array<SessionReplayCustomSignalCount> =\n this.signals.customSignals ?? [];\n let entry: SessionReplayCustomSignalCount | undefined = counts.find(\n (candidate: SessionReplayCustomSignalCount): boolean => {\n return candidate.name === name;\n },\n );\n if (!entry) {\n if (counts.length >= SESSION_REPLAY_MAX_CUSTOM_SIGNALS) {\n return;\n }\n entry = { name, count: 0, frustrationCount: 0 };\n counts.push(entry);\n }\n entry.count += 1;\n if (isFrustration) {\n entry.frustrationCount += 1;\n }\n this.signals.customSignals = counts;\n }\n\n public appendMany(\n events: Array<RrwebEvent>,\n options?: {\n route?: string;\n fidelityNotices?: Array<SessionReplayFidelityNotice>;\n },\n ): number {\n let accepted: number = 0;\n for (const event of events) {\n if (this.append(event, options)) {\n accepted += 1;\n }\n }\n\n return accepted;\n }\n\n public shouldFlush(): boolean {\n return this.approximateBytes >= SESSION_REPLAY_FLUSH_BYTES;\n }\n\n public isEmpty(): boolean {\n return this.events.length === 0;\n }\n\n public take(): BufferedReplaySegment | null {\n if (this.events.length === 0) {\n return null;\n }\n\n const payload: string = JSON.stringify(this.events);\n const segment: BufferedReplaySegment = {\n payload,\n eventCount: this.events.length,\n startUnixMs: this.startUnixMs,\n endUnixMs: this.endUnixMs,\n hasFullSnapshot: this.hasFullSnapshot,\n routes: this.routes.slice(),\n signals: this.copySignals(),\n fidelityNotices: Array.from(this.fidelity),\n droppedEvents: this.droppedEvents,\n };\n this.reset();\n return segment;\n }\n\n public clear(): void {\n this.reset();\n }\n\n /* The counts, with each signal's own entry copied too. */\n private copySignals(): SessionReplaySignalCounts {\n const signals: SessionReplaySignalCounts = { ...this.signals };\n if (this.signals.customSignals) {\n signals.customSignals = this.signals.customSignals.map(\n (\n entry: SessionReplayCustomSignalCount,\n ): SessionReplayCustomSignalCount => {\n return { ...entry };\n },\n );\n }\n return signals;\n }\n\n private addRoute(route: string): void {\n if (\n this.routes.length >= MAX_ROUTES_PER_CHUNK ||\n this.routes[this.routes.length - 1] === route\n ) {\n return;\n }\n\n const bytes: number = byteLength(route);\n\n if (this.routeBytes + bytes > MAX_ROUTE_BYTES_PER_CHUNK) {\n return;\n }\n\n this.routeBytes += bytes;\n this.routes.push(route);\n }\n\n private reset(): void {\n this.events = [];\n this.approximateBytes = 2;\n this.startUnixMs = 0;\n this.endUnixMs = 0;\n this.hasFullSnapshot = false;\n this.routes = [];\n this.routeBytes = 0;\n this.fidelity.clear();\n this.signals = emptySignalCounts();\n this.droppedEvents = 0;\n this.customSignalEvents = 0;\n }\n}\n\nexport class RollingReplayBuffer {\n private segments: Array<BufferedReplaySegment> = [];\n private bytes: number = 0;\n private overflowed: boolean = false;\n\n public push(segment: BufferedReplaySegment, nowUnixMs: number): void {\n this.segments.push(segment);\n this.bytes += byteLength(segment.payload);\n const cutoff: number = nowUnixMs - SESSION_REPLAY_ROLLING_BUFFER_MS;\n\n while (\n this.segments.length > 0 &&\n (this.bytes > SESSION_REPLAY_ROLLING_BUFFER_BYTES ||\n (this.segments[0]?.endUnixMs ?? nowUnixMs) < cutoff)\n ) {\n const removed: BufferedReplaySegment | undefined = this.segments.shift();\n if (removed) {\n this.bytes -= byteLength(removed.payload);\n this.overflowed = true;\n }\n }\n }\n\n public drain(): Array<BufferedReplaySegment> {\n const segments: Array<BufferedReplaySegment> = this.segments;\n if (this.overflowed && segments[0]) {\n const notices: Set<SessionReplayFidelityNotice> = new Set(\n segments[0].fidelityNotices,\n );\n notices.add(SessionReplayFidelityNotice.BufferOverflow);\n segments[0] = {\n ...segments[0],\n fidelityNotices: Array.from(notices),\n };\n }\n\n this.clear();\n return segments;\n }\n\n public clear(): void {\n this.segments = [];\n this.bytes = 0;\n this.overflowed = false;\n }\n\n public get length(): number {\n return this.segments.length;\n }\n}\n", "import {\n SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNALS,\n SessionReplayCustomSignalConfig,\n SessionReplayCustomSignalTrigger,\n} from \"./Contract\";\n\n/*\n * The application's own frustration signals (issue #6443), as this recorder\n * detects them: a route the app moves to, an event it passes to track(), an\n * error whose text it knows. A click on an element is a CSS selector on a\n * web page, so click signals are left to the browser recorder.\n *\n * The reading and the matching are copies of Common's\n * Types/Rum/SessionReplayFrustrationSignals (readCustomSignal and the\n * matchesSessionReplay* functions); ContractParity holds them to Common on\n * the same inputs. Nothing a signal matched against is ever recorded: a hit\n * carries the signal's name.\n */\n\n/* The triggers this recorder can detect. */\nexport type MobileCustomSignalTrigger = Exclude<\n SessionReplayCustomSignalTrigger,\n \"click\"\n>;\n\nconst TRIGGERS: ReadonlyArray<SessionReplayCustomSignalTrigger> = [\n \"click\",\n \"page\",\n \"event\",\n \"error\",\n];\n\nexport interface MobileCustomSignalHit {\n name: string;\n trigger: MobileCustomSignalTrigger;\n isFrustration: boolean;\n atUnixMs: number;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction isTrigger(value: unknown): value is SessionReplayCustomSignalTrigger {\n return (\n typeof value === \"string\" &&\n TRIGGERS.indexOf(value as SessionReplayCustomSignalTrigger) !== -1\n );\n}\n\ninterface ReadCustomSignal extends SessionReplayCustomSignalConfig {\n isEnabled: boolean;\n}\n\nfunction readCustomSignal(value: unknown): ReadCustomSignal | null {\n const record: Record<string, unknown> = asRecord(value);\n const name: string =\n typeof record[\"name\"] === \"string\" ? record[\"name\"].trim() : \"\";\n const trigger: unknown = record[\"trigger\"];\n const match: string =\n typeof record[\"match\"] === \"string\" ? record[\"match\"].trim() : \"\";\n\n if (\n name.length === 0 ||\n name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH ||\n !isTrigger(trigger) ||\n match.length === 0 ||\n match.length >\n (trigger === \"event\"\n ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH\n : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) ||\n (trigger === \"page\" && match.charAt(0) !== \"/\" && match.charAt(0) !== \"*\")\n ) {\n return null;\n }\n\n return {\n name,\n trigger,\n match,\n isFrustration: record[\"isFrustration\"] !== false,\n isEnabled: record[\"isEnabled\"] !== false,\n };\n}\n\n/*\n * The signals in a config response's frustrationSignals - or in a cached\n * copy of the policy, which keeps the same field - that this recorder\n * detects. Never throws: anything unusable is no signal. Read exactly as\n * the server reads them - names unique ignoring case, at most twenty, then\n * the ones switched off left out (the server sends none) - and only then\n * are the click signals, which this recorder cannot detect, set aside.\n */\nexport function readCustomSignals(\n frustrationSignals: unknown,\n): Array<SessionReplayCustomSignalConfig> {\n const list: unknown = asRecord(frustrationSignals)[\"customSignals\"];\n const read: Array<ReadCustomSignal> = [];\n const seenNames: Array<string> = [];\n\n if (Array.isArray(list)) {\n for (const entry of list) {\n const signal: ReadCustomSignal | null = readCustomSignal(entry);\n\n if (!signal) {\n continue;\n }\n\n const key: string = signal.name.toLowerCase();\n\n if (seenNames.indexOf(key) !== -1) {\n continue;\n }\n\n seenNames.push(key);\n read.push(signal);\n\n if (read.length >= SESSION_REPLAY_MAX_CUSTOM_SIGNALS) {\n break;\n }\n }\n }\n\n const signals: Array<SessionReplayCustomSignalConfig> = [];\n\n for (const signal of read) {\n if (signal.isEnabled && signal.trigger !== \"click\") {\n signals.push({\n name: signal.name,\n trigger: signal.trigger,\n match: signal.match,\n isFrustration: signal.isFrustration,\n });\n }\n }\n\n return signals;\n}\n\n// One escaped byte: \"%c3\", \"%2F\".\nconst ESCAPED_BYTE: RegExp = /^%[0-9A-Fa-f]{2}$/;\n\n/*\n * Text with no ASCII in it: an escaped character is decoded only when it\n * stays beyond ASCII composed (NFC writes three in ASCII).\n */\nconst BEYOND_ASCII: RegExp = /^[\\u0080-\\uffff]+$/;\n\n// An escape, or a character beyond ASCII: a path with a spelling to settle.\nconst SPELLED_CHARACTER: RegExp = /[%\\u0080-\\uffff]/;\n\nfunction composed(text: string): string {\n return typeof text.normalize === \"function\" ? text.normalize(\"NFC\") : text;\n}\n\n/*\n * A path in the spelling a person reads it, a copy of Common's\n * UrlScrubber.normalizePathSpelling(path, true) (#8195): each escape of a\n * character beyond ASCII decoded (\"/caf%c3%a9\" and \"/cafe%CC%81\" are\n * \"/caf\u00E9\"), the words composed, and every other escape kept, in upper-case\n * hex, so \"/a%2Fb\" stays apart from \"/a/b\".\n */\nexport function readPathAsWritten(path: string): string {\n if (!SPELLED_CHARACTER.test(path)) {\n return path;\n }\n\n let spelled: string = \"\";\n let words: string = \"\";\n let index: number = 0;\n\n while (index < path.length) {\n const escape: string = path.slice(index, index + 3);\n\n if (!ESCAPED_BYTE.test(escape)) {\n words += path.charAt(index);\n index += 1;\n continue;\n }\n\n // A character's escapes: 2 to 4 bytes, as many as its first says.\n const lead: number = parseInt(escape.slice(1), 16);\n const length: number =\n lead < 0xc2 ? 0 : lead < 0xe0 ? 6 : lead < 0xf0 ? 9 : 12;\n let character: string = \"\";\n\n try {\n character = length\n ? decodeURIComponent(path.slice(index, index + length))\n : \"\";\n } catch {\n // Not UTF-8: cut short, written too long, a surrogate.\n }\n\n if (BEYOND_ASCII.test(composed(character))) {\n words += character;\n index += length;\n continue;\n }\n\n spelled += composed(words) + escape.toUpperCase();\n words = \"\";\n index += 3;\n }\n\n return spelled + composed(words);\n}\n\nfunction canonicalPath(path: string): string {\n let end: number = path.length;\n\n while (end > 1 && path.charAt(end - 1) === \"/\") {\n end--;\n }\n\n return readPathAsWritten(path.slice(0, end)).toLowerCase();\n}\n\n/*\n * Does a route match a page pattern? A star stands for any run of\n * characters; everything else is compared as written, ignoring case and the\n * slashes at the end, in the spelling a person reads (readPathAsWritten).\n * The pattern is split on its stars and the pieces are found in order - no\n * regular expression is built from it.\n */\nexport function matchesPagePattern(pattern: string, path: string): boolean {\n const target: string = canonicalPath(path);\n const pieces: Array<string> = canonicalPath(pattern.trim()).split(\"*\");\n\n if (pieces.length === 1) {\n return target === pieces[0];\n }\n\n const first: string = pieces[0] || \"\";\n const last: string = pieces[pieces.length - 1] || \"\";\n\n if (target.slice(0, first.length) !== first) {\n return false;\n }\n\n let position: number = first.length;\n\n for (let index: number = 1; index < pieces.length - 1; index++) {\n const piece: string = pieces[index] || \"\";\n\n if (piece.length === 0) {\n continue;\n }\n\n const found: number = target.indexOf(piece, position);\n\n if (found === -1) {\n return false;\n }\n\n position = found + piece.length;\n }\n\n return (\n target.length - position >= last.length &&\n target.slice(target.length - last.length) === last\n );\n}\n\nexport function matchesErrorText(match: string, text: string): boolean {\n return (\n match.length > 0 && text.toLowerCase().indexOf(match.toLowerCase()) !== -1\n );\n}\n\nexport function matchesEventName(match: string, name: string): boolean {\n return match.trim().toLowerCase() === name.trim().toLowerCase();\n}\n\n/*\n * The path a route stands for, as written: an absolute URL's path, without\n * its query or fragment, starting with a slash. Unlike the recorded route\n * nothing in it is redacted - a pattern names the app's own screens, and\n * what it is compared with never leaves the device.\n */\nexport function routeMatchPath(route: unknown): string {\n let path: string = typeof route === \"string\" ? route.trim() : \"\";\n\n const scheme: number = path.indexOf(\"://\");\n\n if (scheme > 0 && scheme < 32) {\n const pathStart: number = path.indexOf(\"/\", scheme + 3);\n path = pathStart === -1 ? \"/\" : path.slice(pathStart);\n }\n\n let end: number = path.length;\n\n for (const separator of [\"?\", \"#\"]) {\n const at: number = path.indexOf(separator);\n\n if (at !== -1 && at < end) {\n end = at;\n }\n }\n\n path = path.slice(0, end);\n\n return path.charAt(0) === \"/\" ? path : `/${path}`;\n}\n\n/*\n * Which of the application's signals a moment matches. Each name fires at\n * most once a second, as in the browser recorder: an error thrown in a loop\n * is one moment on the timeline, not fifty.\n */\nexport class CustomSignalMatcher {\n private readonly lastFiredAt: Map<string, number> = new Map<string, number>();\n\n public matchPage(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n route: unknown,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n const path: string = routeMatchPath(route);\n\n return this.collect(\n signals,\n \"page\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesPagePattern(signal.match, path);\n },\n );\n }\n\n public matchEvent(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n eventName: string,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n return this.collect(\n signals,\n \"event\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesEventName(signal.match, eventName);\n },\n );\n }\n\n public matchErrorText(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n text: string,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n if (!text) {\n return [];\n }\n\n return this.collect(\n signals,\n \"error\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesErrorText(signal.match, text);\n },\n );\n }\n\n /* A new session starts with no signal cooling down. */\n public reset(): void {\n this.lastFiredAt.clear();\n }\n\n private collect(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n trigger: MobileCustomSignalTrigger,\n atUnixMs: number,\n matches: (signal: SessionReplayCustomSignalConfig) => boolean,\n ): Array<MobileCustomSignalHit> {\n const hits: Array<MobileCustomSignalHit> = [];\n\n for (const signal of signals) {\n if (signal.trigger !== trigger || !matches(signal)) {\n continue;\n }\n\n const key: string = signal.name.toLowerCase();\n const last: number | undefined = this.lastFiredAt.get(key);\n\n if (\n last !== undefined &&\n atUnixMs >= last &&\n atUnixMs - last < SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS\n ) {\n continue;\n }\n\n this.lastFiredAt.set(key, atUnixMs);\n hits.push({\n name: signal.name,\n trigger,\n isFrustration: signal.isFrustration,\n atUnixMs,\n });\n }\n\n return hits;\n }\n}\n", "/*\n * Build-time copy of the product analytics wire contract (issue #6629):\n * what Common's Types/Rum/ProductAnalyticsEvents.ts says a recorder sends to\n * the events route - the batch, its limits, the event kinds, the metric\n * name rule and the config field that switches it on. This package is\n * installed in customer React Native applications and must not pull the\n * OneUptime monorepo's Common package into their bundle, so it carries a\n * copy, as Contract.ts carries the replay contract. ContractParity holds\n * every constant, type and rule here identical to Common's.\n */\n\n/* ---- Where the recorder posts. ---- */\n\nexport const PRODUCT_ANALYTICS_EVENTS_PATH: string =\n \"/telemetry/session-replay/v1/events\";\n\n/* The batch's wire version. Additive changes keep it; anything else bumps it. */\nexport const PRODUCT_ANALYTICS_WIRE_VERSION: number = 1;\n\nexport const PRODUCT_ANALYTICS_CONTENT_TYPE: string = \"application/json\";\n\n/* ---- What one batch may hold. Enforced on both sides of the wire. ---- */\n\nexport const PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH: number = 100;\nexport const PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH: number = 100;\nexport const PRODUCT_ANALYTICS_MAX_BATCH_BYTES: number = 64 * 1024;\n\n/* How large a batch grows before it is sent, well under the server's cap. */\nexport const PRODUCT_ANALYTICS_TARGET_BATCH_BYTES: number = 24 * 1024;\n\n/* How often the recorder sends what it has, in milliseconds. */\nexport const PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS: number = 5000;\n\n/*\n * Events (and, apart, metric points) the recorder holds while it cannot\n * send them yet - consent not given, the device offline: past this, the\n * oldest are dropped.\n */\nexport const PRODUCT_ANALYTICS_MAX_PENDING_EVENTS: number = 500;\n\n/* A custom event's name, at most this long. */\nexport const PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH: number = 64;\n\n/* The device, system and version a batch says it came from. */\nexport const PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH: number = 64;\n\n/*\n * Common's SESSION_REPLAY_MAX_APP_VERSION_LENGTH: the longest app version\n * the server keeps, and so the longest one sent.\n */\nexport const PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH: number = 64;\n\n/*\n * Events this old when they arrive are dropped by the server, so the\n * recorder drops them itself rather than send them (an app held offline for\n * days).\n */\nexport const PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS: number =\n 3 * 24 * 60 * 60 * 1000;\n\n/*\n * Common's PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE: the shorter side, in\n * points, from which a mobile app's screen is a tablet's - the rule its\n * recorded sessions are filed by, so an event and a session agree.\n */\nexport const PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE: number = 600;\n\n/* ---- Metric names. ---- */\n\nexport const PRODUCT_ANALYTICS_MAX_METRIC_NAME_LENGTH: number = 100;\nconst METRIC_NAME_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;\n\n/* OneUptime's own namespace: metric() refuses every name in it. */\nexport const PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX: string = \"oneuptime.\";\n\n/*\n * A name metric() may send: the OpenTelemetry instrument name shape, and\n * not in OneUptime's namespace.\n */\nexport function isProductAnalyticsMetricName(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n METRIC_NAME_PATTERN.test(value) &&\n !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX)\n );\n}\n\n/* ---- Events. ---- */\n\nexport enum ProductAnalyticsEventKind {\n /* A session started; named \"\". */\n Session = \"session\",\n /* A page (a mobile app's screen) was viewed; named by its path. */\n Page = \"page\",\n /* The application called track(); named as it said. */\n Custom = \"custom\",\n}\n\n/* One event, as it travels. `at` is the device's clock. */\nexport interface ProductAnalyticsWireEvent {\n kind: ProductAnalyticsEventKind;\n name: string;\n at: number;\n /* The page the event happened on. */\n page?: string | undefined;\n properties?: Record<string, string> | undefined;\n}\n\nexport interface ProductAnalyticsWireMetric {\n name: string;\n value: number;\n at: number;\n attributes?: Record<string, string> | undefined;\n}\n\n/* What the session runs on: the same values Session Replay files it under. */\nexport interface ProductAnalyticsWireContext {\n /* desktop, mobile or tablet; \"\" when unknown. */\n deviceType: string;\n browserName: string;\n osName: string;\n /*\n * The app's version: a mobile app's own, or the one a web page gave the\n * browser recorder (its appVersion option, issue #6625); \"\" when unset.\n */\n appVersion: string;\n}\n\nexport interface ProductAnalyticsWireBatch {\n v: number;\n /* 32 hex; the same id on a retry, so a batch lands once. */\n batchId: string;\n sessionId: string;\n visitorId: string;\n /*\n * The signed-in user's reference, only when the application captures user\n * identity, and the traits it keeps for analytics.\n */\n userRef?: string | undefined;\n userProperties?: Record<string, string> | undefined;\n /*\n * The page's consent, as a replay chunk reports it (\"Granted\",\n * \"NotRequired\", \"Unknown\"). An application that asks for explicit\n * consent files a batch only when it says \"Granted\".\n */\n consentState: string;\n sentAt: number;\n context: ProductAnalyticsWireContext;\n events: Array<ProductAnalyticsWireEvent>;\n metrics: Array<ProductAnalyticsWireMetric>;\n}\n\n/*\n * Common's toProductAnalyticsEventName: trimmed, control characters\n * dropped, at most PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH long, or null\n * when nothing is left.\n */\nexport function toProductAnalyticsEventName(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n let name: string = \"\";\n\n for (const character of value) {\n const code: number = character.charCodeAt(0);\n\n if (code < 32 || code === 127) {\n continue;\n }\n\n name += character;\n }\n\n name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();\n\n return name.length > 0 ? name : null;\n}\n\n// eslint-disable-next-line no-control-regex\nconst NOT_PRINTABLE_PATTERN: RegExp = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/*\n * Common's toSessionReplayAppVersion: trimmed, at most\n * PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH long, and \"\" for anything that\n * is not a string or holds a control character, as the server keeps it.\n */\nexport function toProductAnalyticsAppVersion(value: unknown): string {\n if (typeof value !== \"string\") {\n return \"\";\n }\n\n const version: string = value\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH)\n .trim();\n\n return NOT_PRINTABLE_PATTERN.test(version) ? \"\" : version;\n}\n\n/* ---- What the recorder learns from the replay config. ---- */\n\n/* The identify() traits events may carry: at most 20 keys of 40 characters. */\nexport const PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS: number = 20;\nexport const PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH: number = 40;\n\n/*\n * The optional `productAnalytics` field of the replay config. Absent - an\n * older server, or an application with product analytics off - reads as\n * off, so the recorder never sends a batch nobody asked for.\n */\nexport interface ProductAnalyticsRecorderConfig {\n enabled: boolean;\n /* The identify() traits events may carry. */\n userPropertyKeys: Array<string>;\n}\n\n/*\n * Common's normalizeProductAnalyticsUserPropertyKeys: trimmed, without\n * duplicates (ignoring case), at most the key cap of keys of at most the\n * key length.\n */\nexport function normalizeProductAnalyticsUserPropertyKeys(\n value: unknown,\n): Array<string> {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const keys: Array<string> = [];\n const seen: Set<string> = new Set<string>();\n\n for (const entry of value) {\n if (typeof entry !== \"string\") {\n continue;\n }\n\n const key: string = entry\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);\n\n if (key.length === 0 || key === \"__proto__\") {\n continue;\n }\n\n if (seen.has(key.toLowerCase())) {\n continue;\n }\n\n seen.add(key.toLowerCase());\n keys.push(key);\n\n if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {\n break;\n }\n }\n\n return keys;\n}\n\n/* Common's readProductAnalyticsRecorderConfig. */\nexport function readProductAnalyticsRecorderConfig(\n value: unknown,\n): ProductAnalyticsRecorderConfig {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { enabled: false, userPropertyKeys: [] };\n }\n\n const record: Record<string, unknown> = value as Record<string, unknown>;\n\n return {\n enabled: record[\"enabled\"] === true,\n userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(\n record[\"userPropertyKeys\"],\n ),\n };\n}\n", "import {\n AUTH_TOKEN_HEADER,\n CONFIG_PATH,\n MOBILE_RECORDER_KIND,\n SESSION_REPLAY_APP_IDENTIFIER_HEADER,\n SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER,\n SESSION_REPLAY_MAX_OFFLINE_DELAY_MS,\n SESSION_REPLAY_MAX_USER_REF_LENGTH,\n SESSION_REPLAY_RECORDER_KIND_HEADER,\n SESSION_REPLAY_USER_REF_HEADER,\n SessionReplayCaptureTrigger,\n SessionReplayConfigResponse,\n SessionReplayConsentMode,\n SessionReplayCustomSignalConfig,\n SessionReplayMaskingMode,\n} from \"./Contract\";\nimport { readCustomSignals } from \"./CustomSignals\";\nimport {\n ProductAnalyticsRecorderConfig,\n readProductAnalyticsRecorderConfig,\n} from \"./ProductAnalyticsContract\";\nimport { ReplayStorage } from \"./Storage\";\n\nexport const CONFIG_FETCH_TIMEOUT_MS: number = 5_000;\n\nexport interface ReplayFetchResponse {\n ok: boolean;\n status: number;\n headers?: {\n get(name: string): string | null;\n };\n json(): Promise<unknown>;\n}\n\nexport type ReplayFetch = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: unknown;\n signal?: AbortSignal;\n },\n) => Promise<ReplayFetchResponse>;\n\nexport interface MobileReplayStartOptions {\n /** Ingest origin, for example https://oneuptime.com. */\n host: string;\n /** OneUptime telemetry ingestion key. */\n token: string;\n /** Identifier of the OneUptime RUM application receiving the replay. */\n appIdentifier: string;\n /** Android applicationId or iOS bundle identifier. */\n mobileAppIdentifier: string;\n appName?: string;\n appVersion?: string;\n /** Optional opaque reference used by record-next-session targeting. */\n userRef?: string;\n captureIntervalMs?: number;\n fetch?: ReplayFetch;\n debug?: boolean;\n /**\n * Optional connectivity source for offline mode. Recording never depends\n * on it: without one, a lost connection is noticed when an upload fails\n * and the backlog is retried with backoff and whenever the app returns to\n * the foreground. With one, nothing is attempted while it says the device\n * is offline, and the backlog uploads the moment it says it is back. With\n * `@react-native-community/netinfo`:\n *\n * connectivity: {\n * subscribe: (listener) =>\n * NetInfo.addEventListener((state) => listener(state.isConnected)),\n * }\n */\n connectivity?: ReplayConnectivity;\n}\n\nexport interface ReplayConnectivity {\n /**\n * Call `listener` with whether the device has a connection now and on\n * every change (null when unknown), and return a function that stops.\n */\n subscribe(listener: (isConnected: boolean | null) => void): () => void;\n}\n\n/*\n * The part of the application's frustration settings this recorder acts on:\n * its own page, event and error signals (issue #6443). Kept under the\n * response's own field name so a cached policy is read back by the same\n * normalizeReplayConfig as a fresh one.\n */\nexport interface ResolvedFrustrationSignals {\n customSignals: Array<SessionReplayCustomSignalConfig>;\n}\n\nexport interface ResolvedReplayConfig {\n enabled: boolean;\n captureTrigger: SessionReplayCaptureTrigger;\n consentMode: SessionReplayConsentMode;\n maskingMode: SessionReplayMaskingMode.MaskAllText;\n samplePercentage: number;\n captureUserIdentity: boolean;\n configEpoch: number;\n isTargeted: boolean;\n frustrationSignals: ResolvedFrustrationSignals;\n /*\n * Product analytics events (issue #6629): whether the app also sends its\n * session starts, screens, track() events and metric() points - from\n * every session, recorded or not - and which identify() traits they may\n * carry. Kept under the response's own field name, like\n * frustrationSignals, so a cached policy reads back the same.\n */\n productAnalytics: ProductAnalyticsRecorderConfig;\n disabledReason?: string;\n}\n\nexport interface ValidatedStartOptions extends MobileReplayStartOptions {\n host: string;\n token: string;\n appIdentifier: string;\n mobileAppIdentifier: string;\n fetch: ReplayFetch;\n}\n\nconst MOBILE_APP_IDENTIFIER_LABEL_PATTERN: RegExp = /^[a-z0-9_-]+$/u;\nconst WHITESPACE_PATTERN: RegExp = /\\s/u;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTER_PATTERN: RegExp = /[\\u0000-\\u001F\\u007F]/u;\n\n/* Kept byte-for-byte compatible with Common's authorization grammar. */\nexport function normalizeMobileAppIdentifier(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const identifier: string = value.trim().toLowerCase();\n if (\n !identifier ||\n identifier.length > 255 ||\n WHITESPACE_PATTERN.test(identifier)\n ) {\n return null;\n }\n\n const labels: Array<string> = identifier.split(\".\");\n if (labels.length < 2) {\n return null;\n }\n\n for (const label of labels) {\n if (\n !label ||\n !MOBILE_APP_IDENTIFIER_LABEL_PATTERN.test(label) ||\n label.startsWith(\"-\") ||\n label.endsWith(\"-\") ||\n label.startsWith(\"_\") ||\n label.endsWith(\"_\")\n ) {\n return null;\n }\n }\n\n return identifier;\n}\n\nexport function normalizeIngestHost(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n try {\n const parsed: URL = new URL(value.trim());\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== \"/\" ||\n parsed.search ||\n parsed.hash\n ) {\n return null;\n }\n\n return parsed.origin;\n } catch {\n return null;\n }\n}\n\nexport function normalizeRumAppIdentifier(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const identifier: string = value.trim();\n if (\n !identifier ||\n identifier.length > 255 ||\n CONTROL_CHARACTER_PATTERN.test(identifier)\n ) {\n return null;\n }\n\n return identifier;\n}\n\nfunction defaultFetch(\n input: string,\n init?: Parameters<ReplayFetch>[1],\n): Promise<ReplayFetchResponse> {\n const fetchRef: typeof fetch | undefined = globalThis.fetch;\n if (!fetchRef) {\n return Promise.reject(new Error(\"fetch-unavailable\"));\n }\n\n return fetchRef(input, init as RequestInit) as Promise<ReplayFetchResponse>;\n}\n\nexport function validateStartOptions(\n options: MobileReplayStartOptions,\n): ValidatedStartOptions | null {\n if (!options || typeof options !== \"object\") {\n return null;\n }\n\n const host: string | null = normalizeIngestHost(options.host);\n const token: string =\n typeof options.token === \"string\" ? options.token.trim() : \"\";\n const appIdentifier: string | null = normalizeRumAppIdentifier(\n options.appIdentifier,\n );\n const mobileAppIdentifier: string | null = normalizeMobileAppIdentifier(\n options.mobileAppIdentifier,\n );\n const rawUserRef: string =\n typeof options.userRef === \"string\" ? options.userRef.trim() : \"\";\n const userRef: string | undefined = rawUserRef\n ? rawUserRef.slice(0, SESSION_REPLAY_MAX_USER_REF_LENGTH)\n : undefined;\n\n if (!host || !token || !appIdentifier || !mobileAppIdentifier) {\n return null;\n }\n\n const validated: ValidatedStartOptions = {\n ...options,\n host,\n token,\n appIdentifier,\n mobileAppIdentifier,\n fetch: options.fetch ?? defaultFetch,\n };\n if (userRef) {\n validated.userRef = userRef;\n } else {\n delete validated.userRef;\n }\n return validated;\n}\n\nexport function mobileRequestHeaders(\n options: Pick<\n ValidatedStartOptions,\n \"token\" | \"appIdentifier\" | \"mobileAppIdentifier\" | \"userRef\"\n >,\n includeUserRef: boolean = false,\n): Record<string, string> {\n const headers: Record<string, string> = {\n [AUTH_TOKEN_HEADER]: options.token,\n [SESSION_REPLAY_APP_IDENTIFIER_HEADER]: options.appIdentifier,\n [SESSION_REPLAY_RECORDER_KIND_HEADER]: MOBILE_RECORDER_KIND,\n [SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER]: options.mobileAppIdentifier,\n };\n if (includeUserRef && options.userRef) {\n try {\n headers[SESSION_REPLAY_USER_REF_HEADER] = encodeURIComponent(\n options.userRef.slice(0, SESSION_REPLAY_MAX_USER_REF_LENGTH),\n );\n } catch {\n /* An invalid surrogate skips targeting; policy fetch still proceeds. */\n }\n }\n return headers;\n}\n\nfunction failClosed(reason: string): ResolvedReplayConfig {\n return {\n enabled: false,\n captureTrigger: SessionReplayCaptureTrigger.OnErrorOrFrustration,\n consentMode: SessionReplayConsentMode.RequireExplicit,\n maskingMode: SessionReplayMaskingMode.MaskAllText,\n samplePercentage: 0,\n captureUserIdentity: false,\n configEpoch: 0,\n isTargeted: false,\n frustrationSignals: { customSignals: [] },\n productAnalytics: { enabled: false, userPropertyKeys: [] },\n disabledReason: reason,\n };\n}\n\nexport function normalizeReplayConfig(value: unknown): ResolvedReplayConfig {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return failClosed(\"invalid-config\");\n }\n\n const config: Partial<SessionReplayConfigResponse> =\n value as Partial<SessionReplayConfigResponse>;\n const captureTrigger: SessionReplayCaptureTrigger =\n config.captureTrigger === SessionReplayCaptureTrigger.Always\n ? SessionReplayCaptureTrigger.Always\n : SessionReplayCaptureTrigger.OnErrorOrFrustration;\n const consentMode: SessionReplayConsentMode =\n config.consentMode === SessionReplayConsentMode.NotRequired\n ? SessionReplayConsentMode.NotRequired\n : SessionReplayConsentMode.RequireExplicit;\n const samplePercentage: number =\n typeof config.samplePercentage === \"number\" &&\n Number.isFinite(config.samplePercentage) &&\n config.samplePercentage >= 0 &&\n config.samplePercentage <= 100\n ? config.samplePercentage\n : 0;\n const enabled: boolean =\n config.enabled === true && config.directive === \"continue\";\n\n const resolved: ResolvedReplayConfig = {\n enabled,\n captureTrigger,\n consentMode,\n /* Mobile never relaxes text masking, even if web policy is looser. */\n maskingMode: SessionReplayMaskingMode.MaskAllText,\n samplePercentage,\n captureUserIdentity: config.captureUserIdentity === true,\n configEpoch:\n typeof config.configEpoch === \"number\" &&\n Number.isSafeInteger(config.configEpoch) &&\n config.configEpoch >= 0\n ? config.configEpoch\n : 0,\n isTargeted: config.isTargeted === true,\n /*\n * A server from before frustration settings sends none: no signals of\n * the application's own, which is what such an application has.\n */\n frustrationSignals: {\n customSignals: readCustomSignals(config.frustrationSignals),\n },\n /*\n * Absent - a server from before product analytics, or an application\n * with it off - reads as off, so no batch is sent nobody asked for.\n */\n productAnalytics: readProductAnalyticsRecorderConfig(\n config.productAnalytics,\n ),\n };\n if (typeof config.disabledReason === \"string\") {\n resolved.disabledReason = config.disabledReason.slice(0, 100);\n } else if (!enabled) {\n resolved.disabledReason = \"disabled\";\n }\n return resolved;\n}\n\n/*\n * Offline mode: the last policy the server gave this app, kept so that an\n * app launched WITHOUT a connection still records - and uploads when the\n * connection returns - instead of failing closed on a config request that\n * could never succeed. Only ever used when the config request itself failed\n * to get an answer (see isRetryablePolicyFailure's callers); an answer\n * saying replay is off deletes it. Never older than the offline delay, and\n * never \"targeted\": record-next-session is a live decision the server makes\n * again when the connection is back.\n */\ninterface CachedReplayConfig {\n savedAtUnixMs: number;\n config: ResolvedReplayConfig;\n}\n\nexport function replayConfigCacheKey(namespace: string): string {\n return `@oneuptime/replay/${namespace}/config`;\n}\n\nexport async function saveReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n config: ResolvedReplayConfig,\n nowUnixMs: number,\n): Promise<void> {\n try {\n if (!config.enabled) {\n await storage.removeItem(replayConfigCacheKey(namespace));\n return;\n }\n\n const cached: CachedReplayConfig = {\n savedAtUnixMs: nowUnixMs,\n config: { ...config, isTargeted: false },\n };\n await storage.setItem(\n replayConfigCacheKey(namespace),\n JSON.stringify(cached),\n );\n } catch {\n /* A policy that is not cached only means an offline launch does not record. */\n }\n}\n\n/* Consent withdrawn: nothing of the recorder's stays on the device. */\nexport async function forgetReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n): Promise<void> {\n try {\n await storage.removeItem(replayConfigCacheKey(namespace));\n } catch {\n /* Best-effort privacy cleanup. */\n }\n}\n\nexport async function loadCachedReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n nowUnixMs: number,\n): Promise<ResolvedReplayConfig | null> {\n try {\n const raw: string | null = await storage.getItem(\n replayConfigCacheKey(namespace),\n );\n if (!raw) {\n return null;\n }\n\n const cached: Partial<CachedReplayConfig> = JSON.parse(\n raw,\n ) as Partial<CachedReplayConfig>;\n const age: number = nowUnixMs - Number(cached.savedAtUnixMs);\n if (\n !Number.isFinite(age) ||\n age < 0 ||\n age > SESSION_REPLAY_MAX_OFFLINE_DELAY_MS ||\n !cached.config ||\n typeof cached.config !== \"object\"\n ) {\n return null;\n }\n\n /* Re-validated like a fresh response: storage is not trusted. */\n const config: ResolvedReplayConfig = normalizeReplayConfig({\n ...cached.config,\n directive: cached.config.enabled === true ? \"continue\" : \"stop\",\n isTargeted: false,\n });\n return config.enabled ? config : null;\n } catch {\n return null;\n }\n}\n\nexport async function fetchReplayConfig(\n options: ValidatedStartOptions,\n includeUserRef: boolean = false,\n revalidate: boolean = false,\n): Promise<ResolvedReplayConfig> {\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n try {\n const request: Promise<ResolvedReplayConfig> =\n (async (): Promise<ResolvedReplayConfig> => {\n const headers: Record<string, string> = {\n ...mobileRequestHeaders(options, includeUserRef),\n Accept: \"application/json\",\n };\n if (revalidate) {\n headers[\"Cache-Control\"] = \"no-cache\";\n headers[\"Pragma\"] = \"no-cache\";\n }\n const requestInit: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"GET\",\n headers,\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n const response: ReplayFetchResponse = await options.fetch(\n `${options.host}${CONFIG_PATH}`,\n requestInit,\n );\n\n if (!response.ok) {\n return failClosed(`config-http-${response.status}`);\n }\n\n return normalizeReplayConfig(await response.json());\n })();\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n timeout = setTimeout((): void => {\n controller?.abort();\n reject(new Error(\"config-fetch-timeout\"));\n }, CONFIG_FETCH_TIMEOUT_MS);\n },\n );\n return await Promise.race([request, deadline]);\n } catch {\n return failClosed(\"config-fetch-failed\");\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n RrwebIncrementalSource,\n SessionReplayFidelityNotice,\n} from \"./Contract\";\nimport { NativeViewKind, NativeViewTreeNode } from \"./NativeViewTree\";\n\nexport const RRWEB_DOCUMENT_NODE_ID: number = 1;\nexport const RRWEB_HTML_NODE_ID: number = 3;\nexport const RRWEB_HEAD_NODE_ID: number = 4;\nexport const RRWEB_BODY_NODE_ID: number = 5;\nconst FIRST_VIEW_NODE_ID: number = 10;\nconst MAX_VIEW_TREE_DEPTH: number = 64;\nconst MAX_VIEW_TREE_NODES: number = 5_000;\nconst MAX_GEOMETRY_VALUE: number = 100_000;\n\nconst SAFE_KINDS: ReadonlySet<NativeViewKind> = new Set<NativeViewKind>([\n \"view\",\n \"scroll\",\n \"button\",\n \"text\",\n \"input\",\n \"image\",\n \"webview\",\n \"canvas\",\n \"masked\",\n \"unknown\",\n]);\n\ninterface SerializedElement {\n type: 2;\n tagName: \"div\";\n attributes: Record<string, string>;\n childNodes: Array<SerializedElement>;\n id: number;\n}\n\ninterface SerializedRecord {\n key: string;\n id: number;\n parentId: number;\n attributes: Record<string, string>;\n node: SerializedElement;\n}\n\nexport interface SerializedCapture {\n events: Array<RrwebEvent>;\n hasFullSnapshot: boolean;\n fidelityNotices: Array<SessionReplayFidelityNotice>;\n droppedNodes: number;\n}\n\ninterface BuildResult {\n root: SerializedElement;\n records: Map<string, SerializedRecord>;\n byId: Map<number, SerializedRecord>;\n fidelity: Set<SessionReplayFidelityNotice>;\n droppedNodes: number;\n}\n\nfunction finiteGeometry(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return 0;\n }\n\n return Math.min(MAX_GEOMETRY_VALUE, Math.max(-MAX_GEOMETRY_VALUE, value));\n}\n\nfunction safeKind(value: unknown): NativeViewKind {\n if (typeof value === \"string\" && SAFE_KINDS.has(value as NativeViewKind)) {\n return value as NativeViewKind;\n }\n\n return \"unknown\";\n}\n\nfunction geometryStyle(node: NativeViewTreeNode): string {\n const x: number = finiteGeometry(node.x);\n const y: number = finiteGeometry(node.y);\n const width: number = Math.max(0, finiteGeometry(node.width));\n const height: number = Math.max(0, finiteGeometry(node.height));\n const style: Array<string> = [\n \"position:absolute\",\n `left:${x}px`,\n `top:${y}px`,\n `width:${width}px`,\n `height:${height}px`,\n \"box-sizing:border-box\",\n \"overflow:hidden\",\n \"outline:1px solid rgba(148,163,184,0.18)\",\n ];\n const backgroundColor: string | null = safeColor(node.backgroundColor);\n const borderColor: string | null = safeColor(node.borderColor);\n const borderWidth: number = clampedStyleNumber(node.borderWidth, 0, 100, 0);\n const borderRadius: number = clampedStyleNumber(\n node.borderRadius,\n 0,\n MAX_GEOMETRY_VALUE,\n 0,\n );\n const opacity: number = clampedStyleNumber(node.opacity, 0, 1, 1);\n const zIndex: number = clampedStyleNumber(node.zIndex, -10_000, 10_000, 0);\n\n if (backgroundColor) {\n style.push(`background-color:${backgroundColor}`);\n }\n if (borderColor && borderWidth > 0) {\n style.push(`border:${borderWidth}px solid ${borderColor}`);\n }\n if (borderRadius > 0) {\n style.push(`border-radius:${borderRadius}px`);\n }\n if (opacity < 1) {\n style.push(`opacity:${opacity}`);\n }\n if (zIndex !== 0) {\n style.push(`z-index:${zIndex}`);\n }\n\n return style.join(\";\");\n}\n\nconst HEX_COLOR_PATTERN: RegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/u;\n\nfunction safeColor(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const normalized: string = value.trim().toLowerCase();\n return HEX_COLOR_PATTERN.test(normalized) ? normalized : null;\n}\n\nfunction clampedStyleNumber(\n value: unknown,\n minimum: number,\n maximum: number,\n fallback: number,\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n\n return Math.max(minimum, Math.min(maximum, value));\n}\n\nfunction cloneNode(node: SerializedElement): SerializedElement {\n return {\n ...node,\n attributes: { ...node.attributes },\n childNodes: node.childNodes.map(cloneNode),\n };\n}\n\nfunction sameAttributes(\n left: Record<string, string>,\n right: Record<string, string>,\n): boolean {\n const leftKeys: Array<string> = Object.keys(left);\n const rightKeys: Array<string> = Object.keys(right);\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key: string): boolean => {\n return left[key] === right[key];\n })\n );\n}\n\nexport default class ViewTreeSerializer {\n private readonly nodeIds: Map<string, number> = new Map<string, number>();\n private nextNodeId: number = FIRST_VIEW_NODE_ID;\n private previous: BuildResult | null = null;\n\n public capture(\n input: NativeViewTreeNode,\n options: {\n timestamp: number;\n url: string;\n viewportWidth: number;\n viewportHeight: number;\n forceFullSnapshot?: boolean;\n },\n ): SerializedCapture {\n const shouldTakeFullSnapshot: boolean =\n !this.previous || options.forceFullSnapshot === true;\n if (options.forceFullSnapshot === true && this.previous) {\n this.previous = null;\n this.nodeIds.clear();\n this.nextNodeId = FIRST_VIEW_NODE_ID;\n }\n const current: BuildResult = this.build(input);\n const events: Array<RrwebEvent> = shouldTakeFullSnapshot\n ? this.fullSnapshot(current, options)\n : this.mutations(\n this.previous as BuildResult,\n current,\n options.timestamp,\n );\n\n this.previous = current;\n for (const key of this.nodeIds.keys()) {\n if (!current.records.has(key)) {\n this.nodeIds.delete(key);\n }\n }\n\n return {\n events,\n hasFullSnapshot: shouldTakeFullSnapshot,\n fidelityNotices: Array.from(current.fidelity),\n droppedNodes: current.droppedNodes,\n };\n }\n\n public reset(): void {\n this.previous = null;\n this.nodeIds.clear();\n this.nextNodeId = FIRST_VIEW_NODE_ID;\n }\n\n private build(input: NativeViewTreeNode): BuildResult {\n const records: Map<string, SerializedRecord> = new Map<\n string,\n SerializedRecord\n >();\n const byId: Map<number, SerializedRecord> = new Map<\n number,\n SerializedRecord\n >();\n const fidelity: Set<SessionReplayFidelityNotice> =\n new Set<SessionReplayFidelityNotice>([\n SessionReplayFidelityNotice.MobileAnimationSampled,\n ]);\n let visited: number = 0;\n let droppedNodes: number =\n typeof input.truncatedNodes === \"number\" &&\n Number.isSafeInteger(input.truncatedNodes) &&\n input.truncatedNodes > 0\n ? Math.min(input.truncatedNodes, 1_000_000)\n : 0;\n\n const visit: (\n candidate: NativeViewTreeNode,\n parentId: number,\n path: string,\n depth: number,\n ) => SerializedElement | null = (\n candidate: NativeViewTreeNode,\n parentId: number,\n path: string,\n depth: number,\n ): SerializedElement | null => {\n if (\n depth > MAX_VIEW_TREE_DEPTH ||\n visited >= MAX_VIEW_TREE_NODES ||\n !candidate ||\n typeof candidate !== \"object\"\n ) {\n droppedNodes += 1;\n return null;\n }\n\n visited += 1;\n const kind: NativeViewKind = candidate.masked\n ? \"masked\"\n : safeKind(candidate.kind);\n const key: string = `${typeof candidate.nativeId}:${String(\n candidate.nativeId,\n )}:${path}`;\n let id: number | undefined = this.nodeIds.get(key);\n if (id === undefined) {\n id = this.nextNodeId;\n this.nextNodeId += 1;\n this.nodeIds.set(key, id);\n }\n\n const attributes: Record<string, string> = {\n style: geometryStyle(candidate),\n \"data-oneuptime-mobile-view\": kind,\n };\n const isOpaque: boolean =\n candidate.opaque === true ||\n kind === \"image\" ||\n kind === \"webview\" ||\n kind === \"canvas\" ||\n kind === \"masked\";\n\n if (isOpaque) {\n attributes[\"data-oneuptime-replay-placeholder\"] = kind;\n if (!safeColor(candidate.backgroundColor)) {\n attributes[\"style\"] += \";background-color:#94a3b833\";\n }\n } else if (kind === \"text\" || kind === \"input\") {\n /* Fixed fill makes masked copy visible without carrying its value. */\n attributes[\"style\"] += \";background-color:#94a3b826\";\n }\n\n switch (kind) {\n case \"image\":\n fidelity.add(SessionReplayFidelityNotice.MobileImagesOpaque);\n break;\n case \"webview\":\n fidelity.add(SessionReplayFidelityNotice.MobileWebViewOpaque);\n break;\n case \"canvas\":\n fidelity.add(SessionReplayFidelityNotice.MobileCanvasOpaque);\n break;\n default:\n break;\n }\n\n const element: SerializedElement = {\n type: 2,\n tagName: \"div\",\n attributes,\n childNodes: [],\n id,\n };\n const record: SerializedRecord = {\n key,\n id,\n parentId,\n attributes,\n node: element,\n };\n records.set(key, record);\n byId.set(id, record);\n\n /* Masked and opaque content is a hard subtree boundary. */\n if (!isOpaque && Array.isArray(candidate.children)) {\n candidate.children.forEach(\n (child: NativeViewTreeNode, index: number): void => {\n const serialized: SerializedElement | null = visit(\n child,\n id as number,\n `${path}.${index}`,\n depth + 1,\n );\n if (serialized) {\n element.childNodes.push(serialized);\n }\n },\n );\n }\n\n return element;\n };\n\n const root: SerializedElement = visit(\n input,\n RRWEB_BODY_NODE_ID,\n \"0\",\n 0,\n ) ?? {\n type: 2,\n tagName: \"div\",\n attributes: {\n style:\n \"position:absolute;left:0px;top:0px;width:0px;height:0px;box-sizing:border-box;overflow:hidden\",\n \"data-oneuptime-mobile-view\": \"unknown\",\n },\n childNodes: [],\n id: this.nextNodeId++,\n };\n\n if (droppedNodes > 0) {\n fidelity.add(SessionReplayFidelityNotice.BufferOverflow);\n }\n\n return { root, records, byId, fidelity, droppedNodes };\n }\n\n private fullSnapshot(\n current: BuildResult,\n options: {\n timestamp: number;\n url: string;\n viewportWidth: number;\n viewportHeight: number;\n },\n ): Array<RrwebEvent> {\n const width: number = Math.max(0, finiteGeometry(options.viewportWidth));\n const height: number = Math.max(0, finiteGeometry(options.viewportHeight));\n return [\n {\n type: RrwebEventType.Meta,\n data: {\n href: options.url,\n width,\n height,\n },\n timestamp: options.timestamp,\n },\n {\n type: RrwebEventType.FullSnapshot,\n data: {\n node: {\n type: 0,\n childNodes: [\n {\n type: 1,\n name: \"html\",\n publicId: \"\",\n systemId: \"\",\n id: 2,\n },\n {\n type: 2,\n tagName: \"html\",\n attributes: {},\n childNodes: [\n {\n type: 2,\n tagName: \"head\",\n attributes: {},\n childNodes: [],\n id: RRWEB_HEAD_NODE_ID,\n },\n {\n type: 2,\n tagName: \"body\",\n attributes: {\n style: `margin:0;position:relative;width:${width}px;height:${height}px;overflow:hidden`,\n \"data-oneuptime-recorder-kind\": \"rn-view-tree\",\n },\n childNodes: [cloneNode(current.root)],\n id: RRWEB_BODY_NODE_ID,\n },\n ],\n id: RRWEB_HTML_NODE_ID,\n },\n ],\n id: RRWEB_DOCUMENT_NODE_ID,\n },\n initialOffset: { top: 0, left: 0 },\n },\n timestamp: options.timestamp,\n },\n ];\n }\n\n private mutations(\n previous: BuildResult,\n current: BuildResult,\n timestamp: number,\n ): Array<RrwebEvent> {\n const additions: Array<{\n parentId: number;\n nextId: null;\n node: SerializedElement;\n }> = [];\n const removals: Array<{ parentId: number; id: number }> = [];\n const attributes: Array<{\n id: number;\n attributes: Record<string, string>;\n }> = [];\n\n for (const record of current.records.values()) {\n const before: SerializedRecord | undefined = previous.records.get(\n record.key,\n );\n if (!before) {\n const parentWasAdded: boolean =\n record.parentId !== RRWEB_BODY_NODE_ID &&\n !previous.byId.has(record.parentId);\n if (!parentWasAdded) {\n additions.push({\n parentId: record.parentId,\n nextId: null,\n node: cloneNode(record.node),\n });\n }\n } else if (!sameAttributes(before.attributes, record.attributes)) {\n attributes.push({\n id: record.id,\n attributes: { ...record.attributes },\n });\n }\n }\n\n for (const record of previous.records.values()) {\n if (!current.records.has(record.key)) {\n const parentWasRemoved: boolean =\n record.parentId !== RRWEB_BODY_NODE_ID &&\n !current.byId.has(record.parentId);\n if (!parentWasRemoved) {\n removals.push({ parentId: record.parentId, id: record.id });\n }\n }\n }\n\n if (\n additions.length === 0 &&\n removals.length === 0 &&\n attributes.length === 0\n ) {\n return [];\n }\n\n return [\n {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.Mutation,\n texts: [],\n attributes,\n removes: removals,\n adds: additions,\n },\n timestamp,\n },\n ];\n }\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n RrwebIncrementalSource,\n RrwebMouseInteractionType,\n} from \"./Contract\";\nimport { RRWEB_BODY_NODE_ID } from \"./ViewTreeSerializer\";\n\nexport type TouchPhase = \"start\" | \"move\" | \"end\";\n\nexport interface RecordedTouch {\n phase: TouchPhase;\n x: number;\n y: number;\n timestamp: number;\n targetTag?: number;\n pointerId?: number | string;\n}\n\nconst MAX_TOUCH_CLOCK_SKEW_MS: number = 60_000;\n\nfunction coordinate(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(-100_000, Math.min(100_000, value))\n : 0;\n}\n\nexport function sanitizeRecordedTouch(\n value: unknown,\n nowUnixMs: number,\n): RecordedTouch | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n const raw: Partial<Record<keyof RecordedTouch, unknown>> = value as Partial<\n Record<keyof RecordedTouch, unknown>\n >;\n if (raw.phase !== \"start\" && raw.phase !== \"move\" && raw.phase !== \"end\") {\n return null;\n }\n\n const safeNowUnixMs: number = Number.isFinite(nowUnixMs)\n ? nowUnixMs\n : Date.now();\n const candidateTimestamp: unknown = raw.timestamp;\n const timestamp: number =\n typeof candidateTimestamp === \"number\" &&\n Number.isFinite(candidateTimestamp) &&\n candidateTimestamp >= safeNowUnixMs - MAX_TOUCH_CLOCK_SKEW_MS &&\n candidateTimestamp <= safeNowUnixMs + MAX_TOUCH_CLOCK_SKEW_MS\n ? candidateTimestamp\n : safeNowUnixMs;\n\n const touch: RecordedTouch = {\n phase: raw.phase,\n x: coordinate(raw.x),\n y: coordinate(raw.y),\n timestamp,\n };\n if (\n typeof raw.targetTag === \"number\" &&\n Number.isSafeInteger(raw.targetTag) &&\n raw.targetTag > 0\n ) {\n touch.targetTag = raw.targetTag;\n }\n if (\n (typeof raw.pointerId === \"number\" &&\n Number.isSafeInteger(raw.pointerId)) ||\n (typeof raw.pointerId === \"string\" && raw.pointerId.length <= 100)\n ) {\n touch.pointerId = raw.pointerId as number | string;\n }\n return touch;\n}\n\nexport function createTouchEvent(touch: RecordedTouch): RrwebEvent {\n const x: number = coordinate(touch.x);\n const y: number = coordinate(touch.y);\n\n if (touch.phase === \"move\") {\n return {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.TouchMove,\n positions: [\n {\n x,\n y,\n id: RRWEB_BODY_NODE_ID,\n timeOffset: 0,\n },\n ],\n },\n timestamp: touch.timestamp,\n };\n }\n\n return {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.MouseInteraction,\n type:\n touch.phase === \"start\"\n ? RrwebMouseInteractionType.TouchStart\n : RrwebMouseInteractionType.TouchEnd,\n id: RRWEB_BODY_NODE_ID,\n x,\n y,\n },\n timestamp: touch.timestamp,\n };\n}\n\nexport function createCustomEvent(\n tag: string,\n payload: unknown,\n timestamp: number,\n): RrwebEvent {\n return {\n type: RrwebEventType.Custom,\n data: { tag, payload },\n timestamp,\n };\n}\n", "import { Dimensions, NativeModules, Platform } from \"react-native\";\n\nexport type NativeViewKind =\n | \"view\"\n | \"scroll\"\n | \"button\"\n | \"text\"\n | \"input\"\n | \"image\"\n | \"webview\"\n | \"canvas\"\n | \"masked\"\n | \"unknown\";\n\nexport interface NativeViewTreeNode {\n nativeId: number | string;\n kind: NativeViewKind | string;\n x: number;\n y: number;\n width: number;\n height: number;\n /** Root-only origin in React Native pageX/pageY coordinates; never uploaded. */\n touchOriginX?: number;\n /** Root-only origin in React Native pageX/pageY coordinates; never uploaded. */\n touchOriginY?: number;\n opaque?: boolean;\n masked?: boolean;\n backgroundColor?: string;\n borderColor?: string;\n borderWidth?: number;\n borderRadius?: number;\n opacity?: number;\n zIndex?: number;\n /** Count omitted by the bounded native traversal, present on the root. */\n truncatedNodes?: number;\n children?: Array<NativeViewTreeNode>;\n /* Unknown native fields are deliberately ignored by the serialiser. */\n [key: string]: unknown;\n}\n\nexport interface NativeAppMetadata {\n appName: string;\n appVersion: string;\n osName: string;\n osVersion: string;\n}\n\nexport interface NativeViewTreeAdapter {\n isAvailable?(): boolean;\n captureViewTree(rootTag: number): Promise<NativeViewTreeNode>;\n getAppMetadata(): Promise<NativeAppMetadata>;\n isTouchTargetPrivate?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean>;\n}\n\ninterface NativeModuleShape {\n captureViewTree?(rootTag: number): Promise<NativeViewTreeNode>;\n getAppMetadata?(): Promise<Partial<NativeAppMetadata>>;\n isTouchTargetPrivate?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean>;\n}\n\nfunction viewport(): { width: number; height: number } {\n const dimensions: { width?: number; height?: number } = Dimensions.get(\n \"window\",\n ) as { width?: number; height?: number };\n return {\n width:\n typeof dimensions.width === \"number\" && Number.isFinite(dimensions.width)\n ? dimensions.width\n : 0,\n height:\n typeof dimensions.height === \"number\" &&\n Number.isFinite(dimensions.height)\n ? dimensions.height\n : 0,\n };\n}\n\nexport class ReactNativeViewTreeAdapter implements NativeViewTreeAdapter {\n public isAvailable(): boolean {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n return typeof nativeModule?.captureViewTree === \"function\";\n }\n\n public async captureViewTree(rootTag: number): Promise<NativeViewTreeNode> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n\n if (nativeModule?.captureViewTree) {\n return await nativeModule.captureViewTree(rootTag);\n }\n\n throw new Error(\n \"OneUptime replay native module is unavailable. Expo Go is not supported; use an autolinked native or Expo development build.\",\n );\n }\n\n public async getAppMetadata(): Promise<NativeAppMetadata> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n let metadata: Partial<NativeAppMetadata> = {};\n\n try {\n metadata = (await nativeModule?.getAppMetadata?.()) ?? {};\n } catch {\n metadata = {};\n }\n\n return {\n appName:\n typeof metadata.appName === \"string\"\n ? metadata.appName\n : \"React Native\",\n appVersion:\n typeof metadata.appVersion === \"string\"\n ? metadata.appVersion\n : \"unknown\",\n osName:\n typeof metadata.osName === \"string\" ? metadata.osName : Platform.OS,\n osVersion:\n typeof metadata.osVersion === \"string\"\n ? metadata.osVersion\n : String(Platform.Version),\n };\n }\n\n public async isTouchTargetPrivate(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n if (typeof nativeModule?.isTouchTargetPrivate !== \"function\") {\n return true;\n }\n try {\n return (\n (await nativeModule.isTouchTargetPrivate(targetTag, replayRootTag)) !==\n false\n );\n } catch {\n return true;\n }\n }\n}\n\nexport const defaultNativeViewTreeAdapter: NativeViewTreeAdapter =\n new ReactNativeViewTreeAdapter();\n\nexport function getViewport(): { width: number; height: number } {\n return viewport();\n}\n", "// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n ], { type: 'text/javascript' }))));\n w.onmessage = function (e) {\n var d = e.data, ed = d.$e$;\n if (ed) {\n var err = new Error(ed[0]);\n err['code'] = ed[1];\n err.stack = ed[2];\n cb(err, null);\n }\n else\n cb(null, d);\n };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new i32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return { b: b, r: r };\n};\nvar _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 1; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n return new u8(v.subarray(s, e));\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n , // determined by compression function\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, st, buf, dict) {\n // source length dict length\n var sl = dat.length, dl = dict ? dict.length : 0;\n if (!sl || st.f && !st.l)\n return buf || new u8(0);\n var noBuf = !buf;\n // have to estimate size\n var resize = noBuf || st.i != 2;\n // no state\n var noSt = st.i;\n // Assumes roughly 33% compression ratio average\n if (noBuf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (resize)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17\n if (resize)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & (1 << b) - 1, pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (resize)\n cbuf(bt + 131072);\n var end = bt + add;\n if (bt < dt) {\n var shift = dl - dt, dend = Math.min(dt, end);\n if (shift + bt < 0)\n err(3);\n for (; bt < dend; ++bt)\n buf[bt] = dict[shift + bt];\n }\n for (; bt < end; ++bt)\n buf[bt] = buf[bt - dt];\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n // don't reallocate for streams or user buffers\n return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >> 8;\n d[o + 2] |= v >> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return { t: et, l: 0 };\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return { t: v, l: 1 };\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return { t: new u8(tr), l: mbt };\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return { c: cl.subarray(0, cli), n: s };\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;\n var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;\n var _c = lc(dlt), lclt = _c.c, nlc = _c.n;\n var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n ++lcfreq[lclt[i] & 31];\n for (var i = 0; i < lcdt.length; ++i)\n ++lcfreq[lcdt[i] & 31];\n var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];\n if (bs >= 0 && flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n var sym = syms[i];\n if (sym > 255) {\n var len = (sym >> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (sym >> 23) & 31), p += fleb[len];\n var dst = sym & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[sym]), p += ll[sym];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, st) {\n var s = st.z || dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var lst = st.l;\n var pos = (st.r || 0) & 7;\n if (lvl) {\n if (pos)\n w[0] = st.r >> 3;\n var opt = deo[lvl - 1];\n var n = opt >> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new i32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx blkpos\n var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;\n for (; i + 2 < s; ++i) {\n // hash value\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = i - dif + j & 32767;\n var pti = prev[ti];\n var cd = ti - pti & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += imod - pimod & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one int32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n for (i = Math.max(i, wi); i < s; ++i) {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n if (!lst) {\n st.r = (pos & 7) | w[(pos / 8) | 0] << 3;\n // shft(pos) now 1 less if pos & 7 != 0\n pos -= 7;\n st.h = head, st.p = prev, st.i = i, st.w = wi;\n }\n }\n else {\n for (var i = st.w || 0; i < s + lst; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[(pos / 8) | 0] = lst;\n e = s;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n st.i = s;\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Adler32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n if (!st) {\n st = { l: 1 };\n if (opt.dictionary) {\n var dict = opt.dictionary.subarray(-32768);\n var newDat = new u8(dict.length + dat.length);\n newDat.set(dict);\n newDat.set(dat, dict.length);\n dat = newDat;\n st.w = dict.length;\n }\n }\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return fnStr;\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n fnStr = wcln(fns[i], fnStr, td_1);\n ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };\n }\n var td = mrg({}, ch[id].e);\n return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };\nvar bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zls]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get opts\nvar gopt = function (o) { return o && {\n out: o.size && new u8(o.size),\n dictionary: o.dictionary\n}; };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) {\n if (ev.data[0]) {\n strm.push(ev.data[0], ev.data[1]);\n postMessage([ev.data[0].length]);\n }\n else\n strm.flush(ev.data[1]);\n };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id, flush, ext) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else if (!Array.isArray(dat))\n ext(dat);\n else if (dat.length == 1) {\n strm.queuedSize -= dat[0];\n if (strm.ondrain)\n strm.ondrain(dat[0]);\n }\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.queuedSize = 0;\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n strm.queuedSize += d.length;\n // can fail for cross-realm Uint8Array, but ok - only a small performance penalty\n w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []);\n };\n strm.terminate = function () { w.terminate(); };\n if (flush) {\n strm.flush = function (sync) { w.postMessage([0, sync]); };\n }\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\n// read 8 bytes\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += (d[10] | d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);\n c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;\n if (o.dictionary) {\n var h = adler();\n h.p(o.dictionary);\n wbytes(c, 2, h.d());\n }\n};\n// zlib start\nvar zls = function (d, dict) {\n if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if ((d[1] >> 5 & 1) == +!dict)\n err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');\n return (d[1] >> 3 & 4) + 2;\n};\nfunction StrmOpt(opts, cb) {\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n this.s = { l: 0, i: 32768, w: 32768, z: 32768 };\n // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev\n // 98304 = 32768 (lookback) + 65536 (common chunk size)\n this.b = new u8(98304);\n if (this.o.dictionary) {\n var dict = this.o.dictionary.subarray(-32768);\n this.b.set(dict, 32768 - dict.length);\n this.s.i = 32768 - dict.length;\n }\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, this.s), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.s.l)\n err(4);\n var endLen = chunk.length + this.s.z;\n if (endLen > this.b.length) {\n if (endLen > 2 * this.b.length - 32768) {\n var newBuf = new u8(endLen & -32768);\n newBuf.set(this.b.subarray(0, this.s.z));\n this.b = newBuf;\n }\n var split = this.b.length - this.s.z;\n this.b.set(chunk.subarray(0, split), this.s.z);\n this.s.z = this.b.length;\n this.p(this.b, false);\n this.b.set(this.b.subarray(-32768));\n this.b.set(chunk.subarray(split), 32768);\n this.s.z = chunk.length - split + 32768;\n this.s.i = 32766, this.s.w = 32768;\n }\n else {\n this.b.set(chunk, this.s.z);\n this.s.z += chunk.length;\n }\n this.s.l = final & 1;\n if (this.s.z > this.s.w + 8191 || final) {\n this.p(this.b, final || false);\n this.s.w = this.s.i, this.s.i -= 2;\n }\n if (final) {\n // cleanup unneeded buffers/state to reduce memory usage\n this.s = this.o = {};\n this.b = et;\n }\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * deflated output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible. A separate DEFLATE stream may be concatenated\n * with the current output after a sync flush.\n */\n Deflate.prototype.flush = function (sync) {\n if (!this.ondata)\n err(5);\n if (this.s.l)\n err(4);\n this.p(this.b, false);\n this.s.w = this.s.i, this.s.i -= 2;\n // could technically skip writing the type-0 block for (this.s.r & 7) == 0,\n // but the deterministic trailer (00 00 FF FF) is useful in some situations\n if (sync) {\n var c = new u8(6);\n c[0] = this.s.r >> 3;\n // write empty, non-final type-0 block\n var ep = wfblk(c, this.s.r, et);\n this.s.r = 0;\n this.ondata(c.subarray(0, ep >> 3), false);\n }\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6, 1);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n function Inflate(opts, cb) {\n // no StrmOpt here to avoid adding to workerizer\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);\n this.s = { i: 0, b: dict ? dict.length : 0 };\n this.o = new u8(32768);\n this.p = new u8(0);\n if (dict)\n this.o.set(dict);\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n if (!this.p.length)\n this.p = c;\n else if (c.length) {\n var n = new u8(this.p.length + c.length);\n n.set(this.p), n.set(c, this.p.length), this.p = n;\n }\n };\n Inflate.prototype.c = function (final) {\n this.s.i = +(this.d = final || false);\n var bts = this.s.b;\n var dt = inflt(this.p, this.s, this.o);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n function AsyncInflate(opts, cb) {\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Inflate(ev.data);\n onmessage = astrm(strm);\n }, 7, 0);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);\n}\nexport function inflateSync(data, opts) {\n return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n this.c.p(chunk);\n this.l += chunk.length;\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * GZIPped output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible.\n */\n Gzip.prototype.flush = function (sync) {\n Deflate.prototype.flush.call(this, sync);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8, 1);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming single or multi-member GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n function Gunzip(opts, cb) {\n this.v = 1;\n this.r = 0;\n Inflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n this.r += chunk.length;\n if (this.v) {\n var p = this.p.subarray(this.v - 1);\n var s = p.length > 3 ? gzs(p) : 4;\n if (s > p.length) {\n if (!final)\n return;\n }\n else if (this.v > 1 && this.onmember) {\n this.onmember(this.r - p.length);\n }\n this.p = p.subarray(s), this.v = 0;\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, 0);\n // process concatenated GZIP\n if (this.s.f && !this.s.l) {\n this.v = shft(this.s.p) + 9;\n this.s = { i: 0 };\n this.o = new u8(0);\n this.push(new u8(0), final);\n }\n else if (final) {\n Inflate.prototype.c.call(this, final);\n }\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming single or multi-member GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n function AsyncGunzip(opts, cb) {\n var _this = this;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Gunzip(ev.data);\n strm.onmember = function (offset) { return postMessage(offset); };\n onmessage = astrm(strm);\n }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);\n}\nexport function gunzipSync(data, opts) {\n var st = gzs(data);\n if (st + 8 > data.length)\n err(6, 'invalid gzip data');\n return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n this.c.p(chunk);\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * zlibbed output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible.\n */\n Zlib.prototype.flush = function (sync) {\n Deflate.prototype.flush.call(this, sync);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10, 1);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n function Unzlib(opts, cb) {\n Inflate.call(this, opts, cb);\n this.v = opts && opts.dictionary ? 2 : 1;\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 6 && !final)\n return;\n this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n function AsyncUnzlib(opts, cb) {\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Unzlib(ev.data);\n onmessage = astrm(strm);\n }, 11, 0);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);\n}\nexport function unzlibSync(data, opts) {\n return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n function Decompress(opts, cb) {\n this.o = StrmOpt.call(this, opts, cb) || {};\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n }\n // init substream\n // overriden by AsyncDecompress\n Decompress.prototype.i = function () {\n var _this = this;\n this.s.ondata = function (dat, final) {\n _this.ondata(dat, final);\n };\n };\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(this.o)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(this.o)\n : new this.Z(this.o);\n this.i();\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n function AsyncDecompress(opts, cb) {\n Decompress.call(this, opts, cb);\n this.queuedSize = 0;\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n }\n AsyncDecompress.prototype.i = function () {\n var _this = this;\n this.s.ondata = function (err, dat, final) {\n _this.ondata(err, dat, final);\n };\n this.s.ondrain = function (size) {\n _this.queuedSize -= size;\n if (_this.ondrain)\n _this.ondrain(size);\n };\n };\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n this.queuedSize += chunk.length;\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, opts) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, opts)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, opts)\n : unzlibSync(data, opts);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (ArrayBuffer.isView(val))\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return { s: r, r: slc(d, i - 1) };\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), s = _a.s, r = _a.r;\n if (final) {\n if (r.length)\n err(8);\n this.p = null;\n }\n else\n this.p = r;\n this.ondata(s, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td) {\n return td.decode(dat);\n }\n else {\n var _a = dutf8(dat), s = _a.s, r = _a.r;\n if (r.length)\n err(8);\n return s;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;\n var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];\n};\n// read zip64 header sizes\nvar z64hs = function (d, b, l, z, sc, su, off) {\n var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;\n var nf = nsc + nsu + noff;\n if (z && nf) {\n for (; b + 4 < e; b += 4 + b2(d, b + 2)) {\n if (b2(d, b) == 1) {\n return [\n nsc ? b8(d, b + 4 + 8 * nsu) : sc,\n nsu ? b8(d, b + 4) : su,\n noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,\n 1\n ];\n }\n }\n // z == 2 for unknown whether or not zip64\n if (z < 2)\n err(13);\n }\n return [sc, su, off, 0];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n // we shouldn't really do this cast, but properly handling ArrayBufferLike\n // makes the API unergonomic with Buffer\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this.ondata(err, dat, final);\n _this.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this.d & 1))\n return;\n _this.u.splice(-1, 1);\n _this.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (chunk, final) {\n // same as ZipPassThrough: cast to retain Buffer ergonomics\n this.ondata(null, chunk, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this = this;\n this.i = new Inflate(function (dat, final) {\n _this.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (chunk, final) {\n try {\n this.i.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (chunk, final) {\n if (this.i.terminate)\n chunk = slc(chunk, 0);\n this.i.push(chunk, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3];\n if (dd)\n sc_1 = -1 - z64;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this.k[0] == chks_3 && _this.c)\n _this.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = b4(data, e - 20) == 0x7064B50;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n // Synchronously decompress under 512KB, or barely-compressed data\n if (su < 524288 || sc > 0.8 * su) {\n try {\n cbl(null, inflateSync(infl, { out: new u8(su) }));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = b4(data, e - 20) == 0x7064B50;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n", "/*\n * Base64 for the offline outbox, which keeps each frame gzip-compressed in\n * AsyncStorage. AsyncStorage stores strings, and a gzip stream written as a\n * \"binary\" string would put NUL and high bytes into SQLite TEXT columns on\n * Android; base64 is ASCII, costs a third on top of gzip, and still leaves\n * a frame several times smaller than the JSON it came from.\n *\n * Implemented here rather than with btoa/atob: Hermes only has those from\n * React Native 0.74, and this package supports 0.73.\n */\n\nconst ALPHABET: string =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nconst LOOKUP: Int16Array = ((): Int16Array => {\n const table: Int16Array = new Int16Array(128).fill(-1);\n\n for (let index: number = 0; index < ALPHABET.length; index += 1) {\n table[ALPHABET.charCodeAt(index)] = index;\n }\n\n return table;\n})();\n\nexport function encodeBase64(bytes: Uint8Array): string {\n const parts: Array<string> = [];\n\n for (let index: number = 0; index < bytes.length; index += 3) {\n const first: number = bytes[index] as number;\n const second: number | undefined = bytes[index + 1];\n const third: number | undefined = bytes[index + 2];\n const triple: number = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);\n\n parts.push(\n ALPHABET.charAt((triple >> 18) & 63) +\n ALPHABET.charAt((triple >> 12) & 63) +\n (second === undefined ? \"=\" : ALPHABET.charAt((triple >> 6) & 63)) +\n (third === undefined ? \"=\" : ALPHABET.charAt(triple & 63)),\n );\n }\n\n return parts.join(\"\");\n}\n\n/* Null for anything that is not canonical base64: the input is untrusted. */\nexport function decodeBase64(text: string): Uint8Array | null {\n if (typeof text !== \"string\" || text.length % 4 !== 0) {\n return null;\n }\n\n const padding: number = text.endsWith(\"==\") ? 2 : text.endsWith(\"=\") ? 1 : 0;\n const bytes: Uint8Array = new Uint8Array((text.length / 4) * 3 - padding);\n let buffer: number = 0;\n let bits: number = 0;\n let written: number = 0;\n\n for (let index: number = 0; index < text.length - padding; index += 1) {\n const code: number = text.charCodeAt(index);\n const value: number = code < 128 ? (LOOKUP[code] as number) : -1;\n\n if (value < 0) {\n return null;\n }\n\n buffer = ((buffer << 6) | value) & 0xffffff;\n bits += 6;\n\n if (bits >= 8) {\n bits -= 8;\n bytes[written] = (buffer >> bits) & 0xff;\n written += 1;\n }\n }\n\n return written === bytes.length ? bytes : null;\n}\n", "import { gunzipSync, gzipSync, strFromU8, strToU8 } from \"fflate\";\nimport { decodeBase64, encodeBase64 } from \"./Base64\";\nimport {\n SESSION_REPLAY_MAX_OFFLINE_DELAY_MS,\n SessionReplayChunkEnvelope,\n} from \"./Contract\";\nimport { byteLength } from \"./Sanitize\";\nimport { ReplayStorage } from \"./Storage\";\n\n/*\n * The durable upload queue, and so the whole of offline mode's memory: every\n * frame is written here BEFORE it is posted, and removed only once the\n * server has it (or refused it for good). An app that loses its connection\n * keeps recording into this outbox, and an app that is killed while offline\n * finds its backlog here on the next launch.\n *\n * One AsyncStorage key per frame, plus a small index. The first version kept\n * the whole outbox as ONE JSON array under one key, which on Android is a\n * single SQLite row - and AsyncStorage cannot read a row larger than the\n * 2 MB CursorWindow back. An offline backlog past that size failed to read,\n * and a failed read discarded the lot: the longer the outage, the more\n * certainly everything recorded during it was lost. Per-frame keys keep\n * every value to one frame, and writing a frame no longer rewrites every\n * other frame with it.\n *\n * Frames are stored gzip-compressed (base64, since AsyncStorage stores\n * strings). A view-tree frame compresses several times over, and Android's\n * AsyncStorage database is 6 MB by default and shared with the host app, so\n * compression is what turns the bound below into an hour of recording\n * rather than a few minutes - without taking the app's own storage.\n */\n\nexport const MAX_OUTBOX_ENTRIES: number = 240;\nexport const MAX_OUTBOX_BYTES: number = 3 * 1024 * 1024;\n\nexport interface PersistedReplayFrame {\n id: string;\n envelope: SessionReplayChunkEnvelope;\n payload: string;\n attempts: number;\n createdAtUnixMs: number;\n}\n\n/* What the index keeps per frame: enough to order, bound and retry it. */\nexport interface OutboxEntry {\n id: string;\n attempts: number;\n createdAtUnixMs: number;\n\n /* Stored size of the frame's value, which is what the bound counts. */\n bytes: number;\n}\n\n/* A frame as the transport posts it: its payload already gzip-compressed. */\nexport interface StoredReplayFrame {\n id: string;\n envelope: SessionReplayChunkEnvelope;\n compressedPayload: Uint8Array;\n attempts: number;\n createdAtUnixMs: number;\n}\n\nexport interface OutboxMutationResult {\n dropped: number;\n}\n\ninterface FrameValue {\n envelope: SessionReplayChunkEnvelope;\n gzip: string;\n}\n\nfunction isEnvelope(value: unknown): value is SessionReplayChunkEnvelope {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const envelope: Partial<SessionReplayChunkEnvelope> =\n value as Partial<SessionReplayChunkEnvelope>;\n return (\n typeof envelope.sessionId === \"string\" &&\n typeof envelope.tabId === \"string\" &&\n typeof envelope.chunkIndex === \"number\"\n );\n}\n\nfunction isEntry(value: unknown): value is OutboxEntry {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const entry: Partial<OutboxEntry> = value as Partial<OutboxEntry>;\n return (\n typeof entry.id === \"string\" &&\n Number.isSafeInteger(entry.attempts) &&\n typeof entry.createdAtUnixMs === \"number\" &&\n Number.isFinite(entry.createdAtUnixMs) &&\n Number.isSafeInteger(entry.bytes)\n );\n}\n\n/* The single-key layout this file replaced, read once to migrate it. */\nfunction isLegacyFrame(value: unknown): value is PersistedReplayFrame {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const frame: Partial<PersistedReplayFrame> =\n value as Partial<PersistedReplayFrame>;\n return (\n typeof frame.id === \"string\" &&\n typeof frame.payload === \"string\" &&\n typeof frame.attempts === \"number\" &&\n Number.isSafeInteger(frame.attempts) &&\n typeof frame.createdAtUnixMs === \"number\" &&\n isEnvelope(frame.envelope)\n );\n}\n\nfunction byOldest(left: OutboxEntry, right: OutboxEntry): number {\n return left.createdAtUnixMs - right.createdAtUnixMs;\n}\n\nexport function frameId(envelope: SessionReplayChunkEnvelope): string {\n return `${envelope.sessionId}:${envelope.tabId}:${envelope.chunkIndex}`;\n}\n\nexport default class ReplayOutbox {\n private readonly storage: ReplayStorage;\n private readonly legacyKey: string;\n private readonly indexKey: string;\n private readonly framePrefix: string;\n private readonly now: () => number;\n private mutationQueue: Promise<void> = Promise.resolve();\n private migrated: boolean = false;\n\n public constructor(\n storage: ReplayStorage,\n namespace: string,\n now: () => number = Date.now,\n ) {\n this.storage = storage;\n this.legacyKey = `@oneuptime/replay/${namespace}/outbox`;\n this.indexKey = `@oneuptime/replay/${namespace}/outbox-v2`;\n this.framePrefix = `@oneuptime/replay/${namespace}/outbox-v2/`;\n this.now = now;\n }\n\n /* Every queued frame's index entry, oldest first. Reads no payload. */\n public async entries(): Promise<Array<OutboxEntry>> {\n return await this.withLock(async (): Promise<Array<OutboxEntry>> => {\n return await this.readIndexUnlocked();\n });\n }\n\n /*\n * One frame, ready to post. Null when it is no longer queued, and\n * \"unreadable\" when its value could not be read back - it is removed, so\n * one damaged frame never blocks the ones behind it.\n */\n public async load(\n id: string,\n ): Promise<StoredReplayFrame | \"unreadable\" | null> {\n return await this.withLock(\n async (): Promise<StoredReplayFrame | \"unreadable\" | null> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n const entry: OutboxEntry | undefined = entries.find(\n (candidate: OutboxEntry): boolean => {\n return candidate.id === id;\n },\n );\n if (!entry) {\n return null;\n }\n\n const value: {\n envelope: SessionReplayChunkEnvelope;\n bytes: Uint8Array;\n } | null = await this.readFrameUnlocked(id);\n if (!value) {\n await this.removeEntriesUnlocked(entries, [id]);\n return \"unreadable\";\n }\n\n return {\n id,\n envelope: value.envelope,\n compressedPayload: value.bytes,\n attempts: entry.attempts,\n createdAtUnixMs: entry.createdAtUnixMs,\n };\n },\n );\n }\n\n /* Every frame with its payload decompressed, oldest first. */\n public async list(): Promise<Array<PersistedReplayFrame>> {\n const frames: Array<PersistedReplayFrame> = [];\n\n for (const entry of await this.entries()) {\n const frame: StoredReplayFrame | \"unreadable\" | null = await this.load(\n entry.id,\n );\n if (!frame || frame === \"unreadable\") {\n continue;\n }\n\n frames.push({\n id: frame.id,\n envelope: frame.envelope,\n payload: strFromU8(gunzipSync(frame.compressedPayload)),\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n });\n }\n\n return frames;\n }\n\n /*\n * Queue a frame. Past MAX_OUTBOX_ENTRIES or MAX_OUTBOX_BYTES the OLDEST\n * frames are evicted - the newest seconds are the ones closest to whatever\n * went wrong, and a later full snapshot re-anchors the player after a gap -\n * and counted in `dropped`, as is a frame the device had no room to store.\n */\n public async enqueue(\n frame: PersistedReplayFrame,\n ): Promise<OutboxMutationResult> {\n return await this.withLock(async (): Promise<OutboxMutationResult> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n if (\n entries.some((candidate: OutboxEntry): boolean => {\n return candidate.id === frame.id;\n })\n ) {\n return { dropped: 0 };\n }\n\n const bytes: number | null = await this.writeFrameUnlocked(frame);\n if (bytes === null) {\n return { dropped: 1 };\n }\n\n entries.push({\n id: frame.id,\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n bytes,\n });\n entries.sort(byOldest);\n\n let totalBytes: number = 0;\n for (const entry of entries) {\n totalBytes += entry.bytes;\n }\n\n const evicted: Array<string> = [];\n while (\n entries.length > 1 &&\n (entries.length > MAX_OUTBOX_ENTRIES || totalBytes > MAX_OUTBOX_BYTES)\n ) {\n const oldest: OutboxEntry = entries.shift() as OutboxEntry;\n totalBytes -= oldest.bytes;\n evicted.push(oldest.id);\n }\n\n if (!(await this.writeIndexUnlocked(entries))) {\n /* The index is full too: the frame we just wrote is untracked. */\n await this.safeRemove(this.frameKey(frame.id));\n return { dropped: 1 };\n }\n\n await Promise.all(\n evicted.map((id: string): Promise<void> => {\n return this.safeRemove(this.frameKey(id));\n }),\n );\n return { dropped: evicted.length };\n });\n }\n\n public async remove(id: string): Promise<void> {\n await this.withLock(async (): Promise<void> => {\n await this.removeEntriesUnlocked(await this.readIndexUnlocked(), [id]);\n });\n }\n\n public async incrementAttempts(id: string): Promise<number> {\n return await this.withLock(async (): Promise<number> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n let attempts: number = 0;\n for (const entry of entries) {\n if (entry.id === id) {\n entry.attempts += 1;\n attempts = entry.attempts;\n break;\n }\n }\n\n await this.writeIndexUnlocked(entries);\n return attempts;\n });\n }\n\n /*\n * Consent withdrawn, or the server refused this recorder for good: every\n * frame goes, including any a crash left untracked by the index when the\n * storage can list its keys.\n */\n public async clear(): Promise<void> {\n await this.withLock(async (): Promise<void> => {\n const keys: Set<string> = new Set<string>([\n this.legacyKey,\n this.indexKey,\n ]);\n\n for (const entry of await this.readRawIndexUnlocked()) {\n keys.add(this.frameKey(entry.id));\n }\n\n if (typeof this.storage.getAllKeys === \"function\") {\n try {\n for (const key of await this.storage.getAllKeys()) {\n if (key.startsWith(this.framePrefix)) {\n keys.add(key);\n }\n }\n } catch {\n /* Best effort: the index already named every tracked frame. */\n }\n }\n\n this.migrated = true;\n await Promise.all(\n Array.from(keys).map((key: string): Promise<void> => {\n return this.safeRemove(key);\n }),\n );\n });\n }\n\n private frameKey(id: string): string {\n return `${this.framePrefix}${id}`;\n }\n\n /*\n * The index, with the legacy layout migrated into it on first use and\n * anything older than SESSION_REPLAY_MAX_OFFLINE_DELAY_MS pruned: the\n * server would no longer place it on the recording's real timeline.\n */\n private async readIndexUnlocked(): Promise<Array<OutboxEntry>> {\n await this.migrateUnlocked();\n\n const entries: Array<OutboxEntry> = await this.readRawIndexUnlocked();\n const oldestKept: number = this.now() - SESSION_REPLAY_MAX_OFFLINE_DELAY_MS;\n const expired: Array<string> = entries\n .filter((entry: OutboxEntry): boolean => {\n return entry.createdAtUnixMs < oldestKept;\n })\n .map((entry: OutboxEntry): string => {\n return entry.id;\n });\n\n if (expired.length > 0) {\n await this.removeEntriesUnlocked(entries, expired);\n }\n\n return entries.sort(byOldest);\n }\n\n private async readRawIndexUnlocked(): Promise<Array<OutboxEntry>> {\n let raw: string | null = null;\n try {\n raw = await this.storage.getItem(this.indexKey);\n } catch {\n raw = null;\n }\n if (!raw) {\n return [];\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed) && parsed.every(isEntry)) {\n return parsed;\n }\n } catch {\n /* Falls through to the reset below. */\n }\n\n await this.safeRemove(this.indexKey);\n return [];\n }\n\n private async writeIndexUnlocked(\n entries: Array<OutboxEntry>,\n ): Promise<boolean> {\n if (entries.length === 0) {\n await this.safeRemove(this.indexKey);\n return true;\n }\n\n return await this.safeSet(this.indexKey, JSON.stringify(entries));\n }\n\n /* Drop entries from the index and their frames from storage. */\n private async removeEntriesUnlocked(\n entries: Array<OutboxEntry>,\n ids: Array<string>,\n ): Promise<void> {\n const removing: Set<string> = new Set<string>(ids);\n const kept: Array<OutboxEntry> = entries.filter(\n (entry: OutboxEntry): boolean => {\n return !removing.has(entry.id);\n },\n );\n\n entries.splice(0, entries.length, ...kept);\n await this.writeIndexUnlocked(entries);\n await Promise.all(\n ids.map((id: string): Promise<void> => {\n return this.safeRemove(this.frameKey(id));\n }),\n );\n }\n\n /* Store one frame's value. Its size, or null when it could not be stored. */\n private async writeFrameUnlocked(\n frame: PersistedReplayFrame,\n ): Promise<number | null> {\n let value: string;\n try {\n const stored: FrameValue = {\n envelope: frame.envelope,\n gzip: encodeBase64(gzipSync(strToU8(frame.payload))),\n };\n value = JSON.stringify(stored);\n } catch {\n return null;\n }\n\n return (await this.safeSet(this.frameKey(frame.id), value))\n ? byteLength(value)\n : null;\n }\n\n private async readFrameUnlocked(id: string): Promise<{\n envelope: SessionReplayChunkEnvelope;\n bytes: Uint8Array;\n } | null> {\n try {\n const raw: string | null = await this.storage.getItem(this.frameKey(id));\n if (!raw) {\n return null;\n }\n\n const parsed: Partial<FrameValue> = JSON.parse(\n raw,\n ) as Partial<FrameValue>;\n const bytes: Uint8Array | null =\n typeof parsed.gzip === \"string\" ? decodeBase64(parsed.gzip) : null;\n if (!bytes || !isEnvelope(parsed.envelope)) {\n return null;\n }\n\n return { envelope: parsed.envelope, bytes };\n } catch {\n /* Unreadable - on Android, a value past the CursorWindow limit. */\n return null;\n }\n }\n\n /*\n * Move a queue written by an earlier SDK version (one JSON array under the\n * legacy key) into this layout, once. A legacy queue too large to read -\n * the very failure this layout exists to fix - cannot be recovered, only\n * removed so it stops failing.\n */\n private async migrateUnlocked(): Promise<void> {\n if (this.migrated) {\n return;\n }\n this.migrated = true;\n\n let raw: string | null = null;\n try {\n raw = await this.storage.getItem(this.legacyKey);\n } catch {\n await this.safeRemove(this.legacyKey);\n return;\n }\n if (!raw) {\n return;\n }\n\n let legacy: Array<PersistedReplayFrame> = [];\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n legacy = parsed.filter(isLegacyFrame);\n }\n } catch {\n legacy = [];\n }\n\n const entries: Array<OutboxEntry> = await this.readRawIndexUnlocked();\n for (const frame of legacy) {\n if (\n entries.some((entry: OutboxEntry): boolean => {\n return entry.id === frame.id;\n })\n ) {\n continue;\n }\n\n const bytes: number | null = await this.writeFrameUnlocked(frame);\n if (bytes !== null) {\n entries.push({\n id: frame.id,\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n bytes,\n });\n }\n }\n\n await this.writeIndexUnlocked(entries.sort(byOldest));\n await this.safeRemove(this.legacyKey);\n }\n\n private async safeSet(key: string, value: string): Promise<boolean> {\n try {\n await this.storage.setItem(key, value);\n return true;\n } catch {\n /* Recording must never destabilise the host app when storage is full. */\n return false;\n }\n }\n\n private async safeRemove(key: string): Promise<void> {\n try {\n await this.storage.removeItem(key);\n } catch {\n /* Best-effort privacy cleanup. */\n }\n }\n\n private async withLock<T>(operation: () => Promise<T>): Promise<T> {\n const result: Promise<T> = this.mutationQueue.then(operation, operation);\n this.mutationQueue = result.then(\n (): void => {\n return undefined;\n },\n (): void => {\n return undefined;\n },\n );\n return await result;\n }\n}\n", "/*\n * THE RETRY-AFTER RESPONSE HEADER, READ AS RFC 9110 WRITES IT.\n *\n * A server that refuses for now - a 429 or a 503, most often - can say when\n * to ask again (RFC 9110 section 10.2.3):\n *\n * Retry-After = HTTP-date / delay-seconds\n *\n * delay-seconds is a whole number of seconds, in digits and nothing else:\n * \"120\". An HTTP-date is one of the three shapes of section 5.6.7, which a\n * recipient must all accept, case and spaces exactly as written:\n *\n * IMF-fixdate Sun, 06 Nov 1994 08:49:37 GMT (the one senders send)\n * RFC 850 Sunday, 06-Nov-94 08:49:37 GMT (obsolete; a two-digit year\n * more than 50 years ahead\n * is the century before)\n * asctime Sun Nov 6 08:49:37 1994 (obsolete; UTC)\n *\n * Anything else is no Retry-After at all and reads as undefined, so the\n * caller waits its own backoff: a fraction (\"1.5\"), a sign (\"-5\", \"+5\"),\n * words (\"5 seconds\"), an exponent (\"1e3\"), hex (\"0x10\"), a list\n * (\"120, 120\"), a date in any other shape, a day the month does not have.\n * Never Date.parse: V8 reads \"-5\" and \"1.5\" as days in 2001 - a wait long\n * over, so a retry at once - and asctime in the local time zone.\n *\n * A wait that is read is held between two bounds, which a caller may set:\n *\n * - at least minMs, a second unless the caller says otherwise. \"0\", or a\n * date gone by (most often a server clock behind this one), would retry\n * at once, and a server that keeps answering so would be asked again in\n * a tight loop. Waiting longer than asked is always allowed;\n * - at most maxMs, an hour unless the caller says otherwise. A huge\n * number, digits too many for a number, or a date years ahead would\n * stall the caller as long (and setTimeout fires at once past\n * 2^31 - 1 ms). maxMs wins over minMs.\n *\n * The value comes from the network, so nothing here throws, and each value\n * is read in one pass: a megabyte of spaces costs a megabyte.\n *\n * This file imports nothing, so the packages that cannot import Common\n * carry byte-identical copies of it: agents/KubernetesAIAgent and\n * agents/ResourceAIAgent (Common/Utils/RetryAfter.ts, copied by their\n * npm run sync-common) and the React Native recorder\n * (packages/App/FeatureSet/MobileRecorder/src/RetryAfter.ts). Their parity\n * tests fail when a copy drifts. The browser recorder inlines it into a\n * script every page of a customer's site loads, so it is kept small.\n */\n\n// The header's name, in the lower case Node and fetch give it.\nexport const RETRY_AFTER_HEADER: string = \"retry-after\";\n\n// The least a Retry-After that is read waits, unless the caller says otherwise.\nexport const DEFAULT_RETRY_AFTER_MIN_MS: number = 1000;\n\n// The most a Retry-After that is read waits, unless the caller says otherwise.\nexport const DEFAULT_RETRY_AFTER_MAX_MS: number = 60 * 60 * 1000;\n\nexport interface RetryAfterOptions {\n // The time now, in milliseconds since the epoch: Date.now() when left out.\n nowMs?: number | undefined;\n /*\n * The least a value that is read waits: DEFAULT_RETRY_AFTER_MIN_MS when\n * left out, or when it is not a finite number of 0 or more.\n */\n minMs?: number | undefined;\n /*\n * The most a value that is read waits: DEFAULT_RETRY_AFTER_MAX_MS when\n * left out, or when it is not a finite number of 0 or more.\n */\n maxMs?: number | undefined;\n /*\n * False reads delay-seconds only, and an HTTP-date as no Retry-After: for\n * a wait counted down in front of a person, on a device whose clock may be\n * wrong, which a date would move with. True when left out.\n */\n acceptHttpDate?: boolean | undefined;\n}\n\n// delay-seconds: 1*DIGIT. \\d is the ASCII digits alone (no u flag).\nconst DELAY_SECONDS: RegExp = /^\\d+$/;\n\nconst MONTHS: Array<string> =\n \"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\".split(\" \");\n\n// The parts the three shapes are written with (RFC 9110 section 5.6.7).\nconst DAY_NAME: string = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst DAY_NAME_LONG: string = \"(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day\";\nconst MONTH: string = `(${MONTHS.join(\"|\")})`;\nconst TIME_OF_DAY: string = \"(\\\\d\\\\d):(\\\\d\\\\d):(\\\\d\\\\d)\";\n\n// day-name \",\" SP 2DIGIT SP month SP 4DIGIT SP time-of-day SP \"GMT\".\nconst IMF_FIXDATE: RegExp = new RegExp(\n `^${DAY_NAME}, (\\\\d\\\\d) ${MONTH} (\\\\d{4}) ${TIME_OF_DAY} GMT$`,\n);\n\n// day-name-l \",\" SP 2DIGIT \"-\" month \"-\" 2DIGIT SP time-of-day SP \"GMT\".\nconst RFC_850_DATE: RegExp = new RegExp(\n `^${DAY_NAME_LONG}, (\\\\d\\\\d)-${MONTH}-(\\\\d\\\\d) ${TIME_OF_DAY} GMT$`,\n);\n\n// day-name SP month SP ( 2DIGIT / ( SP DIGIT )) SP time-of-day SP 4DIGIT.\nconst ASCTIME_DATE: RegExp = new RegExp(\n `^${DAY_NAME} ${MONTH} (\\\\d\\\\d| \\\\d) ${TIME_OF_DAY} (\\\\d{4})$`,\n);\n\n// How far ahead an RFC 850 date's two-digit year may land (section 5.6.7).\nconst TWO_DIGIT_YEAR_LOOKAHEAD_YEARS: number = 50;\n\n/*\n * A date written in UTC, as milliseconds since the epoch. Undefined for a\n * time past 23:59:60 (60 is a leap second, which section 5.6.7 allows: it\n * reads as the next minute's first) or a day the month does not have\n * (31 Apr, 29 Feb 2023) - never the date it would roll over to. The fields\n * are digits as written; a comparison with one that is missing (NaN) fails.\n */\nfunction toUtcMs(\n year: number,\n month: string | undefined,\n day: string | undefined,\n hour: string | undefined,\n minute: string | undefined,\n second: string | undefined,\n): number | undefined {\n const monthIndex: number = MONTHS.indexOf(month || \"\");\n const dayOfMonth: number = Number(day);\n // setUTCFullYear, not Date.UTC: Date.UTC reads a year below 100 as 19xx.\n const date: Date = new Date(0);\n date.setUTCFullYear(year, monthIndex, dayOfMonth);\n\n if (\n monthIndex < 0 ||\n date.getUTCMonth() !== monthIndex ||\n date.getUTCDate() !== dayOfMonth ||\n !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)\n ) {\n return undefined;\n }\n\n date.setUTCHours(Number(hour), Number(minute), Number(second), 0);\n\n return date.getTime();\n}\n\n/*\n * An RFC 850 date's two-digit year is this century's, unless that is more\n * than 50 years ahead: then it is the most recent year gone by with the\n * same last two digits (RFC 9110 section 5.6.7).\n */\nfunction readRfc850Date(\n match: RegExpExecArray,\n nowMs: number,\n): number | undefined {\n const thisYear: number = new Date(nowMs).getUTCFullYear();\n const lookaheadEnd: Date = new Date(nowMs);\n lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);\n\n let year: number = thisYear - (thisYear % 100) + Number(match[3]);\n let atMs: number | undefined = toUtcMs(\n year,\n match[2],\n match[1],\n match[4],\n match[5],\n match[6],\n );\n\n if (atMs !== undefined && atMs > lookaheadEnd.getTime()) {\n year -= 100;\n atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);\n }\n\n return atMs;\n}\n\n// SP and HTAB: the whitespace RFC 9110 allows around a field's value.\nfunction isSpace(code: number): boolean {\n return code === 32 || code === 9;\n}\n\n/*\n * A value's text, its surrounding spaces and tabs left out; undefined when\n * it is not a string or a number, or nothing is left. Copies of a header\n * sent more than once give their text only when they all agree.\n */\nfunction toText(value: unknown): string | undefined {\n if (Array.isArray(value)) {\n const copies: Array<string | undefined> = value.map(\n (copy: unknown): string | undefined => {\n return Array.isArray(copy) ? undefined : toText(copy);\n },\n );\n\n return copies.every((copy: string | undefined): boolean => {\n return copy === copies[0];\n })\n ? copies[0]\n : undefined;\n }\n\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n return undefined;\n }\n\n const text: string = String(value);\n let start: number = 0;\n let end: number = text.length;\n\n while (start < end && isSpace(text.charCodeAt(start))) {\n start++;\n }\n\n while (end > start && isSpace(text.charCodeAt(end - 1))) {\n end--;\n }\n\n return start < end ? text.slice(start, end) : undefined;\n}\n\nfunction readNow(nowMs: number | undefined): number {\n return typeof nowMs === \"number\" && Number.isFinite(nowMs)\n ? nowMs\n : Date.now();\n}\n\nfunction readBound(bound: number | undefined, fallback: number): number {\n return typeof bound === \"number\" && Number.isFinite(bound) && bound >= 0\n ? bound\n : fallback;\n}\n\nexport default class RetryAfter {\n /*\n * The wait a Retry-After value asks for, in milliseconds, held between\n * minMs and maxMs; undefined when the value is not a Retry-After (absent,\n * empty, or neither delay-seconds nor an HTTP-date), so the caller waits\n * its own backoff. The value is a header's: a string, a number, or the\n * copies of a header sent more than once - which count only when they\n * all say the same.\n */\n public static parseMs(\n value: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n const text: string | undefined = toText(value);\n const asked: RetryAfterOptions = options || {};\n let waitMs: number | undefined;\n\n if (text === undefined) {\n return undefined;\n }\n\n if (DELAY_SECONDS.test(text)) {\n // Digits too many for a number read as Infinity: the ceiling.\n waitMs = Number(text) * 1000;\n } else if (asked.acceptHttpDate !== false) {\n const nowMs: number = readNow(asked.nowMs);\n const retryAtMs: number | undefined = RetryAfter.parseHttpDate(\n text,\n nowMs,\n );\n\n waitMs = retryAtMs === undefined ? undefined : retryAtMs - nowMs;\n }\n\n return waitMs === undefined\n ? undefined\n : Math.min(\n Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),\n readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS),\n );\n }\n\n /*\n * The same wait in whole seconds, rounded up - never sooner than asked -\n * for a caller that counts in seconds.\n */\n public static parseSeconds(\n value: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n const waitMs: number | undefined = RetryAfter.parseMs(value, options);\n\n return waitMs === undefined ? undefined : Math.ceil(waitMs / 1000);\n }\n\n /*\n * The Retry-After header of a response's headers, whatever its case: an\n * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain\n * object of names to values (Node's, a test's). Undefined when there is\n * none; a get() that throws reads as none.\n */\n public static readHeader(headers: unknown): unknown {\n if (!headers || typeof headers !== \"object\") {\n return undefined;\n }\n\n const get: unknown = (headers as { get?: unknown }).get;\n\n if (typeof get === \"function\") {\n try {\n const value: unknown = (get as (name: string) => unknown).call(\n headers,\n RETRY_AFTER_HEADER,\n );\n\n if (value !== undefined && value !== null) {\n return value;\n }\n } catch {\n // A get() that throws is no header; the names are read below.\n }\n }\n\n for (const name of Object.keys(headers)) {\n if (name.toLowerCase() === RETRY_AFTER_HEADER) {\n return (headers as Record<string, unknown>)[name];\n }\n }\n\n return undefined;\n }\n\n // parseMs of a response's Retry-After header.\n public static msFromHeaders(\n headers: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n return RetryAfter.parseMs(RetryAfter.readHeader(headers), options);\n }\n\n // parseSeconds of a response's Retry-After header.\n public static secondsFromHeaders(\n headers: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n return RetryAfter.parseSeconds(RetryAfter.readHeader(headers), options);\n }\n\n /*\n * An HTTP-date in any of its three shapes, exactly as written, as\n * milliseconds since the epoch; undefined for anything else. nowMs is what\n * an RFC 850 date's two-digit year is read against.\n */\n public static parseHttpDate(\n value: string,\n nowMs?: number | undefined,\n ): number | undefined {\n let match: RegExpExecArray | null = IMF_FIXDATE.exec(value);\n\n if (match) {\n return toUtcMs(\n Number(match[3]),\n match[2],\n match[1],\n match[4],\n match[5],\n match[6],\n );\n }\n\n match = RFC_850_DATE.exec(value);\n\n if (match) {\n return readRfc850Date(match, readNow(nowMs));\n }\n\n match = ASCTIME_DATE.exec(value);\n\n // asctime's day is \" 6\" or \"06\": Number reads both as 6.\n return match\n ? toUtcMs(\n Number(match[6]),\n match[1],\n match[2],\n match[3],\n match[4],\n match[5],\n )\n : undefined;\n }\n}\n", "import AsyncStorage from \"@react-native-async-storage/async-storage\";\nimport {\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION,\n SESSION_REPLAY_IDLE_ROLLOVER_MS,\n SESSION_REPLAY_MAX_SESSION_MS,\n} from \"./Contract\";\n\nconst REPLAY_ID_PATTERN: RegExp = /^[0-9a-f]{32}$/u;\n\nexport interface ReplayStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n\n /*\n * Optional. When present, clearing the offline outbox also removes any\n * frame a crash left untracked by its index. AsyncStorage has it.\n */\n getAllKeys?(): Promise<ReadonlyArray<string>>;\n}\n\nexport const defaultReplayStorage: ReplayStorage = AsyncStorage;\n\nexport interface ReplaySessionIdentity {\n sessionId: string;\n tabId: string;\n visitorId: string;\n sessionStartUnixMs: number;\n chunkIndex: number;\n}\n\ninterface StoredSession {\n sessionId: string;\n sessionStartUnixMs: number;\n lastActivityUnixMs: number;\n nextChunkIndex: number;\n}\n\nexport function generateReplayId(): string {\n const bytes: Uint8Array = new Uint8Array(16);\n const cryptoRef: Crypto | undefined = globalThis.crypto;\n\n if (cryptoRef && typeof cryptoRef.getRandomValues === \"function\") {\n cryptoRef.getRandomValues(bytes);\n } else {\n for (let index: number = 0; index < bytes.length; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n\n return Array.from(bytes)\n .map((byte: number): string => {\n return byte.toString(16).padStart(2, \"0\");\n })\n .join(\"\");\n}\n\nfunction isReplayId(value: unknown): value is string {\n return typeof value === \"string\" && REPLAY_ID_PATTERN.test(value);\n}\n\nfunction parseStoredSession(value: string | null): StoredSession | null {\n if (!value) {\n return null;\n }\n\n try {\n const parsed: unknown = JSON.parse(value);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return null;\n }\n\n const candidate: Partial<StoredSession> = parsed as Partial<StoredSession>;\n if (\n !isReplayId(candidate.sessionId) ||\n !Number.isSafeInteger(candidate.sessionStartUnixMs) ||\n !Number.isSafeInteger(candidate.lastActivityUnixMs) ||\n !Number.isSafeInteger(candidate.nextChunkIndex) ||\n (candidate.nextChunkIndex ?? -1) < 0\n ) {\n return null;\n }\n\n return candidate as StoredSession;\n } catch {\n return null;\n }\n}\n\nexport default class ReplaySessionStore {\n private readonly storage: ReplayStorage;\n private readonly sessionKey: string;\n private readonly visitorKey: string;\n private identity: ReplaySessionIdentity | null = null;\n /* When the session's last activity was, as the stored record says. */\n private lastActivityUnixMs: number = 0;\n\n public constructor(storage: ReplayStorage, namespace: string) {\n this.storage = storage;\n this.sessionKey = `@oneuptime/replay/${namespace}/session`;\n this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;\n }\n\n public async resolve(nowUnixMs: number): Promise<ReplaySessionIdentity> {\n const stored: StoredSession | null = parseStoredSession(\n await this.safeGet(this.sessionKey),\n );\n const shouldRotate: boolean =\n !stored ||\n stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION ||\n nowUnixMs - stored.lastActivityUnixMs >=\n SESSION_REPLAY_IDLE_ROLLOVER_MS ||\n nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;\n let session: StoredSession;\n if (shouldRotate || !stored) {\n session = {\n sessionId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: 0,\n };\n } else {\n session = {\n sessionId: stored.sessionId,\n sessionStartUnixMs: stored.sessionStartUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: stored.nextChunkIndex,\n };\n }\n\n let visitorId: string | null = await this.safeGet(this.visitorKey);\n if (!isReplayId(visitorId)) {\n visitorId = generateReplayId();\n await this.safeSet(this.visitorKey, visitorId);\n }\n\n await this.safeSet(this.sessionKey, JSON.stringify(session));\n this.identity = {\n sessionId: session.sessionId,\n tabId: generateReplayId(),\n visitorId,\n sessionStartUnixMs: session.sessionStartUnixMs,\n chunkIndex: session.nextChunkIndex,\n };\n this.lastActivityUnixMs = nowUnixMs;\n return { ...this.identity };\n }\n\n /*\n * The session a product analytics event belongs to while the replay\n * records nothing of it (an unsampled session, issue #6629): nothing else\n * moves the session then, so the event is its activity. The session\n * carries on, or - past the idle window or the longest a session lasts -\n * the next one starts, as resolve() would decide at the next launch.\n * Synchronous: decided in memory and written in the background, where a\n * failed write costs only a relaunch's resume. Null before resolve().\n */\n public continueSession(nowUnixMs: number): ReplaySessionIdentity | null {\n const identity: ReplaySessionIdentity | null = this.identity;\n\n if (!identity) {\n return null;\n }\n\n if (\n nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS ||\n nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS\n ) {\n identity.sessionId = generateReplayId();\n identity.tabId = generateReplayId();\n identity.sessionStartUnixMs = nowUnixMs;\n identity.chunkIndex = 0;\n }\n\n this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);\n const state: StoredSession = {\n sessionId: identity.sessionId,\n sessionStartUnixMs: identity.sessionStartUnixMs,\n lastActivityUnixMs: this.lastActivityUnixMs,\n nextChunkIndex: identity.chunkIndex,\n };\n void this.safeSet(this.sessionKey, JSON.stringify(state));\n return { ...identity };\n }\n\n public async takeChunkIndex(nowUnixMs: number): Promise<number> {\n if (!this.identity) {\n await this.resolve(nowUnixMs);\n }\n\n const identity: ReplaySessionIdentity = this\n .identity as ReplaySessionIdentity;\n const index: number = identity.chunkIndex;\n identity.chunkIndex += 1;\n this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);\n const state: StoredSession = {\n sessionId: identity.sessionId,\n sessionStartUnixMs: identity.sessionStartUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: identity.chunkIndex,\n };\n await this.safeSet(this.sessionKey, JSON.stringify(state));\n return index;\n }\n\n public getNextChunkIndex(): number | null {\n return this.identity?.chunkIndex ?? null;\n }\n\n public async rotate(nowUnixMs: number): Promise<ReplaySessionIdentity> {\n let visitorId: string | null = await this.safeGet(this.visitorKey);\n if (!isReplayId(visitorId)) {\n visitorId = generateReplayId();\n await this.safeSet(this.visitorKey, visitorId);\n }\n const session: StoredSession = {\n sessionId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: 0,\n };\n await this.safeSet(this.sessionKey, JSON.stringify(session));\n this.identity = {\n sessionId: session.sessionId,\n tabId: generateReplayId(),\n visitorId,\n sessionStartUnixMs: nowUnixMs,\n chunkIndex: 0,\n };\n this.lastActivityUnixMs = nowUnixMs;\n return { ...this.identity };\n }\n\n /*\n * Forget the stored session without starting the next one. A session\n * that ends while the recorder is paused for idle has no successor until\n * the person comes back, and its record - last written by its own final\n * chunk, so it looks recent - would otherwise let a relaunch in the\n * meantime carry on a session that is already over. The visitor id stays,\n * and so does the in-memory identity: nothing more is sent under it, and\n * the next rotate() writes the new session.\n */\n public async end(): Promise<void> {\n await this.safeRemove(this.sessionKey);\n }\n\n public async clear(): Promise<void> {\n this.identity = null;\n await Promise.all([\n this.safeRemove(this.sessionKey),\n this.safeRemove(this.visitorKey),\n ]);\n }\n\n private async safeGet(key: string): Promise<string | null> {\n try {\n return await this.storage.getItem(key);\n } catch {\n return null;\n }\n }\n\n private async safeSet(key: string, value: string): Promise<void> {\n try {\n await this.storage.setItem(key, value);\n } catch {\n /* Persistence failure must not throw into a customer application. */\n }\n }\n\n private async safeRemove(key: string): Promise<void> {\n try {\n await this.storage.removeItem(key);\n } catch {\n /* Best-effort storage cleanup. */\n }\n }\n}\n", "import { ReplayConnectivity, ReplayFetch, ReplayFetchResponse } from \"./Config\";\nimport { SessionReplayConsentState } from \"./Contract\";\nimport {\n PRODUCT_ANALYTICS_CONTENT_TYPE,\n PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS,\n PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS,\n PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH,\n PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH,\n PRODUCT_ANALYTICS_MAX_PENDING_EVENTS,\n PRODUCT_ANALYTICS_TARGET_BATCH_BYTES,\n PRODUCT_ANALYTICS_WIRE_VERSION,\n ProductAnalyticsEventKind,\n ProductAnalyticsRecorderConfig,\n ProductAnalyticsWireBatch,\n ProductAnalyticsWireContext,\n ProductAnalyticsWireEvent,\n ProductAnalyticsWireMetric,\n isProductAnalyticsMetricName,\n toProductAnalyticsEventName,\n} from \"./ProductAnalyticsContract\";\nimport RetryAfter from \"./RetryAfter\";\nimport { generateReplayId, ReplayStorage } from \"./Storage\";\n\n/*\n * Product analytics events from a React Native app (issue #6629): the\n * session's start, each screen it shows (a page view, named by the route\n * setRoute() was given), the app's track() events and its metric() points,\n * sent as small JSON batches to PRODUCT_ANALYTICS_EVENTS_PATH - the same\n * batches, limits and answers as the browser recorder's\n * (BrowserRecorder/src/ProductAnalytics.ts), from every session the\n * application's replay policy lets the recorder run in, recorded or not.\n *\n * A second, light channel beside the recording, not a second recorder: the\n * session, the visitor, consent and who signed in come from the replay\n * recorder (the host), so an event and a recording of the same visit carry\n * the same ids. What the host decides, this channel only asks about.\n *\n * Where it parts from the browser's, and why:\n *\n * - Every item it holds keeps the session and the person it happened\n * under, and a batch holds one session's and one person's items. A\n * phone holds items longer than a tab (offline, waiting for consent),\n * and a mobile session changes under them more often - a sign-in or a\n * sign-out starts a new one - so filing a batch under whoever is signed\n * in when it is sent would give one person's events to another.\n * - Before consent there is no session to name: the recorder's session is\n * a throwaway until the person agrees. Items are held unnamed, and the\n * grant files them, and the session's start ahead of them, under the\n * session the grant opens.\n * - Requests time out (a phone's connection can hang a request for\n * minutes), the device's own connectivity source and its return to the\n * foreground send what is held at once, and nothing is tried while the\n * device says it is offline.\n * - Which session the device last announced is kept in the app's storage,\n * not a browser's: a session that carries on across a relaunch (the\n * replay's own session store) is announced once.\n *\n * Property, attribute and user property values arrive masked, as the\n * recorder masks all text (the host's toProperties and traits): event\n * names, keys and metric values are sent as written.\n */\n\n/* How long a request may take before it is given up and tried again later. */\nexport const PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS: number = 10_000;\n\n/* The longest the recorder waits before trying a failed batch again. */\nexport const PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS: number = 5 * 60 * 1000;\n\nconst RETRY_AFTER_LIMIT_SECONDS: number = 300;\n\nconst REPLAY_ID_PATTERN: RegExp = /^[0-9a-f]{32}$/u;\n\n/* Where the device keeps the session it last announced, per namespace. */\nexport function productAnalyticsSessionKey(namespace: string): string {\n return `@oneuptime/replay/${namespace}/analytics-session`;\n}\n\n/* React Native's AppState, as the channel listens to it. */\nexport interface ProductAnalyticsAppState {\n currentState: string | null;\n addEventListener(\n type: \"change\",\n listener: (state: string) => void,\n ): { remove(): void };\n}\n\nexport interface ProductAnalyticsIdentity {\n /* \"\" while nobody is signed in, or the application captures no identity. */\n userRef: string;\n traits: Record<string, string> | null;\n}\n\nexport interface MobileProductAnalyticsHost {\n url: string;\n headers: Record<string, string>;\n fetch: ReplayFetch;\n now: () => number;\n storage: ReplayStorage;\n /* The replay's storage namespace (getReplayStorageNamespace). */\n namespace: string;\n appState?: ProductAnalyticsAppState | null | undefined;\n connectivity?: ReplayConnectivity | undefined;\n /*\n * The session an event that happens now belongs to - the event is\n * activity, so a session the replay does not record is kept alive or\n * rolled over by it. \"\" when there is none to name: before consent (the\n * items are then held until the grant names one), or when the recorder\n * has none at all.\n */\n getSessionId: (nowUnixMs: number) => string;\n /*\n * The same session, only looked at: the timer and the lifecycle look at\n * it without counting as activity, so an app nobody uses lets its\n * session go idle.\n */\n peekSessionId: () => string;\n /* The anonymous visitor's id; \"\" while there is none to send. */\n getVisitorId: () => string;\n getConsentState: () => SessionReplayConsentState;\n /* Whether the application's policy waits for an explicit consent. */\n requiresConsent: () => boolean;\n /* Who is signed in, and their traits, only with identity capture on. */\n getIdentity: () => ProductAnalyticsIdentity;\n /*\n * A track() call's properties or a metric() point's attributes as the\n * recorder keeps them: capped, and masked as it masks all text.\n */\n toProperties: (value: unknown) => Record<string, string>;\n /* The device type, system and app version the batches say. */\n getContext: () => ProductAnalyticsWireContext;\n onDiagnostic: (code: string, details?: Record<string, unknown>) => void;\n}\n\n/* Why the channel stopped, for the diagnostics. */\nexport type ProductAnalyticsStopReason =\n | \"stopped\"\n | \"not-enabled\"\n | \"refused\"\n | \"origin-not-allowed\";\n\nexport interface ProductAnalyticsDiagnostics {\n /* \"off\" when the application has them off, \"on\" while sent, else why they stopped. */\n state: \"off\" | \"on\" | ProductAnalyticsStopReason;\n pending: number;\n dropped: number;\n}\n\n/*\n * The session and the person an item happened under. sessionId is \"\" for\n * an item held before consent, until the grant names its session.\n */\ninterface ProductAnalyticsScope {\n sessionId: string;\n userRef: string;\n userProperties: Record<string, string> | null;\n}\n\ninterface HeldItem {\n scope: ProductAnalyticsScope;\n event?: ProductAnalyticsWireEvent;\n metric?: ProductAnalyticsWireMetric;\n}\n\nfunction itemAt(item: HeldItem): number {\n return item.event ? item.event.at : item.metric?.at ?? 0;\n}\n\nfunction sameScope(\n left: ProductAnalyticsScope,\n right: ProductAnalyticsScope,\n): boolean {\n return (\n left.sessionId === right.sessionId &&\n left.userRef === right.userRef &&\n JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties)\n );\n}\n\n/*\n * The traits an event may carry: those the application listed, matched as\n * written (Common's pickProductAnalyticsUserProperties, over traits the\n * recorder already capped and masked).\n */\nexport function pickProductAnalyticsUserProperties(\n traits: Record<string, string> | null,\n allowedKeys: ReadonlyArray<string>,\n): Record<string, string> {\n const picked: Record<string, string> = {};\n\n if (!traits) {\n return picked;\n }\n\n for (const key of allowedKeys) {\n if (\n Object.prototype.hasOwnProperty.call(traits, key) &&\n typeof traits[key] === \"string\"\n ) {\n picked[key] = traits[key] as string;\n }\n }\n\n return picked;\n}\n\nexport default class MobileProductAnalytics {\n private readonly host: MobileProductAnalyticsHost;\n private config: ProductAnalyticsRecorderConfig;\n\n private items: Array<HeldItem> = [];\n private eventCount: number = 0;\n private metricCount: number = 0;\n\n /*\n * The batch on its way, kept until the server says what became of it, so\n * a retry sends the same batch id and the server files it once.\n */\n private pending: ProductAnalyticsWireBatch | null = null;\n private sending: boolean = false;\n private sendGeneration: number = 0;\n private retryAtUnixMs: number = 0;\n private failures: number = 0;\n\n /* The session items are filed under now, and the screen shown in it. */\n private sessionId: string = \"\";\n private shownPage: string = \"\";\n /* The last screen the app named, in any session. */\n private route: string = \"\";\n /* The session this device last announced; null until read. */\n private announcedSessionId: string | null = null;\n\n private droppedEvents: number = 0;\n private started: boolean = false;\n private stopReason: ProductAnalyticsStopReason | null = null;\n private revoked: boolean = false;\n /* The connectivity source said the device is offline. */\n private offline: boolean = false;\n\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private appStateSubscription: { remove(): void } | null = null;\n private unsubscribeConnectivity: (() => void) | null = null;\n\n public constructor(\n host: MobileProductAnalyticsHost,\n config: ProductAnalyticsRecorderConfig,\n ) {\n this.host = host;\n this.config = config;\n }\n\n /*\n * Reads which session this device last announced, then starts: the\n * session's start (unless announced already), the timer, and the app's\n * lifecycle and connectivity. Items before this resolves are not taken.\n */\n public async start(): Promise<void> {\n if (this.started || this.stopReason) {\n return;\n }\n\n let stored: string | null = null;\n\n try {\n stored = await this.host.storage.getItem(\n productAnalyticsSessionKey(this.host.namespace),\n );\n } catch {\n stored = null;\n }\n\n if (this.started || this.stopReason) {\n return;\n }\n\n this.announcedSessionId =\n typeof stored === \"string\" && REPLAY_ID_PATTERN.test(stored)\n ? stored\n : null;\n this.started = true;\n this.enterCurrentSession(this.host.now(), false);\n\n this.flushTimer = setInterval((): void => {\n this.flush(false);\n }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);\n\n this.listenToLifecycle();\n\n this.host.onDiagnostic(\"analytics-started\", {\n userPropertyKeys: this.config.userPropertyKeys.length,\n });\n }\n\n /* A refreshed policy's keys; whether it waits for consent is asked live. */\n public setConfig(config: ProductAnalyticsRecorderConfig): void {\n this.config = config;\n }\n\n public isStarted(): boolean {\n return this.started && !this.stopReason;\n }\n\n public track(name: unknown, properties?: unknown): void {\n const eventName: string | null = toProductAnalyticsEventName(name);\n\n if (!eventName || !this.accepts()) {\n return;\n }\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope) {\n return;\n }\n\n const event: ProductAnalyticsWireEvent = {\n kind: ProductAnalyticsEventKind.Custom,\n name: eventName,\n at: now,\n properties: this.host.toProperties(properties),\n };\n\n if (this.shownPage) {\n event.page = this.shownPage;\n } else if (this.route) {\n event.page = this.route;\n }\n\n this.pushEvent(scope, event);\n }\n\n /*\n * A screen the app moved to (setRoute(), already scrubbed as the replay\n * keeps a route): a page view, unless it is the screen already shown in\n * this session.\n */\n public page(route: string): void {\n if (!route || !this.accepts()) {\n return;\n }\n\n this.route = route;\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope || route === this.shownPage) {\n return;\n }\n\n this.shownPage = route;\n this.pushEvent(scope, {\n kind: ProductAnalyticsEventKind.Page,\n name: route,\n at: now,\n page: route,\n });\n }\n\n /*\n * metric(name, value, attributes): a number the app measured\n * (\"cart.value\", 42.5), filed in the metric store under the RUM\n * application. A name outside the instrument-name shape, or in\n * OneUptime's own namespace, or a value that is not a finite number, is\n * refused here and says why in the diagnostics.\n */\n public metric(name: unknown, value: unknown, attributes?: unknown): void {\n if (!this.accepts()) {\n return;\n }\n\n if (!isProductAnalyticsMetricName(name)) {\n this.host.onDiagnostic(\"metric-name-refused\", {\n name: typeof name === \"string\" ? name.slice(0, 100) : typeof name,\n });\n return;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n this.host.onDiagnostic(\"metric-value-refused\", { name: name });\n return;\n }\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope) {\n return;\n }\n\n this.items.push({\n scope: scope,\n metric: {\n name: name,\n value: value,\n at: now,\n attributes: this.host.toProperties(attributes),\n },\n });\n this.metricCount++;\n\n /* Held too long (no consent, no network): the oldest go first. */\n if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {\n this.dropOldest(\"metric\");\n }\n\n if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {\n this.flush(false);\n }\n }\n\n /*\n * Send what is held. `final` is the app leaving the foreground: sent at\n * once, whatever a retry was waiting for, while the system still lets\n * the app use the network.\n */\n public flush(final: boolean): void {\n if (!this.started || this.stopReason || this.revoked || this.sending) {\n return;\n }\n\n if (this.isAwaitingConsent() || this.offline) {\n return;\n }\n\n const now: number = this.host.now();\n\n if (!final && now < this.retryAtUnixMs) {\n return;\n }\n\n if (!this.pending) {\n this.enterCurrentSession(now, false);\n this.pending = this.takeBatch(now);\n }\n\n const batch: ProductAnalyticsWireBatch | null = this.pending;\n\n if (!batch) {\n return;\n }\n\n this.send(batch);\n }\n\n /*\n * Consent withdrawn: everything held is dropped, the batch on its way\n * too, the session this device announced is forgotten, and nothing is\n * kept or sent until a new grant.\n */\n public forget(): void {\n this.revoked = true;\n this.clear();\n this.forgetAnnouncedSession();\n }\n\n /*\n * The policy now waits for a consent this run has not been given: what\n * was held, and the device's record, go as on a withdrawal, but what\n * happens from now on is held for the grant, as before any consent.\n */\n public reset(): void {\n this.clear();\n this.forgetAnnouncedSession();\n }\n\n /* Granted: what was held is filed under the session the grant opened, and goes now. */\n public onConsentGranted(): void {\n this.revoked = false;\n this.retryAtUnixMs = 0;\n this.enterCurrentSession(this.host.now(), false);\n this.flush(false);\n }\n\n /*\n * The recorder's session may have changed under the channel - a policy\n * refreshed, a session named after consent: what was held for it is\n * filed under it, and what can go, goes.\n */\n public refresh(): void {\n if (!this.accepts()) {\n return;\n }\n\n this.enterCurrentSession(this.host.now(), false);\n this.flush(false);\n }\n\n public stop(reason: ProductAnalyticsStopReason = \"stopped\"): void {\n if (!this.stopReason) {\n this.stopReason = reason;\n }\n\n this.clear();\n\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n const unsubscribe: (() => void) | null = this.unsubscribeConnectivity;\n this.unsubscribeConnectivity = null;\n\n try {\n unsubscribe?.();\n } catch {\n /* The host's unsubscribe must not break teardown. */\n }\n }\n\n public getStopReason(): ProductAnalyticsStopReason | null {\n return this.stopReason;\n }\n\n public getPendingCount(): number {\n return (\n this.items.length +\n (this.pending\n ? this.pending.events.length + this.pending.metrics.length\n : 0)\n );\n }\n\n public getDroppedEventCount(): number {\n return this.droppedEvents;\n }\n\n public getDiagnostics(): ProductAnalyticsDiagnostics {\n return {\n state: this.stopReason || \"on\",\n pending: this.getPendingCount(),\n dropped: this.droppedEvents,\n };\n }\n\n private accepts(): boolean {\n return this.started && !this.stopReason && !this.revoked;\n }\n\n private isAwaitingConsent(): boolean {\n return (\n this.host.requiresConsent() && this.host.getConsentState() !== \"Granted\"\n );\n }\n\n private clear(): void {\n this.items = [];\n this.eventCount = 0;\n this.metricCount = 0;\n this.pending = null;\n /* An answer still on its way belongs to nothing held any more. */\n this.sendGeneration++;\n this.sending = false;\n this.sessionId = \"\";\n this.shownPage = \"\";\n }\n\n private forgetAnnouncedSession(): void {\n this.announcedSessionId = null;\n void this.host.storage\n .removeItem(productAnalyticsSessionKey(this.host.namespace))\n .catch((): void => {\n /* Best-effort privacy cleanup. */\n });\n }\n\n private announce(sessionId: string): void {\n this.announcedSessionId = sessionId;\n void this.host.storage\n .setItem(productAnalyticsSessionKey(this.host.namespace), sessionId)\n .catch((): void => {\n /* Not kept: a relaunch may announce the session again. */\n });\n }\n\n private makeScope(sessionId: string): ProductAnalyticsScope {\n const identity: ProductAnalyticsIdentity = this.host.getIdentity();\n\n return {\n sessionId: sessionId,\n userRef: identity.userRef,\n userProperties: identity.userRef\n ? pickProductAnalyticsUserProperties(\n identity.traits,\n this.config.userPropertyKeys,\n )\n : null,\n };\n }\n\n /*\n * The scope of an item that happens now, or null when it has none to be\n * filed under (no session, and no consent being waited for).\n */\n private scopeNow(now: number): ProductAnalyticsScope | null {\n const sessionId: string = this.enterCurrentSession(now, true);\n\n if (sessionId) {\n return this.makeScope(sessionId);\n }\n\n return this.isAwaitingConsent() ? this.makeScope(\"\") : null;\n }\n\n /*\n * Follows the host's session: a new one starts with its start (once per\n * session on this device) and the screen the app shows, and items held\n * before consent are filed under the first session there is to name.\n * Returns the session, or \"\" when there is none to name. Only an item\n * that happens now is activity (isActivity); the timer only looks.\n */\n private enterCurrentSession(now: number, isActivity: boolean): string {\n const sessionId: string = isActivity\n ? this.host.getSessionId(now)\n : this.host.peekSessionId();\n\n if (!sessionId) {\n return \"\";\n }\n\n const firstUnnamed: number = this.items.findIndex(\n (item: HeldItem): boolean => {\n return item.scope.sessionId === \"\";\n },\n );\n\n if (sessionId === this.sessionId && firstUnnamed < 0) {\n return sessionId;\n }\n\n const isNewSession: boolean = sessionId !== this.sessionId;\n this.sessionId = sessionId;\n\n /*\n * What was held before consent: this session's, from its start. Their\n * screen views are this session's, so the screen is not shown again.\n */\n let startedAt: number = now;\n let startPage: string = this.route;\n let startScope: ProductAnalyticsScope = this.makeScope(sessionId);\n\n if (firstUnnamed >= 0) {\n const first: HeldItem = this.items[firstUnnamed] as HeldItem;\n\n startedAt = Math.min(now, itemAt(first));\n startPage = first.event?.page || this.route;\n startScope = { ...first.scope, sessionId: sessionId };\n\n for (const item of this.items) {\n if (item.scope.sessionId === \"\") {\n item.scope = { ...item.scope, sessionId: sessionId };\n }\n }\n } else if (isNewSession) {\n this.shownPage = \"\";\n }\n\n if (this.announcedSessionId !== sessionId) {\n const start: ProductAnalyticsWireEvent = {\n kind: ProductAnalyticsEventKind.Session,\n name: \"\",\n at: startedAt,\n };\n\n if (startPage) {\n start.page = startPage;\n }\n\n const item: HeldItem = { scope: startScope, event: start };\n\n if (firstUnnamed >= 0) {\n this.items.splice(firstUnnamed, 0, item);\n } else {\n this.items.push(item);\n }\n\n this.eventCount++;\n this.announce(sessionId);\n this.trimEvents();\n }\n\n /* The screen the app shows is this new session's first page view. */\n if (firstUnnamed < 0 && isNewSession && this.route) {\n this.shownPage = this.route;\n this.items.push({\n scope: this.makeScope(sessionId),\n event: {\n kind: ProductAnalyticsEventKind.Page,\n name: this.route,\n at: now,\n page: this.route,\n },\n });\n this.eventCount++;\n this.trimEvents();\n }\n\n return sessionId;\n }\n\n private pushEvent(\n scope: ProductAnalyticsScope,\n event: ProductAnalyticsWireEvent,\n ): void {\n this.items.push({ scope: scope, event: event });\n this.eventCount++;\n this.trimEvents();\n\n if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {\n this.flush(false);\n }\n }\n\n /* Held too long (no consent, no network): the oldest go first, counted. */\n private trimEvents(): void {\n while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {\n this.dropOldest(\"event\");\n this.droppedEvents++;\n }\n }\n\n private dropOldest(kind: \"event\" | \"metric\"): void {\n const index: number = this.items.findIndex((item: HeldItem): boolean => {\n return kind === \"event\" ? Boolean(item.event) : Boolean(item.metric);\n });\n\n if (index < 0) {\n return;\n }\n\n this.items.splice(index, 1);\n\n if (kind === \"event\") {\n this.eventCount--;\n } else {\n this.metricCount--;\n }\n }\n\n /*\n * The next batch: the oldest items of one session and one person, up to\n * the per-batch counts and the target size. Items the server would drop\n * for their age are dropped here instead.\n */\n private takeBatch(now: number): ProductAnalyticsWireBatch | null {\n this.dropTooOld(now);\n\n const first: HeldItem | undefined = this.items[0];\n\n if (!first || first.scope.sessionId === \"\") {\n return null;\n }\n\n const scope: ProductAnalyticsScope = first.scope;\n let count: number = 0;\n let events: number = 0;\n let metrics: number = 0;\n\n for (const item of this.items) {\n if (!sameScope(item.scope, scope)) {\n break;\n }\n\n if (item.event) {\n if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {\n break;\n }\n\n events++;\n } else {\n if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {\n break;\n }\n\n metrics++;\n }\n\n count++;\n }\n\n const build: (taken: number) => ProductAnalyticsWireBatch = (\n taken: number,\n ): ProductAnalyticsWireBatch => {\n const slice: Array<HeldItem> = this.items.slice(0, taken);\n const batch: ProductAnalyticsWireBatch = {\n v: PRODUCT_ANALYTICS_WIRE_VERSION,\n batchId: generateReplayId(),\n sessionId: scope.sessionId,\n visitorId: this.host.getVisitorId(),\n consentState: this.host.getConsentState(),\n sentAt: now,\n context: this.host.getContext(),\n events: slice\n .filter((item: HeldItem): boolean => {\n return Boolean(item.event);\n })\n .map((item: HeldItem): ProductAnalyticsWireEvent => {\n return item.event as ProductAnalyticsWireEvent;\n }),\n metrics: slice\n .filter((item: HeldItem): boolean => {\n return Boolean(item.metric);\n })\n .map((item: HeldItem): ProductAnalyticsWireMetric => {\n return item.metric as ProductAnalyticsWireMetric;\n }),\n };\n\n if (scope.userRef) {\n batch.userRef = scope.userRef;\n batch.userProperties = scope.userProperties || {};\n }\n\n return batch;\n };\n\n let batch: ProductAnalyticsWireBatch = build(count);\n\n /* Halve until it fits; one item always does (its parts are capped). */\n while (\n JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES &&\n count > 1\n ) {\n count = Math.floor(count / 2);\n batch = build(count);\n }\n\n this.items.splice(0, count);\n this.eventCount -= batch.events.length;\n this.metricCount -= batch.metrics.length;\n\n return batch;\n }\n\n private dropTooOld(now: number): void {\n const oldest: number = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;\n const kept: Array<HeldItem> = [];\n\n for (const item of this.items) {\n if (itemAt(item) >= oldest) {\n kept.push(item);\n continue;\n }\n\n if (item.event) {\n this.eventCount--;\n this.droppedEvents++;\n } else {\n this.metricCount--;\n }\n }\n\n this.items = kept;\n }\n\n private send(batch: ProductAnalyticsWireBatch): void {\n const generation: number = this.sendGeneration;\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n const init: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"POST\",\n headers: {\n ...this.host.headers,\n \"Content-Type\": PRODUCT_ANALYTICS_CONTENT_TYPE,\n },\n body: JSON.stringify(batch),\n };\n\n if (controller) {\n init.signal = controller.signal;\n }\n\n let request: Promise<ReplayFetchResponse>;\n\n try {\n request = this.host.fetch(this.host.url, init);\n } catch {\n this.retryLater(this.host.now(), 0);\n return;\n }\n\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n timeout = setTimeout((): void => {\n controller?.abort();\n reject(new Error(\"analytics-request-timeout\"));\n }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);\n },\n );\n\n this.sending = true;\n\n Promise.race([request, deadline])\n .then((response: ReplayFetchResponse): void => {\n if (generation !== this.sendGeneration) {\n return;\n }\n\n this.sending = false;\n this.onAnswer(response, this.host.now());\n })\n .catch((): void => {\n if (generation !== this.sendGeneration) {\n return;\n }\n\n this.sending = false;\n this.retryLater(this.host.now(), 0);\n })\n .finally((): void => {\n if (timeout) {\n clearTimeout(timeout);\n }\n });\n }\n\n private onAnswer(response: ReplayFetchResponse, now: number): void {\n const status: number = response.status;\n\n if (status === 202 || status === 200) {\n this.pending = null;\n this.failures = 0;\n\n if (this.items.length > 0) {\n this.flush(false);\n }\n\n return;\n }\n\n if (status === 413) {\n /* Never sendable; the next batch is smaller. */\n this.pending = null;\n return;\n }\n\n if (status === 204 || status === 400 || status === 403) {\n let reason: string = \"\";\n\n try {\n reason = response.headers?.get(\"x-oneuptime-replay-reason\") || \"\";\n } catch {\n reason = \"\";\n }\n\n this.host.onDiagnostic(\"analytics-stopped\", {\n status: status,\n reason: reason.slice(0, 100),\n });\n\n this.stop(\n status === 403\n ? \"origin-not-allowed\"\n : status === 204\n ? \"not-enabled\"\n : \"refused\",\n );\n return;\n }\n\n /*\n * A 429's or a 503's Retry-After, as RFC 9110 writes it (RetryAfter):\n * whole seconds or an HTTP date, from one second to\n * RETRY_AFTER_LIMIT_SECONDS. Anything else is none, and the doubling\n * applies.\n */\n const retryAfterMs: number =\n status === 429 || status === 503\n ? RetryAfter.msFromHeaders(response.headers, {\n maxMs: RETRY_AFTER_LIMIT_SECONDS * 1000,\n nowMs: now,\n }) ?? 0\n : 0;\n\n /* 409 (consent not given), 429, 5xx: the same batch later. */\n this.retryLater(now, retryAfterMs);\n }\n\n private retryLater(now: number, delayMs: number): void {\n this.failures++;\n this.retryAtUnixMs =\n now +\n (delayMs > 0\n ? delayMs\n : Math.min(\n PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,\n PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures),\n ));\n }\n\n /*\n * The app leaving the foreground sends what is held while it still can;\n * coming back, or the device saying it is online again, sends a batch\n * that waited at once, rather than when its retry was due.\n */\n private listenToLifecycle(): void {\n const appState: ProductAnalyticsAppState | null | undefined =\n this.host.appState;\n\n if (appState && typeof appState.addEventListener === \"function\") {\n try {\n this.appStateSubscription = appState.addEventListener(\n \"change\",\n (state: string): void => {\n if (state === \"active\") {\n this.retryAtUnixMs = 0;\n this.flush(false);\n return;\n }\n\n this.flush(true);\n },\n );\n } catch {\n this.appStateSubscription = null;\n }\n }\n\n const connectivity: ReplayConnectivity | undefined = this.host.connectivity;\n\n if (!connectivity) {\n return;\n }\n\n try {\n const unsubscribe: unknown = connectivity.subscribe(\n (isConnected: boolean | null): void => {\n if (isConnected === false) {\n this.offline = true;\n return;\n }\n\n if (isConnected === true) {\n const wasOffline: boolean = this.offline;\n this.offline = false;\n\n if (wasOffline) {\n this.retryAtUnixMs = 0;\n this.flush(false);\n }\n }\n },\n );\n\n this.unsubscribeConnectivity =\n typeof unsubscribe === \"function\" ? (unsubscribe as () => void) : null;\n } catch {\n /* A throwing connectivity source only costs the early send. */\n this.unsubscribeConnectivity = null;\n }\n }\n}\n", "import { gzipSync, strToU8 } from \"fflate\";\nimport {\n CHUNK_PATH,\n encodeSessionReplayEnvelopeLine,\n MAX_SESSION_REPLAY_CHUNK_BYTES,\n SESSION_REPLAY_CONTENT_TYPE,\n SessionReplayChunkEnvelope,\n SessionReplayChunkResponse,\n SessionReplayDirective,\n} from \"./Contract\";\nimport {\n mobileRequestHeaders,\n ReplayFetch,\n ReplayFetchResponse,\n ValidatedStartOptions,\n} from \"./Config\";\nimport ReplayOutbox, {\n frameId,\n OutboxEntry,\n OutboxMutationResult,\n StoredReplayFrame,\n} from \"./Outbox\";\nimport RetryAfter from \"./RetryAfter\";\n\n/*\n * Attempts a frame gets against a server that ANSWERS and fails (a 5xx with\n * no Retry-After). Offline mode's rule is that nothing else costs an\n * attempt: a request that never reached the server is the device's\n * connection, and a throttle is the server asking for patience. Counting\n * either dropped a frame after three tries fifteen seconds apart - under a\n * minute of any outage lost everything recorded during it.\n */\nconst MAX_ATTEMPTS_PER_FRAME: number = 3;\nconst DEFAULT_RETRY_MS: number = 15_000;\nconst MAX_RETRY_MS: number = 5 * 60_000;\nexport const CHUNK_POST_TIMEOUT_MS: number = 10_000;\n\n/*\n * Waits after a request that never reached the server: short while a drop\n * is likely brief, then a minute for as long as it lasts. The app coming\n * to the foreground, and a connectivity source saying the network is back\n * (see MobileReplayStartOptions.connectivity), drain at once instead.\n */\nexport const OFFLINE_RETRY_MS: Array<number> = [5_000, 15_000, 30_000, 60_000];\nconst DIRECTIVE_REASON_PATTERN: RegExp = /^[A-Za-z0-9_.:-]{1,100}$/u;\n\nexport interface ReplayTransportOptions {\n startOptions: ValidatedStartOptions;\n outbox: ReplayOutbox;\n onDirective: (\n directive: SessionReplayDirective,\n reason: string | null,\n ) => void;\n onDiagnostic: (code: string, details?: Record<string, unknown>) => void;\n}\n\nexport interface EncodedReplayFrame {\n envelope: SessionReplayChunkEnvelope;\n body: Uint8Array;\n}\n\nexport function encodeReplayFrame(\n originalEnvelope: SessionReplayChunkEnvelope,\n payload: string,\n): EncodedReplayFrame {\n return encodeCompressedReplayFrame(\n originalEnvelope,\n gzipSync(strToU8(payload)),\n );\n}\n\n/*\n * The same frame from a payload the outbox already stores gzip-compressed.\n * clientSendUnixMs is stamped here, as the request is built: a frame that\n * waited out an outage tells the server how long it waited, which is what\n * keeps a recording uploaded hours late on its real timeline.\n */\nexport function encodeCompressedReplayFrame(\n originalEnvelope: SessionReplayChunkEnvelope,\n compressed: Uint8Array,\n): EncodedReplayFrame {\n const envelope: SessionReplayChunkEnvelope = {\n ...originalEnvelope,\n payloadEncoding: \"gzip\",\n payloadBytes: compressed.byteLength,\n clientSendUnixMs: Date.now(),\n };\n const prefix: Uint8Array = strToU8(encodeSessionReplayEnvelopeLine(envelope));\n const body: Uint8Array = new Uint8Array(\n prefix.byteLength + compressed.byteLength,\n );\n body.set(prefix, 0);\n body.set(compressed, prefix.byteLength);\n return { envelope, body };\n}\n\ninterface ParsedDirective {\n directive: SessionReplayDirective | null;\n reason: string | null;\n retryAfterSeconds: number | null;\n}\n\nfunction safeReason(value: unknown): string | null {\n return typeof value === \"string\" && DIRECTIVE_REASON_PATTERN.test(value)\n ? value\n : null;\n}\n\nfunction parseDirectiveValue(value: unknown): SessionReplayDirective | null {\n return value === \"continue\" || value === \"stop\" || value === \"throttle\"\n ? value\n : null;\n}\n\nasync function readDirective(\n response: ReplayFetchResponse,\n): Promise<ParsedDirective> {\n if (response.status === 204) {\n return {\n directive: parseDirectiveValue(\n response.headers?.get(\"x-oneuptime-replay-directive\"),\n ),\n reason: safeReason(response.headers?.get(\"x-oneuptime-replay-reason\")),\n retryAfterSeconds: parseRetryAfter(\n response.headers?.get(\"retry-after\") ?? null,\n ),\n };\n }\n\n try {\n const value: unknown = await response.json();\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return { directive: null, reason: null, retryAfterSeconds: null };\n }\n\n const body: Partial<SessionReplayChunkResponse> & { error?: unknown } =\n value as Partial<SessionReplayChunkResponse> & { error?: unknown };\n return {\n directive: parseDirectiveValue(body.directive),\n reason: safeReason(body.reason) ?? safeReason(body.error),\n retryAfterSeconds:\n typeof body.retryAfterSeconds === \"number\" &&\n Number.isFinite(body.retryAfterSeconds)\n ? Math.max(0, Math.min(300, body.retryAfterSeconds))\n : parseRetryAfter(response.headers?.get(\"retry-after\") ?? null),\n };\n } catch {\n return {\n directive: null,\n reason: null,\n retryAfterSeconds: parseRetryAfter(\n response.headers?.get(\"retry-after\") ?? null,\n ),\n };\n }\n}\n\n/*\n * Retry-After as RFC 9110 writes it (src/RetryAfter.ts, a copy of Common's):\n * whole seconds or an HTTP-date, from one second to 300. Null for anything\n * else, so the default wait applies: Number() read \"1.5\" as a second and a\n * half and \"\" or \" \" as 0 - a retry at once, and a server that kept\n * answering so was asked again in a loop.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n return RetryAfter.parseSeconds(value, { maxMs: 300 * 1000 }) ?? null;\n}\n\ntype PostOutcome = \"remove\" | \"remove-and-halt\" | \"retry\" | \"wait\" | \"stop\";\n\nexport default class ReplayTransport {\n private readonly options: ReplayTransportOptions;\n private readonly fetch: ReplayFetch;\n private drainPromise: Promise<void> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private stopped: boolean = false;\n private flushFailures: number = 0;\n private retryAfterDrainMs: number | null = null;\n private activeAbortController: AbortController | null = null;\n private abortCurrentRequest: (() => void) | null = null;\n\n /* Requests in a row that never reached the server. */\n private connectivityFailures: number = 0;\n\n /* What the host app's connectivity source last said, if it has one. */\n private reportedOffline: boolean = false;\n\n public constructor(options: ReplayTransportOptions) {\n this.options = options;\n this.fetch = options.startOptions.fetch;\n }\n\n /*\n * Offline, as far as uploading goes: the host app's connectivity source\n * says so, or the last request never reached the server.\n */\n public isOffline(): boolean {\n return this.reportedOffline || this.connectivityFailures > 0;\n }\n\n /*\n * The host app's connectivity source changed (NetInfo, typically). While\n * it says offline nothing is attempted. Coming back does NOT drain on its\n * own: whether this recorder may upload right now (consent) is the\n * recorder's decision, so it calls resume() itself. null means \"unknown\",\n * which blocks nothing.\n */\n public setConnectivity(isConnected: boolean | null): void {\n this.reportedOffline = isConnected === false;\n }\n\n /*\n * Drain now rather than on the retry timer: the app came to the\n * foreground, or the network came back. An offline wait ends; a server\n * throttle still stands.\n */\n public resume(): void {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n\n if (this.connectivityFailures > 0 && this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n\n if (!this.retryTimer) {\n void this.drain();\n }\n }\n\n public async enqueue(\n envelope: SessionReplayChunkEnvelope,\n payload: string,\n ): Promise<void> {\n if (this.stopped) {\n return;\n }\n\n const mutation: OutboxMutationResult = await this.options.outbox.enqueue({\n id: frameId(envelope),\n envelope,\n payload,\n attempts: 0,\n createdAtUnixMs: Date.now(),\n });\n if (mutation.dropped > 0) {\n this.options.onDiagnostic(\"outbox-overflow\", {\n dropped: mutation.dropped,\n });\n }\n\n /*\n * Stored either way; posted now only when no retry is pending. A frame\n * closes every 15 s, and posting each one into an outage, or into a\n * throttle the server asked for, is a request on the user's battery the\n * retry timer was about to make anyway.\n */\n if (!this.retryTimer) {\n await this.drain();\n }\n }\n\n public async restore(): Promise<void> {\n await this.drain();\n }\n\n public async drain(): Promise<void> {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n if (this.drainPromise) {\n return await this.drainPromise;\n }\n\n this.drainPromise = this.drainLoop().finally((): void => {\n this.drainPromise = null;\n if (this.retryAfterDrainMs !== null) {\n const delayMs: number = this.retryAfterDrainMs;\n this.retryAfterDrainMs = null;\n this.scheduleRetry(delayMs);\n }\n });\n return await this.drainPromise;\n }\n\n public destroy(): void {\n this.stopped = true;\n this.activeAbortController?.abort();\n this.abortCurrentRequest?.();\n if (this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n }\n\n public getFlushFailures(): number {\n return this.flushFailures;\n }\n\n private async drainLoop(): Promise<void> {\n /*\n * Index entries only; each frame's payload is read as it is posted, so a\n * long offline backlog is never all in memory at once.\n */\n const entries: Array<OutboxEntry> = await this.options.outbox.entries();\n for (const entry of entries) {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n\n const frame: StoredReplayFrame | \"unreadable\" | null =\n await this.options.outbox.load(entry.id);\n if (frame === \"unreadable\") {\n this.options.onDiagnostic(\"outbox-frame-unreadable\");\n continue;\n }\n if (!frame) {\n continue;\n }\n\n const outcome: PostOutcome = await this.post(frame);\n if (outcome === \"remove\") {\n await this.options.outbox.remove(frame.id);\n continue;\n }\n if (outcome === \"remove-and-halt\") {\n await this.options.outbox.remove(frame.id);\n return;\n }\n if (outcome === \"stop\") {\n return;\n }\n\n this.flushFailures += 1;\n if (outcome === \"wait\") {\n /* Offline or throttled: the frame keeps its place and its attempts. */\n return;\n }\n\n const attempts: number = await this.options.outbox.incrementAttempts(\n frame.id,\n );\n if (attempts >= MAX_ATTEMPTS_PER_FRAME) {\n await this.options.outbox.remove(frame.id);\n this.options.onDiagnostic(\"chunk-retry-exhausted\", {\n chunkIndex: frame.envelope.chunkIndex,\n });\n continue;\n }\n\n if (this.retryAfterDrainMs === null) {\n this.retryAfterDrainMs = DEFAULT_RETRY_MS;\n }\n return;\n }\n }\n\n private async post(frame: StoredReplayFrame): Promise<PostOutcome> {\n const encoded: EncodedReplayFrame = encodeCompressedReplayFrame(\n frame.envelope,\n frame.compressedPayload,\n );\n if (encoded.body.byteLength > MAX_SESSION_REPLAY_CHUNK_BYTES) {\n this.options.onDiagnostic(\"chunk-too-large\", {\n chunkIndex: frame.envelope.chunkIndex,\n bytes: encoded.body.byteLength,\n });\n return \"remove\";\n }\n\n let response: ReplayFetchResponse;\n let said: ParsedDirective;\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n this.activeAbortController = controller;\n let timedOut: boolean = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let abortDeadline: (() => void) | null = null;\n try {\n const request: Promise<{\n response: ReplayFetchResponse;\n said: ParsedDirective;\n }> = (async (): Promise<{\n response: ReplayFetchResponse;\n said: ParsedDirective;\n }> => {\n const requestInit: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"POST\",\n headers: {\n ...mobileRequestHeaders(this.options.startOptions),\n \"Content-Type\": SESSION_REPLAY_CONTENT_TYPE,\n },\n body: encoded.body,\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n const fetched: ReplayFetchResponse = await this.fetch(\n `${this.options.startOptions.host}${CHUNK_PATH}`,\n requestInit,\n );\n return { response: fetched, said: await readDirective(fetched) };\n })();\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n abortDeadline = (): void => {\n controller?.abort();\n reject(new Error(\"chunk-post-aborted\"));\n };\n this.abortCurrentRequest = abortDeadline;\n timeout = setTimeout((): void => {\n timedOut = true;\n abortDeadline?.();\n }, CHUNK_POST_TIMEOUT_MS);\n },\n );\n ({ response, said } = await Promise.race([request, deadline]));\n } catch {\n if (this.stopped) {\n return \"stop\";\n }\n this.options.onDiagnostic(\n timedOut ? \"chunk-post-timeout\" : \"chunk-network-failure\",\n {\n chunkIndex: frame.envelope.chunkIndex,\n },\n );\n\n /*\n * The request never reached the server: the device is offline, or on\n * a connection that goes nowhere. Not a failure of the frame - it\n * waits, with no attempt counted, for as long as the outage lasts.\n */\n this.connectivityFailures += 1;\n this.retryAfterDrainMs =\n OFFLINE_RETRY_MS[\n Math.min(this.connectivityFailures, OFFLINE_RETRY_MS.length) - 1\n ]!;\n return \"wait\";\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (this.activeAbortController === controller) {\n this.activeAbortController = null;\n }\n if (this.abortCurrentRequest === abortDeadline) {\n this.abortCurrentRequest = null;\n }\n }\n\n /* Any answer at all: the connection is back. */\n if (this.connectivityFailures > 0) {\n this.connectivityFailures = 0;\n this.options.onDiagnostic(\"back-online\");\n }\n\n if (said.directive) {\n this.options.onDirective(said.directive, said.reason);\n }\n\n if (said.directive === \"stop\") {\n this.stopped = true;\n await this.options.outbox.clear();\n return \"stop\";\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (said.directive === \"throttle\") {\n this.retryAfterDrainMs = Math.min(\n MAX_RETRY_MS,\n (said.retryAfterSeconds ?? DEFAULT_RETRY_MS / 1_000) * 1_000,\n );\n return \"remove-and-halt\";\n }\n return \"remove\";\n }\n\n if (\n response.status === 400 ||\n response.status === 413 ||\n response.status === 422\n ) {\n this.options.onDiagnostic(\"chunk-refused\", {\n status: response.status,\n chunkIndex: frame.envelope.chunkIndex,\n reason: said.reason,\n });\n return \"remove\";\n }\n\n if (\n response.status === 401 ||\n response.status === 403 ||\n response.status === 404\n ) {\n this.options.onDiagnostic(\"transport-disabled\", {\n status: response.status,\n reason: said.reason,\n });\n this.options.onDirective(\"stop\", said.reason ?? \"transport-disabled\");\n this.stopped = true;\n await this.options.outbox.clear();\n return \"stop\";\n }\n\n const retryMs: number = Math.min(\n MAX_RETRY_MS,\n (said.retryAfterSeconds ?? DEFAULT_RETRY_MS / 1_000) * 1_000,\n );\n this.retryAfterDrainMs = retryMs;\n\n /*\n * A 429, or any answer that says when to come back (a throttle directive\n * or a Retry-After): the server asking for patience, which costs the\n * frame nothing. A whole fleet reconnecting at once after an outage is\n * exactly when the project's per-minute rate is spent.\n */\n if (\n response.status === 429 ||\n said.directive === \"throttle\" ||\n said.retryAfterSeconds !== null\n ) {\n return \"wait\";\n }\n\n return \"retry\";\n }\n\n private scheduleRetry(delayMs: number): void {\n if (this.retryTimer || this.stopped) {\n return;\n }\n\n this.retryTimer = setTimeout(\n (): void => {\n this.retryTimer = null;\n void this.drain();\n },\n Math.max(0, delayMs),\n );\n }\n}\n", "import { NativeViewTreeNode } from \"./NativeViewTree\";\n\nconst MAX_PRIVACY_TREE_NODES: number = 5_000;\nconst OPAQUE_KINDS: ReadonlySet<string> = new Set<string>([\n \"image\",\n \"webview\",\n \"canvas\",\n \"masked\",\n]);\n\nexport interface OpaqueTouchRegion {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\nexport interface TouchPrivacyMap {\n regions: Array<OpaqueTouchRegion>;\n suppressAll: boolean;\n}\n\nexport const CONSERVATIVE_TOUCH_PRIVACY_MAP: TouchPrivacyMap = {\n regions: [],\n suppressAll: true,\n};\n\nfunction finite(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\nexport function deriveTouchPrivacyMap(\n root: NativeViewTreeNode,\n): TouchPrivacyMap {\n const regions: Array<OpaqueTouchRegion> = [];\n const hasRootOrigin: boolean =\n finite(root.touchOriginX) && finite(root.touchOriginY);\n const rootX: number = hasRootOrigin ? (root.touchOriginX as number) : 0;\n const rootY: number = hasRootOrigin ? (root.touchOriginY as number) : 0;\n let suppressAll: boolean =\n finite(root.truncatedNodes) && root.truncatedNodes > 0;\n let visited: number = 0;\n\n const visit: (\n node: NativeViewTreeNode,\n parentX: number,\n parentY: number,\n alignedPath: boolean,\n isRoot: boolean,\n ) => void = (\n node: NativeViewTreeNode,\n parentX: number,\n parentY: number,\n alignedPath: boolean,\n isRoot: boolean,\n ): void => {\n if (visited >= MAX_PRIVACY_TREE_NODES) {\n suppressAll = true;\n return;\n }\n visited += 1;\n\n const hasGeometry: boolean =\n finite(node.x) &&\n finite(node.y) &&\n finite(node.width) &&\n finite(node.height);\n const left: number = isRoot\n ? parentX\n : parentX + (finite(node.x) ? node.x : 0);\n const top: number = isRoot\n ? parentY\n : parentY + (finite(node.y) ? node.y : 0);\n const pathIsAligned: boolean = alignedPath && hasGeometry;\n const opaque: boolean =\n node.masked === true ||\n node.opaque === true ||\n OPAQUE_KINDS.has(typeof node.kind === \"string\" ? node.kind : \"\");\n\n if (opaque) {\n if (!pathIsAligned || !hasRootOrigin) {\n suppressAll = true;\n return;\n }\n if ((node.width as number) > 0 && (node.height as number) > 0) {\n regions.push({\n left,\n top,\n right: left + (node.width as number),\n bottom: top + (node.height as number),\n });\n }\n return;\n }\n\n if (Array.isArray(node.children)) {\n for (const child of node.children) {\n if (child && typeof child === \"object\") {\n visit(child, left, top, pathIsAligned, false);\n }\n }\n }\n };\n\n visit(root, rootX, rootY, hasRootOrigin, true);\n return { regions, suppressAll };\n}\n\nexport function isTouchPrivate(\n privacyMap: TouchPrivacyMap,\n x: number,\n y: number,\n): boolean {\n if (privacyMap.suppressAll || !finite(x) || !finite(y)) {\n return true;\n }\n return privacyMap.regions.some((region: OpaqueTouchRegion): boolean => {\n return (\n x >= region.left &&\n x <= region.right &&\n y >= region.top &&\n y <= region.bottom\n );\n });\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAOO;AACP,IAAAA,uBAMO;;;ACdP,IAAAC,uBAAmC;;;ACO5B,IAAM,8BAAsC;AAC5C,IAAM,gCAAwC;AAO9C,IAAM,8BAAsC;AAW5C,IAAM,qCAA6C;AAE1D,IAAM,oBAA4B;AAE3B,SAAS,wBAAwB,MAAsB;AAC5D,SAAO,KAAK;AAAA,IACV;AAAA,IACA,CAAC,OAAe,SAAqC;AACnD,UAAI,SAAS,QAAW;AACtB,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AA,MACtB;AAAA,MACA,YAAY,CAAC,UAAuC;AAClD,eAAO,OAAO,KAAK;AAAA,MACrB;AAAA,MAEC,gBAAM;AAAA;AAAA,EACT,GACF;AAEJ;AAEO,SAAS,qBAA2C;AACzD,aAAO,yBAAW,aAAa;AACjC;AAQO,SAAS,WAAW,OAAsC;AAC/D,SACE;AAAA,IAAC;AAAA;AAAA,MACC,aAAa;AAAA,MACb,UAAS;AAAA,MACT,QAAO;AAAA,MACP,OAAO,MAAM;AAAA,MAEZ,gBAAM;AAAA;AAAA,EACT;AAEJ;AAEO,IAAM,iBACX;;;ADxHK,IAAM,kBACX;AAEF,IAAO,gBAAQ;",
6
- "names": ["import_react_native", "import_react_native", "SessionReplayMaskingMode", "SessionReplayConsentMode", "SessionReplayCaptureTrigger", "SessionReplayTriggerReason", "SessionReplayFidelityNotice", "CONTROL_CHARACTER_PATTERN", "x", "x", "i", "l", "i", "i2", "_a", "_b", "i", "i", "i", "_a", "bits", "AsyncStorage", "REPLAY_ID_PATTERN", "batch", "x", "safeReason", "suppressed", "x"]
4
+ "sourcesContent": ["import MobileReplayRecorder from \"./MobileReplayRecorder\";\nimport { defaultMobileReplayRecorder } from \"./ReplayProvider\";\n\nexport { default as MobileReplayRecorder } from \"./MobileReplayRecorder\";\nexport type {\n MobileReplayDiagnosticEvent,\n MobileReplayDiagnostics,\n MobileReplayRecorderDependencies,\n MobileReplaySessionChangeListener,\n MobileReplayStatus,\n} from \"./MobileReplayRecorder\";\nexport type {\n MobileReplayStartOptions,\n ReplayFetch,\n ReplayFetchResponse,\n} from \"./Config\";\nexport type {\n ProductAnalyticsDiagnostics,\n ProductAnalyticsStopReason,\n} from \"./ProductAnalytics\";\nexport {\n OneUptimeReplayProvider,\n ReplayMask,\n ReplayProvider,\n useOneUptimeReplay,\n} from \"./ReplayProvider\";\nexport type {\n OneUptimeReplayProviderProps,\n ReplayMaskProps,\n} from \"./ReplayProvider\";\nexport type { RecordedTouch, TouchPhase } from \"./Events\";\nexport {\n MOBILE_RECORDER_KIND,\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n SessionReplayCaptureTrigger,\n SessionReplayConsentMode,\n SessionReplayFidelityNotice,\n SessionReplayMaskingMode,\n SessionReplayTriggerReason,\n} from \"./Contract\";\n\n/** Process-wide convenience client used by ReplayProvider by default. */\nexport const OneUptimeReplay: MobileReplayRecorder =\n defaultMobileReplayRecorder;\n\nexport default OneUptimeReplay;\n", "import React, {\n createContext,\n ReactElement,\n ReactNode,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport {\n findNodeHandle,\n GestureResponderEvent,\n StyleProp,\n View,\n ViewStyle,\n} from \"react-native\";\nimport { MobileReplayStartOptions } from \"./Config\";\nimport { RecordedTouch } from \"./Events\";\nimport MobileReplayRecorder from \"./MobileReplayRecorder\";\n\nexport const defaultMobileReplayRecorder: MobileReplayRecorder =\n new MobileReplayRecorder();\n\nconst ReplayContext: React.Context<MobileReplayRecorder> =\n createContext<MobileReplayRecorder>(defaultMobileReplayRecorder);\n\nexport interface OneUptimeReplayProviderProps {\n children: ReactNode;\n recorder?: MobileReplayRecorder;\n /** Optional convenience start; callers may instead call recorder.start(). */\n options?: MobileReplayStartOptions;\n stopOnUnmount?: boolean;\n style?: StyleProp<ViewStyle>;\n}\n\nexport interface GestureTouchPoint {\n x: number;\n y: number;\n}\n\nexport function touchPointFromEvent(\n event: GestureResponderEvent,\n): GestureTouchPoint {\n const nativeEvent: GestureResponderEvent[\"nativeEvent\"] = event.nativeEvent;\n const x: number =\n typeof nativeEvent.pageX === \"number\"\n ? nativeEvent.pageX\n : typeof nativeEvent.locationX === \"number\"\n ? nativeEvent.locationX\n : 0;\n const y: number =\n typeof nativeEvent.pageY === \"number\"\n ? nativeEvent.pageY\n : typeof nativeEvent.locationY === \"number\"\n ? nativeEvent.locationY\n : 0;\n return {\n x: Number.isFinite(x) ? x : 0,\n y: Number.isFinite(y) ? y : 0,\n };\n}\n\nexport function OneUptimeReplayProvider(\n props: OneUptimeReplayProviderProps,\n): ReactElement {\n const recorder: MobileReplayRecorder =\n props.recorder ?? defaultMobileReplayRecorder;\n const rootRef: React.RefObject<View | null> = useRef<View>(null);\n const initialOptions: React.MutableRefObject<\n MobileReplayStartOptions | undefined\n > = useRef(props.options);\n\n useEffect((): (() => void) => {\n const tag: number | null = findNodeHandle(rootRef.current);\n recorder.setRootTag(tag);\n if (initialOptions.current) {\n void recorder.start(initialOptions.current);\n }\n\n return (): void => {\n recorder.setRootTag(null);\n if (initialOptions.current && props.stopOnUnmount !== false) {\n void recorder.stop();\n }\n };\n }, [props.stopOnUnmount, recorder]);\n\n const record: (\n phase: \"start\" | \"move\" | \"end\",\n event: GestureResponderEvent,\n ) => void = (\n phase: \"start\" | \"move\" | \"end\",\n event: GestureResponderEvent,\n ): void => {\n const point: GestureTouchPoint = touchPointFromEvent(event);\n const targetTag: unknown = event.nativeEvent.target;\n const pointerId: unknown = (\n event.nativeEvent as unknown as Record<string, unknown>\n )[\"identifier\"];\n const touch: RecordedTouch = {\n phase,\n x: point.x,\n y: point.y,\n timestamp: Date.now(),\n };\n if (typeof targetTag === \"number\" && Number.isSafeInteger(targetTag)) {\n touch.targetTag = targetTag;\n }\n if (\n (typeof pointerId === \"number\" && Number.isSafeInteger(pointerId)) ||\n typeof pointerId === \"string\"\n ) {\n touch.pointerId = pointerId;\n }\n recorder.recordTouch(touch);\n };\n\n return (\n <ReplayContext.Provider value={recorder}>\n <View\n ref={rootRef}\n collapsable={false}\n style={[{ flex: 1 }, props.style]}\n onTouchStart={(event: GestureResponderEvent): void => {\n record(\"start\", event);\n }}\n onTouchMove={(event: GestureResponderEvent): void => {\n record(\"move\", event);\n }}\n onTouchEnd={(event: GestureResponderEvent): void => {\n record(\"end\", event);\n }}\n >\n {props.children}\n </View>\n </ReplayContext.Provider>\n );\n}\n\nexport function useOneUptimeReplay(): MobileReplayRecorder {\n return useContext(ReplayContext);\n}\n\nexport interface ReplayMaskProps {\n children: ReactNode;\n style?: StyleProp<ViewStyle>;\n}\n\n/** A hard native traversal boundary; descendants are never serialized. */\nexport function ReplayMask(props: ReplayMaskProps): ReactElement {\n return (\n <View\n collapsable={false}\n nativeID=\"oneuptime-replay-mask\"\n testID=\"oneuptime-replay-mask\"\n style={props.style}\n >\n {props.children}\n </View>\n );\n}\n\nexport const ReplayProvider: typeof OneUptimeReplayProvider =\n OneUptimeReplayProvider;\n", "import { AppState, Keyboard } from \"react-native\";\nimport ReplayChunkBuffer, {\n BufferedReplaySegment,\n RollingReplayBuffer,\n} from \"./ChunkBuffer\";\nimport {\n CUSTOM_EVENT_TAG,\n CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,\n ERROR_CUSTOM_EVENT_TAG,\n IDENTIFY_CUSTOM_EVENT_TAG,\n IDLE_PAUSED_CUSTOM_EVENT_TAG,\n IDLE_RESUMED_CUSTOM_EVENT_TAG,\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION,\n MOBILE_CAPTURE_INTERVAL_MS,\n MOBILE_RECORDER_KIND,\n RECORDER_VERSION,\n ROUTE_CUSTOM_EVENT_TAG,\n SESSION_REPLAY_CHECKOUT_INTERVAL_MS,\n SESSION_REPLAY_FLUSH_INTERVAL_MS,\n SESSION_REPLAY_IDLE_PAUSE_MS,\n SESSION_REPLAY_IDLE_ROLLOVER_MS,\n SESSION_REPLAY_MAX_SESSION_MS,\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n SESSION_REPLAY_SCHEMA_VERSION,\n SESSION_REPLAY_WIRE_VERSION,\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n SYNTHETIC_RRWEB_VERSION,\n TAGS_CUSTOM_EVENT_TAG,\n TOUCH_CUSTOM_EVENT_TAG,\n VISIBILITY_CUSTOM_EVENT_TAG,\n RrwebEvent,\n SessionReplayCaptureTrigger,\n SessionReplayChunkEnvelope,\n SessionReplayChunkMeta,\n SessionReplayConsentMode,\n SessionReplayConsentState,\n SessionReplayCustomSignalConfig,\n SessionReplayCustomSignalPayload,\n SessionReplayDirective,\n SessionReplayIdlePausedPayload,\n SessionReplayIdleResumedPayload,\n SessionReplayTriggerReason,\n} from \"./Contract\";\nimport {\n fetchReplayConfig,\n forgetReplayConfig,\n loadCachedReplayConfig,\n MobileReplayStartOptions,\n mobileRequestHeaders,\n ResolvedReplayConfig,\n saveReplayConfig,\n ValidatedStartOptions,\n validateStartOptions,\n} from \"./Config\";\nimport {\n CustomSignalMatcher,\n MobileCustomSignalHit,\n readTapTargetTestIds,\n} from \"./CustomSignals\";\nimport {\n createCustomEvent,\n createTouchEvent,\n RecordedTouch,\n sanitizeRecordedTouch,\n} from \"./Events\";\nimport {\n defaultNativeViewTreeAdapter,\n getViewport,\n NativeAppMetadata,\n NativeViewTreeAdapter,\n NativeViewTreeNode,\n} from \"./NativeViewTree\";\nimport ReplayOutbox from \"./Outbox\";\nimport MobileProductAnalytics, {\n clearStoredProductAnalytics,\n ProductAnalyticsDiagnostics,\n ProductAnalyticsIdentity,\n} from \"./ProductAnalytics\";\nimport {\n PRODUCT_ANALYTICS_EVENTS_PATH,\n PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH,\n PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE,\n ProductAnalyticsWireContext,\n toProductAnalyticsAppVersion,\n} from \"./ProductAnalyticsContract\";\nimport {\n MAX_CAPTURE_REASON_LENGTH,\n MAX_CUSTOM_EVENT_NAME_LENGTH,\n MAX_TAG_KEY_LENGTH,\n MAX_TAG_VALUE_LENGTH,\n MAX_USER_REFERENCE_LENGTH,\n maskStringMapValues,\n maskTextValue,\n sanitizeEventProperties,\n sanitizeRoute,\n sanitizeTags,\n sanitizeTraits,\n toAppUrl,\n truncate,\n} from \"./Sanitize\";\nimport ReplaySessionStore, {\n defaultReplayStorage,\n generateReplayId,\n ReplaySessionIdentity,\n ReplayStorage,\n} from \"./Storage\";\nimport ReplayTransport from \"./Transport\";\nimport {\n CONSERVATIVE_TOUCH_PRIVACY_MAP,\n deriveTouchPrivacyMap,\n isTouchPrivate,\n TouchPrivacyMap,\n} from \"./TouchPrivacy\";\nimport ViewTreeSerializer, { SerializedCapture } from \"./ViewTreeSerializer\";\n\n/*\n * \"paused\" is a recording recorder that nobody has touched for\n * SESSION_REPLAY_IDLE_PAUSE_MS: it captures nothing until the next touch or\n * the app's return to the foreground (see idlePause).\n */\nexport type MobileReplayStatus =\n | \"idle\"\n | \"starting\"\n | \"recording\"\n | \"paused\"\n | \"background\"\n | \"consent-required\"\n | \"disabled\"\n | \"stopped\"\n | \"consent-revoked\";\n\nexport interface MobileReplayDiagnosticEvent {\n code: string;\n atUnixMs: number;\n details?: Record<string, unknown>;\n}\n\nexport interface MobileReplayDiagnostics {\n status: MobileReplayStatus;\n sessionId: string | null;\n recorderKind: \"rn-view-tree\";\n configEpoch: number;\n sampled: boolean;\n triggered: boolean;\n consentState: SessionReplayConsentState;\n pendingEvents: number;\n /*\n * Product analytics events (issue #6629): \"off\" when the application has\n * them off or nothing runs, \"on\" while they are sent, else why they\n * stopped; how many items are held to be sent, and how many events were\n * dropped because too many were held.\n */\n productAnalytics: ProductAnalyticsDiagnostics;\n events: Array<MobileReplayDiagnosticEvent>;\n}\n\nexport type MobileReplaySessionChangeListener = (\n sessionId: string | null,\n) => void;\n\ninterface AppStateSubscription {\n remove(): void;\n}\n\nexport interface ReplayAppState {\n currentState: string | null;\n addEventListener(\n type: \"change\",\n listener: (state: string) => void,\n ): AppStateSubscription;\n}\n\ninterface KeyboardSubscription {\n remove(): void;\n}\n\n/*\n * The soft keyboard, as React Native's Keyboard module reports it. Typing\n * on it never reaches the replay root as a touch - the keyboard is a window\n * of its own - so its showing and hiding are what say someone is typing.\n * The Did events, because Android reports no Will events. isVisible() (React\n * Native 0.71+) says whether it was already up when recording started.\n */\nexport interface ReplayKeyboard {\n addListener(\n eventName: \"keyboardDidShow\" | \"keyboardDidHide\",\n listener: () => void,\n ): KeyboardSubscription;\n isVisible?(): boolean;\n}\n\nexport interface MobileReplayRecorderDependencies {\n storage?: ReplayStorage;\n nativeViewTree?: NativeViewTreeAdapter;\n appState?: ReplayAppState;\n keyboard?: ReplayKeyboard;\n now?: () => number;\n}\n\ntype GlobalErrorHandler = (error: Error, isFatal?: boolean) => void;\n\ninterface GlobalErrorUtils {\n getGlobalHandler?(): GlobalErrorHandler | undefined;\n setGlobalHandler?(handler: GlobalErrorHandler): void;\n}\n\nconst MAX_DIAGNOSTIC_EVENTS: number = 100;\nconst TOUCH_MOVE_SAMPLE_MS: number = 50;\n\n/*\n * A touch that ends within this many points of where it started is a tap,\n * as React Native's own Pressable decides a press: a finger that slides\n * further was scrolling or dragging, not tapping.\n */\nexport const TAP_SLOP_POINTS: number = 10;\n\n/* Touches followed at once for tap signals: more fingers than a hand has. */\nconst MAX_TAP_CANDIDATES: number = 10;\nexport const MOBILE_POLICY_REFRESH_INTERVAL_MS: number = 5 * 60_000;\ntype SessionRotationReason = \"duration\" | \"idle\" | \"chunk-cap\" | \"identity\";\ntype PolicyRefreshReason = \"consent\" | \"foreground\" | \"identity\" | \"periodic\";\ntype ChunkAppendOptions = NonNullable<\n Parameters<ReplayChunkBuffer[\"append\"]>[1]\n>;\n\n/*\n * Capture stopped because nobody touched the app for\n * SESSION_REPLAY_IDLE_PAUSE_MS. Kept from the pause until the snapshot\n * that resumes it is in the buffer, or until the session ends (sealForIdle,\n * or any rotation).\n */\ninterface IdlePause {\n /*\n * The stream the pause belongs to. Only that session and tab are owed\n * the matching idle-resumed marker, and only its stop is dated at the\n * pause: an identity swapped underneath (a consent decision) never had\n * the pause in its stream.\n */\n sessionId: string;\n tabId: string;\n idleSinceUnixMs: number;\n pausedAtUnixMs: number;\n /*\n * The idle-paused marker went out in an uploading stream. A recorder\n * holding its pre-roll in memory marks nothing and drops the pre-roll\n * instead (see pauseForIdle), so its resume owes no marker and its stop\n * sends nothing.\n */\n marked: boolean;\n}\n\n/* An event recorded between an input that ended a pause and its snapshot. */\ninterface HeldReplayEvent {\n event: RrwebEvent;\n options: ChunkAppendOptions;\n}\n\n/*\n * The resuming snapshot normally follows its input within one native\n * capture. This bounds what can pile up when it cannot - a replay root\n * unmounted during the pause leaves nothing to capture until it is back.\n */\nconst MAX_EVENTS_HELD_FOR_RESUME: number = 500;\n\n/*\n * What a touch or a return to the foreground did to an idle pause:\n * nothing (there was none), resumed the paused session, or found that the\n * paused session has ended, so the input starts the next one.\n */\ntype IdleInputOutcome = \"none\" | \"resumed\" | \"session-ended\";\n\nconst SAFE_ERROR_NAMES: ReadonlySet<string> = new Set<string>([\n \"AggregateError\",\n \"Error\",\n \"EvalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/*\n * The text an error's signals are matched on: its message as thrown. Only\n * ever compared on the device; never recorded or sent.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") {\n return error;\n }\n if (error && typeof error === \"object\") {\n const message: unknown = (error as { message?: unknown }).message;\n if (typeof message === \"string\") {\n return message;\n }\n }\n return \"\";\n}\n\nfunction defaultNow(): number {\n return Date.now();\n}\n\nfunction deterministicSample(sessionId: string, percentage: number): boolean {\n if (percentage >= 100) {\n return true;\n }\n if (percentage <= 0) {\n return false;\n }\n\n let hash: number = 2_166_136_261;\n for (let index: number = 0; index < sessionId.length; index += 1) {\n hash ^= sessionId.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n\n return (hash >>> 0) % 10_000 < Math.round(percentage * 100);\n}\n\nfunction hashNamespaceSecret(value: string): string {\n const seeds: Array<number> = [\n 2_166_136_261, 2_654_435_761, 1_013_904_223, 3_747_611_933,\n ];\n return seeds\n .map((seed: number): string => {\n let hash: number = seed;\n for (let index: number = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n })\n .join(\"\");\n}\n\nexport function getReplayStorageNamespace(\n options: Pick<\n ValidatedStartOptions,\n \"host\" | \"token\" | \"appIdentifier\" | \"mobileAppIdentifier\"\n >,\n): string {\n const scope: string = [\n options.host,\n options.appIdentifier,\n options.mobileAppIdentifier,\n hashNamespaceSecret(options.token),\n ].join(\"\\u0000\");\n return `v1-${hashNamespaceSecret(scope)}`;\n}\n\nfunction safeMetadataValue(\n value: unknown,\n fallback: string,\n maximumLength: number = 100,\n): string {\n return typeof value === \"string\" && value.trim()\n ? truncate(value.trim(), maximumLength)\n : fallback;\n}\n\nfunction isRetryablePolicyFailure(config: ResolvedReplayConfig): boolean {\n if (config.disabledReason === \"config-fetch-failed\") {\n return true;\n }\n const match: RegExpMatchArray | null =\n config.disabledReason?.match(/^config-http-(\\d{3})$/u) ?? null;\n if (!match) {\n return false;\n }\n const status: number = Number(match[1]);\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nexport default class MobileReplayRecorder {\n private readonly storage: ReplayStorage;\n private readonly nativeViewTree: NativeViewTreeAdapter;\n private readonly appState: ReplayAppState;\n private readonly keyboard: ReplayKeyboard | null;\n private readonly now: () => number;\n private readonly serializer: ViewTreeSerializer = new ViewTreeSerializer();\n private readonly chunkBuffer: ReplayChunkBuffer = new ReplayChunkBuffer();\n /* The application's own tap, page, event and error signals (#6443, #6517). */\n private readonly customSignalMatcher: CustomSignalMatcher =\n new CustomSignalMatcher();\n private readonly rollingBuffer: RollingReplayBuffer =\n new RollingReplayBuffer();\n private diagnosticsStatus: MobileReplayStatus = \"idle\";\n private diagnosticsEvents: Array<MobileReplayDiagnosticEvent> = [];\n private options: ValidatedStartOptions | null = null;\n private config: ResolvedReplayConfig | null = null;\n private sessionStore: ReplaySessionStore | null = null;\n private identity: ReplaySessionIdentity | null = null;\n private outbox: ReplayOutbox | null = null;\n private transport: ReplayTransport | null = null;\n private metadata: NativeAppMetadata = {\n appName: \"React Native\",\n appVersion: \"unknown\",\n osName: \"unknown\",\n osVersion: \"unknown\",\n };\n private rootTag: number | null = null;\n private route: string = \"/\";\n private entryUrl: string = \"\";\n private captureTimer: ReturnType<typeof setInterval> | null = null;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private appStateSubscription: AppStateSubscription | null = null;\n\n /*\n * Offline mode: the host app's connectivity source (start option\n * `connectivity`), and what it last said, which a transport created later\n * - after a consent or identity change - starts from.\n */\n private unsubscribeConnectivity: (() => void) | null = null;\n private lastConnectivity: boolean | null = null;\n\n /*\n * The policy in force is the cached one an offline launch started with,\n * or the last refresh could not reach the server. Refreshed the moment the\n * connection is back rather than on the five-minute schedule, so a policy\n * changed while the device was offline takes effect before its backlog\n * has finished uploading.\n */\n private policyStale: boolean = false;\n private captureGeneration: number | null = null;\n private running: boolean = false;\n private foreground: boolean = true;\n private forceFullSnapshot: boolean = true;\n private lastFullSnapshotAtUnixMs: number = 0;\n private sampled: boolean = false;\n private triggered: boolean = false;\n private uploadActive: boolean = false;\n private consentGranted: boolean = false;\n private triggerReason: SessionReplayTriggerReason =\n SessionReplayTriggerReason.Sampled;\n private userRef: string | null = null;\n private traits: Record<string, string> = {};\n private tags: Record<string, string> = {};\n private metaDirty: boolean = true;\n private droppedEvents: number = 0;\n private closeQueue: Promise<void> = Promise.resolve();\n private lastTouchMoveAtUnixMs: number = 0;\n private previousGlobalErrorHandler: GlobalErrorHandler | null = null;\n private installedGlobalErrorHandler: GlobalErrorHandler | null = null;\n private globalErrorUtils: GlobalErrorUtils | null = null;\n private lifecycleGeneration: number = 0;\n private lifecycleCancellationEpoch: number = 0;\n private lifecycleQueue: Promise<void> = Promise.resolve();\n private pendingStart: {\n generation: number;\n promise: Promise<boolean>;\n } | null = null;\n private pendingStartCancellation: {\n generation: number;\n cancel: () => void;\n } | null = null;\n private identityPersisted: boolean = false;\n private sessionLastActivityUnixMs: number = 0;\n\n /*\n * The session went the idle window without activity, was sealed where it\n * ended, and nobody has come back since.\n *\n * Rotating on the spot instead (the old behaviour) started a session\n * nobody was in: an app left open in the foreground with the screen on\n * re-snapshots every minute, so it filed a new session every half hour\n * for as long as it stayed open. Now nothing is captured, uploaded or\n * handed to the host as a session id until the user is back - a touch,\n * the soft keyboard, the app returning to the foreground, or an explicit\n * captureSession() - and that starts the next session (see\n * maybeRotateSession). In the foreground the session was almost always\n * paused for idle first (idlePause), so its footage already ended there.\n */\n private sealedForIdle: boolean = false;\n private rotatingSession: boolean = false;\n private rotationPromise: Promise<void> | null = null;\n private appStateQueue: Promise<void> = Promise.resolve();\n private acceptingEvents: boolean = false;\n private lastPolicyRefreshAtUnixMs: number = 0;\n private policyRefreshPromise: Promise<boolean> | null = null;\n private identityQueue: Promise<void> = Promise.resolve();\n private identityCancellationEpoch: number = 0;\n private pendingIdentityOperations: number = 0;\n private readonly sessionChangeListeners: Set<MobileReplaySessionChangeListener> =\n new Set<MobileReplaySessionChangeListener>();\n private lastNotifiedSessionId: string | null = null;\n private touchPrivacyMap: TouchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n private touchQueue: Promise<void> = Promise.resolve();\n private readonly suppressedTouchPointers: Set<string> = new Set<string>();\n private unidentifiedTouchCount: number = 0;\n private unidentifiedTouchPrivate: boolean = false;\n /*\n * Each touch still down that may yet be a tap, for the application's tap\n * signals (issue #6517): where it started and on which view.\n */\n private readonly tapCandidates: Map<\n string,\n { x: number; y: number; targetTag: number | undefined }\n > = new Map<\n string,\n { x: number; y: number; targetTag: number | undefined }\n >();\n\n /*\n * When the person last did something: a touch (any touch - one inside a\n * ReplayMask is still someone using the app, even though it is never\n * recorded), the app coming back to the foreground, or the app starting.\n * Not sessionLastActivityUnixMs, which every recorded event moves: a\n * route change, a track() call or a JS error the app raises by itself is\n * the app, not the person, and a polling screen would otherwise never\n * look idle.\n */\n private lastInputUnixMs: number = 0;\n\n /*\n * The idle pause (SESSION_REPLAY_IDLE_PAUSE_MS, #4208). Set when the\n * capture tick finds nobody has touched the app for that long: the open\n * chunk closes with an idle-paused marker as its last event, the capture\n * timer stops, and from then on nothing is recorded - no view-tree\n * sample, no checkout, no chunk, and every event the app emits is\n * dropped rather than queued. The 15-second flush timer is the only one\n * left, and all it does is end the session (sealForIdle, #4207) if nobody\n * comes back inside SESSION_REPLAY_IDLE_ROLLOVER_MS.\n *\n * It exists because the recorder used to go on sampling the view tree\n * every 500 ms, with a full checkout every minute, for the whole half\n * hour before the idle rollover - the phone's CPU and battery and the\n * customer's upload and storage, all spent on footage of nobody.\n *\n * Input inside that window - a touch, the soft keyboard, the app\n * returning to the foreground - resumes the same session and tab on a\n * fresh full snapshot with an idle-resumed marker directly behind it\n * (idleResumeBacklog), at the next chunk index.\n */\n private idlePause: IdlePause | null = null;\n\n /*\n * Non-null from the input that ends an idle pause until the snapshot it\n * resumes on is in the buffer. What is recorded meanwhile - the touch\n * that woke the recorder, the screen it opened, a track() it caused - is\n * held here and appended behind that snapshot and the idle-resumed\n * marker, so the chunk after a pause always opens on its snapshot.\n */\n private idleResumeBacklog: Array<HeldReplayEvent> | null = null;\n\n /*\n * The soft keyboard is up. Keystrokes reach no view the recorder can see,\n * so someone writing a long message - a chat, a form, a review - would\n * otherwise look exactly like nobody touching the app. While it is up the\n * idle pause waits, and its showing and hiding are input\n * (onKeyboardChange). The 30-minute rollover does not look at it.\n */\n private softKeyboardVisible: boolean = false;\n private keyboardSubscriptions: Array<KeyboardSubscription> = [];\n\n /*\n * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside\n * the recording, from every session the policy lets the recorder run in,\n * recorded or not. Null while the application has them off.\n */\n private analytics: MobileProductAnalytics | null = null;\n\n /*\n * The replay sample left the session out under \"Always\": nothing of it\n * is recorded, but its product analytics events are still sent - and,\n * nothing else moving the session, they are what keeps it alive\n * (ReplaySessionStore.continueSession), as the browser recorder does.\n */\n private analyticsOnly: boolean = false;\n\n public constructor(dependencies: MobileReplayRecorderDependencies = {}) {\n this.storage = dependencies.storage ?? defaultReplayStorage;\n this.nativeViewTree =\n dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;\n this.appState =\n dependencies.appState ?? (AppState as unknown as ReplayAppState);\n /* Absent where React Native has no Keyboard module: no typing signal. */\n this.keyboard =\n dependencies.keyboard ??\n (Keyboard as unknown as ReplayKeyboard | undefined) ??\n null;\n this.now = dependencies.now ?? defaultNow;\n }\n\n public start(options: MobileReplayStartOptions): Promise<boolean> {\n if (\n this.pendingStart &&\n this.pendingStart.generation === this.lifecycleCancellationEpoch\n ) {\n return this.pendingStart.promise;\n }\n\n const requestGeneration: number = this.lifecycleCancellationEpoch;\n const identityBarrier: Promise<void> = this.identityQueue;\n const promise: Promise<boolean> = this.enqueueLifecycleOperation(\n async (): Promise<boolean> => {\n await identityBarrier;\n if (requestGeneration !== this.lifecycleCancellationEpoch) {\n return false;\n }\n return await this.startNow(options);\n },\n );\n this.pendingStart = { generation: requestGeneration, promise };\n void promise.then(\n (): void => {\n if (this.pendingStart?.promise === promise) {\n this.pendingStart = null;\n }\n },\n (): void => {\n if (this.pendingStart?.promise === promise) {\n this.pendingStart = null;\n }\n },\n );\n return promise;\n }\n\n private async startNow(options: MobileReplayStartOptions): Promise<boolean> {\n if (this.running) {\n return true;\n }\n const generation: number = this.lifecycleGeneration + 1;\n this.lifecycleGeneration = generation;\n let cancelStart: () => void = (): void => {\n return undefined;\n };\n const cancellation: Promise<boolean> = new Promise<boolean>(\n (resolve: (value: boolean | PromiseLike<boolean>) => void): void => {\n cancelStart = (): void => {\n resolve(false);\n };\n },\n );\n this.pendingStartCancellation = { generation, cancel: cancelStart };\n const work: Promise<boolean> = this.startInternal(options, generation);\n try {\n return await Promise.race([work, cancellation]);\n } finally {\n if (this.pendingStartCancellation?.generation === generation) {\n this.pendingStartCancellation = null;\n }\n }\n }\n\n private async startInternal(\n options: MobileReplayStartOptions,\n generation: number,\n ): Promise<boolean> {\n this.acceptingEvents = false;\n this.diagnosticsStatus = \"starting\";\n this.serializer.reset();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.closeQueue = Promise.resolve();\n this.appStateQueue = Promise.resolve();\n this.rotationPromise = null;\n this.rotatingSession = false;\n this.sealedForIdle = false;\n this.policyRefreshPromise = null;\n this.lastPolicyRefreshAtUnixMs = 0;\n this.forceFullSnapshot = true;\n this.lastFullSnapshotAtUnixMs = 0;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.touchQueue = Promise.resolve();\n this.resetTouchSequences();\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.customSignalMatcher.reset();\n /* A run before this one (an unsampled session's events) ends here. */\n this.stopProductAnalytics();\n const validated: ValidatedStartOptions | null =\n validateStartOptions(options);\n if (!validated) {\n this.disable(\"invalid-start-options\");\n return false;\n }\n\n if (validated.userRef) {\n this.userRef = truncate(validated.userRef, MAX_USER_REFERENCE_LENGTH);\n }\n this.options = this.userRef\n ? { ...validated, userRef: this.userRef }\n : validated;\n if (this.nativeViewTree.isAvailable?.() === false) {\n this.disable(\"native-module-unavailable\", {\n expoGoUnsupported: true,\n });\n return false;\n }\n\n const namespace: string = getReplayStorageNamespace(validated);\n let config: ResolvedReplayConfig = await fetchReplayConfig(this.options);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n\n /*\n * Offline mode. An app launched without a connection cannot fetch its\n * policy; failing closed there meant nothing was recorded on exactly the\n * launches offline mode exists for. The last policy the server gave is\n * used instead - only when the request got no usable answer, never when\n * the server answered that replay is off - and the periodic refresh\n * replaces it the moment the server can be reached.\n */\n let configFromCache: boolean = false;\n if (isRetryablePolicyFailure(config)) {\n const cached: ResolvedReplayConfig | null = await loadCachedReplayConfig(\n this.storage,\n namespace,\n this.now(),\n );\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n if (cached) {\n this.diagnostic(\"config-from-cache\", {\n reason: config.disabledReason ?? \"not-reported\",\n });\n config = cached;\n configFromCache = true;\n }\n } else if (this.mayPersistUnder(config)) {\n await saveReplayConfig(this.storage, namespace, config, this.now());\n }\n\n if (\n !configFromCache &&\n config.enabled &&\n this.userRef &&\n (config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted)\n ) {\n config = await this.refreshTargetingConfig(config);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n this.config = config;\n if (!config.enabled) {\n this.disable(\"config-disabled\", {\n reason: config.disabledReason ?? \"not-reported\",\n });\n return false;\n }\n /* A cached policy is refreshed at the first chance, not in five minutes. */\n this.lastPolicyRefreshAtUnixMs = configFromCache ? 0 : this.now();\n this.policyStale = configFromCache;\n\n const sessionStore: ReplaySessionStore = new ReplaySessionStore(\n this.storage,\n namespace,\n );\n this.sessionStore = sessionStore;\n const nowUnixMs: number = this.now();\n const awaitingConsent: boolean =\n config.consentMode === SessionReplayConsentMode.RequireExplicit &&\n !this.consentGranted;\n if (awaitingConsent) {\n this.identity = this.ephemeralIdentity(nowUnixMs);\n this.identityPersisted = false;\n this.sampled = false;\n } else {\n const identity: ReplaySessionIdentity =\n await sessionStore.resolve(nowUnixMs);\n if (\n !this.isCurrentGeneration(generation) ||\n this.sessionStore !== sessionStore\n ) {\n return false;\n }\n this.identity = identity;\n this.identityPersisted = true;\n this.sampled = deterministicSample(\n this.identity.sessionId,\n config.samplePercentage,\n );\n }\n this.sessionLastActivityUnixMs = nowUnixMs;\n /*\n * Starting is itself the person: the app was just opened. Without this\n * an app nobody touches after launch would be judged idle from epoch 0\n * and pause on its very first capture.\n */\n this.lastInputUnixMs = nowUnixMs;\n\n /*\n * Product analytics (issue #6629) start before the replay sample is\n * read: a session it leaves out records nothing, but its events still\n * count. Their context needs the app's metadata, read first.\n */\n let metadataRead: boolean = false;\n if (config.productAnalytics.enabled) {\n if (!(await this.readAppMetadata(validated, generation))) {\n return false;\n }\n metadataRead = true;\n await this.startProductAnalytics(validated, config, namespace);\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n\n if (\n !awaitingConsent &&\n config.captureTrigger === SessionReplayCaptureTrigger.Always &&\n !this.sampled &&\n !config.isTargeted\n ) {\n this.analyticsOnly = this.analytics !== null;\n this.disable(\"not-sampled\");\n return false;\n }\n\n this.outbox = new ReplayOutbox(this.storage, namespace, this.now);\n this.transport = this.createTransport(validated, this.outbox);\n this.subscribeConnectivity(validated);\n\n if (!metadataRead && !(await this.readAppMetadata(validated, generation))) {\n return false;\n }\n\n this.route = \"/\";\n this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);\n this.running = true;\n this.acceptingEvents = true;\n this.triggered = config.isTargeted;\n this.triggerReason = config.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n const hasConsent: boolean =\n config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted;\n this.uploadActive =\n hasConsent && (this.sampled || config.isTargeted || this.triggered);\n this.foreground = this.appState.currentState === \"active\";\n this.diagnosticsStatus = hasConsent\n ? this.foreground\n ? \"recording\"\n : \"background\"\n : \"consent-required\";\n this.notifySessionChange();\n this.installLifecycle();\n this.installGlobalErrorHandler();\n if (this.foreground) {\n this.startTimers();\n await this.captureTick(true);\n }\n if (!this.running) {\n return false;\n }\n if (this.uploadActive) {\n await this.transport.restore();\n }\n if (!this.isCurrentGeneration(generation) || !this.running) {\n return false;\n }\n this.diagnostic(\"recorder-started\", {\n sampled: this.sampled,\n consentState: this.consentState(),\n });\n return true;\n }\n\n public stop(): Promise<void> {\n const identityBarrier: Promise<void> = this.identityQueue;\n this.lifecycleGeneration += 1;\n this.lifecycleCancellationEpoch += 1;\n this.pendingStartCancellation?.cancel();\n this.acceptingEvents = false;\n /* What product analytics holds goes now, while it can (issue #6629). */\n this.stopProductAnalytics(true);\n this.quiesceCapture();\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n await identityBarrier;\n await this.stopInternal();\n });\n }\n\n private async stopInternal(): Promise<void> {\n if (!this.running) {\n this.diagnosticsStatus = \"stopped\";\n return;\n }\n\n if (this.rotationPromise) {\n await this.rotationPromise;\n }\n if (!this.running) {\n this.diagnosticsStatus = \"stopped\";\n return;\n }\n\n /*\n * Not on a session that has gone idle: it ended at its last activity,\n * and a marker dated now would stretch it by the whole absence. Any\n * footage it still buffers goes out below, dated by itself.\n */\n const endedIdle: boolean =\n this.sealedForIdle || this.rotationReason(this.now()) === \"idle\";\n const pause: IdlePause | null = this.idlePause;\n if (!endedIdle && pause === null) {\n this.appendCustom(\n VISIBILITY_CUSTOM_EVENT_TAG,\n { state: \"stopped\" },\n undefined,\n true,\n );\n } else if (!endedIdle && pause !== null && this.isPauseInStream(pause)) {\n /*\n * Stopped while paused for idle (#4208): the session's footage ended\n * at the pause, so its final chunk is dated there - dated now, it\n * would run on over the whole stretch nobody recorded. An input that\n * came back without its snapshot yet recorded nothing either.\n */\n this.idleResumeBacklog = null;\n this.appendMarker(\n VISIBILITY_CUSTOM_EVENT_TAG,\n { state: \"stopped\" },\n pause.pausedAtUnixMs,\n );\n }\n /* Quiesce first so no timer or AppState callback can append after final. */\n this.haltCapture();\n await this.closeCurrent(true);\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n this.rollingBuffer.clear();\n }\n this.transport?.destroy();\n this.diagnosticsStatus = \"stopped\";\n this.diagnostic(\"recorder-stopped\");\n }\n\n public grantConsent(): Promise<void> {\n const identityBarrier: Promise<void> = this.identityQueue;\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n await identityBarrier;\n await this.grantConsentInternal();\n });\n }\n\n private async grantConsentInternal(): Promise<void> {\n this.consentGranted = true;\n if (!this.running && this.options) {\n const options: ValidatedStartOptions = this.options;\n await this.startNow(options);\n return;\n }\n if (!this.running || !this.config) {\n return;\n }\n\n const generation: number = this.lifecycleGeneration;\n const refreshed: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"consent\",\n );\n if (\n !refreshed ||\n !this.running ||\n !this.consentGranted ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n this.diagnosticsStatus = this.foreground ? \"recording\" : \"background\";\n this.diagnostic(\"consent-granted\");\n /* Held events go now, under the session the grant opened (issue #6629). */\n this.analytics?.onConsentGranted();\n }\n\n public revokeConsent(): Promise<void> {\n this.lifecycleGeneration += 1;\n this.lifecycleCancellationEpoch += 1;\n this.identityCancellationEpoch += 1;\n this.pendingStartCancellation?.cancel();\n this.consentGranted = false;\n this.acceptingEvents = false;\n /*\n * Product analytics drops what it held, forgets the session it\n * announced, and holds nothing until a new grant (issue #6629).\n */\n this.analytics?.forget();\n this.haltCapture();\n this.transport?.destroy();\n return this.enqueueLifecycleOperation(async (): Promise<void> => {\n return this.revokeConsentInternal();\n });\n }\n\n private async revokeConsentInternal(): Promise<void> {\n this.haltCapture();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n await this.sessionStore?.clear();\n await this.forgetCachedConfig();\n await this.forgetStoredProductAnalytics();\n this.identity = null;\n this.userRef = null;\n this.traits = {};\n this.tags = {};\n this.uploadActive = false;\n this.triggered = false;\n this.diagnosticsStatus = \"consent-revoked\";\n this.diagnostic(\"consent-revoked\");\n }\n\n public identify(userRef: string, traits?: Record<string, unknown>): void {\n const trimmedRef: string =\n typeof userRef === \"string\" ? userRef.trim() : \"\";\n const ref: string | null = trimmedRef\n ? truncate(trimmedRef, MAX_USER_REFERENCE_LENGTH)\n : null;\n const sanitizedTraits: Record<string, string> | null =\n traits === undefined ? null : maskStringMapValues(sanitizeTraits(traits));\n const identityEpoch: number = this.identityCancellationEpoch;\n const lifecycleBarrier: Promise<void> = this.lifecycleQueue;\n this.pendingIdentityOperations += 1;\n const operation: Promise<void> = this.identityQueue.then(\n async (): Promise<void> => {\n await lifecycleBarrier;\n await this.applyIdentityChange(ref, sanitizedTraits, identityEpoch);\n },\n );\n this.identityQueue = operation.then(\n (): void => {\n this.pendingIdentityOperations = Math.max(\n 0,\n this.pendingIdentityOperations - 1,\n );\n },\n (): void => {\n this.pendingIdentityOperations = Math.max(\n 0,\n this.pendingIdentityOperations - 1,\n );\n this.diagnostic(\"identity-change-failed\");\n },\n );\n }\n\n public setTags(tags: Record<string, unknown>): void {\n const sanitizedTags: Record<string, string> = sanitizeTags(tags);\n this.runExternalActivity(this.now(), (): void => {\n this.tags = sanitizedTags;\n this.metaDirty = true;\n this.appendCustom(TAGS_CUSTOM_EVENT_TAG, { ...this.tags });\n });\n }\n\n public addTag(key: string, value: string | number | boolean): void {\n if (typeof key !== \"string\") {\n return;\n }\n const safeKey: string = truncate(key.trim(), MAX_TAG_KEY_LENGTH);\n if (!safeKey) {\n return;\n }\n const safeValue: string = truncate(String(value), MAX_TAG_VALUE_LENGTH);\n this.runExternalActivity(this.now(), (): void => {\n this.tags = sanitizeTags({\n ...this.tags,\n [safeKey]: safeValue,\n });\n this.metaDirty = true;\n this.appendCustom(TAGS_CUSTOM_EVENT_TAG, { ...this.tags });\n });\n }\n\n public track(name: string, properties?: Record<string, unknown>): void {\n const eventName: string =\n typeof name === \"string\"\n ? truncate(name.trim(), MAX_CUSTOM_EVENT_NAME_LENGTH)\n : \"\";\n if (!eventName) {\n return;\n }\n\n /*\n * With product analytics on, also an event the application's Events,\n * Funnels and User Retention pages count, from every session, recorded\n * or not (issue #6629). Not held back by the recording's own state - a\n * session paused or left out by the sample still counts what is done\n * in it - only by an identify() still being applied, as the recording\n * is: a track() right after a sign-in is the signed-in user's.\n */\n this.afterIdentity((): void => {\n this.analytics?.track(name, properties);\n });\n\n const sanitizedProperties: Record<string, string> = maskStringMapValues(\n sanitizeEventProperties(properties),\n this.readableEventPropertyKeys(),\n );\n this.runExternalActivity(this.now(), (): void => {\n this.appendCustom(\n CUSTOM_EVENT_TAG,\n { name: eventName, properties: sanitizedProperties },\n \"customEventCount\",\n );\n if (\n this.recordCustomSignals(\n this.customSignalMatcher.matchEvent(\n this.customSignals(),\n eventName,\n this.now(),\n ),\n )\n ) {\n void this.trigger(SessionReplayTriggerReason.Frustration);\n }\n });\n }\n\n /*\n * A number the app measured (\"cart.value\", 42.5), with optional\n * attributes: a point in the metric store under the RUM application, for\n * charts, dashboards and Metrics monitors (issue #6629). It needs product\n * analytics on for the application; its attribute values are masked, as\n * track()'s property values are.\n */\n public metric(\n name: string,\n value: number,\n attributes?: Record<string, unknown>,\n ): void {\n if (!this.analytics || !this.analytics.isStarted()) {\n this.diagnostic(\"metric-analytics-off\");\n return;\n }\n\n this.afterIdentity((): void => {\n this.analytics?.metric(name, value, attributes);\n });\n }\n\n /*\n * Runs a product analytics call once every identify() made before it has\n * been applied - a change of user starts the next session first - or\n * now, when none is pending. Dropped when consent is withdrawn meanwhile.\n */\n private afterIdentity(action: () => void): void {\n if (this.pendingIdentityOperations === 0) {\n action();\n return;\n }\n const identityEpoch: number = this.identityCancellationEpoch;\n void this.identityQueue.then((): void => {\n if (identityEpoch === this.identityCancellationEpoch) {\n action();\n }\n });\n }\n\n public async setRoute(route: string): Promise<void> {\n await this.identityQueue;\n /*\n * A page view for product analytics (issue #6629), named by the route\n * as the recording keeps it, whatever the recording does with it.\n */\n this.analytics?.page(sanitizeRoute(route));\n /*\n * Paused for idle, the route the app moves to on its own is not\n * recorded (nor counted) - only remembered, so the snapshot the resume\n * takes is on the screen the app is actually showing.\n */\n if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {\n this.route = sanitizeRoute(route);\n return;\n }\n await this.maybeRotateSession(this.now());\n if (!this.options) {\n this.route = sanitizeRoute(route);\n return;\n }\n\n const previous: string = this.route;\n const next: string = sanitizeRoute(route);\n if (previous === next) {\n return;\n }\n\n this.route = next;\n\n /*\n * A navigation on an app whose session ended idle is not the user\n * coming back - it can be a timer, or an inactivity logout - so it\n * starts nothing. The next session opens on this route when they do.\n */\n if (this.sealedForIdle) {\n return;\n }\n\n this.appendCustom(\n ROUTE_CUSTOM_EVENT_TAG,\n {\n from: toAppUrl(this.options.mobileAppIdentifier, previous),\n to: toAppUrl(this.options.mobileAppIdentifier, next),\n kind: \"manual\",\n },\n \"routeCount\",\n );\n /*\n * Matched on the route as the app passed it, not the recorded copy\n * whose ids are redacted: a pattern names the app's own screens, and\n * only the signal's name is recorded.\n */\n const frustrated: boolean = this.recordCustomSignals(\n this.customSignalMatcher.matchPage(\n this.customSignals(),\n route,\n this.now(),\n ),\n );\n await this.closeCurrent(false);\n this.forceFullSnapshot = true;\n await this.captureTick(true);\n if (frustrated) {\n await this.trigger(SessionReplayTriggerReason.Frustration);\n }\n }\n\n public async captureSession(reason: string = \"manual\"): Promise<void> {\n await this.identityQueue;\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n /*\n * The app asked for this moment to be recorded.\n *\n * An explicit ask for a recording starts the next session on an app\n * whose last one ended idle, so the marker lands in it rather than\n * nowhere: the new session's snapshot, the rotation marker, then this\n * marker.\n *\n * Paused for idle inside the session's window (#4208), capture resumes\n * at once in the same session, on a snapshot of what is on screen now,\n * with the idle-resumed marker and then this marker behind it.\n *\n * Either way it is not input: lastInputUnixMs stays where the person\n * left it, so the next pause check pauses again unless someone is\n * actually there - as the browser recorder does. In the background\n * nothing can be captured, so a pause stands.\n */\n const resume: IdleInputOutcome = this.foreground\n ? this.endIdlePause(this.now())\n : \"none\";\n await this.maybeRotateForUser(this.now());\n if (resume === \"resumed\") {\n this.startTimers();\n /*\n * The snapshot first, and without the pause check that follows a\n * sample, which would pause again before this marker is in. Under an\n * error trigger the upload below then opens on that snapshot.\n */\n await this.captureTick(true, false);\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n }\n const safeReason: string = truncate(\n (typeof reason === \"string\" ? reason.trim() : \"\") || \"manual\",\n MAX_CAPTURE_REASON_LENGTH,\n );\n this.appendCustom(CUSTOM_EVENT_TAG, {\n name: \"oneuptime.capture\",\n properties: { reason: maskTextValue(safeReason) },\n });\n await this.trigger(SessionReplayTriggerReason.Manual);\n }\n\n public async captureError(error: unknown): Promise<void> {\n await this.identityQueue;\n if (!this.running || !this.acceptingEvents) {\n return;\n }\n /*\n * Nobody is using the app. A background poll's failure says nothing\n * about what the user went through: it is neither recorded (nothing is,\n * while paused) nor allowed to trigger an upload of a session whose\n * footage ended minutes before it.\n */\n if (this.isIdlePaused()) {\n return;\n }\n await this.maybeRotateSession(this.now());\n /*\n * The session ended idle and nobody is back: an error a background\n * poll threw belongs to no recording, and triggers nothing.\n */\n if (this.sealedForIdle) {\n return;\n }\n const rawName: string =\n error instanceof Error && typeof error.name === \"string\"\n ? error.name.trim()\n : \"\";\n const name: string = SAFE_ERROR_NAMES.has(rawName) ? rawName : \"Error\";\n /* Error text and stacks can quote end-user data; mobile v1 never sends them. */\n this.appendCustom(\n ERROR_CUSTOM_EVENT_TAG,\n { kind: \"error\", name, message: \"[masked]\" },\n \"errorCount\",\n );\n /*\n * The application's error signals are matched on the text the app\n * threw - compared here, on the device, and never sent: the marker\n * carries the signal's name.\n */\n this.recordCustomSignals(\n this.customSignalMatcher.matchErrorText(\n this.customSignals(),\n errorText(error),\n this.now(),\n ),\n );\n await this.trigger(SessionReplayTriggerReason.Error);\n }\n\n public recordTouch(touch: RecordedTouch): void {\n const sanitizedTouch: RecordedTouch | null = sanitizeRecordedTouch(\n touch,\n this.now(),\n );\n if (!sanitizedTouch) {\n this.diagnostic(\"invalid-touch-event\");\n return;\n }\n if (!this.running || !this.acceptingEvents || !this.foreground) {\n return;\n }\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n let resumeCapture: Promise<void> | null = null;\n if (input === \"resumed\") {\n /*\n * The capture that resumes the session starts now, and this touch\n * waits for it: recorded behind the snapshot and the idle-resumed\n * marker, and checked against the privacy map that snapshot derives\n * rather than the one from before the pause, which may describe a\n * screen the app has since left. A touch that finds the session\n * ended starts the next one and is dropped, as on any idle session\n * (recordTouchAfterPrivacyCheck).\n */\n this.startTimers();\n resumeCapture = this.captureTick(true);\n }\n const generation: number = this.lifecycleGeneration;\n const operation: Promise<void> = this.touchQueue.then(\n async (): Promise<void> => {\n if (resumeCapture) {\n await resumeCapture;\n }\n await this.recordTouchAfterPrivacyCheck(sanitizedTouch, generation);\n },\n );\n this.touchQueue = operation.catch((): void => {\n this.diagnostic(\"touch-privacy-check-failed\");\n });\n }\n\n private async recordTouchAfterPrivacyCheck(\n touch: RecordedTouch,\n generation: number,\n ): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n const pointIsPrivate: boolean = await this.isCurrentTouchPrivate(touch);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n const suppressed: boolean = this.updateTouchSuppression(\n touch,\n pointIsPrivate,\n );\n /* Followed whatever is recorded of it: a tap on an image is a tap. */\n const tap: { targetTag: number; x: number; y: number } | null =\n this.followTap(touch);\n if (suppressed) {\n this.diagnostic(\"touch-suppressed-private-region\");\n /*\n * The touch is not recorded, and so neither is where it was: a tap\n * signal on it carries its name alone.\n */\n if (tap) {\n await this.recordTapSignals(tap, touch.timestamp, generation, false);\n }\n return;\n }\n if (\n touch.phase === \"move\" &&\n touch.timestamp - this.lastTouchMoveAtUnixMs < TOUCH_MOVE_SAMPLE_MS\n ) {\n return;\n }\n if (touch.phase === \"move\") {\n this.lastTouchMoveAtUnixMs = touch.timestamp;\n }\n\n /*\n * A touch is the user, so on an idle session it starts the next one.\n * The touch itself is dropped: it lands before that session's first\n * snapshot, which shows its result anyway.\n */\n const nowUnixMs: number = this.now();\n if (\n this.rotatingSession ||\n this.sealedForIdle ||\n this.rotationReason(nowUnixMs)\n ) {\n this.diagnostic(\"touch-dropped-session-rotation\");\n void this.maybeRotateForUser(nowUnixMs);\n return;\n }\n\n this.appendEvent(\n createTouchEvent(touch),\n touch.phase === \"start\" ? \"clickCount\" : undefined,\n );\n if (touch.phase === \"start\") {\n this.appendCustom(TOUCH_CUSTOM_EVENT_TAG, {\n phase: \"start\",\n x: touch.x,\n y: touch.y,\n });\n }\n if (tap) {\n await this.recordTapSignals(tap, touch.timestamp, generation, true);\n }\n }\n\n /* The application's signals that fire on a tap. */\n private tapSignals(): Array<SessionReplayCustomSignalConfig> {\n return this.customSignals().filter(\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return signal.trigger === \"tap\";\n },\n );\n }\n\n /*\n * Follows each touch for the application's tap signals (issue #6517): a\n * touch that ends within TAP_SLOP_POINTS of where it started is a tap on\n * the view it started on, and is returned on its end. A touch that slid\n * further was a scroll or a drag. Nothing is followed while the\n * application has no tap signal, so a touch costs what it always did.\n */\n private followTap(\n touch: RecordedTouch,\n ): { targetTag: number; x: number; y: number } | null {\n const key: string =\n touch.pointerId === undefined\n ? \"unidentified\"\n : `${typeof touch.pointerId}:${String(touch.pointerId)}`;\n\n if (touch.phase === \"start\") {\n if (\n this.tapSignals().length === 0 ||\n (this.tapCandidates.size >= MAX_TAP_CANDIDATES &&\n !this.tapCandidates.has(key))\n ) {\n return null;\n }\n this.tapCandidates.set(key, {\n x: touch.x,\n y: touch.y,\n targetTag: touch.targetTag,\n });\n return null;\n }\n\n const started:\n | { x: number; y: number; targetTag: number | undefined }\n | undefined = this.tapCandidates.get(key);\n if (!started) {\n return null;\n }\n const slid: boolean =\n Math.hypot(touch.x - started.x, touch.y - started.y) > TAP_SLOP_POINTS;\n if (touch.phase === \"move\") {\n if (slid) {\n this.tapCandidates.delete(key);\n }\n return null;\n }\n\n this.tapCandidates.delete(key);\n return slid || started.targetTag === undefined\n ? null\n : { targetTag: started.targetTag, x: touch.x, y: touch.y };\n }\n\n /*\n * A tap's signals: the touched view's testID, and those of the views\n * around it out to the replay root, matched here on the device - never\n * recorded or sent. A hit carries the signal's name, where the tap was\n * when the touch itself is recorded (withPosition), and like a page or\n * an event signal it starts an \"On error or frustration\" upload when it\n * counts as frustration.\n */\n private async recordTapSignals(\n tap: { targetTag: number; x: number; y: number },\n atUnixMs: number,\n generation: number,\n withPosition: boolean,\n ): Promise<void> {\n const signals: Array<SessionReplayCustomSignalConfig> = this.tapSignals();\n if (\n signals.length === 0 ||\n !this.rootTag ||\n typeof this.nativeViewTree.touchTargetTestIds !== \"function\"\n ) {\n return;\n }\n let testIds: Array<string> = [];\n try {\n testIds = readTapTargetTestIds(\n await this.nativeViewTree.touchTargetTestIds(\n tap.targetTag,\n this.rootTag,\n ),\n );\n } catch {\n this.diagnostic(\"tap-target-unreadable\");\n return;\n }\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n const hits: Array<MobileCustomSignalHit> =\n this.customSignalMatcher.matchTap(signals, testIds, atUnixMs);\n if (withPosition) {\n for (const hit of hits) {\n hit.x = tap.x;\n hit.y = tap.y;\n }\n }\n if (this.recordCustomSignals(hits)) {\n await this.trigger(SessionReplayTriggerReason.Frustration);\n }\n }\n\n public setRootTag(rootTag: number | null): void {\n this.rootTag =\n typeof rootTag === \"number\" &&\n Number.isSafeInteger(rootTag) &&\n rootTag > 0\n ? rootTag\n : null;\n this.forceFullSnapshot = true;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n if (\n this.rootTag &&\n this.running &&\n this.acceptingEvents &&\n this.foreground\n ) {\n void this.captureTick(true);\n }\n }\n\n public getDiagnostics(): MobileReplayDiagnostics {\n /*\n * Derived rather than stored: the policy, consent and identity paths\n * all write \"recording\" without knowing about the pause, and a paused\n * recorder that reported \"recording\" is exactly the question a support\n * ticket asks. A session that ended idle while nobody came back is\n * paused too - nothing is captured until someone is - as the browser\n * recorder reports it.\n */\n const status: MobileReplayStatus =\n this.diagnosticsStatus === \"recording\" &&\n this.running &&\n this.foreground &&\n (this.isIdlePaused() || this.sealedForIdle)\n ? \"paused\"\n : this.diagnosticsStatus;\n return {\n status,\n sessionId: this.identity?.sessionId ?? null,\n recorderKind: MOBILE_RECORDER_KIND,\n configEpoch: this.config?.configEpoch ?? 0,\n sampled: this.sampled,\n triggered: this.triggered,\n consentState: this.consentState(),\n pendingEvents:\n this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),\n productAnalytics: this.analytics\n ? this.analytics.getDiagnostics()\n : { state: \"off\", pending: 0, dropped: 0 },\n events: this.diagnosticsEvents.map(\n (event: MobileReplayDiagnosticEvent): MobileReplayDiagnosticEvent => {\n const copied: MobileReplayDiagnosticEvent = {\n code: event.code,\n atUnixMs: event.atUnixMs,\n };\n if (event.details) {\n copied.details = { ...event.details };\n }\n return copied;\n },\n ),\n };\n }\n\n /**\n * Current consented replay session for host trace/log correlation. None\n * while the session has ended idle and nobody is back: a background poll\n * on an idle app is no part of a recording that ended at the user's last\n * activity.\n */\n public getSessionId(): string | null {\n return this.running && this.identityPersisted && !this.sealedForIdle\n ? this.identity?.sessionId ?? null\n : null;\n }\n\n /** Fires immediately when a session exists and again on rotate/clear. */\n public onSessionChange(\n listener: MobileReplaySessionChangeListener,\n ): () => void {\n if (typeof listener !== \"function\") {\n return (): void => {\n return undefined;\n };\n }\n this.sessionChangeListeners.add(listener);\n const sessionId: string | null = this.getSessionId();\n if (sessionId) {\n try {\n listener(sessionId);\n } catch {\n /* Host observers cannot interrupt capture. */\n }\n }\n return (): void => {\n this.sessionChangeListeners.delete(listener);\n };\n }\n\n private async trigger(reason: SessionReplayTriggerReason): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n this.triggered ||\n this.uploadActive ||\n this.sampled ||\n this.config?.isTargeted\n ) {\n return;\n }\n\n this.triggered = true;\n this.triggerReason = reason;\n this.diagnostic(\"capture-triggered\", { reason });\n if (this.consentState() !== \"Unknown\") {\n await this.activateUpload(this.lifecycleGeneration);\n }\n }\n\n private async activateUpload(generation: number): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n this.uploadActive ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n\n await this.closeCurrent(false);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n this.uploadActive = true;\n const buffered: Array<BufferedReplaySegment> = this.rollingBuffer.drain();\n for (const segment of buffered) {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n await this.uploadSegment(segment, false);\n }\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.isCurrentGeneration(generation)\n ) {\n return;\n }\n await this.transport?.restore();\n }\n\n /*\n * mayPauseForIdle is false only for the snapshot captureSession() takes\n * while paused, whose marker must be in before the pause check runs.\n */\n private async captureTick(\n force: boolean = false,\n mayPauseForIdle: boolean = true,\n ): Promise<void> {\n const generation: number = this.lifecycleGeneration;\n /*\n * Nothing is captured while the session has ended idle: there is no\n * session to put it in until the user is back (see sealedForIdle), and\n * an idle app left in the foreground is not walking the view tree\n * twice a second for nobody.\n */\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.rootTag ||\n this.sealedForIdle ||\n this.captureGeneration === generation ||\n !this.options\n ) {\n return;\n }\n /*\n * Paused for idle: no sample, no checkout, and not the periodic policy\n * refresh either. Nothing happens on a tick until input resumes it.\n */\n if (this.isIdlePaused()) {\n return;\n }\n\n this.captureGeneration = generation;\n try {\n const nowUnixMs: number = this.now();\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n false,\n \"periodic\",\n );\n if (!policyReady) {\n return;\n }\n await this.maybeRotateSession(nowUnixMs);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.sealedForIdle\n ) {\n return;\n }\n /*\n * Paused again meanwhile, or the person came back to a session whose\n * window has run out while its successor is not in place yet (another\n * rotation was still finishing): the next tick starts that one.\n * Nothing is captured into a session that is over.\n */\n if (\n this.isIdlePaused() ||\n (this.idlePause !== null && this.rotationReason(nowUnixMs) !== null)\n ) {\n return;\n }\n const capturedSessionId: string | undefined = this.identity?.sessionId;\n const tree: NativeViewTreeNode =\n await this.nativeViewTree.captureViewTree(this.rootTag);\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.rotatingSession ||\n !capturedSessionId ||\n this.identity?.sessionId !== capturedSessionId\n ) {\n return;\n }\n this.touchPrivacyMap = deriveTouchPrivacyMap(tree);\n const shouldForce: boolean =\n force ||\n this.forceFullSnapshot ||\n nowUnixMs - this.lastFullSnapshotAtUnixMs >=\n SESSION_REPLAY_CHECKOUT_INTERVAL_MS;\n if (shouldForce && !this.chunkBuffer.isEmpty()) {\n await this.closeCurrent(false);\n }\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.identity?.sessionId !== capturedSessionId\n ) {\n return;\n }\n\n this.appendCapture(tree, this.options, nowUnixMs, shouldForce);\n if (this.chunkBuffer.shouldFlush()) {\n await this.closeCurrent(false);\n }\n /*\n * Nobody has touched the app for the pause window: stop capturing.\n * Checked after this tick's sample, so the chunk the pause closes ends\n * on the screen as it was when capture stopped. Never while the soft\n * keyboard is up: someone typing touches nothing the recorder sees,\n * so the check waits until it goes away (which is input itself).\n */\n if (\n mayPauseForIdle &&\n !this.softKeyboardVisible &&\n nowUnixMs - this.lastInputUnixMs >= SESSION_REPLAY_IDLE_PAUSE_MS\n ) {\n await this.pauseForIdle(nowUnixMs, generation);\n }\n } catch (error) {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.disable(\"native-capture-failed\", {\n name: error instanceof Error ? error.name : \"Error\",\n });\n this.haltCapture();\n }\n } finally {\n if (this.captureGeneration === generation) {\n this.captureGeneration = null;\n }\n }\n }\n\n private appendCapture(\n tree: NativeViewTreeNode,\n options: ValidatedStartOptions,\n nowUnixMs: number,\n forceFullSnapshot: boolean,\n ): void {\n const size: { width: number; height: number } = getViewport();\n const url: string = toAppUrl(options.mobileAppIdentifier, this.route);\n const capture: SerializedCapture = this.serializer.capture(tree, {\n timestamp: nowUnixMs,\n url,\n viewportWidth: size.width,\n viewportHeight: size.height,\n forceFullSnapshot,\n });\n this.droppedEvents += capture.droppedNodes;\n this.chunkBuffer.appendMany(capture.events, {\n route: url,\n fidelityNotices: capture.fidelityNotices,\n });\n if (capture.hasFullSnapshot) {\n this.lastFullSnapshotAtUnixMs = nowUnixMs;\n this.forceFullSnapshot = false;\n this.completeIdleResume(nowUnixMs);\n }\n }\n\n /*\n * The person did something: a touch, the soft keyboard showing or\n * hiding, or the app coming back to the foreground. It ends an idle\n * pause (see endIdlePause).\n */\n private noteUserInput(nowUnixMs: number): IdleInputOutcome {\n this.lastInputUnixMs = Math.max(this.lastInputUnixMs, nowUnixMs);\n return this.endIdlePause(nowUnixMs);\n }\n\n /*\n * What someone being back does to an idle pause, on its own for\n * captureSession(), which acts on the pause without being input.\n *\n * Inside the session's idle window the same session resumes, on the\n * snapshot of the next capture; the caller starts that capture. Once\n * the window has run out - or the session already ended idle - the\n * session is over, and the caller starts the next one through\n * maybeRotateForUser, as on any idle session; nothing changes here.\n */\n private endIdlePause(nowUnixMs: number): IdleInputOutcome {\n if (this.sealedForIdle) {\n return \"session-ended\";\n }\n if (!this.isIdlePaused()) {\n return \"none\";\n }\n if (this.rotationReason(nowUnixMs) !== null) {\n return \"session-ended\";\n }\n this.idleResumeBacklog = [];\n this.forceFullSnapshot = true;\n /* The return is activity: the session's idle window starts over. */\n this.sessionLastActivityUnixMs = Math.max(\n this.sessionLastActivityUnixMs,\n nowUnixMs,\n );\n return \"resumed\";\n }\n\n /* Paused for idle with nobody back yet: nothing is captured or recorded. */\n private isIdlePaused(): boolean {\n return this.idlePause !== null && this.idleResumeBacklog === null;\n }\n\n /*\n * Whether the pause's marker is in the stream being recorded now, which\n * is what owes it the idle-resumed marker and dates a stop at it.\n */\n private isPauseInStream(pause: IdlePause): boolean {\n return (\n pause.marked &&\n this.identity?.sessionId === pause.sessionId &&\n this.identity?.tabId === pause.tabId\n );\n }\n\n /*\n * Stop capturing: nobody has touched the app for the pause window.\n *\n * In this order: the idle-paused marker goes in as the last event of the\n * open chunk, that chunk goes out through the ordinary path, and the\n * sampler stops. So the last thing the recording holds before the\n * stretch nobody recorded says so - and a session the person never comes\n * back to has already ended there when its idle window runs out, so the\n * idle seal (sealForIdle) has nothing left to send.\n *\n * A recorder holding its pre-roll in memory (error-triggered, or waiting\n * for consent) has nothing to mark and nothing to send. Its pre-roll is\n * dropped instead: a trigger once the person is back must not upload a\n * minute of nobody in front of a snapshot taken after an unrecorded gap.\n */\n private async pauseForIdle(\n nowUnixMs: number,\n generation: number,\n ): Promise<void> {\n if (\n !this.running ||\n !this.acceptingEvents ||\n !this.foreground ||\n !this.isCurrentGeneration(generation) ||\n this.idlePause !== null ||\n this.sealedForIdle ||\n !this.identity\n ) {\n return;\n }\n\n const paused: SessionReplayIdlePausedPayload = {\n /*\n * Never before the session began: one that started with nobody there\n * (the chunk cap rolled it over) was not idle before it existed.\n */\n idleSinceUnixMs: Math.min(\n nowUnixMs,\n Math.max(this.lastInputUnixMs, this.identity.sessionStartUnixMs),\n ),\n pausedAtUnixMs: nowUnixMs,\n };\n const marked: boolean = this.uploadActive;\n this.idlePause = {\n sessionId: this.identity.sessionId,\n tabId: this.identity.tabId,\n idleSinceUnixMs: paused.idleSinceUnixMs,\n pausedAtUnixMs: paused.pausedAtUnixMs,\n marked,\n };\n this.stopCaptureTimer();\n this.diagnostic(\"idle-paused\", {\n idleForMs: nowUnixMs - paused.idleSinceUnixMs,\n });\n\n if (!marked) {\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n return;\n }\n this.appendMarker(IDLE_PAUSED_CUSTOM_EVENT_TAG, paused, nowUnixMs);\n await this.closeCurrent(false);\n }\n\n /*\n * The snapshot the session resumes on is in the buffer: the idle-resumed\n * marker goes directly behind it, then whatever was recorded since the\n * input that woke the recorder. Same session, same tab and - the pause\n * having closed its chunk - the next chunk index.\n */\n private completeIdleResume(nowUnixMs: number): void {\n const pause: IdlePause | null = this.idlePause;\n const held: Array<HeldReplayEvent> | null = this.idleResumeBacklog;\n if (pause === null || held === null) {\n return;\n }\n this.idlePause = null;\n this.idleResumeBacklog = null;\n\n const resumedAtUnixMs: number = Math.max(pause.pausedAtUnixMs, nowUnixMs);\n if (this.isPauseInStream(pause)) {\n const resumed: SessionReplayIdleResumedPayload = {\n pausedAtUnixMs: pause.pausedAtUnixMs,\n resumedAtUnixMs,\n };\n this.appendMarker(\n IDLE_RESUMED_CUSTOM_EVENT_TAG,\n resumed,\n resumedAtUnixMs,\n );\n }\n this.releaseHeldEvents(held);\n this.diagnostic(\"idle-resumed\", {\n pausedForMs: resumedAtUnixMs - pause.pausedAtUnixMs,\n });\n }\n\n /*\n * A marker the recorder writes about itself - the idle pause and resume,\n * and a stop while paused - straight into the open chunk, stamped with\n * the moment it stands for. None of them is activity (the idle rollover\n * must not move for them), and none is \"now\": a stop while paused is\n * dated at the pause.\n */\n private appendMarker(tag: string, payload: unknown, timestamp: number): void {\n const options: ChunkAppendOptions = {};\n if (this.options) {\n options.route = toAppUrl(this.options.mobileAppIdentifier, this.route);\n }\n if (\n !this.chunkBuffer.append(\n createCustomEvent(tag, payload, timestamp),\n options,\n )\n ) {\n this.droppedEvents += 1;\n }\n }\n\n /* What was held for a resume, in the order it was recorded. */\n private releaseHeldEvents(held: Array<HeldReplayEvent>): void {\n for (const entry of held) {\n if (!this.chunkBuffer.append(entry.event, entry.options)) {\n this.droppedEvents += 1;\n }\n }\n }\n\n /* The tap, page, event and error signals the application's policy defines. */\n private customSignals(): ReadonlyArray<SessionReplayCustomSignalConfig> {\n return this.config?.frustrationSignals.customSignals ?? [];\n }\n\n /*\n * The application's readable event properties (issue #7501): none until\n * the policy is read, so a track() before it is masked whole.\n */\n private readableEventPropertyKeys(): Array<string> {\n return this.config?.readableEventPropertyKeys ?? [];\n }\n\n /*\n * Marks each hit in the stream and counts it on the chunk, as the browser\n * recorder does. Returns whether one of them counts as frustration, which\n * starts an upload under \"On error or frustration\" like an error does.\n *\n * Nothing while the recorder records nothing: before start, while\n * waiting, paused for idle or after a session ended idle - a hit then\n * belongs to no recording, and must not start an upload of footage that\n * ended minutes before it.\n */\n private recordCustomSignals(hits: Array<MobileCustomSignalHit>): boolean {\n if (\n hits.length === 0 ||\n !this.running ||\n !this.acceptingEvents ||\n this.sealedForIdle ||\n this.isIdlePaused()\n ) {\n return false;\n }\n let frustrated: boolean = false;\n for (const hit of hits) {\n if (!this.chunkBuffer.hasRoomForCustomSignal()) {\n this.diagnostic(\"custom-signal-cap-reached\");\n break;\n }\n const payload: SessionReplayCustomSignalPayload = {\n name: hit.name,\n trigger: hit.trigger,\n isFrustration: hit.isFrustration,\n atUnixMs: hit.atUnixMs,\n };\n if (\n typeof hit.x === \"number\" &&\n Number.isFinite(hit.x) &&\n typeof hit.y === \"number\" &&\n Number.isFinite(hit.y)\n ) {\n payload.x = hit.x;\n payload.y = hit.y;\n }\n this.appendEvent(\n createCustomEvent(\n CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,\n payload,\n hit.atUnixMs,\n ),\n undefined,\n false,\n { name: hit.name, isFrustration: hit.isFrustration },\n );\n frustrated = frustrated || hit.isFrustration;\n }\n return frustrated;\n }\n\n private appendCustom(\n tag: string,\n payload: unknown,\n signal?: \"errorCount\" | \"routeCount\" | \"customEventCount\",\n allowWhenQuiesced: boolean = false,\n ): void {\n this.appendEvent(\n createCustomEvent(tag, payload, this.now()),\n signal,\n allowWhenQuiesced,\n );\n }\n\n private appendEvent(\n event: RrwebEvent,\n signal?: \"errorCount\" | \"routeCount\" | \"clickCount\" | \"customEventCount\",\n allowWhenQuiesced: boolean = false,\n customSignal?: { name: string; isFrustration: boolean },\n ): void {\n if (!this.running || (!this.acceptingEvents && !allowWhenQuiesced)) {\n return;\n }\n /*\n * Not counted as dropped: nothing is lost. The session ended idle, an\n * event dated after that is no part of it, and the next session opens\n * on a snapshot of its own.\n */\n if (this.sealedForIdle) {\n return;\n }\n if (!Number.isFinite(event.timestamp)) {\n this.droppedEvents += 1;\n this.diagnostic(\"invalid-event-timestamp\");\n return;\n }\n\n /*\n * Paused for idle: nothing is recorded. Dropped, not queued - held\n * until the resume, a route the app changed or a track() it fired\n * twenty minutes earlier would be stamped after the person came back -\n * and neither counted in the chunk's signals nor taken as activity, so\n * an app that keeps raising events cannot hold the idle rollover off.\n */\n if (this.isIdlePaused()) {\n return;\n }\n\n const appendOptions: ChunkAppendOptions = {};\n if (this.options) {\n appendOptions.route = toAppUrl(\n this.options.mobileAppIdentifier,\n this.route,\n );\n }\n if (signal) {\n appendOptions.signal = signal;\n }\n if (customSignal) {\n appendOptions.customSignal = customSignal;\n }\n\n /*\n * The person is back but the snapshot the session resumes on is not in\n * the buffer yet: held, to land behind it (completeIdleResume). Not\n * counted as activity here: the input that woke the recorder already\n * was.\n */\n if (this.idleResumeBacklog !== null) {\n if (this.idleResumeBacklog.length < MAX_EVENTS_HELD_FOR_RESUME) {\n this.idleResumeBacklog.push({ event, options: appendOptions });\n } else {\n this.droppedEvents += 1;\n }\n return;\n }\n\n this.sessionLastActivityUnixMs = Math.max(\n this.sessionLastActivityUnixMs,\n event.timestamp,\n );\n\n const accepted: boolean = this.chunkBuffer.append(event, appendOptions);\n if (!accepted) {\n this.droppedEvents += 1;\n }\n if (this.chunkBuffer.shouldFlush()) {\n void this.closeCurrent(false);\n }\n }\n\n private async closeCurrent(isFinal: boolean): Promise<void> {\n /*\n * Never on a session that ended idle: the cap's marker would be dated\n * now, long after its footage, and the rotation after it would start a\n * session nobody is in.\n */\n const closesFinalChunkSlot: boolean =\n !isFinal &&\n !this.rotatingSession &&\n !this.sealedForIdle &&\n this.uploadActive &&\n this.sessionStore?.getNextChunkIndex() ===\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION - 1;\n if (closesFinalChunkSlot) {\n this.rotatingSession = true;\n const rotationOptions: NonNullable<\n Parameters<ReplayChunkBuffer[\"append\"]>[1]\n > = {};\n if (this.options) {\n rotationOptions.route = toAppUrl(\n this.options.mobileAppIdentifier,\n this.route,\n );\n }\n this.chunkBuffer.append(\n createCustomEvent(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason: \"chunk-cap\" },\n this.now(),\n ),\n rotationOptions,\n );\n }\n const segment: BufferedReplaySegment | null = this.chunkBuffer.take();\n if (!segment) {\n if (closesFinalChunkSlot) {\n this.rotatingSession = false;\n }\n return;\n }\n\n const operation: Promise<void> = this.closeQueue.then(\n async (): Promise<void> => {\n return this.processSegment(segment, isFinal || closesFinalChunkSlot);\n },\n );\n if (closesFinalChunkSlot) {\n const rotation: Promise<void> = operation.then(\n async (): Promise<void> => {\n if (this.running) {\n await this.completeSessionIdentityRotation(this.now(), \"chunk-cap\");\n }\n },\n );\n this.rotationPromise = rotation;\n this.closeQueue = rotation.catch((): void => {\n this.diagnostic(\"chunk-close-failed\");\n });\n try {\n await rotation;\n } finally {\n if (this.rotationPromise === rotation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n return;\n }\n this.closeQueue = operation.catch((): void => {\n this.diagnostic(\"chunk-close-failed\");\n });\n return await operation;\n }\n\n private async processSegment(\n segment: BufferedReplaySegment,\n isFinal: boolean,\n ): Promise<void> {\n if (!this.uploadActive) {\n this.rollingBuffer.push(segment, this.now());\n return;\n }\n\n await this.uploadSegment(segment, isFinal);\n }\n\n private async uploadSegment(\n segment: BufferedReplaySegment,\n isFinal: boolean,\n ): Promise<void> {\n if (\n !this.options ||\n !this.config ||\n !this.identity ||\n !this.sessionStore ||\n !this.transport ||\n !this.identityPersisted\n ) {\n return;\n }\n\n const chunkIndex: number = await this.sessionStore.takeChunkIndex(\n this.now(),\n );\n if (chunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION) {\n this.diagnostic(\"session-chunk-cap-race\", { chunkIndex });\n if (this.running) {\n await this.completeSessionIdentityRotation(this.now(), \"chunk-cap\");\n await this.uploadSegment(segment, isFinal);\n }\n return;\n }\n\n const includeMeta: boolean = chunkIndex === 0 || isFinal || this.metaDirty;\n const envelope: SessionReplayChunkEnvelope = {\n v: SESSION_REPLAY_WIRE_VERSION,\n appIdentifier: this.options.appIdentifier,\n sessionId: this.identity.sessionId,\n tabId: this.identity.tabId,\n chunkIndex,\n sessionStartUnixMs: this.identity.sessionStartUnixMs,\n clientSendUnixMs: this.now(),\n chunkStartOffsetMs: Math.max(\n 0,\n segment.startUnixMs - this.identity.sessionStartUnixMs,\n ),\n chunkEndOffsetMs: Math.max(\n 0,\n segment.endUnixMs - this.identity.sessionStartUnixMs,\n ),\n eventCount: segment.eventCount,\n hasFullSnapshot: segment.hasFullSnapshot,\n isFinal,\n recorderKind: MOBILE_RECORDER_KIND,\n schemaVersion: SESSION_REPLAY_SCHEMA_VERSION,\n rrwebVersion: SYNTHETIC_RRWEB_VERSION,\n recorderVersion: RECORDER_VERSION,\n maskingMode: this.config.maskingMode,\n consentState: this.consentState(),\n triggerReason: this.triggerReason,\n payloadEncoding: \"gzip\",\n payloadBytes: 0,\n url: toAppUrl(this.options.mobileAppIdentifier, this.route),\n routes: segment.routes,\n signals: segment.signals,\n fidelityNotices: segment.fidelityNotices,\n droppedEvents: segment.droppedEvents + this.droppedEvents,\n flushFailures: this.transport.getFlushFailures(),\n };\n if (includeMeta) {\n envelope.meta = this.buildMeta();\n }\n if (chunkIndex === 0) {\n envelope.capabilities = Array.from(\n SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES,\n );\n }\n this.metaDirty = false;\n this.droppedEvents = 0;\n await this.transport.enqueue(envelope, segment.payload);\n }\n\n private buildMeta(): SessionReplayChunkMeta {\n const size: { width: number; height: number } = getViewport();\n const captureIdentity: boolean = this.config?.captureUserIdentity === true;\n const meta: SessionReplayChunkMeta = {\n entryUrl: this.entryUrl,\n browserName: this.metadata.appName,\n browserVersion: this.metadata.appVersion,\n osName: `${this.metadata.osName} ${this.metadata.osVersion}`.trim(),\n deviceType: this.metadata.osName.toLowerCase().includes(\"ios\")\n ? \"ios\"\n : \"android\",\n viewportWidth: size.width,\n viewportHeight: size.height,\n };\n if (this.identity?.visitorId) {\n meta.visitorId = this.identity.visitorId;\n }\n if (captureIdentity && this.userRef) {\n meta.identifiedUserRef = this.userRef;\n }\n if (captureIdentity && Object.keys(this.traits).length > 0) {\n meta.identifiedUserTraits = { ...this.traits };\n }\n if (Object.keys(this.tags).length > 0) {\n meta.tags = { ...this.tags };\n }\n return meta;\n }\n\n private consentState(): SessionReplayConsentState {\n if (this.config?.consentMode === SessionReplayConsentMode.NotRequired) {\n return \"NotRequired\";\n }\n\n return this.consentGranted ? \"Granted\" : \"Unknown\";\n }\n\n private installLifecycle(): void {\n this.appStateSubscription?.remove();\n this.appStateSubscription = this.appState.addEventListener(\n \"change\",\n (state: string): void => {\n const generation: number = this.lifecycleGeneration;\n const operation: Promise<void> = this.appStateQueue.then(\n async (): Promise<void> => {\n await this.onAppStateChange(state, generation);\n },\n );\n this.appStateQueue = operation.catch((): void => {\n this.diagnostic(\"app-state-transition-failed\");\n });\n },\n );\n this.installKeyboardListeners();\n }\n\n private installKeyboardListeners(): void {\n this.removeKeyboardListeners();\n const keyboard: ReplayKeyboard | null = this.keyboard;\n this.softKeyboardVisible = false;\n if (!keyboard || typeof keyboard.addListener !== \"function\") {\n return;\n }\n try {\n /* Already up when recording started: someone is typing. */\n this.softKeyboardVisible = keyboard.isVisible?.() === true;\n } catch {\n this.softKeyboardVisible = false;\n }\n try {\n this.keyboardSubscriptions.push(\n keyboard.addListener(\"keyboardDidShow\", (): void => {\n this.onKeyboardChange(true);\n }),\n keyboard.addListener(\"keyboardDidHide\", (): void => {\n this.onKeyboardChange(false);\n }),\n );\n } catch {\n /* A keyboard module that cannot be observed costs only this signal. */\n this.removeKeyboardListeners();\n this.softKeyboardVisible = false;\n this.diagnostic(\"keyboard-subscribe-failed\");\n }\n }\n\n private removeKeyboardListeners(): void {\n const subscriptions: Array<KeyboardSubscription> =\n this.keyboardSubscriptions;\n this.keyboardSubscriptions = [];\n for (const subscription of subscriptions) {\n try {\n subscription.remove();\n } catch {\n /* The host's keyboard module must not break teardown. */\n }\n }\n }\n\n /*\n * The soft keyboard came up or went away. That is the person - a field\n * tapped, a message sent - so it counts as input and resumes a paused\n * recording the way a touch does; and while it is up the idle pause\n * waits, since what is typed on it reaches no view the recorder sees.\n */\n private onKeyboardChange(visible: boolean): void {\n this.softKeyboardVisible = visible;\n if (!this.running || !this.acceptingEvents || !this.foreground) {\n return;\n }\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n if (input === \"resumed\") {\n this.startTimers();\n void this.captureTick(true);\n } else if (input === \"session-ended\") {\n /* As a touch does on a session that ended idle: the next one starts. */\n void this.maybeRotateForUser(this.now());\n }\n }\n\n private async onAppStateChange(\n state: string,\n generation: number,\n ): Promise<void> {\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n\n const isActive: boolean = state === \"active\";\n if (!isActive && this.foreground) {\n this.foreground = false;\n this.clearTimers();\n this.diagnosticsStatus = \"background\";\n if (this.rotationPromise) {\n await this.rotationPromise;\n }\n if (this.policyRefreshPromise) {\n await this.policyRefreshPromise;\n }\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n if (this.idlePause !== null || this.sealedForIdle) {\n /*\n * Paused for idle - or a touch had just ended the pause and its\n * snapshot never came, which leaves the session paused where it\n * was - or ended idle. Nothing is recorded, not even this: the\n * stream still says \"visible\" from before the pause, and the return\n * will read as the idle-resumed marker (or open the next session).\n * What the outbox already holds - the pause's own chunk, if its\n * upload failed - is still worth one try before the OS suspends\n * the app.\n */\n this.idleResumeBacklog = null;\n if (this.uploadActive) {\n await this.transport?.drain();\n }\n return;\n }\n this.appendCustom(VISIBILITY_CUSTOM_EVENT_TAG, { state: \"hidden\" });\n await this.closeCurrent(false);\n if (this.uploadActive) {\n await this.transport?.drain();\n }\n return;\n }\n\n if (isActive && !this.foreground) {\n this.foreground = true;\n /*\n * Coming back to the app is the person coming back: like a touch, it\n * ends an idle pause (#4208), and the capture below takes the snapshot\n * the paused session resumes on.\n */\n const input: IdleInputOutcome = this.noteUserInput(this.now());\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"foreground\",\n );\n if (!policyReady) {\n return;\n }\n /* Coming back to the app is the user returning. */\n const sessionIdBeforeResume: string | undefined =\n this.identity?.sessionId;\n await this.maybeRotateSession(this.now(), true);\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return;\n }\n /*\n * A return that resumes the paused session records no visibility\n * change: none was recorded when the app left, and the idle-resumed\n * marker is what the return looks like. Any other return records it\n * as it always has.\n */\n const resumedPausedSession: boolean =\n input === \"resumed\" &&\n this.identity?.sessionId === sessionIdBeforeResume;\n if (!resumedPausedSession) {\n this.appendCustom(VISIBILITY_CUSTOM_EVENT_TAG, { state: \"visible\" });\n }\n /*\n * Any other return takes a fresh checkout, as the screen may have\n * changed while the app was away. A session the return just started\n * already leads with a snapshot of this screen; a second one would\n * only repeat it.\n */\n const openedOnSnapshot: boolean =\n this.identity?.sessionId !== sessionIdBeforeResume &&\n this.lastFullSnapshotAtUnixMs > 0;\n if (!openedOnSnapshot) {\n this.forceFullSnapshot = true;\n }\n this.startTimers();\n this.diagnosticsStatus =\n this.consentState() === \"Unknown\" ? \"consent-required\" : \"recording\";\n await this.captureTick(!openedOnSnapshot);\n\n /*\n * Offline mode: returning to the app is the most likely moment the\n * connection is back (the train left the tunnel while the phone was in\n * a pocket), so the backlog is tried now rather than on its timer.\n */\n if (this.uploadActive && this.running) {\n this.transport?.resume();\n }\n }\n }\n\n private startTimers(): void {\n this.clearTimers();\n const intervalMs: number = Math.max(\n 250,\n Math.min(\n 5_000,\n typeof this.options?.captureIntervalMs === \"number\" &&\n Number.isFinite(this.options.captureIntervalMs)\n ? this.options.captureIntervalMs\n : MOBILE_CAPTURE_INTERVAL_MS,\n ),\n );\n this.captureTimer = setInterval((): void => {\n void this.captureTick();\n }, intervalMs);\n this.flushTimer = setInterval((): void => {\n /*\n * Paused for idle, this is the only timer left running, and all it\n * does is end a session nobody came back to: maybeRotateSession seals\n * it once its idle window runs out (see sealForIdle).\n */\n if (this.isIdlePaused()) {\n if (this.acceptingEvents) {\n void this.maybeRotateSession(this.now());\n }\n return;\n }\n if (this.acceptingEvents) {\n void this.closeCurrent(false);\n }\n }, SESSION_REPLAY_FLUSH_INTERVAL_MS);\n }\n\n /*\n * The sampler alone. An idle pause stops it - every tick is a native\n * traversal of the whole view tree, which is what a pause is for not\n * paying - and keeps the 15-second flush timer as its heartbeat, rather\n * than waking the JS thread twice a second to find nothing to do.\n */\n private stopCaptureTimer(): void {\n if (this.captureTimer) {\n clearInterval(this.captureTimer);\n this.captureTimer = null;\n }\n }\n\n private clearTimers(): void {\n this.stopCaptureTimer();\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n private installGlobalErrorHandler(): void {\n const globals: Record<string, unknown> = globalThis as unknown as Record<\n string,\n unknown\n >;\n const errorUtils: GlobalErrorUtils | undefined = globals[\"ErrorUtils\"] as\n | GlobalErrorUtils\n | undefined;\n const previous: GlobalErrorHandler | undefined =\n errorUtils?.getGlobalHandler?.();\n if (!errorUtils?.setGlobalHandler || typeof previous !== \"function\") {\n return;\n }\n\n this.globalErrorUtils = errorUtils;\n this.previousGlobalErrorHandler = previous;\n const handlerGeneration: number = this.lifecycleGeneration;\n const installedHandler: GlobalErrorHandler = (\n error: Error,\n isFatal?: boolean,\n ): void => {\n if (\n this.installedGlobalErrorHandler === installedHandler &&\n this.lifecycleGeneration === handlerGeneration\n ) {\n void this.captureError(error);\n }\n try {\n previous?.(error, isFatal);\n } catch {\n /* A pre-existing handler remains isolated from the recorder. */\n }\n };\n this.installedGlobalErrorHandler = installedHandler;\n errorUtils.setGlobalHandler(installedHandler);\n }\n\n private restoreGlobalErrorHandler(): void {\n if (\n this.globalErrorUtils?.setGlobalHandler &&\n this.globalErrorUtils.getGlobalHandler?.() ===\n this.installedGlobalErrorHandler &&\n this.previousGlobalErrorHandler\n ) {\n this.globalErrorUtils.setGlobalHandler(this.previousGlobalErrorHandler);\n }\n this.globalErrorUtils = null;\n this.previousGlobalErrorHandler = null;\n this.installedGlobalErrorHandler = null;\n }\n\n private createTransport(\n startOptions: ValidatedStartOptions,\n outbox: ReplayOutbox,\n ): ReplayTransport {\n const transport: ReplayTransport = new ReplayTransport({\n startOptions,\n outbox,\n onDirective: (\n directive: SessionReplayDirective,\n reason: string | null,\n ): void => {\n this.onDirective(directive, reason);\n },\n onDiagnostic: (code: string, details?: Record<string, unknown>): void => {\n this.diagnostic(code, details);\n if (code === \"back-online\") {\n this.onBackOnline();\n }\n },\n });\n if (this.lastConnectivity !== null) {\n transport.setConnectivity(this.lastConnectivity);\n }\n return transport;\n }\n\n private onDirective(\n directive: SessionReplayDirective,\n reason: string | null,\n ): void {\n this.diagnostic(\"server-directive\", { directive, reason });\n if (directive === \"stop\") {\n this.disable(\"server-stopped\", { reason });\n this.haltCapture();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.uploadActive = false;\n this.transport?.destroy();\n }\n }\n\n private haltCapture(): void {\n this.running = false;\n this.acceptingEvents = false;\n this.quiesceCapture();\n this.notifySessionChange();\n }\n\n private notifySessionChange(): void {\n const sessionId: string | null = this.getSessionId();\n if (sessionId === this.lastNotifiedSessionId) {\n return;\n }\n this.lastNotifiedSessionId = sessionId;\n for (const listener of this.sessionChangeListeners) {\n try {\n listener(sessionId);\n } catch {\n /* Host observers cannot interrupt capture. */\n }\n }\n }\n\n private quiesceCapture(): void {\n this.clearTimers();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n this.removeKeyboardListeners();\n this.stopConnectivity();\n this.restoreGlobalErrorHandler();\n }\n\n /*\n * Whether this device may be written to under a policy. Nothing is stored\n * before an explicit consent the policy requires - the cached policy\n * included, even though it holds no user data - except a removal: a\n * policy that says replay is off always deletes the cached one.\n */\n /*\n * The cached policy goes with everything else when consent does: it holds\n * no user data, but \"nothing of the recorder stays on the device\" is the\n * promise, and the next consented policy fetch writes it again.\n */\n private async forgetCachedConfig(): Promise<void> {\n if (this.options) {\n await forgetReplayConfig(\n this.storage,\n getReplayStorageNamespace(this.options),\n );\n }\n }\n\n /*\n * The product analytics events and metric points the device kept unsent\n * (issue #9577) go with consent too, as the outbox's chunks do - a\n * channel running now drops its own (forget(), reset()), and this\n * removes them whether one runs or not, a previous launch's included.\n */\n private async forgetStoredProductAnalytics(): Promise<void> {\n if (this.options) {\n await clearStoredProductAnalytics(\n this.storage,\n getReplayStorageNamespace(this.options),\n );\n }\n }\n\n private mayPersistUnder(config: ResolvedReplayConfig): boolean {\n return (\n !config.enabled ||\n config.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted\n );\n }\n\n private subscribeConnectivity(options: ValidatedStartOptions): void {\n this.stopConnectivity();\n this.lastConnectivity = null;\n if (!options.connectivity) {\n return;\n }\n\n try {\n const unsubscribe: unknown = options.connectivity.subscribe(\n (isConnected: boolean | null): void => {\n const connected: boolean | null =\n typeof isConnected === \"boolean\" ? isConnected : null;\n if (connected === this.lastConnectivity) {\n return;\n }\n this.lastConnectivity = connected;\n if (connected !== null) {\n this.diagnostic(connected ? \"network-online\" : \"network-offline\");\n }\n this.transport?.setConnectivity(connected);\n if (connected === true) {\n this.onBackOnline();\n /*\n * The backlog goes now - but only while uploading is allowed. A\n * consent this run has not been given does not become one\n * because the network came back.\n */\n if (this.uploadActive && this.running) {\n this.transport?.resume();\n }\n }\n },\n );\n this.unsubscribeConnectivity =\n typeof unsubscribe === \"function\" ? (unsubscribe as () => void) : null;\n } catch {\n /* A throwing connectivity source only costs the early drain. */\n this.diagnostic(\"connectivity-subscribe-failed\");\n }\n }\n\n /* The next capture tick refreshes a stale policy (see policyStale). */\n private onBackOnline(): void {\n if (this.policyStale) {\n this.lastPolicyRefreshAtUnixMs = 0;\n }\n }\n\n private stopConnectivity(): void {\n const unsubscribe: (() => void) | null = this.unsubscribeConnectivity;\n this.unsubscribeConnectivity = null;\n try {\n unsubscribe?.();\n } catch {\n /* The host's unsubscribe must not break teardown. */\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return generation === this.lifecycleGeneration;\n }\n\n private enqueueLifecycleOperation<T>(action: () => Promise<T>): Promise<T> {\n const operation: Promise<T> = this.lifecycleQueue.then(action, action);\n this.lifecycleQueue = operation.then(\n (): void => {\n return undefined;\n },\n (): void => {\n this.diagnostic(\"lifecycle-operation-failed\");\n },\n );\n return operation;\n }\n\n private async isCurrentTouchPrivate(touch: RecordedTouch): Promise<boolean> {\n if (\n !this.rootTag ||\n !touch.targetTag ||\n typeof this.nativeViewTree.isTouchTargetPrivate !== \"function\"\n ) {\n return true;\n }\n try {\n const privateAncestry: boolean =\n await this.nativeViewTree.isTouchTargetPrivate(\n touch.targetTag,\n this.rootTag,\n );\n if (privateAncestry) {\n return true;\n }\n return isTouchPrivate(this.touchPrivacyMap, touch.x, touch.y);\n } catch {\n return true;\n }\n }\n\n private updateTouchSuppression(\n touch: RecordedTouch,\n pointIsPrivate: boolean,\n ): boolean {\n if (touch.pointerId !== undefined) {\n const pointerKey: string = `${typeof touch.pointerId}:${String(\n touch.pointerId,\n )}`;\n if (pointIsPrivate) {\n this.suppressedTouchPointers.add(pointerKey);\n }\n const suppressed: boolean = this.suppressedTouchPointers.has(pointerKey);\n if (touch.phase === \"end\") {\n this.suppressedTouchPointers.delete(pointerKey);\n }\n return suppressed;\n }\n\n if (touch.phase === \"start\") {\n this.unidentifiedTouchCount += 1;\n }\n if (pointIsPrivate) {\n this.unidentifiedTouchPrivate = true;\n }\n const suppressed: boolean = this.unidentifiedTouchPrivate;\n if (touch.phase === \"end\") {\n this.unidentifiedTouchCount = Math.max(\n 0,\n this.unidentifiedTouchCount - 1,\n );\n if (this.unidentifiedTouchCount === 0) {\n this.unidentifiedTouchPrivate = false;\n }\n }\n return suppressed;\n }\n\n private resetTouchSequences(): void {\n this.suppressedTouchPointers.clear();\n this.unidentifiedTouchCount = 0;\n this.unidentifiedTouchPrivate = false;\n this.tapCandidates.clear();\n }\n\n private async applyIdentityChange(\n ref: string | null,\n traits: Record<string, string> | null,\n identityEpoch: number,\n ): Promise<void> {\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n if (!this.running) {\n /*\n * A session the replay sample left out still sends its events\n * (#6629), and like a recording it is one person's: another user, or\n * none, starts the next session, as a recording one does.\n */\n if (\n this.analyticsOnly &&\n ref !== this.userRef &&\n this.identityPersisted &&\n this.sessionStore\n ) {\n const identity: ReplaySessionIdentity = await this.sessionStore.rotate(\n this.now(),\n );\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n this.identity = identity;\n }\n this.applyIdentityValues(ref, traits, true);\n return;\n }\n\n if (ref === this.userRef) {\n this.applyIdentityValues(ref, traits, false);\n return;\n }\n\n const wasAcceptingEvents: boolean = this.acceptingEvents;\n this.acceptingEvents = false;\n try {\n if (this.policyRefreshPromise) {\n await this.policyRefreshPromise;\n }\n if (!this.running || identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n\n /*\n * A session that went idle before anything noticed (the app sat in\n * the background) ended at its last activity. It is sealed there:\n * closed by the identity marker instead, it was dated now and\n * stretched by the whole absence. A session paused for idle (#4208)\n * is sealed the same way, before its window runs out: nobody is in\n * it, and its footage ended at the pause.\n */\n if (!this.rotationPromise && !this.sealedForIdle) {\n if (this.isIdlePaused()) {\n await this.sealForIdleNow();\n } else if (this.rotationReason(this.now()) === \"idle\") {\n await this.maybeRotateSession(this.now());\n }\n }\n\n /*\n * A session that ended idle needs no rotation to keep two accounts\n * apart: it records nothing more, and the next one - minted when the\n * user is back - belongs to the new identity. Rotating here would\n * start a session nobody is in (an inactivity logout is the usual\n * case).\n */\n if (this.rotationPromise) {\n await this.rotationPromise;\n } else if (!this.sealedForIdle) {\n this.rotatingSession = true;\n const rotation: Promise<void> = this.performSessionRotation(\n this.now(),\n \"identity\",\n );\n this.rotationPromise = rotation;\n try {\n await rotation;\n } finally {\n if (this.rotationPromise === rotation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n if (identityEpoch !== this.identityCancellationEpoch) {\n return;\n }\n this.acceptingEvents = this.running && wasAcceptingEvents;\n /* A trigger belongs to one user/session and cannot cross accounts. */\n this.triggered = false;\n this.triggerReason = SessionReplayTriggerReason.Sampled;\n this.uploadActive = this.consentState() !== \"Unknown\" && this.sampled;\n this.applyIdentityValues(ref, traits, true);\n const generation: number = this.lifecycleGeneration;\n const policyReady: boolean = await this.refreshRuntimePolicy(\n generation,\n true,\n \"identity\",\n );\n if (\n !policyReady ||\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n identityEpoch !== this.identityCancellationEpoch\n ) {\n return;\n }\n if (this.running && this.foreground) {\n this.forceFullSnapshot = true;\n void this.captureTick(true);\n }\n } finally {\n if (this.running && identityEpoch === this.identityCancellationEpoch) {\n this.acceptingEvents = wasAcceptingEvents;\n }\n }\n }\n\n private applyIdentityValues(\n ref: string | null,\n traits: Record<string, string> | null,\n clearTraitsWhenMissing: boolean,\n ): void {\n const changed: boolean = ref !== this.userRef;\n this.userRef = ref;\n if (traits) {\n this.traits = traits;\n } else if (clearTraitsWhenMissing && changed) {\n this.traits = {};\n }\n if (this.options) {\n const currentOptions: ValidatedStartOptions = { ...this.options };\n if (ref) {\n currentOptions.userRef = ref;\n } else {\n delete currentOptions.userRef;\n }\n this.options = currentOptions;\n }\n this.metaDirty = true;\n this.appendCustom(IDENTIFY_CUSTOM_EVENT_TAG, {\n identified: ref !== null,\n traitKeys: Object.keys(this.traits),\n });\n }\n\n private async refreshTargetingConfig(\n baseConfig: ResolvedReplayConfig,\n forceRefresh: boolean = false,\n ): Promise<ResolvedReplayConfig> {\n if (!this.options || (!forceRefresh && !this.userRef)) {\n return baseConfig;\n }\n const currentOptions: ValidatedStartOptions = { ...this.options };\n if (this.userRef) {\n currentOptions.userRef = this.userRef;\n } else {\n delete currentOptions.userRef;\n }\n const targetedConfig: ResolvedReplayConfig = await fetchReplayConfig(\n currentOptions,\n Boolean(this.userRef),\n forceRefresh,\n );\n return targetedConfig;\n }\n\n private async refreshRuntimePolicy(\n generation: number,\n forceRefresh: boolean,\n reason: PolicyRefreshReason,\n ): Promise<boolean> {\n if (\n !this.running ||\n !this.config ||\n !this.options ||\n !this.isCurrentGeneration(generation)\n ) {\n return false;\n }\n\n if (this.policyRefreshPromise) {\n const existingResult: boolean = await this.policyRefreshPromise;\n if (!forceRefresh || !existingResult) {\n return existingResult;\n }\n }\n\n const nowUnixMs: number = this.now();\n if (\n !forceRefresh &&\n nowUnixMs - this.lastPolicyRefreshAtUnixMs <\n MOBILE_POLICY_REFRESH_INTERVAL_MS\n ) {\n return true;\n }\n\n const operation: Promise<boolean> = this.performRuntimePolicyRefresh(\n generation,\n reason,\n nowUnixMs,\n );\n this.policyRefreshPromise = operation;\n try {\n return await operation;\n } finally {\n if (this.policyRefreshPromise === operation) {\n this.policyRefreshPromise = null;\n }\n }\n }\n\n private async performRuntimePolicyRefresh(\n generation: number,\n reason: PolicyRefreshReason,\n nowUnixMs: number,\n ): Promise<boolean> {\n if (!this.options || !this.config) {\n return false;\n }\n const previousConfig: ResolvedReplayConfig = this.config;\n const previousConsentState: SessionReplayConsentState = this.consentState();\n const wasAcceptingEvents: boolean = this.acceptingEvents;\n this.acceptingEvents = false;\n try {\n let currentOptions: ValidatedStartOptions = this.currentStartOptions();\n const maySendUserRef: boolean =\n previousConsentState !== \"Unknown\" && Boolean(currentOptions.userRef);\n let freshConfig: ResolvedReplayConfig = await fetchReplayConfig(\n currentOptions,\n maySendUserRef,\n true,\n );\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n\n if (\n freshConfig.enabled &&\n !maySendUserRef &&\n freshConfig.consentMode === SessionReplayConsentMode.NotRequired &&\n this.userRef\n ) {\n currentOptions = this.currentStartOptions();\n freshConfig = await fetchReplayConfig(currentOptions, true, true);\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n\n this.lastPolicyRefreshAtUnixMs = nowUnixMs;\n if (\n !isRetryablePolicyFailure(freshConfig) &&\n this.mayPersistUnder(freshConfig)\n ) {\n /* What the next offline launch records under (see startInternal). */\n await saveReplayConfig(\n this.storage,\n getReplayStorageNamespace(currentOptions),\n freshConfig,\n nowUnixMs,\n );\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n if (!freshConfig.enabled) {\n if (reason !== \"consent\" && isRetryablePolicyFailure(freshConfig)) {\n this.diagnostic(\"policy-refresh-failed-using-last-config\", {\n reason,\n });\n this.policyStale = true;\n return true;\n }\n this.config = freshConfig;\n await this.discardForPolicyStop(\n reason === \"consent\"\n ? \"config-disabled-after-consent\"\n : \"config-disabled-after-refresh\",\n freshConfig.disabledReason ?? \"not-reported\",\n );\n return false;\n }\n\n this.policyStale = false;\n return await this.applyRuntimePolicy(\n previousConfig,\n freshConfig,\n previousConsentState,\n wasAcceptingEvents,\n generation,\n );\n } catch (error) {\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.lastPolicyRefreshAtUnixMs = nowUnixMs;\n if (reason !== \"consent\") {\n this.diagnostic(\"policy-refresh-failed-using-last-config\", {\n reason,\n name: error instanceof Error ? error.name : \"Error\",\n });\n return true;\n }\n await this.discardForPolicyStop(\n \"config-disabled-after-consent\",\n \"config-fetch-failed\",\n );\n return false;\n } finally {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.acceptingEvents = wasAcceptingEvents;\n }\n }\n }\n\n private async applyRuntimePolicy(\n _previousConfig: ResolvedReplayConfig,\n freshConfig: ResolvedReplayConfig,\n previousConsentState: SessionReplayConsentState,\n wasAcceptingEvents: boolean,\n generation: number,\n ): Promise<boolean> {\n this.config = freshConfig;\n this.metaDirty = true;\n const analyticsStart: Promise<void> | null =\n this.syncProductAnalytics(freshConfig);\n if (analyticsStart) {\n await analyticsStart;\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n }\n const hasConsent: boolean =\n freshConfig.consentMode === SessionReplayConsentMode.NotRequired ||\n this.consentGranted;\n\n if (!hasConsent) {\n const mustWithdrawPersistedState: boolean =\n this.identityPersisted ||\n this.uploadActive ||\n previousConsentState !== \"Unknown\";\n if (mustWithdrawPersistedState) {\n /*\n * Product analytics lets go of what it held and of the session it\n * announced, and holds what comes next for the grant (#6629).\n */\n this.analytics?.reset();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n await this.sessionStore?.clear();\n await this.forgetCachedConfig();\n await this.forgetStoredProductAnalytics();\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n const nowUnixMs: number = this.now();\n this.identity = this.ephemeralIdentity(nowUnixMs);\n this.identityPersisted = false;\n this.notifySessionChange();\n this.sessionLastActivityUnixMs = nowUnixMs;\n this.sampled = false;\n this.uploadActive = false;\n this.forceFullSnapshot = true;\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.recreateTransport();\n }\n this.triggered = freshConfig.isTargeted;\n this.triggerReason = freshConfig.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n this.diagnosticsStatus = \"consent-required\";\n this.acceptingEvents = wasAcceptingEvents;\n this.diagnostic(\"policy-now-requires-consent\");\n return true;\n }\n\n if (!this.identityPersisted && this.sessionStore) {\n const sessionStore: ReplaySessionStore = this.sessionStore;\n const identity: ReplaySessionIdentity = await sessionStore.resolve(\n this.now(),\n );\n if (\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n this.sessionStore !== sessionStore\n ) {\n return false;\n }\n this.identity = identity;\n this.identityPersisted = true;\n this.notifySessionChange();\n this.sessionLastActivityUnixMs = this.now();\n }\n\n if (!this.identity) {\n return false;\n }\n this.sampled = deterministicSample(\n this.identity.sessionId,\n freshConfig.samplePercentage,\n );\n if (freshConfig.isTargeted) {\n this.triggered = true;\n this.triggerReason = SessionReplayTriggerReason.Manual;\n } else if (!this.triggered) {\n this.triggerReason = SessionReplayTriggerReason.Sampled;\n }\n\n if (\n freshConfig.captureTrigger === SessionReplayCaptureTrigger.Always &&\n !this.sampled &&\n !freshConfig.isTargeted\n ) {\n await this.discardForPolicyStop(\n \"not-sampled-after-config-refresh\",\n \"not-sampled\",\n );\n return false;\n }\n\n const shouldUpload: boolean =\n this.sampled || this.triggered || freshConfig.isTargeted;\n if (!shouldUpload && this.uploadActive) {\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.uploadActive = false;\n this.recreateTransport();\n }\n\n this.acceptingEvents = wasAcceptingEvents;\n if (shouldUpload && !this.uploadActive) {\n await this.activateUpload(generation);\n }\n if (!this.running || !this.isCurrentGeneration(generation)) {\n return false;\n }\n this.diagnosticsStatus = this.foreground ? \"recording\" : \"background\";\n this.diagnostic(\"policy-refreshed\", {\n configEpoch: freshConfig.configEpoch,\n });\n /* A session named only now (after consent) takes what was held for it. */\n this.analytics?.refresh();\n return true;\n }\n\n private currentStartOptions(): ValidatedStartOptions {\n const currentOptions: ValidatedStartOptions = {\n ...(this.options as ValidatedStartOptions),\n };\n if (this.userRef) {\n currentOptions.userRef = this.userRef;\n } else {\n delete currentOptions.userRef;\n }\n return currentOptions;\n }\n\n private recreateTransport(): void {\n if (this.options && this.outbox) {\n this.transport = this.createTransport(this.options, this.outbox);\n }\n }\n\n private async discardForPolicyStop(\n code: string,\n reason: string,\n ): Promise<void> {\n if (reason === \"not-sampled\") {\n /* Nothing more is recorded, but the session's events still count. */\n this.analyticsOnly = this.analytics !== null;\n } else {\n /* Replay is off: so are the events its recorder sends. */\n this.stopProductAnalytics();\n }\n this.disable(code, { reason });\n this.haltCapture();\n this.transport?.destroy();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.serializer.reset();\n this.touchPrivacyMap = CONSERVATIVE_TOUCH_PRIVACY_MAP;\n this.resetTouchSequences();\n this.uploadActive = false;\n await this.closeQueue.catch((): void => {\n return undefined;\n });\n await this.outbox?.clear();\n }\n\n private ephemeralIdentity(nowUnixMs: number): ReplaySessionIdentity {\n return {\n sessionId: generateReplayId(),\n tabId: generateReplayId(),\n visitorId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n chunkIndex: 0,\n };\n }\n\n /*\n * Idle before the duration cap, the order Common's SessionIdentity decides\n * them in. A session left for the idle window ended where it was left,\n * even when it has outlived the cap by the time anything notices, and\n * only an idle rotation dates its end there (see performSessionRotation):\n * called \"duration\", a session three hours old put in the background for\n * two more was sealed two hours after its footage.\n */\n private rotationReason(nowUnixMs: number): SessionRotationReason | null {\n if (!this.identity) {\n return null;\n }\n if (\n nowUnixMs - this.sessionLastActivityUnixMs >=\n SESSION_REPLAY_IDLE_ROLLOVER_MS\n ) {\n return \"idle\";\n }\n if (\n nowUnixMs - this.identity.sessionStartUnixMs >=\n SESSION_REPLAY_MAX_SESSION_MS\n ) {\n return \"duration\";\n }\n return null;\n }\n\n private runExternalActivity(nowUnixMs: number, action: () => void): void {\n if (this.pendingIdentityOperations > 0) {\n const identityBarrier: Promise<void> = this.identityQueue;\n const lifecycleEpoch: number = this.lifecycleCancellationEpoch;\n const identityEpoch: number = this.identityCancellationEpoch;\n const wasRunning: boolean = this.running;\n void identityBarrier.then((): void => {\n if (\n lifecycleEpoch !== this.lifecycleCancellationEpoch ||\n identityEpoch !== this.identityCancellationEpoch\n ) {\n return;\n }\n if (\n (this.running && this.acceptingEvents) ||\n (!wasRunning && this.diagnosticsStatus === \"idle\")\n ) {\n action();\n }\n });\n return;\n }\n if (!this.running) {\n action();\n return;\n }\n\n const shouldDefer: boolean =\n this.rotatingSession || this.rotationReason(nowUnixMs) !== null;\n if (!shouldDefer) {\n action();\n return;\n }\n\n const generation: number = this.lifecycleGeneration;\n void this.maybeRotateSession(nowUnixMs).then((): void => {\n if (this.running && this.isCurrentGeneration(generation)) {\n action();\n }\n });\n }\n\n /*\n * isUserBack: the caller knows the user is here - a touch, the app\n * returning to the foreground, an explicit captureSession(). An idle\n * session then rotates at once. Anything else (a capture tick, a route\n * change, a developer event) only finds out the session went idle, and\n * seals it to wait for them (see sealedForIdle).\n */\n private async maybeRotateSession(\n nowUnixMs: number,\n isUserBack: boolean = false,\n ): Promise<void> {\n while (this.rotationPromise) {\n await this.rotationPromise;\n /*\n * What was in flight may have been the idle seal; a returning user\n * still starts the next session after it.\n */\n if (!isUserBack || !this.sealedForIdle) {\n return;\n }\n }\n if (\n !this.running ||\n this.rotatingSession ||\n !this.identity ||\n !this.config ||\n !this.sessionStore ||\n !this.options\n ) {\n return;\n }\n\n let reason: SessionRotationReason | null;\n if (this.sealedForIdle) {\n if (!isUserBack) {\n return;\n }\n reason = \"idle\";\n } else {\n reason = this.rotationReason(nowUnixMs);\n /*\n * Paused for idle (#4208), nobody is in the session and its footage\n * already ended at the pause, so whatever ends it now - its idle\n * window, or the duration cap reached meanwhile - ends it there, as\n * idle: sealed to wait for the user, or followed at once by the next\n * session when they are back.\n */\n if (reason !== null && this.isIdlePaused()) {\n reason = \"idle\";\n }\n }\n if (!reason) {\n return;\n }\n\n this.rotatingSession = true;\n const operation: Promise<void> =\n reason === \"idle\" && !isUserBack\n ? this.sealForIdle()\n : this.performSessionRotation(nowUnixMs, reason);\n this.rotationPromise = operation;\n try {\n await operation;\n } finally {\n if (this.rotationPromise === operation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n\n /*\n * The idle seal on demand, under the lock every rotation takes: for an\n * identity change on a session paused for idle, which no clock has ended\n * yet but nobody is in.\n */\n private async sealForIdleNow(): Promise<void> {\n if (this.rotationPromise || this.rotatingSession || this.sealedForIdle) {\n return;\n }\n this.rotatingSession = true;\n const operation: Promise<void> = this.sealForIdle();\n this.rotationPromise = operation;\n try {\n await operation;\n } finally {\n if (this.rotationPromise === operation) {\n this.rotationPromise = null;\n }\n this.rotatingSession = false;\n }\n }\n\n /*\n * maybeRotateSession for a user who is here. On an app whose session\n * ended idle - or was paused for idle, which stops the capture tick too\n * (#4208) - the policy is brought up to date first: no capture tick has\n * refreshed it while the app sat idle, and the next session must not open\n * under one that has since changed (or turned replay off).\n */\n private async maybeRotateForUser(nowUnixMs: number): Promise<void> {\n if (\n (this.sealedForIdle || this.idlePause !== null) &&\n !this.rotatingSession\n ) {\n const policyReady: boolean = await this.refreshRuntimePolicy(\n this.lifecycleGeneration,\n false,\n \"periodic\",\n );\n if (!policyReady) {\n return;\n }\n }\n await this.maybeRotateSession(nowUnixMs, true);\n }\n\n /*\n * End the session as idle, where it really ended, and wait for the user.\n *\n * Sealed with whatever footage is still buffered - dated by that footage,\n * never by now - and with no marker of its own: a marker stamped now\n * would date the session's end half an hour or more after anything the\n * player can show. With nothing buffered nothing is sent, and the server\n * ends the session at its last chunk - for a session paused for idle\n * (#4208), the chunk its idle-paused marker closed.\n */\n private async sealForIdle(): Promise<void> {\n /* First, so nothing appended while the seal uploads lands in it. */\n this.sealedForIdle = true;\n /*\n * An idle pause ends with its session, and nothing is left to wait for\n * on a timer: the next input starts the next session.\n */\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.clearTimers();\n this.diagnostic(\"session-ended-idle\", {\n idleForMs: Math.max(0, this.now() - this.sessionLastActivityUnixMs),\n });\n this.notifySessionChange();\n await this.closeCurrent(true);\n await this.closeQueue;\n if (!this.running) {\n return;\n }\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n /* Pre-roll of a session that ended; a later trigger is the next one's. */\n this.rollingBuffer.clear();\n }\n /*\n * Its record goes too: written by the session's last chunk, it looks\n * recent, and a relaunch before the user is back would otherwise carry\n * on a session that is over.\n */\n if (this.running && this.identityPersisted) {\n await this.sessionStore?.end();\n }\n }\n\n private async performSessionRotation(\n nowUnixMs: number,\n reason: SessionRotationReason,\n ): Promise<void> {\n /*\n * The marker closes the outgoing session for a rotation the user was\n * active through (the duration cap, an identity change): dated now, it\n * is where that session ended. Not for an idle one. That session ended\n * at its last activity - possibly hours ago, with the app in the\n * background since - and a marker dated now, as its final chunk,\n * stretched it by the whole absence. It opens the next session instead\n * (openSessionAfterIdle). A session paused for idle rotates as idle\n * (maybeRotateSession): its footage ended at the pause.\n */\n if (reason !== \"idle\") {\n this.appendCustom(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason },\n undefined,\n true,\n );\n }\n await this.closeCurrent(true);\n await this.closeQueue;\n if (!this.running) {\n return;\n }\n if (this.uploadActive) {\n await this.transport?.drain();\n } else {\n this.rollingBuffer.clear();\n }\n if (!this.running) {\n return;\n }\n\n await this.completeSessionIdentityRotation(nowUnixMs, reason);\n if (reason === \"idle\" && this.running) {\n await this.openSessionAfterIdle();\n }\n }\n\n /*\n * The first things a session after an idle one records: a full snapshot\n * of the screen the user came back to, then the rotation marker - the\n * snapshot first, so chunk 0 is a seek anchor rather than a lone marker.\n *\n * Taken here, inside the rotation, rather than left to the next capture\n * tick: until the rotation settles, touches are dropped and every other\n * event waits for it (rotatingSession), so nothing can land ahead of the\n * snapshot. A user who has just come back is touching the screen, and\n * half a second of that was otherwise a chunk 0 with no screen in it.\n *\n * In the background or without a registered root there is no screen to\n * capture yet; the marker opens the session alone.\n */\n private async openSessionAfterIdle(): Promise<void> {\n const generation: number = this.lifecycleGeneration;\n const rootTag: number | null = this.rootTag;\n const options: ValidatedStartOptions | null = this.options;\n const sessionId: string | undefined = this.identity?.sessionId;\n if (this.foreground && rootTag && options && sessionId) {\n const capturedAtUnixMs: number = this.now();\n let tree: NativeViewTreeNode;\n try {\n tree = await this.nativeViewTree.captureViewTree(rootTag);\n } catch (error) {\n if (this.running && this.isCurrentGeneration(generation)) {\n this.disable(\"native-capture-failed\", {\n name: error instanceof Error ? error.name : \"Error\",\n });\n this.haltCapture();\n }\n return;\n }\n if (\n !this.running ||\n !this.isCurrentGeneration(generation) ||\n this.identity?.sessionId !== sessionId\n ) {\n return;\n }\n if (this.foreground) {\n this.touchPrivacyMap = deriveTouchPrivacyMap(tree);\n this.appendCapture(tree, options, capturedAtUnixMs, true);\n }\n }\n this.appendCustom(\n SESSION_ROTATED_CUSTOM_EVENT_TAG,\n { reason: \"idle\" },\n undefined,\n true,\n );\n }\n\n private async completeSessionIdentityRotation(\n nowUnixMs: number,\n reason: SessionRotationReason,\n ): Promise<void> {\n if (!this.sessionStore || !this.config || !this.options) {\n return;\n }\n this.identity = this.identityPersisted\n ? await this.sessionStore!.rotate(nowUnixMs)\n : this.ephemeralIdentity(nowUnixMs);\n /*\n * Before the notification, which hands the host the new id. An idle\n * pause, and whatever was held for its resume, belong to the session\n * that just ended (#4208): the new one opens on a snapshot of its own.\n */\n this.sealedForIdle = false;\n this.idlePause = null;\n this.idleResumeBacklog = null;\n this.notifySessionChange();\n this.sampled = this.identityPersisted\n ? deterministicSample(\n this.identity.sessionId,\n this.config.samplePercentage,\n )\n : false;\n this.triggered = this.config.isTargeted;\n this.triggerReason = this.config.isTargeted\n ? SessionReplayTriggerReason.Manual\n : SessionReplayTriggerReason.Sampled;\n this.uploadActive =\n this.consentState() !== \"Unknown\" &&\n (this.sampled || this.config.isTargeted);\n this.serializer.reset();\n this.chunkBuffer.clear();\n this.rollingBuffer.clear();\n this.forceFullSnapshot = true;\n this.lastFullSnapshotAtUnixMs = 0;\n this.sessionLastActivityUnixMs = nowUnixMs;\n this.metaDirty = true;\n this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);\n this.diagnostic(\"session-rotated\", { reason });\n\n if (\n this.config.captureTrigger === SessionReplayCaptureTrigger.Always &&\n this.identityPersisted &&\n !this.sampled &&\n !this.config.isTargeted\n ) {\n /* Nothing of it is recorded, but its events still count (#6629). */\n this.analyticsOnly = this.analytics !== null;\n this.disable(\"not-sampled\");\n this.haltCapture();\n return;\n }\n\n /*\n * An idle pause or seal had stopped the sampler. The new session\n * samples again - and, if nobody is there (a rotation nobody's input\n * caused, such as the chunk cap reached by the pause's own chunk),\n * pauses again on its own.\n */\n if (this.captureTimer === null && this.running && this.foreground) {\n this.startTimers();\n }\n }\n\n /*\n * The app's name, version and system, as the start options and then the\n * native module say them. False when a newer start or a stop took over\n * meanwhile.\n */\n private async readAppMetadata(\n validated: ValidatedStartOptions,\n generation: number,\n ): Promise<boolean> {\n try {\n const nativeMetadata: NativeAppMetadata =\n await this.nativeViewTree.getAppMetadata();\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n this.metadata = {\n appName: safeMetadataValue(\n validated.appName,\n safeMetadataValue(nativeMetadata?.appName, \"React Native\"),\n ),\n appVersion: safeMetadataValue(\n validated.appVersion,\n safeMetadataValue(nativeMetadata?.appVersion, \"unknown\"),\n ),\n osName: safeMetadataValue(nativeMetadata?.osName, \"unknown\"),\n osVersion: safeMetadataValue(nativeMetadata?.osVersion, \"unknown\"),\n };\n } catch {\n if (!this.isCurrentGeneration(generation)) {\n return false;\n }\n this.diagnostic(\"native-metadata-unavailable\");\n }\n return true;\n }\n\n /*\n * Product analytics events (issue #6629, src/ProductAnalytics.ts), when\n * the application has them on: the channel asks this recorder for the\n * session, the visitor, consent and who is signed in, so an event and a\n * recording of the same visit carry the same ids.\n */\n private async startProductAnalytics(\n options: ValidatedStartOptions,\n config: ResolvedReplayConfig,\n namespace: string,\n ): Promise<void> {\n if (this.analytics || !config.productAnalytics.enabled) {\n return;\n }\n\n const analytics: MobileProductAnalytics = new MobileProductAnalytics(\n {\n url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,\n headers: mobileRequestHeaders(options),\n fetch: options.fetch,\n now: this.now,\n storage: this.storage,\n namespace,\n appState: this.appState,\n connectivity: options.connectivity,\n getSessionId: (nowUnixMs: number): string => {\n return this.analyticsSessionId(nowUnixMs, true);\n },\n peekSessionId: (): string => {\n return this.analyticsSessionId(this.now(), false);\n },\n getVisitorId: (): string => {\n return this.identityPersisted ? this.identity?.visitorId ?? \"\" : \"\";\n },\n getConsentState: (): SessionReplayConsentState => {\n return this.consentState();\n },\n requiresConsent: (): boolean => {\n return (\n this.config?.consentMode ===\n SessionReplayConsentMode.RequireExplicit\n );\n },\n getIdentity: (): ProductAnalyticsIdentity => {\n return this.analyticsIdentity();\n },\n toProperties: (value: unknown): Record<string, string> => {\n return maskStringMapValues(\n sanitizeEventProperties(value),\n this.readableEventPropertyKeys(),\n );\n },\n getContext: (): ProductAnalyticsWireContext => {\n return this.analyticsContext();\n },\n onDiagnostic: (\n code: string,\n details?: Record<string, unknown>,\n ): void => {\n this.diagnostic(code, details);\n },\n },\n config.productAnalytics,\n );\n this.analytics = analytics;\n await analytics.start();\n }\n\n /*\n * Ends the product analytics channel this recorder started; `flushFirst`\n * sends what it holds first (stop()).\n */\n private stopProductAnalytics(flushFirst: boolean = false): void {\n const analytics: MobileProductAnalytics | null = this.analytics;\n this.analytics = null;\n this.analyticsOnly = false;\n if (!analytics) {\n return;\n }\n if (flushFirst) {\n analytics.flush(true);\n }\n analytics.stop();\n }\n\n /*\n * A refreshed policy's product analytics: switched off, the channel\n * stops; switched on, it starts - again, too, after the server said they\n * were off - and its trait keys follow the policy. A promise only when a\n * channel has to start.\n */\n private syncProductAnalytics(\n config: ResolvedReplayConfig,\n ): Promise<void> | null {\n if (!config.productAnalytics.enabled) {\n this.stopProductAnalytics();\n return null;\n }\n if (this.analytics && this.analytics.getStopReason() !== \"not-enabled\") {\n this.analytics.setConfig(config.productAnalytics);\n return null;\n }\n if (!this.options) {\n return null;\n }\n const options: ValidatedStartOptions = this.currentStartOptions();\n this.stopProductAnalytics();\n return this.startProductAnalytics(\n options,\n config,\n getReplayStorageNamespace(options),\n );\n }\n\n /*\n * The session a product analytics event belongs to (issue #6629). The\n * recording's own while the recorder runs: it rotates its session\n * itself, and a session that ended idle keeps its id until the next one\n * starts. \"\" before consent, when the session the recorder holds is a\n * throwaway: the events wait for the one the grant opens. A session the\n * replay sample left out records nothing, so an event is its activity\n * (isActivity), and keeps it alive or rolls it over.\n */\n private analyticsSessionId(nowUnixMs: number, isActivity: boolean): string {\n if (!this.identity || !this.identityPersisted) {\n return \"\";\n }\n if (this.running) {\n return this.identity.sessionId;\n }\n if (this.analyticsOnly && this.sessionStore) {\n if (isActivity) {\n const continued: ReplaySessionIdentity | null =\n this.sessionStore.continueSession(nowUnixMs);\n if (continued) {\n this.identity = continued;\n }\n }\n return this.identity.sessionId;\n }\n return \"\";\n }\n\n /* Who is signed in, only while the application captures identity. */\n private analyticsIdentity(): ProductAnalyticsIdentity {\n if (this.config?.captureUserIdentity !== true || !this.userRef) {\n return { userRef: \"\", traits: null };\n }\n return { userRef: this.userRef, traits: { ...this.traits } };\n }\n\n /*\n * What the app runs on, as its recorded sessions are filed (Common's\n * RumProductAnalyticsSession): a phone, or a tablet from a shorter side\n * of 600 points; no browser; the system the native module names; and the\n * app's version, from the start options or the native module.\n */\n private analyticsContext(): ProductAnalyticsWireContext {\n const size: { width: number; height: number } = getViewport();\n const known: (value: string) => string = (value: string): string => {\n return value === \"unknown\" ? \"\" : value;\n };\n return {\n deviceType:\n Math.min(size.width, size.height) >=\n PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE\n ? \"tablet\"\n : \"mobile\",\n browserName: \"\",\n osName: known(this.metadata.osName)\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),\n appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion)),\n };\n }\n\n private disable(code: string, details?: Record<string, unknown>): void {\n this.diagnosticsStatus = \"disabled\";\n this.diagnostic(code, details);\n }\n\n private diagnostic(code: string, details?: Record<string, unknown>): void {\n const event: MobileReplayDiagnosticEvent = {\n code,\n atUnixMs: this.now(),\n };\n if (details) {\n event.details = details;\n }\n this.diagnosticsEvents.push(event);\n if (this.diagnosticsEvents.length > MAX_DIAGNOSTIC_EVENTS) {\n this.diagnosticsEvents.shift();\n }\n if (this.options?.debug) {\n // eslint-disable-next-line no-console\n console.info(`[OneUptime Replay] ${code}`, details ?? {});\n }\n }\n}\n\nexport { deterministicSample };\n", "/*\n * Build-time copy of the pure session-replay wire contract. This package is\n * installed in customer React Native applications and must not pull the\n * OneUptime monorepo's Common package into their bundle. Contract-parity\n * tests compare these additive constants with Common in the repository.\n */\n\nexport const SESSION_REPLAY_WIRE_VERSION: number = 1;\nexport const SESSION_REPLAY_SCHEMA_VERSION: number = 1;\n/*\n * octet-stream, not a vendor type: a web application firewall on the OWASP\n * Core Rule Set (Azure Front Door among them) refuses a Content-Type that\n * is not on its allowlist, and octet-stream is on it and never parsed. The\n * server accepts both. See Common/Types/Rum/SessionReplay.\n */\nexport const SESSION_REPLAY_CONTENT_TYPE: string = \"application/octet-stream\";\nexport const SESSION_REPLAY_LEGACY_CONTENT_TYPE: string =\n \"application/vnd.oneuptime.session-replay.v1\";\n\n/*\n * Copy of Common/Utils/Rum/SessionReplayWireEncoding, which explains why a\n * frame's envelope line has its `%`, `&` and `http/` escaped and a space\n * before its newline: a firewall's request-smuggling rule (CRS 921110)\n * would otherwise read a trait value or a URL plus that newline as an HTTP\n * request line.\n */\nexport const SESSION_REPLAY_ENVELOPE_TERMINATOR: string = \" \\n\";\n\nconst ESCAPED_SEQUENCES: RegExp = /[%&]|(http)\\//gi;\n\nexport function escapeSessionReplayJson(json: string): string {\n return json.replace(\n ESCAPED_SEQUENCES,\n (match: string, http: string | undefined): string => {\n if (http !== undefined) {\n return `${http}\\\\/`;\n }\n\n return match === \"%\" ? \"\\\\u0025\" : \"\\\\u0026\";\n },\n );\n}\n\nexport function encodeSessionReplayEnvelopeLine(envelope: unknown): string {\n return (\n escapeSessionReplayJson(JSON.stringify(envelope)) +\n SESSION_REPLAY_ENVELOPE_TERMINATOR\n );\n}\n\nexport const SESSION_REPLAY_APP_IDENTIFIER_HEADER: string =\n \"x-oneuptime-app-identifier\";\nexport const SESSION_REPLAY_RECORDER_KIND_HEADER: string =\n \"x-oneuptime-replay-recorder-kind\";\nexport const SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER: string =\n \"x-oneuptime-mobile-app-identifier\";\nexport const SESSION_REPLAY_USER_REF_HEADER: string = \"x-oneuptime-user-ref\";\nexport const SESSION_REPLAY_MAX_USER_REF_LENGTH: number = 512;\nexport const AUTH_TOKEN_HEADER: string = \"x-oneuptime-token\";\n\nexport const CONFIG_PATH: string = \"/telemetry/session-replay/v1/config\";\nexport const CHUNK_PATH: string = \"/telemetry/session-replay/v1/chunk\";\nexport const SESSION_REPLAY_FLUSH_INTERVAL_MS: number = 15_000;\nexport const SESSION_REPLAY_FLUSH_BYTES: number = 256 * 1024;\nexport const SESSION_REPLAY_CHECKOUT_INTERVAL_MS: number = 60_000;\nexport const SESSION_REPLAY_ROLLING_BUFFER_MS: number = 60_000;\nexport const SESSION_REPLAY_ROLLING_BUFFER_BYTES: number = 2 * 1024 * 1024;\nexport const SESSION_REPLAY_IDLE_ROLLOVER_MS: number = 30 * 60_000;\n/*\n * How long the recorder keeps capturing with nobody using the app (Common's\n * SESSION_REPLAY_IDLE_PAUSE_MS). After this long without a touch it stops\n * capturing altogether - no view-tree sample, no checkout, no chunk - and\n * the next touch, or the app coming back to the foreground, resumes the\n * same session on a fresh snapshot, as long as that comes inside\n * SESSION_REPLAY_IDLE_ROLLOVER_MS.\n */\nexport const SESSION_REPLAY_IDLE_PAUSE_MS: number = 5 * 60_000;\nexport const SESSION_REPLAY_MAX_SESSION_MS: number = 4 * 60 * 60_000;\nexport const SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES: number =\n 8 * 1024 * 1024;\nexport const MAX_SESSION_REPLAY_CHUNK_BYTES: number = 2 * 1024 * 1024;\nexport const MAX_SESSION_REPLAY_CHUNKS_PER_SESSION: number = 480;\n/*\n * Offline mode: how long a chunk may wait on the device for a connection.\n * The server allows exactly this much upload delay when it places a late\n * recording on its timeline (Common's SESSION_REPLAY_MAX_OFFLINE_DELAY_MS).\n */\nexport const SESSION_REPLAY_MAX_OFFLINE_DELAY_MS: number =\n 3 * 24 * 60 * 60 * 1000;\nexport const MOBILE_CAPTURE_INTERVAL_MS: number = 500;\ntype MobileRecorderKind = \"rn-view-tree\";\nexport const MOBILE_RECORDER_KIND: MobileRecorderKind = \"rn-view-tree\";\nexport const SYNTHETIC_RRWEB_VERSION: string = \"synthetic-1\";\n\ndeclare const __ONEUPTIME_MOBILE_RECORDER_VERSION__: string;\n\nexport const RECORDER_VERSION: string =\n typeof __ONEUPTIME_MOBILE_RECORDER_VERSION__ === \"string\"\n ? __ONEUPTIME_MOBILE_RECORDER_VERSION__\n : \"0.0.0-dev\";\n\nexport const SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES: ReadonlyArray<string> =\n [\n \"mobile-view-tree\",\n \"mobile-touch-events\",\n \"custom-events\",\n \"traits\",\n \"tags\",\n \"visibility\",\n \"visitor-id\",\n \"route-events\",\n \"js-errors\",\n ];\n\nexport enum SessionReplayMaskingMode {\n MaskSensitiveInputsOnly = \"MaskSensitiveInputsOnly\",\n MaskInputsOnly = \"MaskInputsOnly\",\n MaskAllText = \"MaskAllText\",\n}\n\nexport enum SessionReplayConsentMode {\n RequireExplicit = \"RequireExplicit\",\n NotRequired = \"NotRequired\",\n}\n\nexport enum SessionReplayCaptureTrigger {\n Always = \"Always\",\n OnErrorOrFrustration = \"OnErrorOrFrustration\",\n}\n\nexport enum SessionReplayTriggerReason {\n Error = \"error\",\n Frustration = \"frustration\",\n Sampled = \"sampled\",\n Manual = \"manual\",\n Performance = \"performance\",\n}\n\nexport enum SessionReplayFidelityNotice {\n MobileImagesOpaque = \"mobile-images-opaque\",\n MobileWebViewOpaque = \"mobile-webview-opaque\",\n MobileCanvasOpaque = \"mobile-canvas-opaque\",\n MobileAnimationSampled = \"mobile-animation-sampled\",\n BufferOverflow = \"buffer-overflow\",\n SnapshotTooLarge = \"snapshot-too-large\",\n}\n\n/*\n * Frustration signals (issue #6443), copied from Common's\n * Types/Rum/SessionReplayFrustrationSignals: what the config response\n * carries about the application's rules and its signals of its own, and\n * how a chunk counts the signals it saw. ContractParity holds every type\n * and number here identical to Common's.\n *\n * This recorder detects the application's own tap, page, event and error\n * signals. The built-in rules (rage, dead and error clicks, refresh rage)\n * and click signals are about a mouse on a web page, and only the browser\n * recorder detects them.\n */\nexport type SessionReplayCustomSignalTrigger =\n | \"click\"\n | \"tap\"\n | \"page\"\n | \"event\"\n | \"error\";\n\nexport interface SessionReplayRageClickRule {\n isEnabled: boolean;\n clickCount: number;\n windowMs: number;\n radiusPx: number;\n ignoreSelectors: Array<string>;\n}\n\nexport interface SessionReplayDeadClickRule {\n isEnabled: boolean;\n timeoutMs: number;\n ignoreSelectors: Array<string>;\n}\n\nexport interface SessionReplayErrorClickRule {\n isEnabled: boolean;\n windowMs: number;\n}\n\nexport interface SessionReplayRefreshRageRule {\n isEnabled: boolean;\n reloadCount: number;\n windowSeconds: number;\n}\n\nexport interface SessionReplayCustomSignalConfig {\n name: string;\n trigger: SessionReplayCustomSignalTrigger;\n match: string;\n isFrustration: boolean;\n}\n\nexport interface SessionReplayFrustrationSignalsConfig {\n rageClick: SessionReplayRageClickRule;\n deadClick: SessionReplayDeadClickRule;\n errorClick: SessionReplayErrorClickRule;\n refreshRage: SessionReplayRefreshRageRule;\n customSignals: Array<SessionReplayCustomSignalConfig>;\n}\n\nexport interface SessionReplayCustomSignalCount {\n name: string;\n count: number;\n frustrationCount: number;\n}\n\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNALS: number = 20;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH: number = 40;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH: number = 200;\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH: number = 64;\n/* The same signal is not counted twice within a second. */\nexport const SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS: number = 1000;\n/* How many signal markers one chunk holds. */\nexport const SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK: number = 50;\n\nexport type SessionReplayConsentState = \"Granted\" | \"NotRequired\" | \"Unknown\";\nexport type SessionReplayDirective = \"continue\" | \"stop\" | \"throttle\";\nexport type SessionReplayPayloadEncoding = \"gzip\" | \"identity\";\nexport type SessionReplayRecorderKind = \"dom\" | \"rn-view-tree\";\n\nexport interface SessionReplayConfigResponse {\n enabled: boolean;\n recorderVersion: string;\n maskingMode: SessionReplayMaskingMode;\n captureTrigger: string;\n consentMode: SessionReplayConsentMode;\n samplePercentage: number;\n maskSelectors: Array<string>;\n blockSelectors: Array<string>;\n urlAllowlist: Array<string>;\n recordCanvas: boolean;\n captureUserIdentity: boolean;\n ignoreErrorPatterns: Array<string>;\n respectDoNotTrack: boolean;\n configEpoch: number;\n directive: SessionReplayDirective;\n isTargeted?: boolean;\n disabledReason?: string;\n disabledDetail?: string;\n budgetResetsAt?: string;\n debug?: boolean;\n frustrationSignals?: SessionReplayFrustrationSignalsConfig;\n /*\n * Product analytics events (Common's SessionReplayConfigResponse\n * .productAnalytics, issue #6629): absent reads as off.\n */\n productAnalytics?: {\n enabled: boolean;\n userPropertyKeys: Array<string>;\n };\n /*\n * Readable event properties (Common's SessionReplayConfigResponse\n * .readableEventPropertyKeys, issue #7501): the property keys whose short\n * token values stay as written. Absent reads as none.\n */\n readableEventPropertyKeys?: Array<string>;\n}\n\nexport interface SessionReplaySignalCounts {\n errorCount: number;\n rageClickCount: number;\n deadClickCount: number;\n errorClickCount: number;\n refreshRageCount: number;\n routeCount: number;\n clickCount?: number;\n customEventCount?: number;\n customSignals?: Array<SessionReplayCustomSignalCount>;\n}\n\n/* The counts a chunk adds one to at a time. */\nexport type SessionReplayNumericSignalKey = Exclude<\n keyof SessionReplaySignalCounts,\n \"customSignals\"\n>;\n\nexport interface SessionReplayChunkMeta {\n entryUrl: string;\n browserName: string;\n browserVersion: string;\n osName: string;\n deviceType: string;\n viewportWidth: number;\n viewportHeight: number;\n identifiedUserRef?: string;\n visitorId?: string;\n identifiedUserTraits?: Record<string, string>;\n tags?: Record<string, string>;\n}\n\nexport interface SessionReplayChunkEnvelope {\n v: number;\n appIdentifier: string;\n sessionId: string;\n tabId: string;\n chunkIndex: number;\n sessionStartUnixMs: number;\n clientSendUnixMs: number;\n chunkStartOffsetMs: number;\n chunkEndOffsetMs: number;\n eventCount: number;\n hasFullSnapshot: boolean;\n isFinal: boolean;\n recorderKind: SessionReplayRecorderKind;\n schemaVersion: number;\n rrwebVersion: string;\n recorderVersion: string;\n maskingMode: SessionReplayMaskingMode;\n consentState: SessionReplayConsentState;\n triggerReason: SessionReplayTriggerReason;\n payloadEncoding: SessionReplayPayloadEncoding;\n payloadBytes: number;\n url: string;\n routes?: Array<string>;\n signals: SessionReplaySignalCounts;\n fidelityNotices: Array<string>;\n droppedEvents: number;\n flushFailures: number;\n meta?: SessionReplayChunkMeta;\n capabilities?: Array<string>;\n}\n\nexport interface SessionReplayChunkResponse {\n directive: SessionReplayDirective;\n configEpoch: number;\n retryAfterSeconds?: number;\n reason?: string;\n}\n\nexport enum RrwebEventType {\n DomContentLoaded = 0,\n Load = 1,\n FullSnapshot = 2,\n IncrementalSnapshot = 3,\n Meta = 4,\n Custom = 5,\n}\n\nexport enum RrwebIncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n}\n\nexport enum RrwebMouseInteractionType {\n TouchStart = 7,\n TouchEnd = 9,\n}\n\nexport interface RrwebEvent<TData = unknown> {\n type: RrwebEventType;\n data: TData;\n timestamp: number;\n}\n\nexport const ROUTE_CUSTOM_EVENT_TAG: string = \"oneuptime.route\";\nexport const ERROR_CUSTOM_EVENT_TAG: string = \"oneuptime.error\";\nexport const CUSTOM_EVENT_TAG: string = \"oneuptime.custom\";\nexport const IDENTIFY_CUSTOM_EVENT_TAG: string = \"oneuptime.identify\";\nexport const TAGS_CUSTOM_EVENT_TAG: string = \"oneuptime.tags\";\nexport const VISIBILITY_CUSTOM_EVENT_TAG: string = \"oneuptime.visibility\";\nexport const TOUCH_CUSTOM_EVENT_TAG: string = \"oneuptime.touch\";\nexport const SESSION_ROTATED_CUSTOM_EVENT_TAG: string =\n \"oneuptime.session-rotated\";\n\n/*\n * A signal of the application's own (Common's\n * SessionReplayCustomEventTag.CustomSignal and its payload). Carries the\n * signal's name, never what it matched: not the error's text, not the\n * route.\n */\nexport const CUSTOM_SIGNAL_CUSTOM_EVENT_TAG: string = \"oneuptime.signal\";\n\nexport interface SessionReplayCustomSignalPayload {\n name: string;\n trigger: SessionReplayCustomSignalTrigger;\n isFrustration: boolean;\n atUnixMs: number;\n /*\n * Present for click signals, and for a tap signal whose touch was\n * recorded. Viewport coordinates, never content.\n */\n x?: number;\n y?: number;\n}\n\n/*\n * The idle pause's two markers, copied from Common's\n * SessionReplayCustomEvents with their payloads. The player draws the\n * stretch between them as unrecorded rather than as footage of a screen\n * that sat still, so nothing at all is recorded between the two.\n */\nexport const IDLE_PAUSED_CUSTOM_EVENT_TAG: string = \"oneuptime.idle-paused\";\nexport const IDLE_RESUMED_CUSTOM_EVENT_TAG: string = \"oneuptime.idle-resumed\";\n\n/* The last thing in the stream before an idle pause. */\nexport interface SessionReplayIdlePausedPayload {\n /* The last input before the pause: where the user actually stopped. */\n idleSinceUnixMs: number;\n /* When capture stopped. */\n pausedAtUnixMs: number;\n /*\n * \"page\" when a web page paused recording itself (the browser recorder's\n * OneUptimeReplay.pause(), issue #6834). This recorder has no such call\n * and never sets it: every pause it marks is one nobody used the app for.\n */\n reason?: \"page\";\n}\n\n/*\n * The first marker after an idle pause, directly behind the fresh snapshot\n * that resumed capture. Carries the pause's start too, so the unrecorded\n * stretch can be drawn from this marker alone.\n */\nexport interface SessionReplayIdleResumedPayload {\n pausedAtUnixMs: number;\n resumedAtUnixMs: number;\n /*\n * The reason of the pause this ends, as its paused marker gave it\n * (issue #7498). Never set here, as reason is never set on a paused\n * marker of this recorder's.\n */\n reason?: \"page\";\n}\n", "import {\n SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES,\n SessionReplaySignalCounts,\n} from \"./Contract\";\n\nexport const MAX_TRAIT_KEYS: number = 20;\nexport const MAX_TRAIT_KEY_LENGTH: number = 40;\nexport const MAX_TRAIT_VALUE_LENGTH: number = 200;\nexport const MAX_TAG_KEYS: number = 20;\nexport const MAX_TAG_KEY_LENGTH: number = 32;\nexport const MAX_TAG_VALUE_LENGTH: number = 128;\nexport const MAX_CUSTOM_EVENT_NAME_LENGTH: number = 64;\nexport const MAX_CUSTOM_EVENT_PROPERTY_KEYS: number = 20;\nexport const MAX_CAPTURE_REASON_LENGTH: number = 80;\nexport const MAX_USER_REFERENCE_LENGTH: number = 200;\n\nconst SAFE_IDENTIFIER_PATTERN: RegExp = /^[A-Za-z0-9._:-]+$/;\nconst BLOCKED_KEYS: ReadonlySet<string> = new Set<string>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\nconst UUID_SEGMENT: RegExp =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;\nconst OBJECT_ID_SEGMENT: RegExp = /^[0-9a-f]{24}$/iu;\n/*\n * An email-shaped route segment. Each run is length-bounded (a local part, a\n * domain and a last label, at the sizes RFC 5321 allows) and anchored, so a\n * segment of any length is read once from end to end - the recorder runs\n * this on the device over whatever route the app was opened at.\n */\nconst EMAIL_SEGMENT: RegExp = /^[^@\\s/]{1,64}@[^@\\s/]{1,253}\\.[^@\\s/]{1,63}$/u;\nconst LONG_DIGIT_SEGMENT: RegExp = /^\\d{9,}$/u;\n/*\n * A token in base64url or standard base64, with up to two \"=\" of padding\n * (Common's UrlScrubber, #8489).\n */\nconst OPAQUE_TOKEN_SEGMENT: RegExp = /^[A-Za-z0-9_+/-]{32,}={0,2}$/u;\n/*\n * A JSON Web Token, signed, unsigned or encrypted: a header of base64url\n * JSON (\"eyJ\") and one to four more parts joined by dots, which kept it out\n * of the token rule (Common's UrlScrubber, #8385). Anchored at both ends of\n * one segment, and no part can hold a dot, so a segment is read once.\n */\nconst JWT_SEGMENT: RegExp = /^eyJ[A-Za-z0-9_-]{8,}(?:\\.[A-Za-z0-9_-]*){1,4}$/u;\nconst ABSOLUTE_URL_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTER_PATTERN: RegExp = /[\\u0000-\\u001F\\u007F]/gu;\n\nexport function truncate(value: string, length: number): string {\n return value.slice(0, Math.max(0, length));\n}\n\nexport function sanitizeIdentifier(\n value: unknown,\n maximumLength: number,\n): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed: string = value.trim();\n if (\n trimmed.length === 0 ||\n trimmed.length > maximumLength ||\n !SAFE_IDENTIFIER_PATTERN.test(trimmed)\n ) {\n return null;\n }\n\n return trimmed;\n}\n\nfunction stringifyPrimitive(value: unknown): string | null {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"number\":\n return Number.isFinite(value) ? String(value) : null;\n case \"boolean\":\n return value ? \"true\" : \"false\";\n default:\n return value === null ? \"null\" : null;\n }\n}\n\nexport function sanitizeStringMap(\n value: unknown,\n limits: {\n keys: number;\n keyLength: number;\n valueLength: number;\n },\n): Record<string, string> {\n const result: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return result;\n }\n\n for (const [rawKey, rawValue] of Object.entries(\n value as Record<string, unknown>,\n )) {\n if (Object.keys(result).length >= limits.keys) {\n break;\n }\n\n const key: string = truncate(rawKey.trim(), limits.keyLength);\n const stringValue: string | null = stringifyPrimitive(rawValue);\n\n if (!key || BLOCKED_KEYS.has(key) || stringValue === null) {\n continue;\n }\n\n result[key] = truncate(stringValue, limits.valueLength);\n }\n\n return result;\n}\n\nexport function sanitizeTraits(value: unknown): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_TRAIT_KEYS,\n keyLength: MAX_TRAIT_KEY_LENGTH,\n valueLength: MAX_TRAIT_VALUE_LENGTH,\n });\n}\n\nexport function sanitizeTags(value: unknown): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_TAG_KEYS,\n keyLength: MAX_TAG_KEY_LENGTH,\n valueLength: MAX_TAG_VALUE_LENGTH,\n });\n}\n\nexport function sanitizeEventProperties(\n value: unknown,\n): Record<string, string> {\n return sanitizeStringMap(value, {\n keys: MAX_CUSTOM_EVENT_PROPERTY_KEYS,\n keyLength: MAX_TRAIT_KEY_LENGTH,\n valueLength: MAX_TRAIT_VALUE_LENGTH,\n });\n}\n\n/* Mirrors Common/Utils/Rum/Masking.maskText without a runtime dependency. */\nexport function maskTextValue(value: string): string {\n if (!value || value.trim().length === 0) {\n return value;\n }\n\n const length: number = value.trim().length;\n const maskedLength: number = length <= 8 ? 4 : length <= 32 ? 16 : 40;\n return \"\u2022\".repeat(maskedLength);\n}\n\n/*\n * A short token, not text: mirrors Common's\n * SESSION_REPLAY_READABLE_VALUE_PATTERN without a runtime dependency.\n */\nexport const READABLE_VALUE_PATTERN: RegExp = /^[A-Za-z0-9_.:/-]{0,32}$/;\n\n/*\n * Every value masked, as this recorder masks all text - except where the\n * application listed the key as a readable event property (issue #7501)\n * and the value is a short token. Mirrors Common's\n * maskSessionReplayProperties. Traits are masked with no keys listed.\n */\nexport function maskStringMapValues(\n values: Record<string, string>,\n readableKeys: ReadonlyArray<string> = [],\n): Record<string, string> {\n const masked: Record<string, string> = Object.create(null) as Record<\n string,\n string\n >;\n for (const [key, value] of Object.entries(values)) {\n masked[key] =\n readableKeys.indexOf(key) !== -1 && READABLE_VALUE_PATTERN.test(value)\n ? value\n : maskTextValue(value);\n }\n return masked;\n}\n\nexport function sanitizeRoute(route: unknown): string {\n if (typeof route !== \"string\") {\n return \"/\";\n }\n\n let path: string = route.trim();\n if (!path) {\n return \"/\";\n }\n\n try {\n if (ABSOLUTE_URL_PATTERN.test(path)) {\n path = new URL(path).pathname;\n }\n } catch {\n path = \"/\";\n }\n\n path = path.split(/[?#]/u, 1)[0] || \"/\";\n if (!path.startsWith(\"/\")) {\n path = `/${path}`;\n }\n\n path = path\n .split(\"/\")\n .map((segment: string): string => {\n let decoded: string = segment;\n /*\n * Decoded once, and once more for an address escaped twice\n * (\"someone%2540example.com\"), as Common's UrlScrubber reads it.\n */\n for (let pass: number = 0; pass < 2; pass++) {\n try {\n decoded = decodeURIComponent(decoded);\n } catch {\n // Matched as it is.\n }\n if (\n UUID_SEGMENT.test(decoded) ||\n OBJECT_ID_SEGMENT.test(decoded) ||\n EMAIL_SEGMENT.test(decoded) ||\n LONG_DIGIT_SEGMENT.test(decoded) ||\n OPAQUE_TOKEN_SEGMENT.test(decoded) ||\n JWT_SEGMENT.test(decoded)\n ) {\n return \"[redacted]\";\n }\n }\n return segment;\n })\n .join(\"/\");\n\n return truncate(path.replace(CONTROL_CHARACTER_PATTERN, \"\"), 2048);\n}\n\nexport function toAppUrl(mobileAppIdentifier: string, route: string): string {\n return `app://${mobileAppIdentifier}${sanitizeRoute(route)}`;\n}\n\nexport function emptySignalCounts(): SessionReplaySignalCounts {\n return {\n errorCount: 0,\n rageClickCount: 0,\n deadClickCount: 0,\n errorClickCount: 0,\n refreshRageCount: 0,\n routeCount: 0,\n clickCount: 0,\n customEventCount: 0,\n };\n}\n\nexport function byteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).byteLength;\n }\n\n return unescape(encodeURIComponent(value)).length;\n}\n\nexport function isPayloadWithinLimit(payload: string): boolean {\n return byteLength(payload) <= SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES;\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n SESSION_REPLAY_FLUSH_BYTES,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK,\n SESSION_REPLAY_MAX_CUSTOM_SIGNALS,\n SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES,\n SESSION_REPLAY_ROLLING_BUFFER_BYTES,\n SESSION_REPLAY_ROLLING_BUFFER_MS,\n SessionReplayCustomSignalCount,\n SessionReplayFidelityNotice,\n SessionReplayNumericSignalKey,\n SessionReplaySignalCounts,\n} from \"./Contract\";\nimport { byteLength, emptySignalCounts } from \"./Sanitize\";\n\n/*\n * Per-chunk caps on recorded routes, as the browser recorder's Chunker has.\n * The list rides the envelope, which the server refuses outright over 8 KB,\n * and it keeps a screen the user came back to, so nothing else bounds it. A\n * chunk with more route changes than this is an app rewriting its route\n * rather than a person moving through it; routeCount still counts them.\n */\nconst MAX_ROUTES_PER_CHUNK: number = 32;\nconst MAX_ROUTE_BYTES_PER_CHUNK: number = 2 * 1024;\n\nexport interface BufferedReplaySegment {\n payload: string;\n eventCount: number;\n startUnixMs: number;\n endUnixMs: number;\n hasFullSnapshot: boolean;\n routes: Array<string>;\n signals: SessionReplaySignalCounts;\n fidelityNotices: Array<SessionReplayFidelityNotice>;\n droppedEvents: number;\n}\n\nexport default class ReplayChunkBuffer {\n private events: Array<RrwebEvent> = [];\n private approximateBytes: number = 2;\n private startUnixMs: number = 0;\n private endUnixMs: number = 0;\n private hasFullSnapshot: boolean = false;\n /* In the order visited: a return to a screen is what a journey is read from. */\n private routes: Array<string> = [];\n private routeBytes: number = 0;\n private readonly fidelity: Set<SessionReplayFidelityNotice> =\n new Set<SessionReplayFidelityNotice>();\n private signals: SessionReplaySignalCounts = emptySignalCounts();\n private droppedEvents: number = 0;\n private customSignalEvents: number = 0;\n\n public append(\n event: RrwebEvent,\n options?: {\n route?: string;\n fidelityNotices?: Array<SessionReplayFidelityNotice>;\n signal?: SessionReplayNumericSignalKey;\n /*\n * The event marks a signal of the application's own: counted by name\n * on the envelope (signals.customSignals), as the browser's Chunker\n * counts it.\n */\n customSignal?: { name: string; isFrustration: boolean };\n },\n ): boolean {\n let serialized: string;\n try {\n serialized = JSON.stringify(event);\n } catch {\n this.droppedEvents += 1;\n return false;\n }\n\n const eventBytes: number = byteLength(serialized) + 1;\n if (eventBytes > SESSION_REPLAY_MAX_DECOMPRESSED_FRAME_BYTES) {\n this.droppedEvents += 1;\n this.fidelity.add(SessionReplayFidelityNotice.SnapshotTooLarge);\n return false;\n }\n\n this.events.push(event);\n this.approximateBytes += eventBytes;\n this.startUnixMs =\n this.startUnixMs === 0 ? event.timestamp : this.startUnixMs;\n this.endUnixMs = Math.max(this.endUnixMs, event.timestamp);\n if (event.type === RrwebEventType.FullSnapshot) {\n this.hasFullSnapshot = true;\n }\n\n if (options?.route) {\n this.addRoute(options.route);\n }\n for (const notice of options?.fidelityNotices ?? []) {\n this.fidelity.add(notice);\n }\n if (options?.signal) {\n const current: number = this.signals[options.signal] ?? 0;\n this.signals[options.signal] = current + 1;\n }\n if (options?.customSignal) {\n this.countCustomSignal(\n options.customSignal.name,\n options.customSignal.isFrustration,\n );\n }\n\n return true;\n }\n\n /*\n * Whether this chunk takes another signal marker. Capped like the\n * browser's: a signal that fires in a loop is one moment a second (the\n * matcher's cooldown), and fifty of them a chunk is plenty to see it.\n */\n public hasRoomForCustomSignal(): boolean {\n return (\n this.customSignalEvents <\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENTS_PER_CHUNK\n );\n }\n\n private countCustomSignal(name: string, isFrustration: boolean): void {\n this.customSignalEvents += 1;\n const counts: Array<SessionReplayCustomSignalCount> =\n this.signals.customSignals ?? [];\n let entry: SessionReplayCustomSignalCount | undefined = counts.find(\n (candidate: SessionReplayCustomSignalCount): boolean => {\n return candidate.name === name;\n },\n );\n if (!entry) {\n if (counts.length >= SESSION_REPLAY_MAX_CUSTOM_SIGNALS) {\n return;\n }\n entry = { name, count: 0, frustrationCount: 0 };\n counts.push(entry);\n }\n entry.count += 1;\n if (isFrustration) {\n entry.frustrationCount += 1;\n }\n this.signals.customSignals = counts;\n }\n\n public appendMany(\n events: Array<RrwebEvent>,\n options?: {\n route?: string;\n fidelityNotices?: Array<SessionReplayFidelityNotice>;\n },\n ): number {\n let accepted: number = 0;\n for (const event of events) {\n if (this.append(event, options)) {\n accepted += 1;\n }\n }\n\n return accepted;\n }\n\n public shouldFlush(): boolean {\n return this.approximateBytes >= SESSION_REPLAY_FLUSH_BYTES;\n }\n\n public isEmpty(): boolean {\n return this.events.length === 0;\n }\n\n public take(): BufferedReplaySegment | null {\n if (this.events.length === 0) {\n return null;\n }\n\n const payload: string = JSON.stringify(this.events);\n const segment: BufferedReplaySegment = {\n payload,\n eventCount: this.events.length,\n startUnixMs: this.startUnixMs,\n endUnixMs: this.endUnixMs,\n hasFullSnapshot: this.hasFullSnapshot,\n routes: this.routes.slice(),\n signals: this.copySignals(),\n fidelityNotices: Array.from(this.fidelity),\n droppedEvents: this.droppedEvents,\n };\n this.reset();\n return segment;\n }\n\n public clear(): void {\n this.reset();\n }\n\n /* The counts, with each signal's own entry copied too. */\n private copySignals(): SessionReplaySignalCounts {\n const signals: SessionReplaySignalCounts = { ...this.signals };\n if (this.signals.customSignals) {\n signals.customSignals = this.signals.customSignals.map(\n (\n entry: SessionReplayCustomSignalCount,\n ): SessionReplayCustomSignalCount => {\n return { ...entry };\n },\n );\n }\n return signals;\n }\n\n private addRoute(route: string): void {\n if (\n this.routes.length >= MAX_ROUTES_PER_CHUNK ||\n this.routes[this.routes.length - 1] === route\n ) {\n return;\n }\n\n const bytes: number = byteLength(route);\n\n if (this.routeBytes + bytes > MAX_ROUTE_BYTES_PER_CHUNK) {\n return;\n }\n\n this.routeBytes += bytes;\n this.routes.push(route);\n }\n\n private reset(): void {\n this.events = [];\n this.approximateBytes = 2;\n this.startUnixMs = 0;\n this.endUnixMs = 0;\n this.hasFullSnapshot = false;\n this.routes = [];\n this.routeBytes = 0;\n this.fidelity.clear();\n this.signals = emptySignalCounts();\n this.droppedEvents = 0;\n this.customSignalEvents = 0;\n }\n}\n\nexport class RollingReplayBuffer {\n private segments: Array<BufferedReplaySegment> = [];\n private bytes: number = 0;\n private overflowed: boolean = false;\n\n public push(segment: BufferedReplaySegment, nowUnixMs: number): void {\n this.segments.push(segment);\n this.bytes += byteLength(segment.payload);\n const cutoff: number = nowUnixMs - SESSION_REPLAY_ROLLING_BUFFER_MS;\n\n while (\n this.segments.length > 0 &&\n (this.bytes > SESSION_REPLAY_ROLLING_BUFFER_BYTES ||\n (this.segments[0]?.endUnixMs ?? nowUnixMs) < cutoff)\n ) {\n const removed: BufferedReplaySegment | undefined = this.segments.shift();\n if (removed) {\n this.bytes -= byteLength(removed.payload);\n this.overflowed = true;\n }\n }\n }\n\n public drain(): Array<BufferedReplaySegment> {\n const segments: Array<BufferedReplaySegment> = this.segments;\n if (this.overflowed && segments[0]) {\n const notices: Set<SessionReplayFidelityNotice> = new Set(\n segments[0].fidelityNotices,\n );\n notices.add(SessionReplayFidelityNotice.BufferOverflow);\n segments[0] = {\n ...segments[0],\n fidelityNotices: Array.from(notices),\n };\n }\n\n this.clear();\n return segments;\n }\n\n public clear(): void {\n this.segments = [];\n this.bytes = 0;\n this.overflowed = false;\n }\n\n public get length(): number {\n return this.segments.length;\n }\n}\n", "import {\n SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH,\n SESSION_REPLAY_MAX_CUSTOM_SIGNALS,\n SessionReplayCustomSignalConfig,\n SessionReplayCustomSignalTrigger,\n} from \"./Contract\";\n\n/*\n * The application's own frustration signals (issue #6443), as this recorder\n * detects them: a tap on a view it names by testID (issue #6517), a route\n * the app moves to, an event it passes to track(), an error whose text it\n * knows. A click on an element is a CSS selector on a web page, so click\n * signals are left to the browser recorder.\n *\n * The reading and the matching are copies of Common's\n * Types/Rum/SessionReplayFrustrationSignals (readCustomSignal and the\n * matchesSessionReplay* functions); ContractParity holds them to Common on\n * the same inputs. Nothing a signal matched against is ever recorded: a hit\n * carries the signal's name - and, for a tap whose touch was recorded,\n * where on the screen it was, as the touch itself already says.\n */\n\n/* The triggers this recorder can detect. */\nexport type MobileCustomSignalTrigger = Exclude<\n SessionReplayCustomSignalTrigger,\n \"click\"\n>;\n\nconst TRIGGERS: ReadonlyArray<SessionReplayCustomSignalTrigger> = [\n \"click\",\n \"tap\",\n \"page\",\n \"event\",\n \"error\",\n];\n\n/* How many testIDs, from the touched view up, a tap is matched against. */\nexport const MAX_TAP_TARGET_TEST_IDS: number = 32;\n\nexport interface MobileCustomSignalHit {\n name: string;\n trigger: MobileCustomSignalTrigger;\n isFrustration: boolean;\n atUnixMs: number;\n /* A tap signal's position, only when its touch was recorded. */\n x?: number;\n y?: number;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction isTrigger(value: unknown): value is SessionReplayCustomSignalTrigger {\n return (\n typeof value === \"string\" &&\n TRIGGERS.indexOf(value as SessionReplayCustomSignalTrigger) !== -1\n );\n}\n\ninterface ReadCustomSignal extends SessionReplayCustomSignalConfig {\n isEnabled: boolean;\n}\n\n/*\n * Common's isSessionReplayTapPatternUsable: some of a testID, then at most\n * one star, at its end.\n */\nexport function isTapPatternUsable(pattern: string): boolean {\n const star: number = pattern.indexOf(\"*\");\n\n return star === -1 || (star > 0 && star === pattern.length - 1);\n}\n\nfunction readCustomSignal(value: unknown): ReadCustomSignal | null {\n const record: Record<string, unknown> = asRecord(value);\n const name: string =\n typeof record[\"name\"] === \"string\" ? record[\"name\"].trim() : \"\";\n const trigger: unknown = record[\"trigger\"];\n const match: string =\n typeof record[\"match\"] === \"string\" ? record[\"match\"].trim() : \"\";\n\n if (\n name.length === 0 ||\n name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH ||\n !isTrigger(trigger) ||\n match.length === 0 ||\n match.length >\n (trigger === \"event\"\n ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH\n : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) ||\n (trigger === \"page\" &&\n match.charAt(0) !== \"/\" &&\n match.charAt(0) !== \"*\") ||\n (trigger === \"tap\" && !isTapPatternUsable(match))\n ) {\n return null;\n }\n\n return {\n name,\n trigger,\n match,\n isFrustration: record[\"isFrustration\"] !== false,\n isEnabled: record[\"isEnabled\"] !== false,\n };\n}\n\n/*\n * The signals in a config response's frustrationSignals - or in a cached\n * copy of the policy, which keeps the same field - that this recorder\n * detects. Never throws: anything unusable is no signal. Read exactly as\n * the server reads them - names unique ignoring case, at most twenty, then\n * the ones switched off left out (the server sends none) - and only then\n * are the click signals, which this recorder cannot detect, set aside.\n */\nexport function readCustomSignals(\n frustrationSignals: unknown,\n): Array<SessionReplayCustomSignalConfig> {\n const list: unknown = asRecord(frustrationSignals)[\"customSignals\"];\n const read: Array<ReadCustomSignal> = [];\n const seenNames: Array<string> = [];\n\n if (Array.isArray(list)) {\n for (const entry of list) {\n const signal: ReadCustomSignal | null = readCustomSignal(entry);\n\n if (!signal) {\n continue;\n }\n\n const key: string = signal.name.toLowerCase();\n\n if (seenNames.indexOf(key) !== -1) {\n continue;\n }\n\n seenNames.push(key);\n read.push(signal);\n\n if (read.length >= SESSION_REPLAY_MAX_CUSTOM_SIGNALS) {\n break;\n }\n }\n }\n\n const signals: Array<SessionReplayCustomSignalConfig> = [];\n\n for (const signal of read) {\n if (signal.isEnabled && signal.trigger !== \"click\") {\n signals.push({\n name: signal.name,\n trigger: signal.trigger,\n match: signal.match,\n isFrustration: signal.isFrustration,\n });\n }\n }\n\n return signals;\n}\n\n// One escaped byte: \"%c3\", \"%2F\".\nconst ESCAPED_BYTE: RegExp = /^%[0-9A-Fa-f]{2}$/;\n\n/*\n * Text with no ASCII in it: an escaped character is decoded only when it\n * stays beyond ASCII composed (NFC writes three in ASCII).\n */\nconst BEYOND_ASCII: RegExp = /^[\\u0080-\\uffff]+$/;\n\n// An escape, or a character beyond ASCII: a path with a spelling to settle.\nconst SPELLED_CHARACTER: RegExp = /[%\\u0080-\\uffff]/;\n\nfunction composed(text: string): string {\n return typeof text.normalize === \"function\" ? text.normalize(\"NFC\") : text;\n}\n\n/*\n * A path in the spelling a person reads it, a copy of Common's\n * UrlScrubber.normalizePathSpelling(path, true) (#8195): each escape of a\n * character beyond ASCII decoded (\"/caf%c3%a9\" and \"/cafe%CC%81\" are\n * \"/caf\u00E9\"), the words composed, and every other escape kept, in upper-case\n * hex, so \"/a%2Fb\" stays apart from \"/a/b\".\n */\nexport function readPathAsWritten(path: string): string {\n if (!SPELLED_CHARACTER.test(path)) {\n return path;\n }\n\n let spelled: string = \"\";\n let words: string = \"\";\n let index: number = 0;\n\n while (index < path.length) {\n const escape: string = path.slice(index, index + 3);\n\n if (!ESCAPED_BYTE.test(escape)) {\n words += path.charAt(index);\n index += 1;\n continue;\n }\n\n // A character's escapes: 2 to 4 bytes, as many as its first says.\n const lead: number = parseInt(escape.slice(1), 16);\n const length: number =\n lead < 0xc2 ? 0 : lead < 0xe0 ? 6 : lead < 0xf0 ? 9 : 12;\n let character: string = \"\";\n\n try {\n character = length\n ? decodeURIComponent(path.slice(index, index + length))\n : \"\";\n } catch {\n // Not UTF-8: cut short, written too long, a surrogate.\n }\n\n if (BEYOND_ASCII.test(composed(character))) {\n words += character;\n index += length;\n continue;\n }\n\n spelled += composed(words) + escape.toUpperCase();\n words = \"\";\n index += 3;\n }\n\n return spelled + composed(words);\n}\n\nfunction canonicalPath(path: string): string {\n let end: number = path.length;\n\n while (end > 1 && path.charAt(end - 1) === \"/\") {\n end--;\n }\n\n return readPathAsWritten(path.slice(0, end)).toLowerCase();\n}\n\n/*\n * Does a route match a page pattern? A star stands for any run of\n * characters; everything else is compared as written, ignoring case and the\n * slashes at the end, in the spelling a person reads (readPathAsWritten).\n * The pattern is split on its stars and the pieces are found in order - no\n * regular expression is built from it.\n */\nexport function matchesPagePattern(pattern: string, path: string): boolean {\n const target: string = canonicalPath(path);\n const pieces: Array<string> = canonicalPath(pattern.trim()).split(\"*\");\n\n if (pieces.length === 1) {\n return target === pieces[0];\n }\n\n const first: string = pieces[0] || \"\";\n const last: string = pieces[pieces.length - 1] || \"\";\n\n if (target.slice(0, first.length) !== first) {\n return false;\n }\n\n let position: number = first.length;\n\n for (let index: number = 1; index < pieces.length - 1; index++) {\n const piece: string = pieces[index] || \"\";\n\n if (piece.length === 0) {\n continue;\n }\n\n const found: number = target.indexOf(piece, position);\n\n if (found === -1) {\n return false;\n }\n\n position = found + piece.length;\n }\n\n return (\n target.length - position >= last.length &&\n target.slice(target.length - last.length) === last\n );\n}\n\nexport function matchesErrorText(match: string, text: string): boolean {\n return (\n match.length > 0 && text.toLowerCase().indexOf(match.toLowerCase()) !== -1\n );\n}\n\nexport function matchesEventName(match: string, name: string): boolean {\n return match.trim().toLowerCase() === name.trim().toLowerCase();\n}\n\n/*\n * Common's matchesSessionReplayTapTarget: the testID exactly, or - a\n * pattern ending in a star - one that starts with what comes before it.\n * Case is ignored.\n */\nexport function matchesTapTarget(match: string, testId: string): boolean {\n const pattern: string = match.trim().toLowerCase();\n const target: string = testId.toLowerCase();\n\n if (!pattern || !target || !isTapPatternUsable(pattern)) {\n return false;\n }\n\n return pattern.charAt(pattern.length - 1) === \"*\"\n ? target.indexOf(pattern.slice(0, -1)) === 0\n : target === pattern;\n}\n\n/*\n * The testIDs a tap can be matched against, as the native module hands\n * them over: strings only, none empty or longer than a match can be, at\n * most MAX_TAP_TARGET_TEST_IDS of them. Anything else is no testID.\n */\nexport function readTapTargetTestIds(value: unknown): Array<string> {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const testIds: Array<string> = [];\n\n for (const entry of value) {\n if (\n typeof entry === \"string\" &&\n entry.length > 0 &&\n entry.length <= SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH\n ) {\n testIds.push(entry);\n }\n\n if (testIds.length >= MAX_TAP_TARGET_TEST_IDS) {\n break;\n }\n }\n\n return testIds;\n}\n\n/*\n * The path a route stands for, as written: an absolute URL's path, without\n * its query or fragment, starting with a slash. Unlike the recorded route\n * nothing in it is redacted - a pattern names the app's own screens, and\n * what it is compared with never leaves the device.\n */\nexport function routeMatchPath(route: unknown): string {\n let path: string = typeof route === \"string\" ? route.trim() : \"\";\n\n const scheme: number = path.indexOf(\"://\");\n\n if (scheme > 0 && scheme < 32) {\n const pathStart: number = path.indexOf(\"/\", scheme + 3);\n path = pathStart === -1 ? \"/\" : path.slice(pathStart);\n }\n\n let end: number = path.length;\n\n for (const separator of [\"?\", \"#\"]) {\n const at: number = path.indexOf(separator);\n\n if (at !== -1 && at < end) {\n end = at;\n }\n }\n\n path = path.slice(0, end);\n\n return path.charAt(0) === \"/\" ? path : `/${path}`;\n}\n\n/*\n * Which of the application's signals a moment matches. Each name fires at\n * most once a second, as in the browser recorder: an error thrown in a loop\n * is one moment on the timeline, not fifty.\n */\nexport class CustomSignalMatcher {\n private readonly lastFiredAt: Map<string, number> = new Map<string, number>();\n\n /*\n * A tap on a view whose testID a tap signal names - or on anything inside\n * it: testIds holds the touched view's testID and those of the views\n * around it, out to the replay root, the touched one first.\n */\n public matchTap(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n testIds: ReadonlyArray<string>,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n if (testIds.length === 0) {\n return [];\n }\n\n return this.collect(\n signals,\n \"tap\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return testIds.some((testId: string): boolean => {\n return matchesTapTarget(signal.match, testId);\n });\n },\n );\n }\n\n public matchPage(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n route: unknown,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n const path: string = routeMatchPath(route);\n\n return this.collect(\n signals,\n \"page\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesPagePattern(signal.match, path);\n },\n );\n }\n\n public matchEvent(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n eventName: string,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n return this.collect(\n signals,\n \"event\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesEventName(signal.match, eventName);\n },\n );\n }\n\n public matchErrorText(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n text: string,\n atUnixMs: number,\n ): Array<MobileCustomSignalHit> {\n if (!text) {\n return [];\n }\n\n return this.collect(\n signals,\n \"error\",\n atUnixMs,\n (signal: SessionReplayCustomSignalConfig): boolean => {\n return matchesErrorText(signal.match, text);\n },\n );\n }\n\n /* A new session starts with no signal cooling down. */\n public reset(): void {\n this.lastFiredAt.clear();\n }\n\n private collect(\n signals: ReadonlyArray<SessionReplayCustomSignalConfig>,\n trigger: MobileCustomSignalTrigger,\n atUnixMs: number,\n matches: (signal: SessionReplayCustomSignalConfig) => boolean,\n ): Array<MobileCustomSignalHit> {\n const hits: Array<MobileCustomSignalHit> = [];\n\n for (const signal of signals) {\n if (signal.trigger !== trigger || !matches(signal)) {\n continue;\n }\n\n const key: string = signal.name.toLowerCase();\n const last: number | undefined = this.lastFiredAt.get(key);\n\n if (\n last !== undefined &&\n atUnixMs >= last &&\n atUnixMs - last < SESSION_REPLAY_CUSTOM_SIGNAL_COOLDOWN_MS\n ) {\n continue;\n }\n\n this.lastFiredAt.set(key, atUnixMs);\n hits.push({\n name: signal.name,\n trigger,\n isFrustration: signal.isFrustration,\n atUnixMs,\n });\n }\n\n return hits;\n }\n}\n", "/*\n * Build-time copy of the product analytics wire contract (issue #6629):\n * what Common's Types/Rum/ProductAnalyticsEvents.ts says a recorder sends to\n * the events route - the batch, its limits, the event kinds, the metric\n * name rule and the config field that switches it on. This package is\n * installed in customer React Native applications and must not pull the\n * OneUptime monorepo's Common package into their bundle, so it carries a\n * copy, as Contract.ts carries the replay contract. ContractParity holds\n * every constant, type and rule here identical to Common's.\n */\n\n/* ---- Where the recorder posts. ---- */\n\nexport const PRODUCT_ANALYTICS_EVENTS_PATH: string =\n \"/telemetry/session-replay/v1/events\";\n\n/* The batch's wire version. Additive changes keep it; anything else bumps it. */\nexport const PRODUCT_ANALYTICS_WIRE_VERSION: number = 1;\n\nexport const PRODUCT_ANALYTICS_CONTENT_TYPE: string = \"application/json\";\n\n/* ---- What one batch may hold. Enforced on both sides of the wire. ---- */\n\nexport const PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH: number = 100;\nexport const PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH: number = 100;\nexport const PRODUCT_ANALYTICS_MAX_BATCH_BYTES: number = 64 * 1024;\n\n/* How large a batch grows before it is sent, well under the server's cap. */\nexport const PRODUCT_ANALYTICS_TARGET_BATCH_BYTES: number = 24 * 1024;\n\n/* How often the recorder sends what it has, in milliseconds. */\nexport const PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS: number = 5000;\n\n/*\n * Events (and, apart, metric points) the recorder holds while it cannot\n * send them yet - consent not given, the device offline: past this, the\n * oldest are dropped.\n */\nexport const PRODUCT_ANALYTICS_MAX_PENDING_EVENTS: number = 500;\n\n/* A custom event's name, at most this long. */\nexport const PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH: number = 64;\n\n/* The device, system and version a batch says it came from. */\nexport const PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH: number = 64;\n\n/*\n * Common's SESSION_REPLAY_MAX_APP_VERSION_LENGTH: the longest app version\n * the server keeps, and so the longest one sent.\n */\nexport const PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH: number = 64;\n\n/*\n * Events this old when they arrive are dropped by the server, so the\n * recorder drops them itself rather than send them (an app held offline for\n * days).\n */\nexport const PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS: number =\n 3 * 24 * 60 * 60 * 1000;\n\n/*\n * Common's PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE: the shorter side, in\n * points, from which a mobile app's screen is a tablet's - the rule its\n * recorded sessions are filed by, so an event and a session agree.\n */\nexport const PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE: number = 600;\n\n/* ---- Metric names. ---- */\n\nexport const PRODUCT_ANALYTICS_MAX_METRIC_NAME_LENGTH: number = 100;\nconst METRIC_NAME_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;\n\n/* OneUptime's own namespace: metric() refuses every name in it. */\nexport const PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX: string = \"oneuptime.\";\n\n/*\n * A name metric() may send: the OpenTelemetry instrument name shape, and\n * not in OneUptime's namespace.\n */\nexport function isProductAnalyticsMetricName(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n METRIC_NAME_PATTERN.test(value) &&\n !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX)\n );\n}\n\n/* ---- Events. ---- */\n\nexport enum ProductAnalyticsEventKind {\n /* A session started; named \"\". */\n Session = \"session\",\n /* A page (a mobile app's screen) was viewed; named by its path. */\n Page = \"page\",\n /* The application called track(); named as it said. */\n Custom = \"custom\",\n}\n\n/* One event, as it travels. `at` is the device's clock. */\nexport interface ProductAnalyticsWireEvent {\n kind: ProductAnalyticsEventKind;\n name: string;\n at: number;\n /* The page the event happened on. */\n page?: string | undefined;\n properties?: Record<string, string> | undefined;\n}\n\nexport interface ProductAnalyticsWireMetric {\n name: string;\n value: number;\n at: number;\n attributes?: Record<string, string> | undefined;\n}\n\n/* What the session runs on: the same values Session Replay files it under. */\nexport interface ProductAnalyticsWireContext {\n /* desktop, mobile or tablet; \"\" when unknown. */\n deviceType: string;\n browserName: string;\n osName: string;\n /*\n * The app's version: a mobile app's own, or the one a web page gave the\n * browser recorder (its appVersion option, issue #6625); \"\" when unset.\n */\n appVersion: string;\n}\n\nexport interface ProductAnalyticsWireBatch {\n v: number;\n /* 32 hex; the same id on a retry, so a batch lands once. */\n batchId: string;\n sessionId: string;\n visitorId: string;\n /*\n * The signed-in user's reference, only when the application captures user\n * identity, and the traits it keeps for analytics.\n */\n userRef?: string | undefined;\n userProperties?: Record<string, string> | undefined;\n /*\n * The page's consent, as a replay chunk reports it (\"Granted\",\n * \"NotRequired\", \"Unknown\"). An application that asks for explicit\n * consent files a batch only when it says \"Granted\".\n */\n consentState: string;\n sentAt: number;\n context: ProductAnalyticsWireContext;\n events: Array<ProductAnalyticsWireEvent>;\n metrics: Array<ProductAnalyticsWireMetric>;\n}\n\n/*\n * Common's toProductAnalyticsEventName: trimmed, control characters\n * dropped, at most PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH long, or null\n * when nothing is left.\n */\nexport function toProductAnalyticsEventName(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n let name: string = \"\";\n\n for (const character of value) {\n const code: number = character.charCodeAt(0);\n\n if (code < 32 || code === 127) {\n continue;\n }\n\n name += character;\n }\n\n name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();\n\n return name.length > 0 ? name : null;\n}\n\n// eslint-disable-next-line no-control-regex\nconst NOT_PRINTABLE_PATTERN: RegExp = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/*\n * Common's toSessionReplayAppVersion: trimmed, at most\n * PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH long, and \"\" for anything that\n * is not a string or holds a control character, as the server keeps it.\n */\nexport function toProductAnalyticsAppVersion(value: unknown): string {\n if (typeof value !== \"string\") {\n return \"\";\n }\n\n const version: string = value\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH)\n .trim();\n\n return NOT_PRINTABLE_PATTERN.test(version) ? \"\" : version;\n}\n\n/* ---- What the recorder learns from the replay config. ---- */\n\n/* The identify() traits events may carry: at most 20 keys of 40 characters. */\nexport const PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS: number = 20;\nexport const PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH: number = 40;\n\n/*\n * The optional `productAnalytics` field of the replay config. Absent - an\n * older server, or an application with product analytics off - reads as\n * off, so the recorder never sends a batch nobody asked for.\n */\nexport interface ProductAnalyticsRecorderConfig {\n enabled: boolean;\n /* The identify() traits events may carry. */\n userPropertyKeys: Array<string>;\n}\n\n/*\n * Common's normalizeProductAnalyticsUserPropertyKeys: trimmed, without\n * duplicates (ignoring case), at most the key cap of keys of at most the\n * key length.\n */\nexport function normalizeProductAnalyticsUserPropertyKeys(\n value: unknown,\n): Array<string> {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const keys: Array<string> = [];\n const seen: Set<string> = new Set<string>();\n\n for (const entry of value) {\n if (typeof entry !== \"string\") {\n continue;\n }\n\n const key: string = entry\n .trim()\n .slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);\n\n if (key.length === 0 || key === \"__proto__\") {\n continue;\n }\n\n if (seen.has(key.toLowerCase())) {\n continue;\n }\n\n seen.add(key.toLowerCase());\n keys.push(key);\n\n if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {\n break;\n }\n }\n\n return keys;\n}\n\n/* Common's readProductAnalyticsRecorderConfig. */\nexport function readProductAnalyticsRecorderConfig(\n value: unknown,\n): ProductAnalyticsRecorderConfig {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { enabled: false, userPropertyKeys: [] };\n }\n\n const record: Record<string, unknown> = value as Record<string, unknown>;\n\n return {\n enabled: record[\"enabled\"] === true,\n userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(\n record[\"userPropertyKeys\"],\n ),\n };\n}\n", "import {\n AUTH_TOKEN_HEADER,\n CONFIG_PATH,\n MOBILE_RECORDER_KIND,\n SESSION_REPLAY_APP_IDENTIFIER_HEADER,\n SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER,\n SESSION_REPLAY_MAX_OFFLINE_DELAY_MS,\n SESSION_REPLAY_MAX_USER_REF_LENGTH,\n SESSION_REPLAY_RECORDER_KIND_HEADER,\n SESSION_REPLAY_USER_REF_HEADER,\n SessionReplayCaptureTrigger,\n SessionReplayConfigResponse,\n SessionReplayConsentMode,\n SessionReplayCustomSignalConfig,\n SessionReplayMaskingMode,\n} from \"./Contract\";\nimport { readCustomSignals } from \"./CustomSignals\";\nimport {\n ProductAnalyticsRecorderConfig,\n normalizeProductAnalyticsUserPropertyKeys,\n readProductAnalyticsRecorderConfig,\n} from \"./ProductAnalyticsContract\";\nimport { ReplayStorage } from \"./Storage\";\n\nexport const CONFIG_FETCH_TIMEOUT_MS: number = 5_000;\n\nexport interface ReplayFetchResponse {\n ok: boolean;\n status: number;\n headers?: {\n get(name: string): string | null;\n };\n json(): Promise<unknown>;\n}\n\nexport type ReplayFetch = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: unknown;\n signal?: AbortSignal;\n },\n) => Promise<ReplayFetchResponse>;\n\nexport interface MobileReplayStartOptions {\n /** Ingest origin, for example https://oneuptime.com. */\n host: string;\n /** OneUptime telemetry ingestion key. */\n token: string;\n /** Identifier of the OneUptime RUM application receiving the replay. */\n appIdentifier: string;\n /** Android applicationId or iOS bundle identifier. */\n mobileAppIdentifier: string;\n appName?: string;\n appVersion?: string;\n /** Optional opaque reference used by record-next-session targeting. */\n userRef?: string;\n captureIntervalMs?: number;\n fetch?: ReplayFetch;\n debug?: boolean;\n /**\n * Optional connectivity source for offline mode. Recording never depends\n * on it: without one, a lost connection is noticed when an upload fails\n * and the backlog is retried with backoff and whenever the app returns to\n * the foreground. With one, nothing is attempted while it says the device\n * is offline, and the backlog uploads the moment it says it is back. With\n * `@react-native-community/netinfo`:\n *\n * connectivity: {\n * subscribe: (listener) =>\n * NetInfo.addEventListener((state) => listener(state.isConnected)),\n * }\n */\n connectivity?: ReplayConnectivity;\n}\n\nexport interface ReplayConnectivity {\n /**\n * Call `listener` with whether the device has a connection now and on\n * every change (null when unknown), and return a function that stops.\n */\n subscribe(listener: (isConnected: boolean | null) => void): () => void;\n}\n\n/*\n * The part of the application's frustration settings this recorder acts on:\n * its own tap, page, event and error signals (issues #6443, #6517). Kept under the\n * response's own field name so a cached policy is read back by the same\n * normalizeReplayConfig as a fresh one.\n */\nexport interface ResolvedFrustrationSignals {\n customSignals: Array<SessionReplayCustomSignalConfig>;\n}\n\nexport interface ResolvedReplayConfig {\n enabled: boolean;\n captureTrigger: SessionReplayCaptureTrigger;\n consentMode: SessionReplayConsentMode;\n maskingMode: SessionReplayMaskingMode.MaskAllText;\n samplePercentage: number;\n captureUserIdentity: boolean;\n configEpoch: number;\n isTargeted: boolean;\n frustrationSignals: ResolvedFrustrationSignals;\n /*\n * Product analytics events (issue #6629): whether the app also sends its\n * session starts, screens, track() events and metric() points - from\n * every session, recorded or not - and which identify() traits they may\n * carry. Kept under the response's own field name, like\n * frustrationSignals, so a cached policy reads back the same.\n */\n productAnalytics: ProductAnalyticsRecorderConfig;\n /*\n * Readable event properties (issue #7501): the keys whose short token\n * values a track() property or a metric() attribute keeps as written,\n * though this recorder masks all text. Kept under the response's own\n * field name too; a cached policy from before it reads as none.\n */\n readableEventPropertyKeys: Array<string>;\n disabledReason?: string;\n}\n\nexport interface ValidatedStartOptions extends MobileReplayStartOptions {\n host: string;\n token: string;\n appIdentifier: string;\n mobileAppIdentifier: string;\n fetch: ReplayFetch;\n}\n\nconst MOBILE_APP_IDENTIFIER_LABEL_PATTERN: RegExp = /^[a-z0-9_-]+$/u;\nconst WHITESPACE_PATTERN: RegExp = /\\s/u;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTER_PATTERN: RegExp = /[\\u0000-\\u001F\\u007F]/u;\n\n/* Kept byte-for-byte compatible with Common's authorization grammar. */\nexport function normalizeMobileAppIdentifier(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const identifier: string = value.trim().toLowerCase();\n if (\n !identifier ||\n identifier.length > 255 ||\n WHITESPACE_PATTERN.test(identifier)\n ) {\n return null;\n }\n\n const labels: Array<string> = identifier.split(\".\");\n if (labels.length < 2) {\n return null;\n }\n\n for (const label of labels) {\n if (\n !label ||\n !MOBILE_APP_IDENTIFIER_LABEL_PATTERN.test(label) ||\n label.startsWith(\"-\") ||\n label.endsWith(\"-\") ||\n label.startsWith(\"_\") ||\n label.endsWith(\"_\")\n ) {\n return null;\n }\n }\n\n return identifier;\n}\n\nexport function normalizeIngestHost(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n try {\n const parsed: URL = new URL(value.trim());\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== \"/\" ||\n parsed.search ||\n parsed.hash\n ) {\n return null;\n }\n\n return parsed.origin;\n } catch {\n return null;\n }\n}\n\nexport function normalizeRumAppIdentifier(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const identifier: string = value.trim();\n if (\n !identifier ||\n identifier.length > 255 ||\n CONTROL_CHARACTER_PATTERN.test(identifier)\n ) {\n return null;\n }\n\n return identifier;\n}\n\nfunction defaultFetch(\n input: string,\n init?: Parameters<ReplayFetch>[1],\n): Promise<ReplayFetchResponse> {\n const fetchRef: typeof fetch | undefined = globalThis.fetch;\n if (!fetchRef) {\n return Promise.reject(new Error(\"fetch-unavailable\"));\n }\n\n return fetchRef(input, init as RequestInit) as Promise<ReplayFetchResponse>;\n}\n\nexport function validateStartOptions(\n options: MobileReplayStartOptions,\n): ValidatedStartOptions | null {\n if (!options || typeof options !== \"object\") {\n return null;\n }\n\n const host: string | null = normalizeIngestHost(options.host);\n const token: string =\n typeof options.token === \"string\" ? options.token.trim() : \"\";\n const appIdentifier: string | null = normalizeRumAppIdentifier(\n options.appIdentifier,\n );\n const mobileAppIdentifier: string | null = normalizeMobileAppIdentifier(\n options.mobileAppIdentifier,\n );\n const rawUserRef: string =\n typeof options.userRef === \"string\" ? options.userRef.trim() : \"\";\n const userRef: string | undefined = rawUserRef\n ? rawUserRef.slice(0, SESSION_REPLAY_MAX_USER_REF_LENGTH)\n : undefined;\n\n if (!host || !token || !appIdentifier || !mobileAppIdentifier) {\n return null;\n }\n\n const validated: ValidatedStartOptions = {\n ...options,\n host,\n token,\n appIdentifier,\n mobileAppIdentifier,\n fetch: options.fetch ?? defaultFetch,\n };\n if (userRef) {\n validated.userRef = userRef;\n } else {\n delete validated.userRef;\n }\n return validated;\n}\n\nexport function mobileRequestHeaders(\n options: Pick<\n ValidatedStartOptions,\n \"token\" | \"appIdentifier\" | \"mobileAppIdentifier\" | \"userRef\"\n >,\n includeUserRef: boolean = false,\n): Record<string, string> {\n const headers: Record<string, string> = {\n [AUTH_TOKEN_HEADER]: options.token,\n [SESSION_REPLAY_APP_IDENTIFIER_HEADER]: options.appIdentifier,\n [SESSION_REPLAY_RECORDER_KIND_HEADER]: MOBILE_RECORDER_KIND,\n [SESSION_REPLAY_MOBILE_APP_IDENTIFIER_HEADER]: options.mobileAppIdentifier,\n };\n if (includeUserRef && options.userRef) {\n try {\n headers[SESSION_REPLAY_USER_REF_HEADER] = encodeURIComponent(\n options.userRef.slice(0, SESSION_REPLAY_MAX_USER_REF_LENGTH),\n );\n } catch {\n /* An invalid surrogate skips targeting; policy fetch still proceeds. */\n }\n }\n return headers;\n}\n\nfunction failClosed(reason: string): ResolvedReplayConfig {\n return {\n enabled: false,\n captureTrigger: SessionReplayCaptureTrigger.OnErrorOrFrustration,\n consentMode: SessionReplayConsentMode.RequireExplicit,\n maskingMode: SessionReplayMaskingMode.MaskAllText,\n samplePercentage: 0,\n captureUserIdentity: false,\n configEpoch: 0,\n isTargeted: false,\n frustrationSignals: { customSignals: [] },\n productAnalytics: { enabled: false, userPropertyKeys: [] },\n readableEventPropertyKeys: [],\n disabledReason: reason,\n };\n}\n\nexport function normalizeReplayConfig(value: unknown): ResolvedReplayConfig {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return failClosed(\"invalid-config\");\n }\n\n const config: Partial<SessionReplayConfigResponse> =\n value as Partial<SessionReplayConfigResponse>;\n const captureTrigger: SessionReplayCaptureTrigger =\n config.captureTrigger === SessionReplayCaptureTrigger.Always\n ? SessionReplayCaptureTrigger.Always\n : SessionReplayCaptureTrigger.OnErrorOrFrustration;\n const consentMode: SessionReplayConsentMode =\n config.consentMode === SessionReplayConsentMode.NotRequired\n ? SessionReplayConsentMode.NotRequired\n : SessionReplayConsentMode.RequireExplicit;\n const samplePercentage: number =\n typeof config.samplePercentage === \"number\" &&\n Number.isFinite(config.samplePercentage) &&\n config.samplePercentage >= 0 &&\n config.samplePercentage <= 100\n ? config.samplePercentage\n : 0;\n const enabled: boolean =\n config.enabled === true && config.directive === \"continue\";\n\n const resolved: ResolvedReplayConfig = {\n enabled,\n captureTrigger,\n consentMode,\n /* Mobile never relaxes text masking, even if web policy is looser. */\n maskingMode: SessionReplayMaskingMode.MaskAllText,\n samplePercentage,\n captureUserIdentity: config.captureUserIdentity === true,\n configEpoch:\n typeof config.configEpoch === \"number\" &&\n Number.isSafeInteger(config.configEpoch) &&\n config.configEpoch >= 0\n ? config.configEpoch\n : 0,\n isTargeted: config.isTargeted === true,\n /*\n * A server from before frustration settings sends none: no signals of\n * the application's own, which is what such an application has.\n */\n frustrationSignals: {\n customSignals: readCustomSignals(config.frustrationSignals),\n },\n /*\n * Absent - a server from before product analytics, or an application\n * with it off - reads as off, so no batch is sent nobody asked for.\n */\n productAnalytics: readProductAnalyticsRecorderConfig(\n config.productAnalytics,\n ),\n /*\n * Read as product analytics reads the traits it keeps, as Common's\n * normalizeSessionReplayReadablePropertyKeys does: absent, none.\n */\n readableEventPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(\n config.readableEventPropertyKeys,\n ),\n };\n if (typeof config.disabledReason === \"string\") {\n resolved.disabledReason = config.disabledReason.slice(0, 100);\n } else if (!enabled) {\n resolved.disabledReason = \"disabled\";\n }\n return resolved;\n}\n\n/*\n * Offline mode: the last policy the server gave this app, kept so that an\n * app launched WITHOUT a connection still records - and uploads when the\n * connection returns - instead of failing closed on a config request that\n * could never succeed. Only ever used when the config request itself failed\n * to get an answer (see isRetryablePolicyFailure's callers); an answer\n * saying replay is off deletes it. Never older than the offline delay, and\n * never \"targeted\": record-next-session is a live decision the server makes\n * again when the connection is back.\n */\ninterface CachedReplayConfig {\n savedAtUnixMs: number;\n config: ResolvedReplayConfig;\n}\n\nexport function replayConfigCacheKey(namespace: string): string {\n return `@oneuptime/replay/${namespace}/config`;\n}\n\nexport async function saveReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n config: ResolvedReplayConfig,\n nowUnixMs: number,\n): Promise<void> {\n try {\n if (!config.enabled) {\n await storage.removeItem(replayConfigCacheKey(namespace));\n return;\n }\n\n const cached: CachedReplayConfig = {\n savedAtUnixMs: nowUnixMs,\n config: { ...config, isTargeted: false },\n };\n await storage.setItem(\n replayConfigCacheKey(namespace),\n JSON.stringify(cached),\n );\n } catch {\n /* A policy that is not cached only means an offline launch does not record. */\n }\n}\n\n/* Consent withdrawn: nothing of the recorder's stays on the device. */\nexport async function forgetReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n): Promise<void> {\n try {\n await storage.removeItem(replayConfigCacheKey(namespace));\n } catch {\n /* Best-effort privacy cleanup. */\n }\n}\n\nexport async function loadCachedReplayConfig(\n storage: ReplayStorage,\n namespace: string,\n nowUnixMs: number,\n): Promise<ResolvedReplayConfig | null> {\n try {\n const raw: string | null = await storage.getItem(\n replayConfigCacheKey(namespace),\n );\n if (!raw) {\n return null;\n }\n\n const cached: Partial<CachedReplayConfig> = JSON.parse(\n raw,\n ) as Partial<CachedReplayConfig>;\n const age: number = nowUnixMs - Number(cached.savedAtUnixMs);\n if (\n !Number.isFinite(age) ||\n age < 0 ||\n age > SESSION_REPLAY_MAX_OFFLINE_DELAY_MS ||\n !cached.config ||\n typeof cached.config !== \"object\"\n ) {\n return null;\n }\n\n /* Re-validated like a fresh response: storage is not trusted. */\n const config: ResolvedReplayConfig = normalizeReplayConfig({\n ...cached.config,\n directive: cached.config.enabled === true ? \"continue\" : \"stop\",\n isTargeted: false,\n });\n return config.enabled ? config : null;\n } catch {\n return null;\n }\n}\n\nexport async function fetchReplayConfig(\n options: ValidatedStartOptions,\n includeUserRef: boolean = false,\n revalidate: boolean = false,\n): Promise<ResolvedReplayConfig> {\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n try {\n const request: Promise<ResolvedReplayConfig> =\n (async (): Promise<ResolvedReplayConfig> => {\n const headers: Record<string, string> = {\n ...mobileRequestHeaders(options, includeUserRef),\n Accept: \"application/json\",\n };\n if (revalidate) {\n headers[\"Cache-Control\"] = \"no-cache\";\n headers[\"Pragma\"] = \"no-cache\";\n }\n const requestInit: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"GET\",\n headers,\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n const response: ReplayFetchResponse = await options.fetch(\n `${options.host}${CONFIG_PATH}`,\n requestInit,\n );\n\n if (!response.ok) {\n return failClosed(`config-http-${response.status}`);\n }\n\n return normalizeReplayConfig(await response.json());\n })();\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n timeout = setTimeout((): void => {\n controller?.abort();\n reject(new Error(\"config-fetch-timeout\"));\n }, CONFIG_FETCH_TIMEOUT_MS);\n },\n );\n return await Promise.race([request, deadline]);\n } catch {\n return failClosed(\"config-fetch-failed\");\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n RrwebIncrementalSource,\n SessionReplayFidelityNotice,\n} from \"./Contract\";\nimport { NativeViewKind, NativeViewTreeNode } from \"./NativeViewTree\";\n\nexport const RRWEB_DOCUMENT_NODE_ID: number = 1;\nexport const RRWEB_HTML_NODE_ID: number = 3;\nexport const RRWEB_HEAD_NODE_ID: number = 4;\nexport const RRWEB_BODY_NODE_ID: number = 5;\nconst FIRST_VIEW_NODE_ID: number = 10;\nconst MAX_VIEW_TREE_DEPTH: number = 64;\nconst MAX_VIEW_TREE_NODES: number = 5_000;\nconst MAX_GEOMETRY_VALUE: number = 100_000;\n\nconst SAFE_KINDS: ReadonlySet<NativeViewKind> = new Set<NativeViewKind>([\n \"view\",\n \"scroll\",\n \"button\",\n \"text\",\n \"input\",\n \"image\",\n \"webview\",\n \"canvas\",\n \"masked\",\n \"unknown\",\n]);\n\ninterface SerializedElement {\n type: 2;\n tagName: \"div\";\n attributes: Record<string, string>;\n childNodes: Array<SerializedElement>;\n id: number;\n}\n\ninterface SerializedRecord {\n key: string;\n id: number;\n parentId: number;\n attributes: Record<string, string>;\n node: SerializedElement;\n}\n\nexport interface SerializedCapture {\n events: Array<RrwebEvent>;\n hasFullSnapshot: boolean;\n fidelityNotices: Array<SessionReplayFidelityNotice>;\n droppedNodes: number;\n}\n\ninterface BuildResult {\n root: SerializedElement;\n records: Map<string, SerializedRecord>;\n byId: Map<number, SerializedRecord>;\n fidelity: Set<SessionReplayFidelityNotice>;\n droppedNodes: number;\n}\n\nfunction finiteGeometry(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return 0;\n }\n\n return Math.min(MAX_GEOMETRY_VALUE, Math.max(-MAX_GEOMETRY_VALUE, value));\n}\n\nfunction safeKind(value: unknown): NativeViewKind {\n if (typeof value === \"string\" && SAFE_KINDS.has(value as NativeViewKind)) {\n return value as NativeViewKind;\n }\n\n return \"unknown\";\n}\n\nfunction geometryStyle(node: NativeViewTreeNode): string {\n const x: number = finiteGeometry(node.x);\n const y: number = finiteGeometry(node.y);\n const width: number = Math.max(0, finiteGeometry(node.width));\n const height: number = Math.max(0, finiteGeometry(node.height));\n const style: Array<string> = [\n \"position:absolute\",\n `left:${x}px`,\n `top:${y}px`,\n `width:${width}px`,\n `height:${height}px`,\n \"box-sizing:border-box\",\n \"overflow:hidden\",\n \"outline:1px solid rgba(148,163,184,0.18)\",\n ];\n const backgroundColor: string | null = safeColor(node.backgroundColor);\n const borderColor: string | null = safeColor(node.borderColor);\n const borderWidth: number = clampedStyleNumber(node.borderWidth, 0, 100, 0);\n const borderRadius: number = clampedStyleNumber(\n node.borderRadius,\n 0,\n MAX_GEOMETRY_VALUE,\n 0,\n );\n const opacity: number = clampedStyleNumber(node.opacity, 0, 1, 1);\n const zIndex: number = clampedStyleNumber(node.zIndex, -10_000, 10_000, 0);\n\n if (backgroundColor) {\n style.push(`background-color:${backgroundColor}`);\n }\n if (borderColor && borderWidth > 0) {\n style.push(`border:${borderWidth}px solid ${borderColor}`);\n }\n if (borderRadius > 0) {\n style.push(`border-radius:${borderRadius}px`);\n }\n if (opacity < 1) {\n style.push(`opacity:${opacity}`);\n }\n if (zIndex !== 0) {\n style.push(`z-index:${zIndex}`);\n }\n\n return style.join(\";\");\n}\n\nconst HEX_COLOR_PATTERN: RegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/u;\n\nfunction safeColor(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const normalized: string = value.trim().toLowerCase();\n return HEX_COLOR_PATTERN.test(normalized) ? normalized : null;\n}\n\nfunction clampedStyleNumber(\n value: unknown,\n minimum: number,\n maximum: number,\n fallback: number,\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n\n return Math.max(minimum, Math.min(maximum, value));\n}\n\nfunction cloneNode(node: SerializedElement): SerializedElement {\n return {\n ...node,\n attributes: { ...node.attributes },\n childNodes: node.childNodes.map(cloneNode),\n };\n}\n\nfunction sameAttributes(\n left: Record<string, string>,\n right: Record<string, string>,\n): boolean {\n const leftKeys: Array<string> = Object.keys(left);\n const rightKeys: Array<string> = Object.keys(right);\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key: string): boolean => {\n return left[key] === right[key];\n })\n );\n}\n\nexport default class ViewTreeSerializer {\n private readonly nodeIds: Map<string, number> = new Map<string, number>();\n private nextNodeId: number = FIRST_VIEW_NODE_ID;\n private previous: BuildResult | null = null;\n\n public capture(\n input: NativeViewTreeNode,\n options: {\n timestamp: number;\n url: string;\n viewportWidth: number;\n viewportHeight: number;\n forceFullSnapshot?: boolean;\n },\n ): SerializedCapture {\n const shouldTakeFullSnapshot: boolean =\n !this.previous || options.forceFullSnapshot === true;\n if (options.forceFullSnapshot === true && this.previous) {\n this.previous = null;\n this.nodeIds.clear();\n this.nextNodeId = FIRST_VIEW_NODE_ID;\n }\n const current: BuildResult = this.build(input);\n const events: Array<RrwebEvent> = shouldTakeFullSnapshot\n ? this.fullSnapshot(current, options)\n : this.mutations(\n this.previous as BuildResult,\n current,\n options.timestamp,\n );\n\n this.previous = current;\n for (const key of this.nodeIds.keys()) {\n if (!current.records.has(key)) {\n this.nodeIds.delete(key);\n }\n }\n\n return {\n events,\n hasFullSnapshot: shouldTakeFullSnapshot,\n fidelityNotices: Array.from(current.fidelity),\n droppedNodes: current.droppedNodes,\n };\n }\n\n public reset(): void {\n this.previous = null;\n this.nodeIds.clear();\n this.nextNodeId = FIRST_VIEW_NODE_ID;\n }\n\n private build(input: NativeViewTreeNode): BuildResult {\n const records: Map<string, SerializedRecord> = new Map<\n string,\n SerializedRecord\n >();\n const byId: Map<number, SerializedRecord> = new Map<\n number,\n SerializedRecord\n >();\n const fidelity: Set<SessionReplayFidelityNotice> =\n new Set<SessionReplayFidelityNotice>([\n SessionReplayFidelityNotice.MobileAnimationSampled,\n ]);\n let visited: number = 0;\n let droppedNodes: number =\n typeof input.truncatedNodes === \"number\" &&\n Number.isSafeInteger(input.truncatedNodes) &&\n input.truncatedNodes > 0\n ? Math.min(input.truncatedNodes, 1_000_000)\n : 0;\n\n const visit: (\n candidate: NativeViewTreeNode,\n parentId: number,\n path: string,\n depth: number,\n ) => SerializedElement | null = (\n candidate: NativeViewTreeNode,\n parentId: number,\n path: string,\n depth: number,\n ): SerializedElement | null => {\n if (\n depth > MAX_VIEW_TREE_DEPTH ||\n visited >= MAX_VIEW_TREE_NODES ||\n !candidate ||\n typeof candidate !== \"object\"\n ) {\n droppedNodes += 1;\n return null;\n }\n\n visited += 1;\n const kind: NativeViewKind = candidate.masked\n ? \"masked\"\n : safeKind(candidate.kind);\n const key: string = `${typeof candidate.nativeId}:${String(\n candidate.nativeId,\n )}:${path}`;\n let id: number | undefined = this.nodeIds.get(key);\n if (id === undefined) {\n id = this.nextNodeId;\n this.nextNodeId += 1;\n this.nodeIds.set(key, id);\n }\n\n const attributes: Record<string, string> = {\n style: geometryStyle(candidate),\n \"data-oneuptime-mobile-view\": kind,\n };\n const isOpaque: boolean =\n candidate.opaque === true ||\n kind === \"image\" ||\n kind === \"webview\" ||\n kind === \"canvas\" ||\n kind === \"masked\";\n\n if (isOpaque) {\n attributes[\"data-oneuptime-replay-placeholder\"] = kind;\n if (!safeColor(candidate.backgroundColor)) {\n attributes[\"style\"] += \";background-color:#94a3b833\";\n }\n } else if (kind === \"text\" || kind === \"input\") {\n /* Fixed fill makes masked copy visible without carrying its value. */\n attributes[\"style\"] += \";background-color:#94a3b826\";\n }\n\n switch (kind) {\n case \"image\":\n fidelity.add(SessionReplayFidelityNotice.MobileImagesOpaque);\n break;\n case \"webview\":\n fidelity.add(SessionReplayFidelityNotice.MobileWebViewOpaque);\n break;\n case \"canvas\":\n fidelity.add(SessionReplayFidelityNotice.MobileCanvasOpaque);\n break;\n default:\n break;\n }\n\n const element: SerializedElement = {\n type: 2,\n tagName: \"div\",\n attributes,\n childNodes: [],\n id,\n };\n const record: SerializedRecord = {\n key,\n id,\n parentId,\n attributes,\n node: element,\n };\n records.set(key, record);\n byId.set(id, record);\n\n /* Masked and opaque content is a hard subtree boundary. */\n if (!isOpaque && Array.isArray(candidate.children)) {\n candidate.children.forEach(\n (child: NativeViewTreeNode, index: number): void => {\n const serialized: SerializedElement | null = visit(\n child,\n id as number,\n `${path}.${index}`,\n depth + 1,\n );\n if (serialized) {\n element.childNodes.push(serialized);\n }\n },\n );\n }\n\n return element;\n };\n\n const root: SerializedElement = visit(\n input,\n RRWEB_BODY_NODE_ID,\n \"0\",\n 0,\n ) ?? {\n type: 2,\n tagName: \"div\",\n attributes: {\n style:\n \"position:absolute;left:0px;top:0px;width:0px;height:0px;box-sizing:border-box;overflow:hidden\",\n \"data-oneuptime-mobile-view\": \"unknown\",\n },\n childNodes: [],\n id: this.nextNodeId++,\n };\n\n if (droppedNodes > 0) {\n fidelity.add(SessionReplayFidelityNotice.BufferOverflow);\n }\n\n return { root, records, byId, fidelity, droppedNodes };\n }\n\n private fullSnapshot(\n current: BuildResult,\n options: {\n timestamp: number;\n url: string;\n viewportWidth: number;\n viewportHeight: number;\n },\n ): Array<RrwebEvent> {\n const width: number = Math.max(0, finiteGeometry(options.viewportWidth));\n const height: number = Math.max(0, finiteGeometry(options.viewportHeight));\n return [\n {\n type: RrwebEventType.Meta,\n data: {\n href: options.url,\n width,\n height,\n },\n timestamp: options.timestamp,\n },\n {\n type: RrwebEventType.FullSnapshot,\n data: {\n node: {\n type: 0,\n childNodes: [\n {\n type: 1,\n name: \"html\",\n publicId: \"\",\n systemId: \"\",\n id: 2,\n },\n {\n type: 2,\n tagName: \"html\",\n attributes: {},\n childNodes: [\n {\n type: 2,\n tagName: \"head\",\n attributes: {},\n childNodes: [],\n id: RRWEB_HEAD_NODE_ID,\n },\n {\n type: 2,\n tagName: \"body\",\n attributes: {\n style: `margin:0;position:relative;width:${width}px;height:${height}px;overflow:hidden`,\n \"data-oneuptime-recorder-kind\": \"rn-view-tree\",\n },\n childNodes: [cloneNode(current.root)],\n id: RRWEB_BODY_NODE_ID,\n },\n ],\n id: RRWEB_HTML_NODE_ID,\n },\n ],\n id: RRWEB_DOCUMENT_NODE_ID,\n },\n initialOffset: { top: 0, left: 0 },\n },\n timestamp: options.timestamp,\n },\n ];\n }\n\n private mutations(\n previous: BuildResult,\n current: BuildResult,\n timestamp: number,\n ): Array<RrwebEvent> {\n const additions: Array<{\n parentId: number;\n nextId: null;\n node: SerializedElement;\n }> = [];\n const removals: Array<{ parentId: number; id: number }> = [];\n const attributes: Array<{\n id: number;\n attributes: Record<string, string>;\n }> = [];\n\n for (const record of current.records.values()) {\n const before: SerializedRecord | undefined = previous.records.get(\n record.key,\n );\n if (!before) {\n const parentWasAdded: boolean =\n record.parentId !== RRWEB_BODY_NODE_ID &&\n !previous.byId.has(record.parentId);\n if (!parentWasAdded) {\n additions.push({\n parentId: record.parentId,\n nextId: null,\n node: cloneNode(record.node),\n });\n }\n } else if (!sameAttributes(before.attributes, record.attributes)) {\n attributes.push({\n id: record.id,\n attributes: { ...record.attributes },\n });\n }\n }\n\n for (const record of previous.records.values()) {\n if (!current.records.has(record.key)) {\n const parentWasRemoved: boolean =\n record.parentId !== RRWEB_BODY_NODE_ID &&\n !current.byId.has(record.parentId);\n if (!parentWasRemoved) {\n removals.push({ parentId: record.parentId, id: record.id });\n }\n }\n }\n\n if (\n additions.length === 0 &&\n removals.length === 0 &&\n attributes.length === 0\n ) {\n return [];\n }\n\n return [\n {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.Mutation,\n texts: [],\n attributes,\n removes: removals,\n adds: additions,\n },\n timestamp,\n },\n ];\n }\n}\n", "import {\n RrwebEvent,\n RrwebEventType,\n RrwebIncrementalSource,\n RrwebMouseInteractionType,\n} from \"./Contract\";\nimport { RRWEB_BODY_NODE_ID } from \"./ViewTreeSerializer\";\n\nexport type TouchPhase = \"start\" | \"move\" | \"end\";\n\nexport interface RecordedTouch {\n phase: TouchPhase;\n x: number;\n y: number;\n timestamp: number;\n targetTag?: number;\n pointerId?: number | string;\n}\n\nconst MAX_TOUCH_CLOCK_SKEW_MS: number = 60_000;\n\nfunction coordinate(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(-100_000, Math.min(100_000, value))\n : 0;\n}\n\nexport function sanitizeRecordedTouch(\n value: unknown,\n nowUnixMs: number,\n): RecordedTouch | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n const raw: Partial<Record<keyof RecordedTouch, unknown>> = value as Partial<\n Record<keyof RecordedTouch, unknown>\n >;\n if (raw.phase !== \"start\" && raw.phase !== \"move\" && raw.phase !== \"end\") {\n return null;\n }\n\n const safeNowUnixMs: number = Number.isFinite(nowUnixMs)\n ? nowUnixMs\n : Date.now();\n const candidateTimestamp: unknown = raw.timestamp;\n const timestamp: number =\n typeof candidateTimestamp === \"number\" &&\n Number.isFinite(candidateTimestamp) &&\n candidateTimestamp >= safeNowUnixMs - MAX_TOUCH_CLOCK_SKEW_MS &&\n candidateTimestamp <= safeNowUnixMs + MAX_TOUCH_CLOCK_SKEW_MS\n ? candidateTimestamp\n : safeNowUnixMs;\n\n const touch: RecordedTouch = {\n phase: raw.phase,\n x: coordinate(raw.x),\n y: coordinate(raw.y),\n timestamp,\n };\n if (\n typeof raw.targetTag === \"number\" &&\n Number.isSafeInteger(raw.targetTag) &&\n raw.targetTag > 0\n ) {\n touch.targetTag = raw.targetTag;\n }\n if (\n (typeof raw.pointerId === \"number\" &&\n Number.isSafeInteger(raw.pointerId)) ||\n (typeof raw.pointerId === \"string\" && raw.pointerId.length <= 100)\n ) {\n touch.pointerId = raw.pointerId as number | string;\n }\n return touch;\n}\n\nexport function createTouchEvent(touch: RecordedTouch): RrwebEvent {\n const x: number = coordinate(touch.x);\n const y: number = coordinate(touch.y);\n\n if (touch.phase === \"move\") {\n return {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.TouchMove,\n positions: [\n {\n x,\n y,\n id: RRWEB_BODY_NODE_ID,\n timeOffset: 0,\n },\n ],\n },\n timestamp: touch.timestamp,\n };\n }\n\n return {\n type: RrwebEventType.IncrementalSnapshot,\n data: {\n source: RrwebIncrementalSource.MouseInteraction,\n type:\n touch.phase === \"start\"\n ? RrwebMouseInteractionType.TouchStart\n : RrwebMouseInteractionType.TouchEnd,\n id: RRWEB_BODY_NODE_ID,\n x,\n y,\n },\n timestamp: touch.timestamp,\n };\n}\n\nexport function createCustomEvent(\n tag: string,\n payload: unknown,\n timestamp: number,\n): RrwebEvent {\n return {\n type: RrwebEventType.Custom,\n data: { tag, payload },\n timestamp,\n };\n}\n", "import { Dimensions, NativeModules, Platform } from \"react-native\";\nimport { readTapTargetTestIds } from \"./CustomSignals\";\n\nexport type NativeViewKind =\n | \"view\"\n | \"scroll\"\n | \"button\"\n | \"text\"\n | \"input\"\n | \"image\"\n | \"webview\"\n | \"canvas\"\n | \"masked\"\n | \"unknown\";\n\nexport interface NativeViewTreeNode {\n nativeId: number | string;\n kind: NativeViewKind | string;\n x: number;\n y: number;\n width: number;\n height: number;\n /** Root-only origin in React Native pageX/pageY coordinates; never uploaded. */\n touchOriginX?: number;\n /** Root-only origin in React Native pageX/pageY coordinates; never uploaded. */\n touchOriginY?: number;\n opaque?: boolean;\n masked?: boolean;\n backgroundColor?: string;\n borderColor?: string;\n borderWidth?: number;\n borderRadius?: number;\n opacity?: number;\n zIndex?: number;\n /** Count omitted by the bounded native traversal, present on the root. */\n truncatedNodes?: number;\n children?: Array<NativeViewTreeNode>;\n /* Unknown native fields are deliberately ignored by the serialiser. */\n [key: string]: unknown;\n}\n\nexport interface NativeAppMetadata {\n appName: string;\n appVersion: string;\n osName: string;\n osVersion: string;\n}\n\nexport interface NativeViewTreeAdapter {\n isAvailable?(): boolean;\n captureViewTree(rootTag: number): Promise<NativeViewTreeNode>;\n getAppMetadata(): Promise<NativeAppMetadata>;\n isTouchTargetPrivate?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean>;\n /*\n * The testIDs of the touched view and of the views around it, out to the\n * replay root, the touched one first (issue #6517): what a tap signal of\n * the application's is matched against, on the device. Empty when the\n * view is gone or outside the replay root. Never recorded or sent.\n */\n touchTargetTestIds?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<Array<string>>;\n}\n\ninterface NativeModuleShape {\n captureViewTree?(rootTag: number): Promise<NativeViewTreeNode>;\n getAppMetadata?(): Promise<Partial<NativeAppMetadata>>;\n isTouchTargetPrivate?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean>;\n touchTargetTestIds?(\n targetTag: number,\n replayRootTag: number,\n ): Promise<unknown>;\n}\n\nfunction viewport(): { width: number; height: number } {\n const dimensions: { width?: number; height?: number } = Dimensions.get(\n \"window\",\n ) as { width?: number; height?: number };\n return {\n width:\n typeof dimensions.width === \"number\" && Number.isFinite(dimensions.width)\n ? dimensions.width\n : 0,\n height:\n typeof dimensions.height === \"number\" &&\n Number.isFinite(dimensions.height)\n ? dimensions.height\n : 0,\n };\n}\n\nexport class ReactNativeViewTreeAdapter implements NativeViewTreeAdapter {\n public isAvailable(): boolean {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n return typeof nativeModule?.captureViewTree === \"function\";\n }\n\n public async captureViewTree(rootTag: number): Promise<NativeViewTreeNode> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n\n if (nativeModule?.captureViewTree) {\n return await nativeModule.captureViewTree(rootTag);\n }\n\n throw new Error(\n \"OneUptime replay native module is unavailable. Expo Go is not supported; use an autolinked native or Expo development build.\",\n );\n }\n\n public async getAppMetadata(): Promise<NativeAppMetadata> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n let metadata: Partial<NativeAppMetadata> = {};\n\n try {\n metadata = (await nativeModule?.getAppMetadata?.()) ?? {};\n } catch {\n metadata = {};\n }\n\n return {\n appName:\n typeof metadata.appName === \"string\"\n ? metadata.appName\n : \"React Native\",\n appVersion:\n typeof metadata.appVersion === \"string\"\n ? metadata.appVersion\n : \"unknown\",\n osName:\n typeof metadata.osName === \"string\" ? metadata.osName : Platform.OS,\n osVersion:\n typeof metadata.osVersion === \"string\"\n ? metadata.osVersion\n : String(Platform.Version),\n };\n }\n\n public async isTouchTargetPrivate(\n targetTag: number,\n replayRootTag: number,\n ): Promise<boolean> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n if (typeof nativeModule?.isTouchTargetPrivate !== \"function\") {\n return true;\n }\n try {\n return (\n (await nativeModule.isTouchTargetPrivate(targetTag, replayRootTag)) !==\n false\n );\n } catch {\n return true;\n }\n }\n\n /*\n * A native module built before tap signals existed (an over-the-air\n * update of the JavaScript alone) has no such method: no testIDs, so no\n * tap signal fires, and nothing else changes.\n */\n public async touchTargetTestIds(\n targetTag: number,\n replayRootTag: number,\n ): Promise<Array<string>> {\n const nativeModule: NativeModuleShape | undefined = (\n NativeModules as Record<string, NativeModuleShape | undefined>\n )[\"OneUptimeReplayViewTree\"];\n if (typeof nativeModule?.touchTargetTestIds !== \"function\") {\n return [];\n }\n try {\n return readTapTargetTestIds(\n await nativeModule.touchTargetTestIds(targetTag, replayRootTag),\n );\n } catch {\n return [];\n }\n }\n}\n\nexport const defaultNativeViewTreeAdapter: NativeViewTreeAdapter =\n new ReactNativeViewTreeAdapter();\n\nexport function getViewport(): { width: number; height: number } {\n return viewport();\n}\n", "// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar ch2 = {};\nvar wk = (function (c, id, msg, transfer, cb) {\n var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([\n c + ';addEventListener(\"error\",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'\n ], { type: 'text/javascript' }))));\n w.onmessage = function (e) {\n var d = e.data, ed = d.$e$;\n if (ed) {\n var err = new Error(ed[0]);\n err['code'] = ed[1];\n err.stack = ed[2];\n cb(err, null);\n }\n else\n cb(null, d);\n };\n w.postMessage(msg, transfer);\n return w;\n});\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n var b = new u16(31);\n for (var i = 0; i < 31; ++i) {\n b[i] = start += 1 << eb[i - 1];\n }\n // numbers here are at max 18 bits\n var r = new i32(b[30]);\n for (var i = 1; i < 30; ++i) {\n for (var j = b[i]; j < b[i + 1]; ++j) {\n r[j] = ((j - b[i]) << 5) | i;\n }\n }\n return { b: b, r: r };\n};\nvar _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n // reverse table algorithm from SO\n var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);\n x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);\n x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);\n rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n var s = cd.length;\n // index\n var i = 0;\n // u16 \"map\": index -> # of codes with bit length = index\n var l = new u16(mb);\n // length of cd must be 288 (total # of codes)\n for (; i < s; ++i) {\n if (cd[i])\n ++l[cd[i] - 1];\n }\n // u16 \"map\": index -> minimum code for bit length = index\n var le = new u16(mb);\n for (i = 1; i < mb; ++i) {\n le[i] = (le[i - 1] + l[i - 1]) << 1;\n }\n var co;\n if (r) {\n // u16 \"map\": index -> number of actual bits, symbol for code\n co = new u16(1 << mb);\n // bits to remove for reverser\n var rvb = 15 - mb;\n for (i = 0; i < s; ++i) {\n // ignore 0 lengths\n if (cd[i]) {\n // num encoding both symbol and bits read\n var sv = (i << 4) | cd[i];\n // free bits\n var r_1 = mb - cd[i];\n // start value\n var v = le[cd[i] - 1]++ << r_1;\n // m is end value\n for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n // every 16 bit value starting with the code yields the same result\n co[rev[v] >> rvb] = sv;\n }\n }\n }\n }\n else {\n co = new u16(s);\n for (i = 0; i < s; ++i) {\n if (cd[i]) {\n co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);\n }\n }\n }\n return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n var m = a[0];\n for (var i = 1; i < a.length; ++i) {\n if (a[i] > m)\n m = a[i];\n }\n return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n var o = (p / 8) | 0;\n return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n if (s == null || s < 0)\n s = 0;\n if (e == null || e > v.length)\n e = v.length;\n // can't use .constructor in case user-supplied\n return new u8(v.subarray(s, e));\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n UnexpectedEOF: 0,\n InvalidBlockType: 1,\n InvalidLengthLiteral: 2,\n InvalidDistance: 3,\n StreamFinished: 4,\n NoStreamHandler: 5,\n InvalidHeader: 6,\n NoCallback: 7,\n InvalidUTF8: 8,\n ExtraFieldTooLong: 9,\n InvalidDate: 10,\n FilenameTooLong: 11,\n StreamFinishing: 12,\n InvalidZipData: 13,\n UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n 'unexpected EOF',\n 'invalid block type',\n 'invalid length/literal',\n 'invalid distance',\n 'stream finished',\n 'no stream handler',\n , // determined by compression function\n 'no callback',\n 'invalid UTF-8 data',\n 'extra field too long',\n 'date not in range 1980-2099',\n 'filename too long',\n 'stream finishing',\n 'invalid zip data'\n // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n var e = new Error(msg || ec[ind]);\n e.code = ind;\n if (Error.captureStackTrace)\n Error.captureStackTrace(e, err);\n if (!nt)\n throw e;\n return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, st, buf, dict) {\n // source length dict length\n var sl = dat.length, dl = dict ? dict.length : 0;\n if (!sl || st.f && !st.l)\n return buf || new u8(0);\n var noBuf = !buf;\n // have to estimate size\n var resize = noBuf || st.i != 2;\n // no state\n var noSt = st.i;\n // Assumes roughly 33% compression ratio average\n if (noBuf)\n buf = new u8(sl * 3);\n // ensure buffer can fit at least l elements\n var cbuf = function (l) {\n var bl = buf.length;\n // need to increase size to fit\n if (l > bl) {\n // Double or set to necessary, whichever is greater\n var nbuf = new u8(Math.max(bl * 2, l));\n nbuf.set(buf);\n buf = nbuf;\n }\n };\n // last chunk bitpos bytes\n var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n // total bits\n var tbts = sl * 8;\n do {\n if (!lm) {\n // BFINAL - this is only 1 when last chunk is next\n final = bits(dat, pos, 1);\n // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n var type = bits(dat, pos + 1, 3);\n pos += 3;\n if (!type) {\n // go to end of byte boundary\n var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n if (t > sl) {\n if (noSt)\n err(0);\n break;\n }\n // ensure size\n if (resize)\n cbuf(bt + l);\n // Copy over uncompressed data\n buf.set(dat.subarray(s, t), bt);\n // Get new bitpos, update byte count\n st.b = bt += l, st.p = pos = t * 8, st.f = final;\n continue;\n }\n else if (type == 1)\n lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n else if (type == 2) {\n // literal lengths\n var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n var tl = hLit + bits(dat, pos + 5, 31) + 1;\n pos += 14;\n // length+distance tree\n var ldt = new u8(tl);\n // code length tree\n var clt = new u8(19);\n for (var i = 0; i < hcLen; ++i) {\n // use index map to get real code\n clt[clim[i]] = bits(dat, pos + i * 3, 7);\n }\n pos += hcLen * 3;\n // code lengths bits\n var clb = max(clt), clbmsk = (1 << clb) - 1;\n // code lengths map\n var clm = hMap(clt, clb, 1);\n for (var i = 0; i < tl;) {\n var r = clm[bits(dat, pos, clbmsk)];\n // bits read\n pos += r & 15;\n // symbol\n var s = r >> 4;\n // code length to copy\n if (s < 16) {\n ldt[i++] = s;\n }\n else {\n // copy count\n var c = 0, n = 0;\n if (s == 16)\n n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n else if (s == 17)\n n = 3 + bits(dat, pos, 7), pos += 3;\n else if (s == 18)\n n = 11 + bits(dat, pos, 127), pos += 7;\n while (n--)\n ldt[i++] = c;\n }\n }\n // length tree distance tree\n var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n // max length bits\n lbt = max(lt);\n // max dist bits\n dbt = max(dt);\n lm = hMap(lt, lbt, 1);\n dm = hMap(dt, dbt, 1);\n }\n else\n err(1);\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n }\n // Make sure the buffer can hold this + the largest possible addition\n // Maximum chunk size (practically, theoretically infinite) is 2^17\n if (resize)\n cbuf(bt + 131072);\n var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n var lpos = pos;\n for (;; lpos = pos) {\n // bits read, code\n var c = lm[bits16(dat, pos) & lms], sym = c >> 4;\n pos += c & 15;\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (!c)\n err(2);\n if (sym < 256)\n buf[bt++] = sym;\n else if (sym == 256) {\n lpos = pos, lm = null;\n break;\n }\n else {\n var add = sym - 254;\n // no extra bits needed if less\n if (sym > 264) {\n // index\n var i = sym - 257, b = fleb[i];\n add = bits(dat, pos, (1 << b) - 1) + fl[i];\n pos += b;\n }\n // dist\n var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;\n if (!d)\n err(3);\n pos += d & 15;\n var dt = fd[dsym];\n if (dsym > 3) {\n var b = fdeb[dsym];\n dt += bits16(dat, pos) & (1 << b) - 1, pos += b;\n }\n if (pos > tbts) {\n if (noSt)\n err(0);\n break;\n }\n if (resize)\n cbuf(bt + 131072);\n var end = bt + add;\n if (bt < dt) {\n var shift = dl - dt, dend = Math.min(dt, end);\n if (shift + bt < 0)\n err(3);\n for (; bt < dend; ++bt)\n buf[bt] = dict[shift + bt];\n }\n for (; bt < end; ++bt)\n buf[bt] = buf[bt - dt];\n }\n }\n st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n if (lm)\n final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n } while (!final);\n // don't reallocate for streams or user buffers\n return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n v <<= p & 7;\n var o = (p / 8) | 0;\n d[o] |= v;\n d[o + 1] |= v >> 8;\n d[o + 2] |= v >> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n // Need extra info to make a tree\n var t = [];\n for (var i = 0; i < d.length; ++i) {\n if (d[i])\n t.push({ s: i, f: d[i] });\n }\n var s = t.length;\n var t2 = t.slice();\n if (!s)\n return { t: et, l: 0 };\n if (s == 1) {\n var v = new u8(t[0].s + 1);\n v[t[0].s] = 1;\n return { t: v, l: 1 };\n }\n t.sort(function (a, b) { return a.f - b.f; });\n // after i2 reaches last ind, will be stopped\n // freq must be greater than largest possible number of symbols\n t.push({ s: -1, f: 25001 });\n var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n // efficient algorithm from UZIP.js\n // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n // symbols that combined have high freq, will start processing i2 (high-freq,\n // non-composite) symbols instead\n // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n while (i1 != s - 1) {\n l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n }\n var maxSym = t2[0].s;\n for (var i = 1; i < s; ++i) {\n if (t2[i].s > maxSym)\n maxSym = t2[i].s;\n }\n // code lengths\n var tr = new u16(maxSym + 1);\n // max bits in tree\n var mbt = ln(t[i1 - 1], tr, 0);\n if (mbt > mb) {\n // more algorithms from UZIP.js\n // TODO: find out how this code works (debt)\n // ind debt\n var i = 0, dt = 0;\n // left cost\n var lft = mbt - mb, cst = 1 << lft;\n t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n for (; i < s; ++i) {\n var i2_1 = t2[i].s;\n if (tr[i2_1] > mb) {\n dt += cst - (1 << (mbt - tr[i2_1]));\n tr[i2_1] = mb;\n }\n else\n break;\n }\n dt >>= lft;\n while (dt > 0) {\n var i2_2 = t2[i].s;\n if (tr[i2_2] < mb)\n dt -= 1 << (mb - tr[i2_2]++ - 1);\n else\n ++i;\n }\n for (; i >= 0 && dt; --i) {\n var i2_3 = t2[i].s;\n if (tr[i2_3] == mb) {\n --tr[i2_3];\n ++dt;\n }\n }\n mbt = mb;\n }\n return { t: new u8(tr), l: mbt };\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n return n.s == -1\n ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n var s = c.length;\n // Note that the semicolon was intentional\n while (s && !c[--s])\n ;\n var cl = new u16(++s);\n // ind num streak\n var cli = 0, cln = c[0], cls = 1;\n var w = function (v) { cl[cli++] = v; };\n for (var i = 1; i <= s; ++i) {\n if (c[i] == cln && i != s)\n ++cls;\n else {\n if (!cln && cls > 2) {\n for (; cls > 138; cls -= 138)\n w(32754);\n if (cls > 2) {\n w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n cls = 0;\n }\n }\n else if (cls > 3) {\n w(cln), --cls;\n for (; cls > 6; cls -= 6)\n w(8304);\n if (cls > 2)\n w(((cls - 3) << 5) | 8208), cls = 0;\n }\n while (cls--)\n w(cln);\n cls = 1;\n cln = c[i];\n }\n }\n return { c: cl.subarray(0, cli), n: s };\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n var l = 0;\n for (var i = 0; i < cl.length; ++i)\n l += cf[i] * cl[i];\n return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n // no need to write 00 as type: TypedArray defaults to 0\n var s = dat.length;\n var o = shft(pos + 2);\n out[o] = s & 255;\n out[o + 1] = s >> 8;\n out[o + 2] = out[o] ^ 255;\n out[o + 3] = out[o + 1] ^ 255;\n for (var i = 0; i < s; ++i)\n out[o + i + 4] = dat[i];\n return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n wbits(out, p++, final);\n ++lf[256];\n var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;\n var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;\n var _c = lc(dlt), lclt = _c.c, nlc = _c.n;\n var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;\n var lcfreq = new u16(19);\n for (var i = 0; i < lclt.length; ++i)\n ++lcfreq[lclt[i] & 31];\n for (var i = 0; i < lcdt.length; ++i)\n ++lcfreq[lcdt[i] & 31];\n var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;\n var nlcc = 19;\n for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n ;\n var flen = (bl + 5) << 3;\n var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];\n if (bs >= 0 && flen <= ftlen && flen <= dtlen)\n return wfblk(out, p, dat.subarray(bs, bs + bl));\n var lm, ll, dm, dl;\n wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n if (dtlen < ftlen) {\n lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n var llm = hMap(lct, mlcb, 0);\n wbits(out, p, nlc - 257);\n wbits(out, p + 5, ndc - 1);\n wbits(out, p + 10, nlcc - 4);\n p += 14;\n for (var i = 0; i < nlcc; ++i)\n wbits(out, p + 3 * i, lct[clim[i]]);\n p += 3 * nlcc;\n var lcts = [lclt, lcdt];\n for (var it = 0; it < 2; ++it) {\n var clct = lcts[it];\n for (var i = 0; i < clct.length; ++i) {\n var len = clct[i] & 31;\n wbits(out, p, llm[len]), p += lct[len];\n if (len > 15)\n wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;\n }\n }\n }\n else {\n lm = flm, ll = flt, dm = fdm, dl = fdt;\n }\n for (var i = 0; i < li; ++i) {\n var sym = syms[i];\n if (sym > 255) {\n var len = (sym >> 18) & 31;\n wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n if (len > 7)\n wbits(out, p, (sym >> 23) & 31), p += fleb[len];\n var dst = sym & 31;\n wbits16(out, p, dm[dst]), p += dl[dst];\n if (dst > 3)\n wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];\n }\n else {\n wbits16(out, p, lm[sym]), p += ll[sym];\n }\n }\n wbits16(out, p, lm[256]);\n return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, st) {\n var s = st.z || dat.length;\n var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n // writing to this writes to the output buffer\n var w = o.subarray(pre, o.length - post);\n var lst = st.l;\n var pos = (st.r || 0) & 7;\n if (lvl) {\n if (pos)\n w[0] = st.r >> 3;\n var opt = deo[lvl - 1];\n var n = opt >> 13, c = opt & 8191;\n var msk_1 = (1 << plvl) - 1;\n // prev 2-byte val map curr 2-byte val map\n var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);\n var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n // 24576 is an arbitrary number of maximum symbols per block\n // 424 buffer for last block\n var syms = new i32(25000);\n // length/literal freq distance freq\n var lf = new u16(288), df = new u16(32);\n // l/lcnt exbits index l/lind waitdx blkpos\n var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;\n for (; i + 2 < s; ++i) {\n // hash value\n var hv = hsh(i);\n // index mod 32768 previous index mod\n var imod = i & 32767, pimod = head[hv];\n prev[imod] = pimod;\n head[hv] = imod;\n // We always should modify head and prev, but only add symbols if\n // this data is not yet processed (\"wait\" for wait index)\n if (wi <= i) {\n // bytes remaining\n var rem = s - i;\n if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {\n pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n li = lc_1 = eb = 0, bs = i;\n for (var j = 0; j < 286; ++j)\n lf[j] = 0;\n for (var j = 0; j < 30; ++j)\n df[j] = 0;\n }\n // len dist chain\n var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;\n if (rem > 2 && hv == hsh(i - dif)) {\n var maxn = Math.min(n, rem) - 1;\n var maxd = Math.min(32767, i);\n // max possible length\n // not capped at dif because decompressors implement \"rolling\" index population\n var ml = Math.min(258, rem);\n while (dif <= maxd && --ch_1 && imod != pimod) {\n if (dat[i + l] == dat[i + l - dif]) {\n var nl = 0;\n for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n ;\n if (nl > l) {\n l = nl, d = dif;\n // break out early when we reach \"nice\" (we are satisfied enough)\n if (nl > maxn)\n break;\n // now, find the rarest 2-byte sequence within this\n // length of literals and search for that instead.\n // Much faster than just using the start\n var mmd = Math.min(dif, nl - 2);\n var md = 0;\n for (var j = 0; j < mmd; ++j) {\n var ti = i - dif + j & 32767;\n var pti = prev[ti];\n var cd = ti - pti & 32767;\n if (cd > md)\n md = cd, pimod = ti;\n }\n }\n }\n // check the previous match\n imod = pimod, pimod = prev[imod];\n dif += imod - pimod & 32767;\n }\n }\n // d will be nonzero only when a match was found\n if (d) {\n // store both dist and len data in one int32\n // Make sure this is recognized as a len/dist with 28th bit (2^28)\n syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n var lin = revfl[l] & 31, din = revfd[d] & 31;\n eb += fleb[lin] + fdeb[din];\n ++lf[257 + lin];\n ++df[din];\n wi = i + l;\n ++lc_1;\n }\n else {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n }\n }\n for (i = Math.max(i, wi); i < s; ++i) {\n syms[li++] = dat[i];\n ++lf[dat[i]];\n }\n pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n if (!lst) {\n st.r = (pos & 7) | w[(pos / 8) | 0] << 3;\n // shft(pos) now 1 less if pos & 7 != 0\n pos -= 7;\n st.h = head, st.p = prev, st.i = i, st.w = wi;\n }\n }\n else {\n for (var i = st.w || 0; i < s + lst; i += 65535) {\n // end\n var e = i + 65535;\n if (e >= s) {\n // write final block\n w[(pos / 8) | 0] = lst;\n e = s;\n }\n pos = wfblk(w, pos + 1, dat.subarray(i, e));\n }\n st.i = s;\n }\n return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n var t = new Int32Array(256);\n for (var i = 0; i < 256; ++i) {\n var c = i, k = 9;\n while (--k)\n c = ((c & 1) && -306674912) ^ (c >>> 1);\n t[i] = c;\n }\n return t;\n})();\n// CRC32\nvar crc = function () {\n var c = -1;\n return {\n p: function (d) {\n // closures have awful performance\n var cr = c;\n for (var i = 0; i < d.length; ++i)\n cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n c = cr;\n },\n d: function () { return ~c; }\n };\n};\n// Adler32\nvar adler = function () {\n var a = 1, b = 0;\n return {\n p: function (d) {\n // closures have awful performance\n var n = a, m = b;\n var l = d.length | 0;\n for (var i = 0; i != l;) {\n var e = Math.min(i + 2655, l);\n for (; i < e; ++i)\n m += n += d[i];\n n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n }\n a = n, b = m;\n },\n d: function () {\n a %= 65521, b %= 65521;\n return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);\n }\n };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n if (!st) {\n st = { l: 1 };\n if (opt.dictionary) {\n var dict = opt.dictionary.subarray(-32768);\n var newDat = new u8(dict.length + dat.length);\n newDat.set(dict);\n newDat.set(dat, dict.length);\n dat = newDat;\n st.w = dict.length;\n }\n }\n return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n var o = {};\n for (var k in a)\n o[k] = a[k];\n for (var k in b)\n o[k] = b[k];\n return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n var dt = fn();\n var st = fn.toString();\n var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n for (var i = 0; i < dt.length; ++i) {\n var v = dt[i], k = ks[i];\n if (typeof v == 'function') {\n fnStr += ';' + k + '=';\n var st_1 = v.toString();\n if (v.prototype) {\n // for global objects\n if (st_1.indexOf('[native code]') != -1) {\n var spInd = st_1.indexOf(' ', 8) + 1;\n fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n }\n else {\n fnStr += st_1;\n for (var t in v.prototype)\n fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n }\n }\n else\n fnStr += st_1;\n }\n else\n td[k] = v;\n }\n return fnStr;\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n var tl = [];\n for (var k in v) {\n if (v[k].buffer) {\n tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n }\n }\n return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n if (!ch[id]) {\n var fnStr = '', td_1 = {}, m = fns.length - 1;\n for (var i = 0; i < m; ++i)\n fnStr = wcln(fns[i], fnStr, td_1);\n ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };\n }\n var td = mrg({}, ch[id].e);\n return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };\nvar bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zls]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get opts\nvar gopt = function (o) { return o && {\n out: o.size && new u8(o.size),\n dictionary: o.dictionary\n}; };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n var w = wrkr(fns, init, id, function (err, dat) {\n w.terminate();\n cb(err, dat);\n });\n w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n return function (ev) {\n if (ev.data[0]) {\n strm.push(ev.data[0], ev.data[1]);\n postMessage([ev.data[0].length]);\n }\n else\n strm.flush(ev.data[1]);\n };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id, flush, ext) {\n var t;\n var w = wrkr(fns, init, id, function (err, dat) {\n if (err)\n w.terminate(), strm.ondata.call(strm, err);\n else if (!Array.isArray(dat))\n ext(dat);\n else if (dat.length == 1) {\n strm.queuedSize -= dat[0];\n if (strm.ondrain)\n strm.ondrain(dat[0]);\n }\n else {\n if (dat[1])\n w.terminate();\n strm.ondata.call(strm, err, dat[0], dat[1]);\n }\n });\n w.postMessage(opts);\n strm.queuedSize = 0;\n strm.push = function (d, f) {\n if (!strm.ondata)\n err(5);\n if (t)\n strm.ondata(err(4, 0, 1), null, !!f);\n strm.queuedSize += d.length;\n // can fail for cross-realm Uint8Array, but ok - only a small performance penalty\n w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []);\n };\n strm.terminate = function () { w.terminate(); };\n if (flush) {\n strm.flush = function (sync) { w.postMessage([0, sync]); };\n }\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\n// read 8 bytes\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n for (; v; ++b)\n d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n var fn = o.filename;\n c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n if (o.mtime != 0)\n wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n if (fn) {\n c[3] = 8;\n for (var i = 0; i <= fn.length; ++i)\n c[i + 10] = fn.charCodeAt(i);\n }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n err(6, 'invalid gzip data');\n var flg = d[3];\n var st = 10;\n if (flg & 4)\n st += (d[10] | d[11] << 8) + 2;\n for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n ;\n return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n var l = d.length;\n return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };\n// zlib header\nvar zlh = function (c, o) {\n var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);\n c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;\n if (o.dictionary) {\n var h = adler();\n h.p(o.dictionary);\n wbytes(c, 2, h.d());\n }\n};\n// zlib start\nvar zls = function (d, dict) {\n if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n err(6, 'invalid zlib data');\n if ((d[1] >> 5 & 1) == +!dict)\n err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');\n return (d[1] >> 3 & 4) + 2;\n};\nfunction StrmOpt(opts, cb) {\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n return opts;\n}\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n function Deflate(opts, cb) {\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n this.o = opts || {};\n this.s = { l: 0, i: 32768, w: 32768, z: 32768 };\n // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev\n // 98304 = 32768 (lookback) + 65536 (common chunk size)\n this.b = new u8(98304);\n if (this.o.dictionary) {\n var dict = this.o.dictionary.subarray(-32768);\n this.b.set(dict, 32768 - dict.length);\n this.s.i = 32768 - dict.length;\n }\n }\n Deflate.prototype.p = function (c, f) {\n this.ondata(dopt(c, this.o, 0, 0, this.s), f);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Deflate.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.s.l)\n err(4);\n var endLen = chunk.length + this.s.z;\n if (endLen > this.b.length) {\n if (endLen > 2 * this.b.length - 32768) {\n var newBuf = new u8(endLen & -32768);\n newBuf.set(this.b.subarray(0, this.s.z));\n this.b = newBuf;\n }\n var split = this.b.length - this.s.z;\n this.b.set(chunk.subarray(0, split), this.s.z);\n this.s.z = this.b.length;\n this.p(this.b, false);\n this.b.set(this.b.subarray(-32768));\n this.b.set(chunk.subarray(split), 32768);\n this.s.z = chunk.length - split + 32768;\n this.s.i = 32766, this.s.w = 32768;\n }\n else {\n this.b.set(chunk, this.s.z);\n this.s.z += chunk.length;\n }\n this.s.l = final & 1;\n if (this.s.z > this.s.w + 8191 || final) {\n this.p(this.b, final || false);\n this.s.w = this.s.i, this.s.i -= 2;\n }\n if (final) {\n // cleanup unneeded buffers/state to reduce memory usage\n this.s = this.o = {};\n this.b = et;\n }\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * deflated output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible. A separate DEFLATE stream may be concatenated\n * with the current output after a sync flush.\n */\n Deflate.prototype.flush = function (sync) {\n if (!this.ondata)\n err(5);\n if (this.s.l)\n err(4);\n this.p(this.b, false);\n this.s.w = this.s.i, this.s.i -= 2;\n // could technically skip writing the type-0 block for (this.s.r & 7) == 0,\n // but the deterministic trailer (00 00 FF FF) is useful in some situations\n if (sync) {\n var c = new u8(6);\n c[0] = this.s.r >> 3;\n // write empty, non-final type-0 block\n var ep = wfblk(c, this.s.r, et);\n this.s.r = 0;\n this.ondata(c.subarray(0, ep >> 3), false);\n }\n };\n return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n function AsyncDeflate(opts, cb) {\n astrmify([\n bDflt,\n function () { return [astrm, Deflate]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Deflate(ev.data);\n onmessage = astrm(strm);\n }, 6, 1);\n }\n return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n function Inflate(opts, cb) {\n // no StrmOpt here to avoid adding to workerizer\n if (typeof opts == 'function')\n cb = opts, opts = {};\n this.ondata = cb;\n var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);\n this.s = { i: 0, b: dict ? dict.length : 0 };\n this.o = new u8(32768);\n this.p = new u8(0);\n if (dict)\n this.o.set(dict);\n }\n Inflate.prototype.e = function (c) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n if (!this.p.length)\n this.p = c;\n else if (c.length) {\n var n = new u8(this.p.length + c.length);\n n.set(this.p), n.set(c, this.p.length), this.p = n;\n }\n };\n Inflate.prototype.c = function (final) {\n this.s.i = +(this.d = final || false);\n var bts = this.s.b;\n var dt = inflt(this.p, this.s, this.o);\n this.ondata(slc(dt, bts, this.s.b), this.d);\n this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n };\n /**\n * Pushes a chunk to be inflated\n * @param chunk The chunk to push\n * @param final Whether this is the final chunk\n */\n Inflate.prototype.push = function (chunk, final) {\n this.e(chunk), this.c(final);\n };\n return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n function AsyncInflate(opts, cb) {\n astrmify([\n bInflt,\n function () { return [astrm, Inflate]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Inflate(ev.data);\n onmessage = astrm(strm);\n }, 7, 0);\n }\n return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt\n ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);\n}\nexport function inflateSync(data, opts) {\n return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n function Gzip(opts, cb) {\n this.c = crc();\n this.l = 0;\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gzip.prototype.push = function (chunk, final) {\n this.c.p(chunk);\n this.l += chunk.length;\n Deflate.prototype.push.call(this, chunk, final);\n };\n Gzip.prototype.p = function (c, f) {\n var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);\n if (this.v)\n gzh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n this.ondata(raw, f);\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * GZIPped output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible.\n */\n Gzip.prototype.flush = function (sync) {\n Deflate.prototype.flush.call(this, sync);\n };\n return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n function AsyncGzip(opts, cb) {\n astrmify([\n bDflt,\n gze,\n function () { return [astrm, Deflate, Gzip]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Gzip(ev.data);\n onmessage = astrm(strm);\n }, 8, 1);\n }\n return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n gze,\n function () { return [gzipSync]; }\n ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n if (!opts)\n opts = {};\n var c = crc(), l = data.length;\n c.p(data);\n var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming single or multi-member GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n function Gunzip(opts, cb) {\n this.v = 1;\n this.r = 0;\n Inflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be GUNZIPped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Gunzip.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n this.r += chunk.length;\n if (this.v) {\n var p = this.p.subarray(this.v - 1);\n var s = p.length > 3 ? gzs(p) : 4;\n if (s > p.length) {\n if (!final)\n return;\n }\n else if (this.v > 1 && this.onmember) {\n this.onmember(this.r - p.length);\n }\n this.p = p.subarray(s), this.v = 0;\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, 0);\n // process concatenated GZIP\n if (this.s.f && !this.s.l) {\n this.v = shft(this.s.p) + 9;\n this.s = { i: 0 };\n this.o = new u8(0);\n this.push(new u8(0), final);\n }\n else if (final) {\n Inflate.prototype.c.call(this, final);\n }\n };\n return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming single or multi-member GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n function AsyncGunzip(opts, cb) {\n var _this = this;\n astrmify([\n bInflt,\n guze,\n function () { return [astrm, Inflate, Gunzip]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Gunzip(ev.data);\n strm.onmember = function (offset) { return postMessage(offset); };\n onmessage = astrm(strm);\n }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });\n }\n return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n guze,\n function () { return [gunzipSync]; }\n ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);\n}\nexport function gunzipSync(data, opts) {\n var st = gzs(data);\n if (st + 8 > data.length)\n err(6, 'invalid gzip data');\n return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n function Zlib(opts, cb) {\n this.c = adler();\n this.v = 1;\n Deflate.call(this, opts, cb);\n }\n /**\n * Pushes a chunk to be zlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Zlib.prototype.push = function (chunk, final) {\n this.c.p(chunk);\n Deflate.prototype.push.call(this, chunk, final);\n };\n Zlib.prototype.p = function (c, f) {\n var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);\n if (this.v)\n zlh(raw, this.o), this.v = 0;\n if (f)\n wbytes(raw, raw.length - 4, this.c.d());\n this.ondata(raw, f);\n };\n /**\n * Flushes buffered uncompressed data. Useful to immediately retrieve the\n * zlibbed output for small inputs.\n * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n * extra bytes, but guarantees all pushed data is immediately\n * decompressible.\n */\n Zlib.prototype.flush = function (sync) {\n Deflate.prototype.flush.call(this, sync);\n };\n return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n function AsyncZlib(opts, cb) {\n astrmify([\n bDflt,\n zle,\n function () { return [astrm, Deflate, Zlib]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Zlib(ev.data);\n onmessage = astrm(strm);\n }, 10, 1);\n }\n return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bDflt,\n zle,\n function () { return [zlibSync]; }\n ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n if (!opts)\n opts = {};\n var a = adler();\n a.p(data);\n var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);\n return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n function Unzlib(opts, cb) {\n Inflate.call(this, opts, cb);\n this.v = opts && opts.dictionary ? 2 : 1;\n }\n /**\n * Pushes a chunk to be unzlibbed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzlib.prototype.push = function (chunk, final) {\n Inflate.prototype.e.call(this, chunk);\n if (this.v) {\n if (this.p.length < 6 && !final)\n return;\n this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;\n }\n if (final) {\n if (this.p.length < 4)\n err(6, 'invalid zlib data');\n this.p = this.p.subarray(0, -4);\n }\n // necessary to prevent TS from using the closure value\n // This allows for workerization to function correctly\n Inflate.prototype.c.call(this, final);\n };\n return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n function AsyncUnzlib(opts, cb) {\n astrmify([\n bInflt,\n zule,\n function () { return [astrm, Inflate, Unzlib]; }\n ], this, StrmOpt.call(this, opts, cb), function (ev) {\n var strm = new Unzlib(ev.data);\n onmessage = astrm(strm);\n }, 11, 0);\n }\n return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return cbify(data, opts, [\n bInflt,\n zule,\n function () { return [unzlibSync]; }\n ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);\n}\nexport function unzlibSync(data, opts) {\n return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n function Decompress(opts, cb) {\n this.o = StrmOpt.call(this, opts, cb) || {};\n this.G = Gunzip;\n this.I = Inflate;\n this.Z = Unzlib;\n }\n // init substream\n // overriden by AsyncDecompress\n Decompress.prototype.i = function () {\n var _this = this;\n this.s.ondata = function (dat, final) {\n _this.ondata(dat, final);\n };\n };\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Decompress.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (!this.s) {\n if (this.p && this.p.length) {\n var n = new u8(this.p.length + chunk.length);\n n.set(this.p), n.set(chunk, this.p.length);\n }\n else\n this.p = chunk;\n if (this.p.length > 2) {\n this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n ? new this.G(this.o)\n : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n ? new this.I(this.o)\n : new this.Z(this.o);\n this.i();\n this.s.push(this.p, final);\n this.p = null;\n }\n }\n else\n this.s.push(chunk, final);\n };\n return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n function AsyncDecompress(opts, cb) {\n Decompress.call(this, opts, cb);\n this.queuedSize = 0;\n this.G = AsyncGunzip;\n this.I = AsyncInflate;\n this.Z = AsyncUnzlib;\n }\n AsyncDecompress.prototype.i = function () {\n var _this = this;\n this.s.ondata = function (err, dat, final) {\n _this.ondata(err, dat, final);\n };\n this.s.ondrain = function (size) {\n _this.queuedSize -= size;\n if (_this.ondrain)\n _this.ondrain(size);\n };\n };\n /**\n * Pushes a chunk to be decompressed\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncDecompress.prototype.push = function (chunk, final) {\n this.queuedSize += chunk.length;\n Decompress.prototype.push.call(this, chunk, final);\n };\n return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzip(data, opts, cb)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflate(data, opts, cb)\n : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, opts) {\n return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n ? gunzipSync(data, opts)\n : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n ? inflateSync(data, opts)\n : unzlibSync(data, opts);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n for (var k in d) {\n var val = d[k], n = p + k, op = o;\n if (Array.isArray(val))\n op = mrg(o, val[1]), val = val[0];\n if (ArrayBuffer.isView(val))\n t[n] = [val, op];\n else {\n t[n += '/'] = [new u8(0), op];\n fltn(val, n, t, o);\n }\n }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n td.decode(et, { stream: true });\n tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n for (var r = '', i = 0;;) {\n var c = d[i++];\n var eb = (c > 127) + (c > 223) + (c > 239);\n if (i + eb > d.length)\n return { s: r, r: slc(d, i - 1) };\n if (!eb)\n r += String.fromCharCode(c);\n else if (eb == 3) {\n c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n }\n else if (eb & 1)\n r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n else\n r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is decoded\n */\n function DecodeUTF8(cb) {\n this.ondata = cb;\n if (tds)\n this.t = new TextDecoder();\n else\n this.p = et;\n }\n /**\n * Pushes a chunk to be decoded from UTF-8 binary\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n DecodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n final = !!final;\n if (this.t) {\n this.ondata(this.t.decode(chunk, { stream: true }), final);\n if (final) {\n if (this.t.decode().length)\n err(8);\n this.t = null;\n }\n return;\n }\n if (!this.p)\n err(4);\n var dat = new u8(this.p.length + chunk.length);\n dat.set(this.p);\n dat.set(chunk, this.p.length);\n var _a = dutf8(dat), s = _a.s, r = _a.r;\n if (final) {\n if (r.length)\n err(8);\n this.p = null;\n }\n else\n this.p = r;\n this.ondata(s, final);\n };\n return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n /**\n * Creates a UTF-8 decoding stream\n * @param cb The callback to call whenever data is encoded\n */\n function EncodeUTF8(cb) {\n this.ondata = cb;\n }\n /**\n * Pushes a chunk to be encoded to UTF-8\n * @param chunk The string data to push\n * @param final Whether this is the last chunk\n */\n EncodeUTF8.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n if (this.d)\n err(4);\n this.ondata(strToU8(chunk), this.d = final || false);\n };\n return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n if (latin1) {\n var ar_1 = new u8(str.length);\n for (var i = 0; i < str.length; ++i)\n ar_1[i] = str.charCodeAt(i);\n return ar_1;\n }\n if (te)\n return te.encode(str);\n var l = str.length;\n var ar = new u8(str.length + (str.length >> 1));\n var ai = 0;\n var w = function (v) { ar[ai++] = v; };\n for (var i = 0; i < l; ++i) {\n if (ai + 5 > ar.length) {\n var n = new u8(ai + 8 + ((l - i) << 1));\n n.set(ar);\n ar = n;\n }\n var c = str.charCodeAt(i);\n if (c < 128 || latin1)\n w(c);\n else if (c < 2048)\n w(192 | (c >> 6)), w(128 | (c & 63));\n else if (c > 55295 && c < 57344)\n c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n else\n w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n }\n return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n * not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n if (latin1) {\n var r = '';\n for (var i = 0; i < dat.length; i += 16384)\n r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n return r;\n }\n else if (td) {\n return td.decode(dat);\n }\n else {\n var _a = dutf8(dat), s = _a.s, r = _a.r;\n if (r.length)\n err(8);\n return s;\n }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;\n var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2];\n return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];\n};\n// read zip64 header sizes\nvar z64hs = function (d, b, l, z, sc, su, off) {\n var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;\n var nf = nsc + nsu + noff;\n if (z && nf) {\n for (; b + 4 < e; b += 4 + b2(d, b + 2)) {\n if (b2(d, b) == 1) {\n return [\n nsc ? b8(d, b + 4 + 8 * nsu) : sc,\n nsu ? b8(d, b + 4) : su,\n noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,\n 1\n ];\n }\n }\n // z == 2 for unknown whether or not zip64\n if (z < 2)\n err(13);\n }\n return [sc, su, off, 0];\n};\n// extra field length\nvar exfl = function (ex) {\n var le = 0;\n if (ex) {\n for (var k in ex) {\n var l = ex[k].length;\n if (l > 65535)\n err(9);\n le += l + 4;\n }\n }\n return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n var fl = fn.length, ex = f.extra, col = co && co.length;\n var exl = exfl(ex);\n wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n if (ce != null)\n d[b++] = 20, d[b++] = f.os;\n d[b] = 20, b += 2; // spec compliance? what's that?\n d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n if (y < 0 || y > 119)\n err(10);\n wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;\n if (c != -1) {\n wbytes(d, b, f.crc);\n wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n wbytes(d, b + 8, f.size);\n }\n wbytes(d, b + 12, fl);\n wbytes(d, b + 14, exl), b += 16;\n if (ce != null) {\n wbytes(d, b, col);\n wbytes(d, b + 6, f.attrs);\n wbytes(d, b + 10, ce), b += 14;\n }\n d.set(fn, b);\n b += fl;\n if (exl) {\n for (var k in ex) {\n var exf = ex[k], l = exf.length;\n wbytes(d, b, +k);\n wbytes(d, b + 2, l);\n d.set(exf, b + 4), b += 4 + l;\n }\n }\n if (col)\n d.set(co, b), b += col;\n return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n wbytes(o, b, 0x6054B50); // skip disk\n wbytes(o, b + 8, c);\n wbytes(o, b + 10, c);\n wbytes(o, b + 12, d);\n wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n /**\n * Creates a pass-through stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n */\n function ZipPassThrough(filename) {\n this.filename = filename;\n this.c = crc();\n this.size = 0;\n this.compression = 0;\n }\n /**\n * Processes a chunk and pushes to the output stream. You can override this\n * method in a subclass for custom behavior, but by default this passes\n * the data through. You must call this.ondata(err, chunk, final) at some\n * point in this method.\n * @param chunk The chunk to process\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.process = function (chunk, final) {\n this.ondata(null, chunk, final);\n };\n /**\n * Pushes a chunk to be added. If you are subclassing this with a custom\n * compression algorithm, note that you must push data from the source\n * file only, pre-compression.\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipPassThrough.prototype.push = function (chunk, final) {\n if (!this.ondata)\n err(5);\n this.c.p(chunk);\n this.size += chunk.length;\n if (final)\n this.crc = this.c.d();\n // we shouldn't really do this cast, but properly handling ArrayBufferLike\n // makes the API unergonomic with Buffer\n this.process(chunk, final || false);\n };\n return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function ZipDeflate(filename, opts) {\n var _this = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new Deflate(opts, function (dat, final) {\n _this.ondata(null, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n }\n ZipDeflate.prototype.process = function (chunk, final) {\n try {\n this.d.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n ZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n /**\n * Creates an asynchronous DEFLATE stream that can be added to ZIP archives\n * @param filename The filename to associate with this data stream\n * @param opts The compression options\n */\n function AsyncZipDeflate(filename, opts) {\n var _this = this;\n if (!opts)\n opts = {};\n ZipPassThrough.call(this, filename);\n this.d = new AsyncDeflate(opts, function (err, dat, final) {\n _this.ondata(err, dat, final);\n });\n this.compression = 8;\n this.flag = dbf(opts.level);\n this.terminate = this.d.terminate;\n }\n AsyncZipDeflate.prototype.process = function (chunk, final) {\n this.d.push(chunk, final);\n };\n /**\n * Pushes a chunk to be deflated\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n AsyncZipDeflate.prototype.push = function (chunk, final) {\n ZipPassThrough.prototype.push.call(this, chunk, final);\n };\n return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n /**\n * Creates an empty ZIP archive to which files can be added\n * @param cb The callback to call whenever data for the generated ZIP archive\n * is available\n */\n function Zip(cb) {\n this.ondata = cb;\n this.u = [];\n this.d = 1;\n }\n /**\n * Adds a file to the ZIP archive\n * @param file The file stream to add\n */\n Zip.prototype.add = function (file) {\n var _this = this;\n if (!this.ondata)\n err(5);\n // finishing or finished\n if (this.d & 2)\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n else {\n var f = strToU8(file.filename), fl_1 = f.length;\n var com = file.comment, o = com && strToU8(com);\n var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n var hl_1 = fl_1 + exfl(file.extra) + 30;\n if (fl_1 > 65535)\n this.ondata(err(11, 0, 1), null, false);\n var header = new u8(hl_1);\n wzh(header, 0, file, f, u, -1);\n var chks_1 = [header];\n var pAll_1 = function () {\n for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n var chk = chks_2[_i];\n _this.ondata(null, chk, false);\n }\n chks_1 = [];\n };\n var tr_1 = this.d;\n this.d = 0;\n var ind_1 = this.u.length;\n var uf_1 = mrg(file, {\n f: f,\n u: u,\n o: o,\n t: function () {\n if (file.terminate)\n file.terminate();\n },\n r: function () {\n pAll_1();\n if (tr_1) {\n var nxt = _this.u[ind_1 + 1];\n if (nxt)\n nxt.r();\n else\n _this.d = 1;\n }\n tr_1 = 1;\n }\n });\n var cl_1 = 0;\n file.ondata = function (err, dat, final) {\n if (err) {\n _this.ondata(err, dat, final);\n _this.terminate();\n }\n else {\n cl_1 += dat.length;\n chks_1.push(dat);\n if (final) {\n var dd = new u8(16);\n wbytes(dd, 0, 0x8074B50);\n wbytes(dd, 4, file.crc);\n wbytes(dd, 8, cl_1);\n wbytes(dd, 12, file.size);\n chks_1.push(dd);\n uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n if (tr_1)\n uf_1.r();\n tr_1 = 1;\n }\n else if (tr_1)\n pAll_1();\n }\n };\n this.u.push(uf_1);\n }\n };\n /**\n * Ends the process of adding files and prepares to emit the final chunks.\n * This *must* be called after adding all desired files for the resulting\n * ZIP file to work properly.\n */\n Zip.prototype.end = function () {\n var _this = this;\n if (this.d & 2) {\n this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n return;\n }\n if (this.d)\n this.e();\n else\n this.u.push({\n r: function () {\n if (!(_this.d & 1))\n return;\n _this.u.splice(-1, 1);\n _this.e();\n },\n t: function () { }\n });\n this.d = 3;\n };\n Zip.prototype.e = function () {\n var bt = 0, l = 0, tl = 0;\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n }\n var out = new u8(tl + 22);\n for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n var f = _c[_b];\n wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n }\n wzf(out, bt, this.u.length, tl, l);\n this.ondata(null, out, true);\n this.d = 2;\n };\n /**\n * A method to terminate any internal workers used by the stream. Subsequent\n * calls to add() will fail.\n */\n Zip.prototype.terminate = function () {\n for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n var f = _a[_i];\n f.t();\n }\n this.d = 2;\n };\n return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var r = {};\n fltn(data, '', r, opts);\n var k = Object.keys(r);\n var lft = k.length, o = 0, tot = 0;\n var slft = lft, files = new Array(lft);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var cbf = function () {\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n tot = 0;\n for (var i = 0; i < slft; ++i) {\n var f = files[i];\n try {\n var l = f.c.length;\n wzh(out, tot, f, f.f, f.u, l);\n var badd = 30 + f.f.length + exfl(f.extra);\n var loc = tot + badd;\n out.set(f.c, loc);\n wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n }\n catch (e) {\n return cbd(e, null);\n }\n }\n wzf(out, o, files.length, cdl, oe);\n cbd(null, out);\n };\n if (!lft)\n cbf();\n var _loop_1 = function (i) {\n var fn = k[i];\n var _a = r[fn], file = _a[0], p = _a[1];\n var c = crc(), size = file.length;\n c.p(file);\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n var compression = p.level == 0 ? 0 : 8;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n var l = d.length;\n files[i] = mrg(p, {\n size: size,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n compression: compression\n });\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n if (!--lft)\n cbf();\n }\n };\n if (s > 65535)\n cbl(err(11, 0, 1), null);\n if (!compression)\n cbl(null, file);\n else if (size < 160000) {\n try {\n cbl(null, deflateSync(file, p));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(deflate(file, p, cbl));\n };\n // Cannot use lft because it can decrease\n for (var i = 0; i < slft; ++i) {\n _loop_1(i);\n }\n return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n if (!opts)\n opts = {};\n var r = {};\n var files = [];\n fltn(data, '', r, opts);\n var o = 0;\n var tot = 0;\n for (var fn in r) {\n var _a = r[fn], file = _a[0], p = _a[1];\n var compression = p.level == 0 ? 0 : 8;\n var f = strToU8(fn), s = f.length;\n var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n var exl = exfl(p.extra);\n if (s > 65535)\n err(11);\n var d = compression ? deflateSync(file, p) : file, l = d.length;\n var c = crc();\n c.p(file);\n files.push(mrg(p, {\n size: file.length,\n crc: c.d(),\n c: d,\n f: f,\n m: m,\n u: s != fn.length || (m && (com.length != ms)),\n o: o,\n compression: compression\n }));\n o += 30 + s + exl + l;\n tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n }\n var out = new u8(tot + 22), oe = o, cdl = tot - o;\n for (var i = 0; i < files.length; ++i) {\n var f = files[i];\n wzh(out, f.o, f, f.f, f.u, f.c.length);\n var badd = 30 + f.f.length + exfl(f.extra);\n out.set(f.c, f.o + badd);\n wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n }\n wzf(out, o, files.length, cdl, oe);\n return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n function UnzipPassThrough() {\n }\n UnzipPassThrough.prototype.push = function (chunk, final) {\n // same as ZipPassThrough: cast to retain Buffer ergonomics\n this.ondata(null, chunk, final);\n };\n UnzipPassThrough.compression = 0;\n return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function UnzipInflate() {\n var _this = this;\n this.i = new Inflate(function (dat, final) {\n _this.ondata(null, dat, final);\n });\n }\n UnzipInflate.prototype.push = function (chunk, final) {\n try {\n this.i.push(chunk, final);\n }\n catch (e) {\n this.ondata(e, null, final);\n }\n };\n UnzipInflate.compression = 8;\n return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n /**\n * Creates a DEFLATE decompression that can be used in ZIP archives\n */\n function AsyncUnzipInflate(_, sz) {\n var _this = this;\n if (sz < 320000) {\n this.i = new Inflate(function (dat, final) {\n _this.ondata(null, dat, final);\n });\n }\n else {\n this.i = new AsyncInflate(function (err, dat, final) {\n _this.ondata(err, dat, final);\n });\n this.terminate = this.i.terminate;\n }\n }\n AsyncUnzipInflate.prototype.push = function (chunk, final) {\n if (this.i.terminate)\n chunk = slc(chunk, 0);\n this.i.push(chunk, final);\n };\n AsyncUnzipInflate.compression = 8;\n return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n /**\n * Creates a ZIP decompression stream\n * @param cb The callback to call whenever a file in the ZIP archive is found\n */\n function Unzip(cb) {\n this.onfile = cb;\n this.k = [];\n this.o = {\n 0: UnzipPassThrough\n };\n this.p = et;\n }\n /**\n * Pushes a chunk to be unzipped\n * @param chunk The chunk to push\n * @param final Whether this is the last chunk\n */\n Unzip.prototype.push = function (chunk, final) {\n var _this = this;\n if (!this.onfile)\n err(5);\n if (!this.p)\n err(4);\n if (this.c > 0) {\n var len = Math.min(this.c, chunk.length);\n var toAdd = chunk.subarray(0, len);\n this.c -= len;\n if (this.d)\n this.d.push(toAdd, !this.c);\n else\n this.k[0].push(toAdd);\n chunk = chunk.subarray(len);\n if (chunk.length)\n return this.push(chunk, final);\n }\n else {\n var f = 0, i = 0, is = void 0, buf = void 0;\n if (!this.p.length)\n buf = chunk;\n else if (!chunk.length)\n buf = this.p;\n else {\n buf = new u8(this.p.length + chunk.length);\n buf.set(this.p), buf.set(chunk, this.p.length);\n }\n var l = buf.length, oc = this.c, add = oc && this.d;\n var _loop_2 = function () {\n var sig = b4(buf, i);\n if (sig == 0x4034B50) {\n f = 1, is = i;\n this_1.d = null;\n this_1.c = 0;\n var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n if (l > i + 30 + fnl + es) {\n var chks_3 = [];\n this_1.k.unshift(chks_3);\n f = 2;\n var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22);\n var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3];\n if (dd)\n sc_1 = -1 - z64;\n i += es;\n this_1.c = sc_1;\n var d_1;\n var file_1 = {\n name: fn_1,\n compression: cmp_1,\n start: function () {\n if (!file_1.ondata)\n err(5);\n if (!sc_1)\n file_1.ondata(null, et, true);\n else {\n var ctr = _this.o[cmp_1];\n if (!ctr)\n file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n var dat = chks_4[_i];\n d_1.push(dat, false);\n }\n if (_this.k[0] == chks_3 && _this.c)\n _this.d = d_1;\n else\n d_1.push(et, true);\n }\n },\n terminate: function () {\n if (d_1 && d_1.terminate)\n d_1.terminate();\n }\n };\n if (sc_1 >= 0)\n file_1.size = sc_1, file_1.originalSize = su_1;\n this_1.onfile(file_1);\n }\n return \"break\";\n }\n else if (oc) {\n if (sig == 0x8074B50) {\n is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n return \"break\";\n }\n else if (sig == 0x2014B50) {\n is = i -= 4, f = 3, this_1.c = 0;\n return \"break\";\n }\n }\n };\n var this_1 = this;\n for (; i < l - 4; ++i) {\n var state_1 = _loop_2();\n if (state_1 === \"break\")\n break;\n }\n this.p = et;\n if (oc < 0) {\n var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n if (add)\n add.push(dat, !!f);\n else\n this.k[+(f == 2)].push(dat);\n }\n if (f & 2)\n return this.push(buf.subarray(i), final);\n this.p = buf.subarray(i);\n }\n if (final) {\n if (this.c)\n err(13);\n this.p = null;\n }\n };\n /**\n * Registers a decoder with the stream, allowing for files compressed with\n * the compression type provided to be expanded correctly\n * @param decoder The decoder constructor\n */\n Unzip.prototype.register = function (decoder) {\n this.o[decoder.compression] = decoder;\n };\n return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n if (!cb)\n cb = opts, opts = {};\n if (typeof cb != 'function')\n err(7);\n var term = [];\n var tAll = function () {\n for (var i = 0; i < term.length; ++i)\n term[i]();\n };\n var files = {};\n var cbd = function (a, b) {\n mt(function () { cb(a, b); });\n };\n mt(function () { cbd = cb; });\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558) {\n cbd(err(13, 0, 1), null);\n return tAll;\n }\n }\n ;\n var lft = b2(data, e + 8);\n if (lft) {\n var c = lft;\n var o = b4(data, e + 16);\n var z = b4(data, e - 20) == 0x7064B50;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = lft = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n var _loop_3 = function (i) {\n var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n var cbl = function (e, d) {\n if (e) {\n tAll();\n cbd(e, null);\n }\n else {\n if (d)\n files[fn] = d;\n if (!--lft)\n cbd(null, files);\n }\n };\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_1\n })) {\n if (!c_1)\n cbl(null, slc(data, b, b + sc));\n else if (c_1 == 8) {\n var infl = data.subarray(b, b + sc);\n // Synchronously decompress under 512KB, or barely-compressed data\n if (su < 524288 || sc > 0.8 * su) {\n try {\n cbl(null, inflateSync(infl, { out: new u8(su) }));\n }\n catch (e) {\n cbl(e, null);\n }\n }\n else\n term.push(inflate(infl, { size: su }, cbl));\n }\n else\n cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n }\n else\n cbl(null, null);\n };\n for (var i = 0; i < c; ++i) {\n _loop_3(i);\n }\n }\n else\n cbd(null, {});\n return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n var files = {};\n var e = data.length - 22;\n for (; b4(data, e) != 0x6054B50; --e) {\n if (!e || data.length - e > 65558)\n err(13);\n }\n ;\n var c = b2(data, e + 8);\n if (!c)\n return {};\n var o = b4(data, e + 16);\n var z = b4(data, e - 20) == 0x7064B50;\n if (z) {\n var ze = b4(data, e - 12);\n z = b4(data, ze) == 0x6064B50;\n if (z) {\n c = b4(data, ze + 32);\n o = b4(data, ze + 48);\n }\n }\n var fltr = opts && opts.filter;\n for (var i = 0; i < c; ++i) {\n var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n o = no;\n if (!fltr || fltr({\n name: fn,\n size: sc,\n originalSize: su,\n compression: c_2\n })) {\n if (!c_2)\n files[fn] = slc(data, b, b + sc);\n else if (c_2 == 8)\n files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });\n else\n err(14, 'unknown compression type ' + c_2);\n }\n }\n return files;\n}\n", "/*\n * Base64 for the offline outbox, which keeps each frame gzip-compressed in\n * AsyncStorage. AsyncStorage stores strings, and a gzip stream written as a\n * \"binary\" string would put NUL and high bytes into SQLite TEXT columns on\n * Android; base64 is ASCII, costs a third on top of gzip, and still leaves\n * a frame several times smaller than the JSON it came from.\n *\n * Implemented here rather than with btoa/atob: Hermes only has those from\n * React Native 0.74, and this package supports 0.73.\n */\n\nconst ALPHABET: string =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nconst LOOKUP: Int16Array = ((): Int16Array => {\n const table: Int16Array = new Int16Array(128).fill(-1);\n\n for (let index: number = 0; index < ALPHABET.length; index += 1) {\n table[ALPHABET.charCodeAt(index)] = index;\n }\n\n return table;\n})();\n\nexport function encodeBase64(bytes: Uint8Array): string {\n const parts: Array<string> = [];\n\n for (let index: number = 0; index < bytes.length; index += 3) {\n const first: number = bytes[index] as number;\n const second: number | undefined = bytes[index + 1];\n const third: number | undefined = bytes[index + 2];\n const triple: number = (first << 16) | ((second ?? 0) << 8) | (third ?? 0);\n\n parts.push(\n ALPHABET.charAt((triple >> 18) & 63) +\n ALPHABET.charAt((triple >> 12) & 63) +\n (second === undefined ? \"=\" : ALPHABET.charAt((triple >> 6) & 63)) +\n (third === undefined ? \"=\" : ALPHABET.charAt(triple & 63)),\n );\n }\n\n return parts.join(\"\");\n}\n\n/* Null for anything that is not canonical base64: the input is untrusted. */\nexport function decodeBase64(text: string): Uint8Array | null {\n if (typeof text !== \"string\" || text.length % 4 !== 0) {\n return null;\n }\n\n const padding: number = text.endsWith(\"==\") ? 2 : text.endsWith(\"=\") ? 1 : 0;\n const bytes: Uint8Array = new Uint8Array((text.length / 4) * 3 - padding);\n let buffer: number = 0;\n let bits: number = 0;\n let written: number = 0;\n\n for (let index: number = 0; index < text.length - padding; index += 1) {\n const code: number = text.charCodeAt(index);\n const value: number = code < 128 ? (LOOKUP[code] as number) : -1;\n\n if (value < 0) {\n return null;\n }\n\n buffer = ((buffer << 6) | value) & 0xffffff;\n bits += 6;\n\n if (bits >= 8) {\n bits -= 8;\n bytes[written] = (buffer >> bits) & 0xff;\n written += 1;\n }\n }\n\n return written === bytes.length ? bytes : null;\n}\n", "import { gunzipSync, gzipSync, strFromU8, strToU8 } from \"fflate\";\nimport { decodeBase64, encodeBase64 } from \"./Base64\";\nimport {\n SESSION_REPLAY_MAX_OFFLINE_DELAY_MS,\n SessionReplayChunkEnvelope,\n} from \"./Contract\";\nimport { byteLength } from \"./Sanitize\";\nimport { ReplayStorage } from \"./Storage\";\n\n/*\n * The durable upload queue, and so the whole of offline mode's memory: every\n * frame is written here BEFORE it is posted, and removed only once the\n * server has it (or refused it for good). An app that loses its connection\n * keeps recording into this outbox, and an app that is killed while offline\n * finds its backlog here on the next launch.\n *\n * One AsyncStorage key per frame, plus a small index. The first version kept\n * the whole outbox as ONE JSON array under one key, which on Android is a\n * single SQLite row - and AsyncStorage cannot read a row larger than the\n * 2 MB CursorWindow back. An offline backlog past that size failed to read,\n * and a failed read discarded the lot: the longer the outage, the more\n * certainly everything recorded during it was lost. Per-frame keys keep\n * every value to one frame, and writing a frame no longer rewrites every\n * other frame with it.\n *\n * Frames are stored gzip-compressed (base64, since AsyncStorage stores\n * strings). A view-tree frame compresses several times over, and Android's\n * AsyncStorage database is 6 MB by default and shared with the host app, so\n * compression is what turns the bound below into an hour of recording\n * rather than a few minutes - without taking the app's own storage.\n */\n\nexport const MAX_OUTBOX_ENTRIES: number = 240;\nexport const MAX_OUTBOX_BYTES: number = 3 * 1024 * 1024;\n\nexport interface PersistedReplayFrame {\n id: string;\n envelope: SessionReplayChunkEnvelope;\n payload: string;\n attempts: number;\n createdAtUnixMs: number;\n}\n\n/* What the index keeps per frame: enough to order, bound and retry it. */\nexport interface OutboxEntry {\n id: string;\n attempts: number;\n createdAtUnixMs: number;\n\n /* Stored size of the frame's value, which is what the bound counts. */\n bytes: number;\n}\n\n/* A frame as the transport posts it: its payload already gzip-compressed. */\nexport interface StoredReplayFrame {\n id: string;\n envelope: SessionReplayChunkEnvelope;\n compressedPayload: Uint8Array;\n attempts: number;\n createdAtUnixMs: number;\n}\n\nexport interface OutboxMutationResult {\n dropped: number;\n}\n\ninterface FrameValue {\n envelope: SessionReplayChunkEnvelope;\n gzip: string;\n}\n\nfunction isEnvelope(value: unknown): value is SessionReplayChunkEnvelope {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const envelope: Partial<SessionReplayChunkEnvelope> =\n value as Partial<SessionReplayChunkEnvelope>;\n return (\n typeof envelope.sessionId === \"string\" &&\n typeof envelope.tabId === \"string\" &&\n typeof envelope.chunkIndex === \"number\"\n );\n}\n\nfunction isEntry(value: unknown): value is OutboxEntry {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const entry: Partial<OutboxEntry> = value as Partial<OutboxEntry>;\n return (\n typeof entry.id === \"string\" &&\n Number.isSafeInteger(entry.attempts) &&\n typeof entry.createdAtUnixMs === \"number\" &&\n Number.isFinite(entry.createdAtUnixMs) &&\n Number.isSafeInteger(entry.bytes)\n );\n}\n\n/* The single-key layout this file replaced, read once to migrate it. */\nfunction isLegacyFrame(value: unknown): value is PersistedReplayFrame {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n const frame: Partial<PersistedReplayFrame> =\n value as Partial<PersistedReplayFrame>;\n return (\n typeof frame.id === \"string\" &&\n typeof frame.payload === \"string\" &&\n typeof frame.attempts === \"number\" &&\n Number.isSafeInteger(frame.attempts) &&\n typeof frame.createdAtUnixMs === \"number\" &&\n isEnvelope(frame.envelope)\n );\n}\n\nfunction byOldest(left: OutboxEntry, right: OutboxEntry): number {\n return left.createdAtUnixMs - right.createdAtUnixMs;\n}\n\nexport function frameId(envelope: SessionReplayChunkEnvelope): string {\n return `${envelope.sessionId}:${envelope.tabId}:${envelope.chunkIndex}`;\n}\n\nexport default class ReplayOutbox {\n private readonly storage: ReplayStorage;\n private readonly legacyKey: string;\n private readonly indexKey: string;\n private readonly framePrefix: string;\n private readonly now: () => number;\n private mutationQueue: Promise<void> = Promise.resolve();\n private migrated: boolean = false;\n\n public constructor(\n storage: ReplayStorage,\n namespace: string,\n now: () => number = Date.now,\n ) {\n this.storage = storage;\n this.legacyKey = `@oneuptime/replay/${namespace}/outbox`;\n this.indexKey = `@oneuptime/replay/${namespace}/outbox-v2`;\n this.framePrefix = `@oneuptime/replay/${namespace}/outbox-v2/`;\n this.now = now;\n }\n\n /* Every queued frame's index entry, oldest first. Reads no payload. */\n public async entries(): Promise<Array<OutboxEntry>> {\n return await this.withLock(async (): Promise<Array<OutboxEntry>> => {\n return await this.readIndexUnlocked();\n });\n }\n\n /*\n * One frame, ready to post. Null when it is no longer queued, and\n * \"unreadable\" when its value could not be read back - it is removed, so\n * one damaged frame never blocks the ones behind it.\n */\n public async load(\n id: string,\n ): Promise<StoredReplayFrame | \"unreadable\" | null> {\n return await this.withLock(\n async (): Promise<StoredReplayFrame | \"unreadable\" | null> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n const entry: OutboxEntry | undefined = entries.find(\n (candidate: OutboxEntry): boolean => {\n return candidate.id === id;\n },\n );\n if (!entry) {\n return null;\n }\n\n const value: {\n envelope: SessionReplayChunkEnvelope;\n bytes: Uint8Array;\n } | null = await this.readFrameUnlocked(id);\n if (!value) {\n await this.removeEntriesUnlocked(entries, [id]);\n return \"unreadable\";\n }\n\n return {\n id,\n envelope: value.envelope,\n compressedPayload: value.bytes,\n attempts: entry.attempts,\n createdAtUnixMs: entry.createdAtUnixMs,\n };\n },\n );\n }\n\n /* Every frame with its payload decompressed, oldest first. */\n public async list(): Promise<Array<PersistedReplayFrame>> {\n const frames: Array<PersistedReplayFrame> = [];\n\n for (const entry of await this.entries()) {\n const frame: StoredReplayFrame | \"unreadable\" | null = await this.load(\n entry.id,\n );\n if (!frame || frame === \"unreadable\") {\n continue;\n }\n\n frames.push({\n id: frame.id,\n envelope: frame.envelope,\n payload: strFromU8(gunzipSync(frame.compressedPayload)),\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n });\n }\n\n return frames;\n }\n\n /*\n * Queue a frame. Past MAX_OUTBOX_ENTRIES or MAX_OUTBOX_BYTES the OLDEST\n * frames are evicted - the newest seconds are the ones closest to whatever\n * went wrong, and a later full snapshot re-anchors the player after a gap -\n * and counted in `dropped`, as is a frame the device had no room to store.\n */\n public async enqueue(\n frame: PersistedReplayFrame,\n ): Promise<OutboxMutationResult> {\n return await this.withLock(async (): Promise<OutboxMutationResult> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n if (\n entries.some((candidate: OutboxEntry): boolean => {\n return candidate.id === frame.id;\n })\n ) {\n return { dropped: 0 };\n }\n\n const bytes: number | null = await this.writeFrameUnlocked(frame);\n if (bytes === null) {\n return { dropped: 1 };\n }\n\n entries.push({\n id: frame.id,\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n bytes,\n });\n entries.sort(byOldest);\n\n let totalBytes: number = 0;\n for (const entry of entries) {\n totalBytes += entry.bytes;\n }\n\n const evicted: Array<string> = [];\n while (\n entries.length > 1 &&\n (entries.length > MAX_OUTBOX_ENTRIES || totalBytes > MAX_OUTBOX_BYTES)\n ) {\n const oldest: OutboxEntry = entries.shift() as OutboxEntry;\n totalBytes -= oldest.bytes;\n evicted.push(oldest.id);\n }\n\n if (!(await this.writeIndexUnlocked(entries))) {\n /* The index is full too: the frame we just wrote is untracked. */\n await this.safeRemove(this.frameKey(frame.id));\n return { dropped: 1 };\n }\n\n await Promise.all(\n evicted.map((id: string): Promise<void> => {\n return this.safeRemove(this.frameKey(id));\n }),\n );\n return { dropped: evicted.length };\n });\n }\n\n public async remove(id: string): Promise<void> {\n await this.withLock(async (): Promise<void> => {\n await this.removeEntriesUnlocked(await this.readIndexUnlocked(), [id]);\n });\n }\n\n public async incrementAttempts(id: string): Promise<number> {\n return await this.withLock(async (): Promise<number> => {\n const entries: Array<OutboxEntry> = await this.readIndexUnlocked();\n let attempts: number = 0;\n for (const entry of entries) {\n if (entry.id === id) {\n entry.attempts += 1;\n attempts = entry.attempts;\n break;\n }\n }\n\n await this.writeIndexUnlocked(entries);\n return attempts;\n });\n }\n\n /*\n * Consent withdrawn, or the server refused this recorder for good: every\n * frame goes, including any a crash left untracked by the index when the\n * storage can list its keys.\n */\n public async clear(): Promise<void> {\n await this.withLock(async (): Promise<void> => {\n const keys: Set<string> = new Set<string>([\n this.legacyKey,\n this.indexKey,\n ]);\n\n for (const entry of await this.readRawIndexUnlocked()) {\n keys.add(this.frameKey(entry.id));\n }\n\n if (typeof this.storage.getAllKeys === \"function\") {\n try {\n for (const key of await this.storage.getAllKeys()) {\n if (key.startsWith(this.framePrefix)) {\n keys.add(key);\n }\n }\n } catch {\n /* Best effort: the index already named every tracked frame. */\n }\n }\n\n this.migrated = true;\n await Promise.all(\n Array.from(keys).map((key: string): Promise<void> => {\n return this.safeRemove(key);\n }),\n );\n });\n }\n\n private frameKey(id: string): string {\n return `${this.framePrefix}${id}`;\n }\n\n /*\n * The index, with the legacy layout migrated into it on first use and\n * anything older than SESSION_REPLAY_MAX_OFFLINE_DELAY_MS pruned: the\n * server would no longer place it on the recording's real timeline.\n */\n private async readIndexUnlocked(): Promise<Array<OutboxEntry>> {\n await this.migrateUnlocked();\n\n const entries: Array<OutboxEntry> = await this.readRawIndexUnlocked();\n const oldestKept: number = this.now() - SESSION_REPLAY_MAX_OFFLINE_DELAY_MS;\n const expired: Array<string> = entries\n .filter((entry: OutboxEntry): boolean => {\n return entry.createdAtUnixMs < oldestKept;\n })\n .map((entry: OutboxEntry): string => {\n return entry.id;\n });\n\n if (expired.length > 0) {\n await this.removeEntriesUnlocked(entries, expired);\n }\n\n return entries.sort(byOldest);\n }\n\n private async readRawIndexUnlocked(): Promise<Array<OutboxEntry>> {\n let raw: string | null = null;\n try {\n raw = await this.storage.getItem(this.indexKey);\n } catch {\n raw = null;\n }\n if (!raw) {\n return [];\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed) && parsed.every(isEntry)) {\n return parsed;\n }\n } catch {\n /* Falls through to the reset below. */\n }\n\n await this.safeRemove(this.indexKey);\n return [];\n }\n\n private async writeIndexUnlocked(\n entries: Array<OutboxEntry>,\n ): Promise<boolean> {\n if (entries.length === 0) {\n await this.safeRemove(this.indexKey);\n return true;\n }\n\n return await this.safeSet(this.indexKey, JSON.stringify(entries));\n }\n\n /* Drop entries from the index and their frames from storage. */\n private async removeEntriesUnlocked(\n entries: Array<OutboxEntry>,\n ids: Array<string>,\n ): Promise<void> {\n const removing: Set<string> = new Set<string>(ids);\n const kept: Array<OutboxEntry> = entries.filter(\n (entry: OutboxEntry): boolean => {\n return !removing.has(entry.id);\n },\n );\n\n entries.splice(0, entries.length, ...kept);\n await this.writeIndexUnlocked(entries);\n await Promise.all(\n ids.map((id: string): Promise<void> => {\n return this.safeRemove(this.frameKey(id));\n }),\n );\n }\n\n /* Store one frame's value. Its size, or null when it could not be stored. */\n private async writeFrameUnlocked(\n frame: PersistedReplayFrame,\n ): Promise<number | null> {\n let value: string;\n try {\n const stored: FrameValue = {\n envelope: frame.envelope,\n gzip: encodeBase64(gzipSync(strToU8(frame.payload))),\n };\n value = JSON.stringify(stored);\n } catch {\n return null;\n }\n\n return (await this.safeSet(this.frameKey(frame.id), value))\n ? byteLength(value)\n : null;\n }\n\n private async readFrameUnlocked(id: string): Promise<{\n envelope: SessionReplayChunkEnvelope;\n bytes: Uint8Array;\n } | null> {\n try {\n const raw: string | null = await this.storage.getItem(this.frameKey(id));\n if (!raw) {\n return null;\n }\n\n const parsed: Partial<FrameValue> = JSON.parse(\n raw,\n ) as Partial<FrameValue>;\n const bytes: Uint8Array | null =\n typeof parsed.gzip === \"string\" ? decodeBase64(parsed.gzip) : null;\n if (!bytes || !isEnvelope(parsed.envelope)) {\n return null;\n }\n\n return { envelope: parsed.envelope, bytes };\n } catch {\n /* Unreadable - on Android, a value past the CursorWindow limit. */\n return null;\n }\n }\n\n /*\n * Move a queue written by an earlier SDK version (one JSON array under the\n * legacy key) into this layout, once. A legacy queue too large to read -\n * the very failure this layout exists to fix - cannot be recovered, only\n * removed so it stops failing.\n */\n private async migrateUnlocked(): Promise<void> {\n if (this.migrated) {\n return;\n }\n this.migrated = true;\n\n let raw: string | null = null;\n try {\n raw = await this.storage.getItem(this.legacyKey);\n } catch {\n await this.safeRemove(this.legacyKey);\n return;\n }\n if (!raw) {\n return;\n }\n\n let legacy: Array<PersistedReplayFrame> = [];\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n legacy = parsed.filter(isLegacyFrame);\n }\n } catch {\n legacy = [];\n }\n\n const entries: Array<OutboxEntry> = await this.readRawIndexUnlocked();\n for (const frame of legacy) {\n if (\n entries.some((entry: OutboxEntry): boolean => {\n return entry.id === frame.id;\n })\n ) {\n continue;\n }\n\n const bytes: number | null = await this.writeFrameUnlocked(frame);\n if (bytes !== null) {\n entries.push({\n id: frame.id,\n attempts: frame.attempts,\n createdAtUnixMs: frame.createdAtUnixMs,\n bytes,\n });\n }\n }\n\n await this.writeIndexUnlocked(entries.sort(byOldest));\n await this.safeRemove(this.legacyKey);\n }\n\n private async safeSet(key: string, value: string): Promise<boolean> {\n try {\n await this.storage.setItem(key, value);\n return true;\n } catch {\n /* Recording must never destabilise the host app when storage is full. */\n return false;\n }\n }\n\n private async safeRemove(key: string): Promise<void> {\n try {\n await this.storage.removeItem(key);\n } catch {\n /* Best-effort privacy cleanup. */\n }\n }\n\n private async withLock<T>(operation: () => Promise<T>): Promise<T> {\n const result: Promise<T> = this.mutationQueue.then(operation, operation);\n this.mutationQueue = result.then(\n (): void => {\n return undefined;\n },\n (): void => {\n return undefined;\n },\n );\n return await result;\n }\n}\n", "/*\n * THE RETRY-AFTER RESPONSE HEADER, READ AS RFC 9110 WRITES IT.\n *\n * A server that refuses for now - a 429 or a 503, most often - can say when\n * to ask again (RFC 9110 section 10.2.3):\n *\n * Retry-After = HTTP-date / delay-seconds\n *\n * delay-seconds is a whole number of seconds, in digits and nothing else:\n * \"120\". An HTTP-date is one of the three shapes of section 5.6.7, which a\n * recipient must all accept, case and spaces exactly as written:\n *\n * IMF-fixdate Sun, 06 Nov 1994 08:49:37 GMT (the one senders send)\n * RFC 850 Sunday, 06-Nov-94 08:49:37 GMT (obsolete; a two-digit year\n * more than 50 years ahead\n * is the century before)\n * asctime Sun Nov 6 08:49:37 1994 (obsolete; UTC)\n *\n * Anything else is no Retry-After at all and reads as undefined, so the\n * caller waits its own backoff: a fraction (\"1.5\"), a sign (\"-5\", \"+5\"),\n * words (\"5 seconds\"), an exponent (\"1e3\"), hex (\"0x10\"), a list\n * (\"120, 120\"), a date in any other shape, a day the month does not have.\n * Never Date.parse: V8 reads \"-5\" and \"1.5\" as days in 2001 - a wait long\n * over, so a retry at once - and asctime in the local time zone.\n *\n * A wait that is read is held between two bounds, which a caller may set:\n *\n * - at least minMs, a second unless the caller says otherwise. \"0\", or a\n * date gone by (most often a server clock behind this one), would retry\n * at once, and a server that keeps answering so would be asked again in\n * a tight loop. Waiting longer than asked is always allowed;\n * - at most maxMs, an hour unless the caller says otherwise. A huge\n * number, digits too many for a number, or a date years ahead would\n * stall the caller as long (and setTimeout fires at once past\n * 2^31 - 1 ms). maxMs wins over minMs.\n *\n * The value comes from the network, so nothing here throws, and each value\n * is read in one pass: a megabyte of spaces costs a megabyte.\n *\n * This file imports nothing, so the packages that cannot import Common\n * carry byte-identical copies of it: agents/KubernetesAIAgent and\n * agents/ResourceAIAgent (Common/Utils/RetryAfter.ts, copied by their\n * npm run sync-common) and the React Native recorder\n * (packages/App/FeatureSet/MobileRecorder/src/RetryAfter.ts). Their parity\n * tests fail when a copy drifts. The browser recorder inlines it into a\n * script every page of a customer's site loads, so it is kept small.\n */\n\n// The header's name, in the lower case Node and fetch give it.\nexport const RETRY_AFTER_HEADER: string = \"retry-after\";\n\n// The least a Retry-After that is read waits, unless the caller says otherwise.\nexport const DEFAULT_RETRY_AFTER_MIN_MS: number = 1000;\n\n// The most a Retry-After that is read waits, unless the caller says otherwise.\nexport const DEFAULT_RETRY_AFTER_MAX_MS: number = 60 * 60 * 1000;\n\nexport interface RetryAfterOptions {\n // The time now, in milliseconds since the epoch: Date.now() when left out.\n nowMs?: number | undefined;\n /*\n * The least a value that is read waits: DEFAULT_RETRY_AFTER_MIN_MS when\n * left out, or when it is not a finite number of 0 or more.\n */\n minMs?: number | undefined;\n /*\n * The most a value that is read waits: DEFAULT_RETRY_AFTER_MAX_MS when\n * left out, or when it is not a finite number of 0 or more.\n */\n maxMs?: number | undefined;\n /*\n * False reads delay-seconds only, and an HTTP-date as no Retry-After: for\n * a wait counted down in front of a person, on a device whose clock may be\n * wrong, which a date would move with. True when left out.\n */\n acceptHttpDate?: boolean | undefined;\n}\n\n// delay-seconds: 1*DIGIT. \\d is the ASCII digits alone (no u flag).\nconst DELAY_SECONDS: RegExp = /^\\d+$/;\n\nconst MONTHS: Array<string> =\n \"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\".split(\" \");\n\n// The parts the three shapes are written with (RFC 9110 section 5.6.7).\nconst DAY_NAME: string = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst DAY_NAME_LONG: string = \"(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day\";\nconst MONTH: string = `(${MONTHS.join(\"|\")})`;\nconst TIME_OF_DAY: string = \"(\\\\d\\\\d):(\\\\d\\\\d):(\\\\d\\\\d)\";\n\n// day-name \",\" SP 2DIGIT SP month SP 4DIGIT SP time-of-day SP \"GMT\".\nconst IMF_FIXDATE: RegExp = new RegExp(\n `^${DAY_NAME}, (\\\\d\\\\d) ${MONTH} (\\\\d{4}) ${TIME_OF_DAY} GMT$`,\n);\n\n// day-name-l \",\" SP 2DIGIT \"-\" month \"-\" 2DIGIT SP time-of-day SP \"GMT\".\nconst RFC_850_DATE: RegExp = new RegExp(\n `^${DAY_NAME_LONG}, (\\\\d\\\\d)-${MONTH}-(\\\\d\\\\d) ${TIME_OF_DAY} GMT$`,\n);\n\n// day-name SP month SP ( 2DIGIT / ( SP DIGIT )) SP time-of-day SP 4DIGIT.\nconst ASCTIME_DATE: RegExp = new RegExp(\n `^${DAY_NAME} ${MONTH} (\\\\d\\\\d| \\\\d) ${TIME_OF_DAY} (\\\\d{4})$`,\n);\n\n// How far ahead an RFC 850 date's two-digit year may land (section 5.6.7).\nconst TWO_DIGIT_YEAR_LOOKAHEAD_YEARS: number = 50;\n\n/*\n * A date written in UTC, as milliseconds since the epoch. Undefined for a\n * time past 23:59:60 (60 is a leap second, which section 5.6.7 allows: it\n * reads as the next minute's first) or a day the month does not have\n * (31 Apr, 29 Feb 2023) - never the date it would roll over to. The fields\n * are digits as written; a comparison with one that is missing (NaN) fails.\n */\nfunction toUtcMs(\n year: number,\n month: string | undefined,\n day: string | undefined,\n hour: string | undefined,\n minute: string | undefined,\n second: string | undefined,\n): number | undefined {\n const monthIndex: number = MONTHS.indexOf(month || \"\");\n const dayOfMonth: number = Number(day);\n // setUTCFullYear, not Date.UTC: Date.UTC reads a year below 100 as 19xx.\n const date: Date = new Date(0);\n date.setUTCFullYear(year, monthIndex, dayOfMonth);\n\n if (\n monthIndex < 0 ||\n date.getUTCMonth() !== monthIndex ||\n date.getUTCDate() !== dayOfMonth ||\n !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)\n ) {\n return undefined;\n }\n\n date.setUTCHours(Number(hour), Number(minute), Number(second), 0);\n\n return date.getTime();\n}\n\n/*\n * An RFC 850 date's two-digit year is this century's, unless that is more\n * than 50 years ahead: then it is the most recent year gone by with the\n * same last two digits (RFC 9110 section 5.6.7).\n */\nfunction readRfc850Date(\n match: RegExpExecArray,\n nowMs: number,\n): number | undefined {\n const thisYear: number = new Date(nowMs).getUTCFullYear();\n const lookaheadEnd: Date = new Date(nowMs);\n lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);\n\n let year: number = thisYear - (thisYear % 100) + Number(match[3]);\n let atMs: number | undefined = toUtcMs(\n year,\n match[2],\n match[1],\n match[4],\n match[5],\n match[6],\n );\n\n if (atMs !== undefined && atMs > lookaheadEnd.getTime()) {\n year -= 100;\n atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);\n }\n\n return atMs;\n}\n\n// SP and HTAB: the whitespace RFC 9110 allows around a field's value.\nfunction isSpace(code: number): boolean {\n return code === 32 || code === 9;\n}\n\n/*\n * A value's text, its surrounding spaces and tabs left out; undefined when\n * it is not a string or a number, or nothing is left. Copies of a header\n * sent more than once give their text only when they all agree.\n */\nfunction toText(value: unknown): string | undefined {\n if (Array.isArray(value)) {\n const copies: Array<string | undefined> = value.map(\n (copy: unknown): string | undefined => {\n return Array.isArray(copy) ? undefined : toText(copy);\n },\n );\n\n return copies.every((copy: string | undefined): boolean => {\n return copy === copies[0];\n })\n ? copies[0]\n : undefined;\n }\n\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n return undefined;\n }\n\n const text: string = String(value);\n let start: number = 0;\n let end: number = text.length;\n\n while (start < end && isSpace(text.charCodeAt(start))) {\n start++;\n }\n\n while (end > start && isSpace(text.charCodeAt(end - 1))) {\n end--;\n }\n\n return start < end ? text.slice(start, end) : undefined;\n}\n\nfunction readNow(nowMs: number | undefined): number {\n return typeof nowMs === \"number\" && Number.isFinite(nowMs)\n ? nowMs\n : Date.now();\n}\n\nfunction readBound(bound: number | undefined, fallback: number): number {\n return typeof bound === \"number\" && Number.isFinite(bound) && bound >= 0\n ? bound\n : fallback;\n}\n\nexport default class RetryAfter {\n /*\n * The wait a Retry-After value asks for, in milliseconds, held between\n * minMs and maxMs; undefined when the value is not a Retry-After (absent,\n * empty, or neither delay-seconds nor an HTTP-date), so the caller waits\n * its own backoff. The value is a header's: a string, a number, or the\n * copies of a header sent more than once - which count only when they\n * all say the same.\n */\n public static parseMs(\n value: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n const text: string | undefined = toText(value);\n const asked: RetryAfterOptions = options || {};\n let waitMs: number | undefined;\n\n if (text === undefined) {\n return undefined;\n }\n\n if (DELAY_SECONDS.test(text)) {\n // Digits too many for a number read as Infinity: the ceiling.\n waitMs = Number(text) * 1000;\n } else if (asked.acceptHttpDate !== false) {\n const nowMs: number = readNow(asked.nowMs);\n const retryAtMs: number | undefined = RetryAfter.parseHttpDate(\n text,\n nowMs,\n );\n\n waitMs = retryAtMs === undefined ? undefined : retryAtMs - nowMs;\n }\n\n return waitMs === undefined\n ? undefined\n : Math.min(\n Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),\n readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS),\n );\n }\n\n /*\n * The same wait in whole seconds, rounded up - never sooner than asked -\n * for a caller that counts in seconds.\n */\n public static parseSeconds(\n value: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n const waitMs: number | undefined = RetryAfter.parseMs(value, options);\n\n return waitMs === undefined ? undefined : Math.ceil(waitMs / 1000);\n }\n\n /*\n * The Retry-After header of a response's headers, whatever its case: an\n * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain\n * object of names to values (Node's, a test's). Undefined when there is\n * none; a get() that throws reads as none.\n */\n public static readHeader(headers: unknown): unknown {\n if (!headers || typeof headers !== \"object\") {\n return undefined;\n }\n\n const get: unknown = (headers as { get?: unknown }).get;\n\n if (typeof get === \"function\") {\n try {\n const value: unknown = (get as (name: string) => unknown).call(\n headers,\n RETRY_AFTER_HEADER,\n );\n\n if (value !== undefined && value !== null) {\n return value;\n }\n } catch {\n // A get() that throws is no header; the names are read below.\n }\n }\n\n for (const name of Object.keys(headers)) {\n if (name.toLowerCase() === RETRY_AFTER_HEADER) {\n return (headers as Record<string, unknown>)[name];\n }\n }\n\n return undefined;\n }\n\n // parseMs of a response's Retry-After header.\n public static msFromHeaders(\n headers: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n return RetryAfter.parseMs(RetryAfter.readHeader(headers), options);\n }\n\n // parseSeconds of a response's Retry-After header.\n public static secondsFromHeaders(\n headers: unknown,\n options?: RetryAfterOptions | undefined,\n ): number | undefined {\n return RetryAfter.parseSeconds(RetryAfter.readHeader(headers), options);\n }\n\n /*\n * An HTTP-date in any of its three shapes, exactly as written, as\n * milliseconds since the epoch; undefined for anything else. nowMs is what\n * an RFC 850 date's two-digit year is read against.\n */\n public static parseHttpDate(\n value: string,\n nowMs?: number | undefined,\n ): number | undefined {\n let match: RegExpExecArray | null = IMF_FIXDATE.exec(value);\n\n if (match) {\n return toUtcMs(\n Number(match[3]),\n match[2],\n match[1],\n match[4],\n match[5],\n match[6],\n );\n }\n\n match = RFC_850_DATE.exec(value);\n\n if (match) {\n return readRfc850Date(match, readNow(nowMs));\n }\n\n match = ASCTIME_DATE.exec(value);\n\n // asctime's day is \" 6\" or \"06\": Number reads both as 6.\n return match\n ? toUtcMs(\n Number(match[6]),\n match[1],\n match[2],\n match[3],\n match[4],\n match[5],\n )\n : undefined;\n }\n}\n", "import AsyncStorage from \"@react-native-async-storage/async-storage\";\nimport {\n MAX_SESSION_REPLAY_CHUNKS_PER_SESSION,\n SESSION_REPLAY_IDLE_ROLLOVER_MS,\n SESSION_REPLAY_MAX_SESSION_MS,\n} from \"./Contract\";\n\nconst REPLAY_ID_PATTERN: RegExp = /^[0-9a-f]{32}$/u;\n\nexport interface ReplayStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n\n /*\n * Optional. When present, clearing the offline outbox also removes any\n * frame a crash left untracked by its index. AsyncStorage has it.\n */\n getAllKeys?(): Promise<ReadonlyArray<string>>;\n}\n\nexport const defaultReplayStorage: ReplayStorage = AsyncStorage;\n\nexport interface ReplaySessionIdentity {\n sessionId: string;\n tabId: string;\n visitorId: string;\n sessionStartUnixMs: number;\n chunkIndex: number;\n}\n\ninterface StoredSession {\n sessionId: string;\n sessionStartUnixMs: number;\n lastActivityUnixMs: number;\n nextChunkIndex: number;\n}\n\nexport function generateReplayId(): string {\n const bytes: Uint8Array = new Uint8Array(16);\n const cryptoRef: Crypto | undefined = globalThis.crypto;\n\n if (cryptoRef && typeof cryptoRef.getRandomValues === \"function\") {\n cryptoRef.getRandomValues(bytes);\n } else {\n for (let index: number = 0; index < bytes.length; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n\n return Array.from(bytes)\n .map((byte: number): string => {\n return byte.toString(16).padStart(2, \"0\");\n })\n .join(\"\");\n}\n\nfunction isReplayId(value: unknown): value is string {\n return typeof value === \"string\" && REPLAY_ID_PATTERN.test(value);\n}\n\nfunction parseStoredSession(value: string | null): StoredSession | null {\n if (!value) {\n return null;\n }\n\n try {\n const parsed: unknown = JSON.parse(value);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return null;\n }\n\n const candidate: Partial<StoredSession> = parsed as Partial<StoredSession>;\n if (\n !isReplayId(candidate.sessionId) ||\n !Number.isSafeInteger(candidate.sessionStartUnixMs) ||\n !Number.isSafeInteger(candidate.lastActivityUnixMs) ||\n !Number.isSafeInteger(candidate.nextChunkIndex) ||\n (candidate.nextChunkIndex ?? -1) < 0\n ) {\n return null;\n }\n\n return candidate as StoredSession;\n } catch {\n return null;\n }\n}\n\nexport default class ReplaySessionStore {\n private readonly storage: ReplayStorage;\n private readonly sessionKey: string;\n private readonly visitorKey: string;\n private identity: ReplaySessionIdentity | null = null;\n /* When the session's last activity was, as the stored record says. */\n private lastActivityUnixMs: number = 0;\n\n public constructor(storage: ReplayStorage, namespace: string) {\n this.storage = storage;\n this.sessionKey = `@oneuptime/replay/${namespace}/session`;\n this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;\n }\n\n public async resolve(nowUnixMs: number): Promise<ReplaySessionIdentity> {\n const stored: StoredSession | null = parseStoredSession(\n await this.safeGet(this.sessionKey),\n );\n const shouldRotate: boolean =\n !stored ||\n stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION ||\n nowUnixMs - stored.lastActivityUnixMs >=\n SESSION_REPLAY_IDLE_ROLLOVER_MS ||\n nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;\n let session: StoredSession;\n if (shouldRotate || !stored) {\n session = {\n sessionId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: 0,\n };\n } else {\n session = {\n sessionId: stored.sessionId,\n sessionStartUnixMs: stored.sessionStartUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: stored.nextChunkIndex,\n };\n }\n\n let visitorId: string | null = await this.safeGet(this.visitorKey);\n if (!isReplayId(visitorId)) {\n visitorId = generateReplayId();\n await this.safeSet(this.visitorKey, visitorId);\n }\n\n await this.safeSet(this.sessionKey, JSON.stringify(session));\n this.identity = {\n sessionId: session.sessionId,\n tabId: generateReplayId(),\n visitorId,\n sessionStartUnixMs: session.sessionStartUnixMs,\n chunkIndex: session.nextChunkIndex,\n };\n this.lastActivityUnixMs = nowUnixMs;\n return { ...this.identity };\n }\n\n /*\n * The session a product analytics event belongs to while the replay\n * records nothing of it (an unsampled session, issue #6629): nothing else\n * moves the session then, so the event is its activity. The session\n * carries on, or - past the idle window or the longest a session lasts -\n * the next one starts, as resolve() would decide at the next launch.\n * Synchronous: decided in memory and written in the background, where a\n * failed write costs only a relaunch's resume. Null before resolve().\n */\n public continueSession(nowUnixMs: number): ReplaySessionIdentity | null {\n const identity: ReplaySessionIdentity | null = this.identity;\n\n if (!identity) {\n return null;\n }\n\n if (\n nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS ||\n nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS\n ) {\n identity.sessionId = generateReplayId();\n identity.tabId = generateReplayId();\n identity.sessionStartUnixMs = nowUnixMs;\n identity.chunkIndex = 0;\n }\n\n this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);\n const state: StoredSession = {\n sessionId: identity.sessionId,\n sessionStartUnixMs: identity.sessionStartUnixMs,\n lastActivityUnixMs: this.lastActivityUnixMs,\n nextChunkIndex: identity.chunkIndex,\n };\n void this.safeSet(this.sessionKey, JSON.stringify(state));\n return { ...identity };\n }\n\n public async takeChunkIndex(nowUnixMs: number): Promise<number> {\n if (!this.identity) {\n await this.resolve(nowUnixMs);\n }\n\n const identity: ReplaySessionIdentity = this\n .identity as ReplaySessionIdentity;\n const index: number = identity.chunkIndex;\n identity.chunkIndex += 1;\n this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);\n const state: StoredSession = {\n sessionId: identity.sessionId,\n sessionStartUnixMs: identity.sessionStartUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: identity.chunkIndex,\n };\n await this.safeSet(this.sessionKey, JSON.stringify(state));\n return index;\n }\n\n public getNextChunkIndex(): number | null {\n return this.identity?.chunkIndex ?? null;\n }\n\n public async rotate(nowUnixMs: number): Promise<ReplaySessionIdentity> {\n let visitorId: string | null = await this.safeGet(this.visitorKey);\n if (!isReplayId(visitorId)) {\n visitorId = generateReplayId();\n await this.safeSet(this.visitorKey, visitorId);\n }\n const session: StoredSession = {\n sessionId: generateReplayId(),\n sessionStartUnixMs: nowUnixMs,\n lastActivityUnixMs: nowUnixMs,\n nextChunkIndex: 0,\n };\n await this.safeSet(this.sessionKey, JSON.stringify(session));\n this.identity = {\n sessionId: session.sessionId,\n tabId: generateReplayId(),\n visitorId,\n sessionStartUnixMs: nowUnixMs,\n chunkIndex: 0,\n };\n this.lastActivityUnixMs = nowUnixMs;\n return { ...this.identity };\n }\n\n /*\n * Forget the stored session without starting the next one. A session\n * that ends while the recorder is paused for idle has no successor until\n * the person comes back, and its record - last written by its own final\n * chunk, so it looks recent - would otherwise let a relaunch in the\n * meantime carry on a session that is already over. The visitor id stays,\n * and so does the in-memory identity: nothing more is sent under it, and\n * the next rotate() writes the new session.\n */\n public async end(): Promise<void> {\n await this.safeRemove(this.sessionKey);\n }\n\n public async clear(): Promise<void> {\n this.identity = null;\n await Promise.all([\n this.safeRemove(this.sessionKey),\n this.safeRemove(this.visitorKey),\n ]);\n }\n\n private async safeGet(key: string): Promise<string | null> {\n try {\n return await this.storage.getItem(key);\n } catch {\n return null;\n }\n }\n\n private async safeSet(key: string, value: string): Promise<void> {\n try {\n await this.storage.setItem(key, value);\n } catch {\n /* Persistence failure must not throw into a customer application. */\n }\n }\n\n private async safeRemove(key: string): Promise<void> {\n try {\n await this.storage.removeItem(key);\n } catch {\n /* Best-effort storage cleanup. */\n }\n }\n}\n", "import { ReplayConnectivity, ReplayFetch, ReplayFetchResponse } from \"./Config\";\nimport { SessionReplayConsentState } from \"./Contract\";\nimport {\n PRODUCT_ANALYTICS_CONTENT_TYPE,\n PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS,\n PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS,\n PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH,\n PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH,\n PRODUCT_ANALYTICS_MAX_PENDING_EVENTS,\n PRODUCT_ANALYTICS_TARGET_BATCH_BYTES,\n PRODUCT_ANALYTICS_WIRE_VERSION,\n ProductAnalyticsEventKind,\n ProductAnalyticsRecorderConfig,\n ProductAnalyticsWireBatch,\n ProductAnalyticsWireContext,\n ProductAnalyticsWireEvent,\n ProductAnalyticsWireMetric,\n isProductAnalyticsMetricName,\n toProductAnalyticsEventName,\n} from \"./ProductAnalyticsContract\";\nimport RetryAfter from \"./RetryAfter\";\nimport { byteLength } from \"./Sanitize\";\nimport { generateReplayId, ReplayStorage } from \"./Storage\";\n\n/*\n * Product analytics events from a React Native app (issue #6629): the\n * session's start, each screen it shows (a page view, named by the route\n * setRoute() was given), the app's track() events and its metric() points,\n * sent as small JSON batches to PRODUCT_ANALYTICS_EVENTS_PATH - the same\n * batches, limits and answers as the browser recorder's\n * (BrowserRecorder/src/ProductAnalytics.ts), from every session the\n * application's replay policy lets the recorder run in, recorded or not.\n *\n * A second, light channel beside the recording, not a second recorder: the\n * session, the visitor, consent and who signed in come from the replay\n * recorder (the host), so an event and a recording of the same visit carry\n * the same ids. What the host decides, this channel only asks about.\n *\n * Where it parts from the browser's, and why:\n *\n * - Every item it holds keeps the session and the person it happened\n * under, and a batch holds one session's and one person's items. A\n * phone holds items longer than a tab (offline, waiting for consent),\n * and a mobile session changes under them more often - a sign-in or a\n * sign-out starts a new one - so filing a batch under whoever is signed\n * in when it is sent would give one person's events to another.\n * - Before consent there is no session to name: the recorder's session is\n * a throwaway until the person agrees. Items are held unnamed, and the\n * grant files them, and the session's start ahead of them, under the\n * session the grant opens.\n * - Requests time out (a phone's connection can hang a request for\n * minutes), the device's own connectivity source and its return to the\n * foreground send what is held at once, and nothing is tried while the\n * device says it is offline.\n * - Which session the device last announced is kept in the app's storage,\n * not a browser's: a session that carries on across a relaunch (the\n * replay's own session store) is announced once.\n * - What it has not sent yet is kept in the app's storage too (issue\n * #9577), as the replay outbox keeps unsent chunks: an app used offline\n * and then killed, or stopped by the system in the background, sends\n * those events and metric points on its next start(), under the session\n * and the person they happened under. A tab that closes loses its\n * unsent ones; a phone is much more often offline for a while and then\n * stopped. Nothing held before consent is written - it has no session\n * yet - and withdrawing consent, or a policy that starts waiting for\n * it, removes what was written.\n *\n * Property, attribute and user property values arrive masked, as the\n * recorder masks all text (the host's toProperties and traits): event\n * names, keys and metric values are sent as written.\n */\n\n/* How long a request may take before it is given up and tried again later. */\nexport const PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS: number = 10_000;\n\n/* The longest the recorder waits before trying a failed batch again. */\nexport const PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS: number = 5 * 60 * 1000;\n\nconst RETRY_AFTER_LIMIT_SECONDS: number = 300;\n\nconst REPLAY_ID_PATTERN: RegExp = /^[0-9a-f]{32}$/u;\n\n/* Where the device keeps the session it last announced, per namespace. */\nexport function productAnalyticsSessionKey(namespace: string): string {\n return `@oneuptime/replay/${namespace}/analytics-session`;\n}\n\n/*\n * Where the device keeps what has not been sent yet, per namespace (issue\n * #9577): the events and metric points held, and the batch on its way.\n */\nexport function productAnalyticsQueueKey(namespace: string): string {\n return `@oneuptime/replay/${namespace}/analytics-queue`;\n}\n\n/* The stored queue's layout. A value of any other is read as nothing. */\nexport const PRODUCT_ANALYTICS_STORED_QUEUE_VERSION: number = 1;\n\n/*\n * The most the stored queue takes, as UTF-8 bytes. AsyncStorage's database\n * on Android is 6 MB by default, shared with the app and with the replay\n * outbox (3 MB), and a value past 2 MB cannot be read back there at all.\n * The cap of 500 events and 500 metric points is reached long before this\n * with ordinary events; with very large ones the oldest are left out of the\n * stored copy - still sent while the app runs, lost only if it is killed.\n */\nexport const PRODUCT_ANALYTICS_MAX_STORED_BYTES: number = 512 * 1024;\n\n/*\n * How long a change waits before it is written, so a burst of track()\n * calls is one write. The app leaving the foreground, when the system may\n * stop it, writes at once.\n */\nexport const PRODUCT_ANALYTICS_STORE_DELAY_MS: number = 1000;\n\n/*\n * The writes to each stored key, in order, per storage: a channel that\n * starts while the one before it is still writing what it held (a policy\n * refresh, a restart of the recorder) reads only after that write.\n */\nconst storeWrites: WeakMap<\n ReplayStorage,\n Map<string, Promise<void>>\n> = new WeakMap<ReplayStorage, Map<string, Promise<void>>>();\n\nfunction writesOf(storage: ReplayStorage): Map<string, Promise<void>> {\n let writes: Map<string, Promise<void>> | undefined = storeWrites.get(storage);\n\n if (!writes) {\n writes = new Map<string, Promise<void>>();\n storeWrites.set(storage, writes);\n }\n\n return writes;\n}\n\nfunction enqueueStoreWrite(\n storage: ReplayStorage,\n key: string,\n write: () => Promise<void>,\n): Promise<void> {\n const writes: Map<string, Promise<void>> = writesOf(storage);\n const run: () => Promise<void> = async (): Promise<void> => {\n try {\n await write();\n } catch {\n /* Storage full or unavailable: the items are still held in memory. */\n }\n };\n const next: Promise<void> = (writes.get(key) ?? Promise.resolve()).then(\n run,\n run,\n );\n\n writes.set(key, next);\n\n return next;\n}\n\n/* Resolves once every write to the key queued so far has been made. */\nasync function storeWritesSettled(\n storage: ReplayStorage,\n key: string,\n): Promise<void> {\n try {\n await writesOf(storage).get(key);\n } catch {\n /* The writes never reject; nothing to wait for. */\n }\n}\n\n/*\n * Consent withdrawn, or a policy that now waits for consent: what the device\n * kept for product analytics is removed, whether or not a channel is\n * running - one a previous launch left behind included.\n */\nexport async function clearStoredProductAnalytics(\n storage: ReplayStorage,\n namespace: string,\n): Promise<void> {\n await Promise.all([\n enqueueStoreWrite(\n storage,\n productAnalyticsQueueKey(namespace),\n async (): Promise<void> => {\n await storage.removeItem(productAnalyticsQueueKey(namespace));\n },\n ),\n enqueueStoreWrite(\n storage,\n productAnalyticsSessionKey(namespace),\n async (): Promise<void> => {\n await storage.removeItem(productAnalyticsSessionKey(namespace));\n },\n ),\n ]);\n}\n\n/* React Native's AppState, as the channel listens to it. */\nexport interface ProductAnalyticsAppState {\n currentState: string | null;\n addEventListener(\n type: \"change\",\n listener: (state: string) => void,\n ): { remove(): void };\n}\n\nexport interface ProductAnalyticsIdentity {\n /* \"\" while nobody is signed in, or the application captures no identity. */\n userRef: string;\n traits: Record<string, string> | null;\n}\n\nexport interface MobileProductAnalyticsHost {\n url: string;\n headers: Record<string, string>;\n fetch: ReplayFetch;\n now: () => number;\n storage: ReplayStorage;\n /* The replay's storage namespace (getReplayStorageNamespace). */\n namespace: string;\n appState?: ProductAnalyticsAppState | null | undefined;\n connectivity?: ReplayConnectivity | undefined;\n /*\n * The session an event that happens now belongs to - the event is\n * activity, so a session the replay does not record is kept alive or\n * rolled over by it. \"\" when there is none to name: before consent (the\n * items are then held until the grant names one), or when the recorder\n * has none at all.\n */\n getSessionId: (nowUnixMs: number) => string;\n /*\n * The same session, only looked at: the timer and the lifecycle look at\n * it without counting as activity, so an app nobody uses lets its\n * session go idle.\n */\n peekSessionId: () => string;\n /* The anonymous visitor's id; \"\" while there is none to send. */\n getVisitorId: () => string;\n getConsentState: () => SessionReplayConsentState;\n /* Whether the application's policy waits for an explicit consent. */\n requiresConsent: () => boolean;\n /* Who is signed in, and their traits, only with identity capture on. */\n getIdentity: () => ProductAnalyticsIdentity;\n /*\n * A track() call's properties or a metric() point's attributes as the\n * recorder keeps them: capped, and masked as it masks all text.\n */\n toProperties: (value: unknown) => Record<string, string>;\n /* The device type, system and app version the batches say. */\n getContext: () => ProductAnalyticsWireContext;\n onDiagnostic: (code: string, details?: Record<string, unknown>) => void;\n}\n\n/* Why the channel stopped, for the diagnostics. */\nexport type ProductAnalyticsStopReason =\n | \"stopped\"\n | \"not-enabled\"\n | \"refused\"\n | \"origin-not-allowed\";\n\nexport interface ProductAnalyticsDiagnostics {\n /* \"off\" when the application has them off, \"on\" while sent, else why they stopped. */\n state: \"off\" | \"on\" | ProductAnalyticsStopReason;\n pending: number;\n dropped: number;\n}\n\n/*\n * The session and the person an item happened under. sessionId is \"\" for\n * an item held before consent, until the grant names its session.\n */\ninterface ProductAnalyticsScope {\n sessionId: string;\n userRef: string;\n userProperties: Record<string, string> | null;\n}\n\ninterface HeldItem {\n scope: ProductAnalyticsScope;\n event?: ProductAnalyticsWireEvent;\n metric?: ProductAnalyticsWireMetric;\n}\n\n/*\n * The queue as the device keeps it: each distinct scope once, each item\n * pointing at its scope, and the batch on its way, which goes again under\n * its own id - the server files a batch id once.\n */\ninterface StoredQueue {\n v: number;\n scopes: Array<ProductAnalyticsScope>;\n items: Array<StoredItem>;\n pending: ProductAnalyticsWireBatch | null;\n}\n\ninterface StoredItem {\n s: number;\n e?: ProductAnalyticsWireEvent;\n m?: ProductAnalyticsWireMetric;\n}\n\n/* What a stored queue holds, once read back and checked. */\ninterface RestoredQueue {\n items: Array<HeldItem>;\n pending: ProductAnalyticsWireBatch | null;\n}\n\nconst EVENT_KINDS: ReadonlyArray<string> = [\n ProductAnalyticsEventKind.Session,\n ProductAnalyticsEventKind.Page,\n ProductAnalyticsEventKind.Custom,\n];\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isStringMap(value: unknown): value is Record<string, string> {\n return (\n isPlainRecord(value) &&\n Object.keys(value).every((key: string): boolean => {\n return typeof value[key] === \"string\";\n })\n );\n}\n\nfunction isFiniteTime(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/* Read back from the device: a value of the shape this file writes, or null. */\nfunction readStoredEvent(value: unknown): ProductAnalyticsWireEvent | null {\n if (\n !isPlainRecord(value) ||\n typeof value[\"kind\"] !== \"string\" ||\n EVENT_KINDS.indexOf(value[\"kind\"]) === -1 ||\n typeof value[\"name\"] !== \"string\" ||\n !isFiniteTime(value[\"at\"]) ||\n (value[\"page\"] !== undefined && typeof value[\"page\"] !== \"string\") ||\n (value[\"properties\"] !== undefined && !isStringMap(value[\"properties\"]))\n ) {\n return null;\n }\n\n const event: ProductAnalyticsWireEvent = {\n kind: value[\"kind\"] as ProductAnalyticsEventKind,\n name: value[\"name\"],\n at: value[\"at\"],\n };\n\n if (typeof value[\"page\"] === \"string\") {\n event.page = value[\"page\"];\n }\n\n if (isStringMap(value[\"properties\"])) {\n event.properties = value[\"properties\"];\n }\n\n return event;\n}\n\nfunction readStoredMetric(value: unknown): ProductAnalyticsWireMetric | null {\n if (\n !isPlainRecord(value) ||\n !isProductAnalyticsMetricName(value[\"name\"]) ||\n !isFiniteTime(value[\"value\"]) ||\n !isFiniteTime(value[\"at\"]) ||\n (value[\"attributes\"] !== undefined && !isStringMap(value[\"attributes\"]))\n ) {\n return null;\n }\n\n const metric: ProductAnalyticsWireMetric = {\n name: value[\"name\"],\n value: value[\"value\"],\n at: value[\"at\"],\n };\n\n if (isStringMap(value[\"attributes\"])) {\n metric.attributes = value[\"attributes\"];\n }\n\n return metric;\n}\n\nfunction readStoredScope(value: unknown): ProductAnalyticsScope | null {\n if (\n !isPlainRecord(value) ||\n typeof value[\"sessionId\"] !== \"string\" ||\n !REPLAY_ID_PATTERN.test(value[\"sessionId\"]) ||\n typeof value[\"userRef\"] !== \"string\" ||\n (value[\"userProperties\"] !== null && !isStringMap(value[\"userProperties\"]))\n ) {\n return null;\n }\n\n return {\n sessionId: value[\"sessionId\"],\n userRef: value[\"userRef\"],\n userProperties: value[\"userProperties\"] as Record<string, string> | null,\n };\n}\n\nfunction readStoredBatch(value: unknown): ProductAnalyticsWireBatch | null {\n if (\n !isPlainRecord(value) ||\n value[\"v\"] !== PRODUCT_ANALYTICS_WIRE_VERSION ||\n typeof value[\"batchId\"] !== \"string\" ||\n !REPLAY_ID_PATTERN.test(value[\"batchId\"]) ||\n typeof value[\"sessionId\"] !== \"string\" ||\n !REPLAY_ID_PATTERN.test(value[\"sessionId\"]) ||\n typeof value[\"visitorId\"] !== \"string\" ||\n typeof value[\"consentState\"] !== \"string\" ||\n !isFiniteTime(value[\"sentAt\"]) ||\n !isStringMap(value[\"context\"]) ||\n !Array.isArray(value[\"events\"]) ||\n !Array.isArray(value[\"metrics\"]) ||\n value[\"events\"].length > PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH ||\n value[\"metrics\"].length > PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH ||\n (value[\"userRef\"] !== undefined && typeof value[\"userRef\"] !== \"string\") ||\n (value[\"userProperties\"] !== undefined &&\n !isStringMap(value[\"userProperties\"]))\n ) {\n return null;\n }\n\n const events: Array<ProductAnalyticsWireEvent> = [];\n const metrics: Array<ProductAnalyticsWireMetric> = [];\n\n for (const entry of value[\"events\"] as Array<unknown>) {\n const event: ProductAnalyticsWireEvent | null = readStoredEvent(entry);\n\n if (!event) {\n return null;\n }\n\n events.push(event);\n }\n\n for (const entry of value[\"metrics\"] as Array<unknown>) {\n const metric: ProductAnalyticsWireMetric | null = readStoredMetric(entry);\n\n if (!metric) {\n return null;\n }\n\n metrics.push(metric);\n }\n\n const context: Record<string, string> = value[\"context\"];\n const batch: ProductAnalyticsWireBatch = {\n v: PRODUCT_ANALYTICS_WIRE_VERSION,\n batchId: value[\"batchId\"],\n sessionId: value[\"sessionId\"],\n visitorId: value[\"visitorId\"],\n consentState: value[\"consentState\"],\n sentAt: value[\"sentAt\"],\n context: {\n deviceType: context[\"deviceType\"] ?? \"\",\n browserName: context[\"browserName\"] ?? \"\",\n osName: context[\"osName\"] ?? \"\",\n appVersion: context[\"appVersion\"] ?? \"\",\n },\n events: events,\n metrics: metrics,\n };\n\n if (typeof value[\"userRef\"] === \"string\") {\n batch.userRef = value[\"userRef\"];\n batch.userProperties = isStringMap(value[\"userProperties\"])\n ? value[\"userProperties\"]\n : {};\n }\n\n return batch;\n}\n\n/*\n * The stored queue read back, or null when there is none or it is not one\n * this file wrote - a damaged value is never half-read: an item whose scope\n * or shape is wrong is left out alone, a layout of another version is\n * nothing at all.\n */\nfunction readStoredQueue(raw: string | null): RestoredQueue | null {\n if (!raw) {\n return null;\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n\n if (\n !isPlainRecord(parsed) ||\n parsed[\"v\"] !== PRODUCT_ANALYTICS_STORED_QUEUE_VERSION ||\n !Array.isArray(parsed[\"scopes\"]) ||\n !Array.isArray(parsed[\"items\"])\n ) {\n return null;\n }\n\n const scopes: Array<ProductAnalyticsScope | null> = (\n parsed[\"scopes\"] as Array<unknown>\n ).map(readStoredScope);\n const items: Array<HeldItem> = [];\n\n for (const entry of parsed[\"items\"] as Array<unknown>) {\n if (!isPlainRecord(entry) || typeof entry[\"s\"] !== \"number\") {\n continue;\n }\n\n const scope: ProductAnalyticsScope | null | undefined = scopes[entry[\"s\"]];\n\n if (!scope) {\n continue;\n }\n\n if (entry[\"e\"] !== undefined) {\n const event: ProductAnalyticsWireEvent | null = readStoredEvent(\n entry[\"e\"],\n );\n\n if (event) {\n items.push({ scope: scope, event: event });\n }\n\n continue;\n }\n\n const metric: ProductAnalyticsWireMetric | null = readStoredMetric(\n entry[\"m\"],\n );\n\n if (metric) {\n items.push({ scope: scope, metric: metric });\n }\n }\n\n return {\n items: items,\n pending:\n parsed[\"pending\"] === null || parsed[\"pending\"] === undefined\n ? null\n : readStoredBatch(parsed[\"pending\"]),\n };\n}\n\nfunction scopeKey(scope: ProductAnalyticsScope): string {\n return JSON.stringify([scope.sessionId, scope.userRef, scope.userProperties]);\n}\n\n/*\n * The queue as the device keeps it, or null when there is nothing to keep:\n * the batch on its way, then the newest items that fit under\n * PRODUCT_ANALYTICS_MAX_STORED_BYTES, in the order they were held. An item\n * with no session yet - held for a consent not given - is never written.\n */\nfunction buildStoredQueue(\n items: ReadonlyArray<HeldItem>,\n pending: ProductAnalyticsWireBatch | null,\n): string | null {\n const named: Array<HeldItem> = items.filter((item: HeldItem): boolean => {\n return item.scope.sessionId !== \"\";\n });\n\n if (named.length === 0 && !pending) {\n return null;\n }\n\n const build: (from: number) => string = (from: number): string => {\n const scopes: Array<ProductAnalyticsScope> = [];\n const scopeIndex: Map<string, number> = new Map<string, number>();\n const stored: Array<StoredItem> = [];\n\n for (const item of named.slice(from)) {\n const key: string = scopeKey(item.scope);\n let index: number | undefined = scopeIndex.get(key);\n\n if (index === undefined) {\n index = scopes.length;\n scopes.push(item.scope);\n scopeIndex.set(key, index);\n }\n\n if (item.event) {\n stored.push({ s: index, e: item.event });\n } else if (item.metric) {\n stored.push({ s: index, m: item.metric });\n }\n }\n\n const queue: StoredQueue = {\n v: PRODUCT_ANALYTICS_STORED_QUEUE_VERSION,\n scopes: scopes,\n items: stored,\n pending: pending,\n };\n\n return JSON.stringify(queue);\n };\n\n let from: number = 0;\n let value: string = build(from);\n\n if (byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {\n return value;\n }\n\n /*\n * Too large: the fewest of the oldest left out until it fits, found by\n * halving - a handful of builds, however many items are held.\n */\n let low: number = 1;\n let high: number = named.length;\n\n while (low < high) {\n const middle: number = Math.floor((low + high) / 2);\n\n if (byteLength(build(middle)) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {\n high = middle;\n } else {\n low = middle + 1;\n }\n }\n\n from = low;\n value = build(from);\n\n return byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES ? value : null;\n}\n\nfunction itemAt(item: HeldItem): number {\n return item.event ? item.event.at : item.metric?.at ?? 0;\n}\n\nfunction sameScope(\n left: ProductAnalyticsScope,\n right: ProductAnalyticsScope,\n): boolean {\n return (\n left.sessionId === right.sessionId &&\n left.userRef === right.userRef &&\n JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties)\n );\n}\n\n/*\n * The traits an event may carry: those the application listed, matched as\n * written (Common's pickProductAnalyticsUserProperties, over traits the\n * recorder already capped and masked).\n */\nexport function pickProductAnalyticsUserProperties(\n traits: Record<string, string> | null,\n allowedKeys: ReadonlyArray<string>,\n): Record<string, string> {\n const picked: Record<string, string> = {};\n\n if (!traits) {\n return picked;\n }\n\n for (const key of allowedKeys) {\n if (\n Object.prototype.hasOwnProperty.call(traits, key) &&\n typeof traits[key] === \"string\"\n ) {\n picked[key] = traits[key] as string;\n }\n }\n\n return picked;\n}\n\nexport default class MobileProductAnalytics {\n private readonly host: MobileProductAnalyticsHost;\n private config: ProductAnalyticsRecorderConfig;\n\n private items: Array<HeldItem> = [];\n private eventCount: number = 0;\n private metricCount: number = 0;\n\n /*\n * The batch on its way, kept until the server says what became of it, so\n * a retry sends the same batch id and the server files it once.\n */\n private pending: ProductAnalyticsWireBatch | null = null;\n private sending: boolean = false;\n private sendGeneration: number = 0;\n private retryAtUnixMs: number = 0;\n private failures: number = 0;\n\n /* The session items are filed under now, and the screen shown in it. */\n private sessionId: string = \"\";\n private shownPage: string = \"\";\n /* The last screen the app named, in any session. */\n private route: string = \"\";\n /* The session this device last announced; null until read. */\n private announcedSessionId: string | null = null;\n\n private droppedEvents: number = 0;\n private started: boolean = false;\n private stopReason: ProductAnalyticsStopReason | null = null;\n private revoked: boolean = false;\n /* The connectivity source said the device is offline. */\n private offline: boolean = false;\n\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private appStateSubscription: { remove(): void } | null = null;\n private unsubscribeConnectivity: (() => void) | null = null;\n\n /*\n * The stored queue (issue #9577). Written only once what a previous run\n * left there has been read back, so a channel that never got that far\n * can never overwrite it with nothing.\n */\n private restored: boolean = false;\n private storeTimer: ReturnType<typeof setTimeout> | null = null;\n\n public constructor(\n host: MobileProductAnalyticsHost,\n config: ProductAnalyticsRecorderConfig,\n ) {\n this.host = host;\n this.config = config;\n }\n\n /*\n * Reads which session this device last announced, then starts: the\n * session's start (unless announced already), the timer, and the app's\n * lifecycle and connectivity. Items before this resolves are not taken.\n */\n public async start(): Promise<void> {\n if (this.started || this.stopReason) {\n return;\n }\n\n let stored: string | null = null;\n let storedQueue: string | null = null;\n const queueKey: string = productAnalyticsQueueKey(this.host.namespace);\n\n /* What a channel before this one is still writing comes first. */\n await storeWritesSettled(this.host.storage, queueKey);\n\n try {\n stored = await this.host.storage.getItem(\n productAnalyticsSessionKey(this.host.namespace),\n );\n } catch {\n stored = null;\n }\n\n try {\n storedQueue = await this.host.storage.getItem(queueKey);\n } catch {\n storedQueue = null;\n }\n\n if (this.started || this.stopReason) {\n return;\n }\n\n this.announcedSessionId =\n typeof stored === \"string\" && REPLAY_ID_PATTERN.test(stored)\n ? stored\n : null;\n this.started = true;\n this.restored = true;\n\n /* Consent withdrawn while the queue was being read: nothing comes back. */\n if (!this.revoked) {\n this.restoreQueue(storedQueue, this.host.now());\n }\n\n this.enterCurrentSession(this.host.now(), false);\n\n this.flushTimer = setInterval((): void => {\n this.flush(false);\n }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);\n\n this.listenToLifecycle();\n\n this.host.onDiagnostic(\"analytics-started\", {\n userPropertyKeys: this.config.userPropertyKeys.length,\n });\n }\n\n /* A refreshed policy's keys; whether it waits for consent is asked live. */\n public setConfig(config: ProductAnalyticsRecorderConfig): void {\n this.config = config;\n }\n\n public isStarted(): boolean {\n return this.started && !this.stopReason;\n }\n\n public track(name: unknown, properties?: unknown): void {\n const eventName: string | null = toProductAnalyticsEventName(name);\n\n if (!eventName || !this.accepts()) {\n return;\n }\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope) {\n return;\n }\n\n const event: ProductAnalyticsWireEvent = {\n kind: ProductAnalyticsEventKind.Custom,\n name: eventName,\n at: now,\n properties: this.host.toProperties(properties),\n };\n\n if (this.shownPage) {\n event.page = this.shownPage;\n } else if (this.route) {\n event.page = this.route;\n }\n\n this.pushEvent(scope, event);\n }\n\n /*\n * A screen the app moved to (setRoute(), already scrubbed as the replay\n * keeps a route): a page view, unless it is the screen already shown in\n * this session.\n */\n public page(route: string): void {\n if (!route || !this.accepts()) {\n return;\n }\n\n this.route = route;\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope || route === this.shownPage) {\n return;\n }\n\n this.shownPage = route;\n this.pushEvent(scope, {\n kind: ProductAnalyticsEventKind.Page,\n name: route,\n at: now,\n page: route,\n });\n }\n\n /*\n * metric(name, value, attributes): a number the app measured\n * (\"cart.value\", 42.5), filed in the metric store under the RUM\n * application. A name outside the instrument-name shape, or in\n * OneUptime's own namespace, or a value that is not a finite number, is\n * refused here and says why in the diagnostics.\n */\n public metric(name: unknown, value: unknown, attributes?: unknown): void {\n if (!this.accepts()) {\n return;\n }\n\n if (!isProductAnalyticsMetricName(name)) {\n this.host.onDiagnostic(\"metric-name-refused\", {\n name: typeof name === \"string\" ? name.slice(0, 100) : typeof name,\n });\n return;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n this.host.onDiagnostic(\"metric-value-refused\", { name: name });\n return;\n }\n\n const now: number = this.host.now();\n const scope: ProductAnalyticsScope | null = this.scopeNow(now);\n\n if (!scope) {\n return;\n }\n\n this.items.push({\n scope: scope,\n metric: {\n name: name,\n value: value,\n at: now,\n attributes: this.host.toProperties(attributes),\n },\n });\n this.metricCount++;\n\n /* Held too long (no consent, no network): the oldest go first. */\n if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {\n this.dropOldest(\"metric\");\n }\n\n this.scheduleStore();\n\n if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {\n this.flush(false);\n }\n }\n\n /*\n * Send what is held. `final` is the app leaving the foreground: sent at\n * once, whatever a retry was waiting for, while the system still lets\n * the app use the network.\n */\n public flush(final: boolean): void {\n if (!this.started || this.stopReason || this.revoked || this.sending) {\n return;\n }\n\n if (this.isAwaitingConsent() || this.offline) {\n return;\n }\n\n const now: number = this.host.now();\n\n if (!final && now < this.retryAtUnixMs) {\n return;\n }\n\n if (!this.pending) {\n this.enterCurrentSession(now, false);\n this.pending = this.takeBatch(now);\n }\n\n const batch: ProductAnalyticsWireBatch | null = this.pending;\n\n if (!batch) {\n return;\n }\n\n this.send(batch);\n }\n\n /*\n * Consent withdrawn: everything held is dropped, the batch on its way\n * too, the session this device announced is forgotten, and nothing is\n * kept or sent until a new grant.\n */\n public forget(): void {\n this.revoked = true;\n this.clear();\n this.forgetStoredQueue();\n this.forgetAnnouncedSession();\n }\n\n /*\n * The policy now waits for a consent this run has not been given: what\n * was held, and the device's record, go as on a withdrawal, but what\n * happens from now on is held for the grant, as before any consent.\n */\n public reset(): void {\n this.clear();\n this.forgetStoredQueue();\n this.forgetAnnouncedSession();\n }\n\n /* Granted: what was held is filed under the session the grant opened, and goes now. */\n public onConsentGranted(): void {\n this.revoked = false;\n this.retryAtUnixMs = 0;\n this.enterCurrentSession(this.host.now(), false);\n this.scheduleStore();\n this.flush(false);\n }\n\n /*\n * The recorder's session may have changed under the channel - a policy\n * refreshed, a session named after consent: what was held for it is\n * filed under it, and what can go, goes.\n */\n public refresh(): void {\n if (!this.accepts()) {\n return;\n }\n\n this.enterCurrentSession(this.host.now(), false);\n this.scheduleStore();\n this.flush(false);\n }\n\n public stop(reason: ProductAnalyticsStopReason = \"stopped\"): void {\n const isFirstStop: boolean = !this.stopReason;\n\n if (!this.stopReason) {\n this.stopReason = reason;\n }\n\n /*\n * Stopped by the app or a restart of the recorder: what is held is\n * written, for the next start() to send. Stopped by the server - the\n * application has product analytics off, or will not take this app's\n * batches - it would only refuse them again, so they go.\n */\n if (isFirstStop && this.restored) {\n if (reason === \"stopped\") {\n this.storeNow();\n } else {\n this.forgetStoredQueue();\n }\n }\n\n this.clear();\n this.cancelStoreTimer();\n\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n const unsubscribe: (() => void) | null = this.unsubscribeConnectivity;\n this.unsubscribeConnectivity = null;\n\n try {\n unsubscribe?.();\n } catch {\n /* The host's unsubscribe must not break teardown. */\n }\n }\n\n public getStopReason(): ProductAnalyticsStopReason | null {\n return this.stopReason;\n }\n\n public getPendingCount(): number {\n return (\n this.items.length +\n (this.pending\n ? this.pending.events.length + this.pending.metrics.length\n : 0)\n );\n }\n\n public getDroppedEventCount(): number {\n return this.droppedEvents;\n }\n\n public getDiagnostics(): ProductAnalyticsDiagnostics {\n return {\n state: this.stopReason || \"on\",\n pending: this.getPendingCount(),\n dropped: this.droppedEvents,\n };\n }\n\n private accepts(): boolean {\n return this.started && !this.stopReason && !this.revoked;\n }\n\n private isAwaitingConsent(): boolean {\n return (\n this.host.requiresConsent() && this.host.getConsentState() !== \"Granted\"\n );\n }\n\n private clear(): void {\n this.items = [];\n this.eventCount = 0;\n this.metricCount = 0;\n this.pending = null;\n /* An answer still on its way belongs to nothing held any more. */\n this.sendGeneration++;\n this.sending = false;\n this.sessionId = \"\";\n this.shownPage = \"\";\n }\n\n private forgetAnnouncedSession(): void {\n this.announcedSessionId = null;\n void this.host.storage\n .removeItem(productAnalyticsSessionKey(this.host.namespace))\n .catch((): void => {\n /* Best-effort privacy cleanup. */\n });\n }\n\n private announce(sessionId: string): void {\n this.announcedSessionId = sessionId;\n void this.host.storage\n .setItem(productAnalyticsSessionKey(this.host.namespace), sessionId)\n .catch((): void => {\n /* Not kept: a relaunch may announce the session again. */\n });\n }\n\n private makeScope(sessionId: string): ProductAnalyticsScope {\n const identity: ProductAnalyticsIdentity = this.host.getIdentity();\n\n return {\n sessionId: sessionId,\n userRef: identity.userRef,\n userProperties: identity.userRef\n ? pickProductAnalyticsUserProperties(\n identity.traits,\n this.config.userPropertyKeys,\n )\n : null,\n };\n }\n\n /*\n * The scope of an item that happens now, or null when it has none to be\n * filed under (no session, and no consent being waited for).\n */\n private scopeNow(now: number): ProductAnalyticsScope | null {\n const sessionId: string = this.enterCurrentSession(now, true);\n\n if (sessionId) {\n return this.makeScope(sessionId);\n }\n\n return this.isAwaitingConsent() ? this.makeScope(\"\") : null;\n }\n\n /*\n * Follows the host's session: a new one starts with its start (once per\n * session on this device) and the screen the app shows, and items held\n * before consent are filed under the first session there is to name.\n * Returns the session, or \"\" when there is none to name. Only an item\n * that happens now is activity (isActivity); the timer only looks.\n */\n private enterCurrentSession(now: number, isActivity: boolean): string {\n const sessionId: string = isActivity\n ? this.host.getSessionId(now)\n : this.host.peekSessionId();\n\n if (!sessionId) {\n return \"\";\n }\n\n const firstUnnamed: number = this.items.findIndex(\n (item: HeldItem): boolean => {\n return item.scope.sessionId === \"\";\n },\n );\n\n if (sessionId === this.sessionId && firstUnnamed < 0) {\n return sessionId;\n }\n\n const isNewSession: boolean = sessionId !== this.sessionId;\n this.sessionId = sessionId;\n\n /*\n * What was held before consent: this session's, from its start. Their\n * screen views are this session's, so the screen is not shown again.\n */\n let startedAt: number = now;\n let startPage: string = this.route;\n let startScope: ProductAnalyticsScope = this.makeScope(sessionId);\n\n if (firstUnnamed >= 0) {\n const first: HeldItem = this.items[firstUnnamed] as HeldItem;\n\n startedAt = Math.min(now, itemAt(first));\n startPage = first.event?.page || this.route;\n startScope = { ...first.scope, sessionId: sessionId };\n\n for (const item of this.items) {\n if (item.scope.sessionId === \"\") {\n item.scope = { ...item.scope, sessionId: sessionId };\n }\n }\n } else if (isNewSession) {\n this.shownPage = \"\";\n }\n\n if (this.announcedSessionId !== sessionId) {\n const start: ProductAnalyticsWireEvent = {\n kind: ProductAnalyticsEventKind.Session,\n name: \"\",\n at: startedAt,\n };\n\n if (startPage) {\n start.page = startPage;\n }\n\n const item: HeldItem = { scope: startScope, event: start };\n\n if (firstUnnamed >= 0) {\n this.items.splice(firstUnnamed, 0, item);\n } else {\n this.items.push(item);\n }\n\n this.eventCount++;\n this.announce(sessionId);\n this.trimEvents();\n this.scheduleStore();\n }\n\n /* The screen the app shows is this new session's first page view. */\n if (firstUnnamed < 0 && isNewSession && this.route) {\n this.shownPage = this.route;\n this.items.push({\n scope: this.makeScope(sessionId),\n event: {\n kind: ProductAnalyticsEventKind.Page,\n name: this.route,\n at: now,\n page: this.route,\n },\n });\n this.eventCount++;\n this.trimEvents();\n this.scheduleStore();\n }\n\n return sessionId;\n }\n\n private pushEvent(\n scope: ProductAnalyticsScope,\n event: ProductAnalyticsWireEvent,\n ): void {\n this.items.push({ scope: scope, event: event });\n this.eventCount++;\n this.trimEvents();\n this.scheduleStore();\n\n if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {\n this.flush(false);\n }\n }\n\n /* Held too long (no consent, no network): the oldest go first, counted. */\n private trimEvents(): void {\n while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {\n this.dropOldest(\"event\");\n this.droppedEvents++;\n }\n }\n\n private dropOldest(kind: \"event\" | \"metric\"): void {\n const index: number = this.items.findIndex((item: HeldItem): boolean => {\n return kind === \"event\" ? Boolean(item.event) : Boolean(item.metric);\n });\n\n if (index < 0) {\n return;\n }\n\n this.items.splice(index, 1);\n\n if (kind === \"event\") {\n this.eventCount--;\n } else {\n this.metricCount--;\n }\n }\n\n /*\n * The next batch: the oldest items of one session and one person, up to\n * the per-batch counts and the target size. Items the server would drop\n * for their age are dropped here instead.\n */\n private takeBatch(now: number): ProductAnalyticsWireBatch | null {\n this.dropTooOld(now);\n\n const first: HeldItem | undefined = this.items[0];\n\n if (!first || first.scope.sessionId === \"\") {\n return null;\n }\n\n const scope: ProductAnalyticsScope = first.scope;\n let count: number = 0;\n let events: number = 0;\n let metrics: number = 0;\n\n for (const item of this.items) {\n if (!sameScope(item.scope, scope)) {\n break;\n }\n\n if (item.event) {\n if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {\n break;\n }\n\n events++;\n } else {\n if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {\n break;\n }\n\n metrics++;\n }\n\n count++;\n }\n\n const build: (taken: number) => ProductAnalyticsWireBatch = (\n taken: number,\n ): ProductAnalyticsWireBatch => {\n const slice: Array<HeldItem> = this.items.slice(0, taken);\n const batch: ProductAnalyticsWireBatch = {\n v: PRODUCT_ANALYTICS_WIRE_VERSION,\n batchId: generateReplayId(),\n sessionId: scope.sessionId,\n visitorId: this.host.getVisitorId(),\n consentState: this.host.getConsentState(),\n sentAt: now,\n context: this.host.getContext(),\n events: slice\n .filter((item: HeldItem): boolean => {\n return Boolean(item.event);\n })\n .map((item: HeldItem): ProductAnalyticsWireEvent => {\n return item.event as ProductAnalyticsWireEvent;\n }),\n metrics: slice\n .filter((item: HeldItem): boolean => {\n return Boolean(item.metric);\n })\n .map((item: HeldItem): ProductAnalyticsWireMetric => {\n return item.metric as ProductAnalyticsWireMetric;\n }),\n };\n\n if (scope.userRef) {\n batch.userRef = scope.userRef;\n batch.userProperties = scope.userProperties || {};\n }\n\n return batch;\n };\n\n let batch: ProductAnalyticsWireBatch = build(count);\n\n /* Halve until it fits; one item always does (its parts are capped). */\n while (\n JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES &&\n count > 1\n ) {\n count = Math.floor(count / 2);\n batch = build(count);\n }\n\n this.items.splice(0, count);\n this.eventCount -= batch.events.length;\n this.metricCount -= batch.metrics.length;\n this.scheduleStore();\n\n return batch;\n }\n\n private dropTooOld(now: number): void {\n const oldest: number = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;\n const kept: Array<HeldItem> = [];\n\n for (const item of this.items) {\n if (itemAt(item) >= oldest) {\n kept.push(item);\n continue;\n }\n\n if (item.event) {\n this.eventCount--;\n this.droppedEvents++;\n } else {\n this.metricCount--;\n }\n }\n\n if (kept.length !== this.items.length) {\n this.scheduleStore();\n }\n\n this.items = kept;\n }\n\n /*\n * What a previous run left in the device's storage (issue #9577), taken\n * back before anything new: the items under the sessions and people they\n * happened under, the batch that was on its way under its own id. What\n * the server would no longer keep (PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS) is\n * left out, and the caps apply as to anything held: past them the oldest\n * events go, counted in the diagnostics' dropped.\n */\n private restoreQueue(raw: string | null, now: number): void {\n if (!raw) {\n return;\n }\n\n const queue: RestoredQueue | null = readStoredQueue(raw);\n\n if (!queue) {\n this.host.onDiagnostic(\"analytics-store-unreadable\");\n this.forgetStoredQueue();\n return;\n }\n\n const oldest: number = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;\n const droppedBefore: number = this.droppedEvents;\n let tooOld: number = 0;\n\n /* The batch on its way goes again, unless everything in it is too old. */\n const pending: ProductAnalyticsWireBatch | null = queue.pending;\n\n if (pending) {\n const isLive: boolean = [...pending.events, ...pending.metrics].some(\n (item: { at: number }): boolean => {\n return item.at >= oldest;\n },\n );\n\n if (isLive) {\n this.pending = pending;\n } else {\n this.droppedEvents += pending.events.length;\n tooOld += pending.events.length + pending.metrics.length;\n }\n }\n\n this.items = queue.items.filter((item: HeldItem): boolean => {\n if (itemAt(item) >= oldest) {\n return true;\n }\n\n if (item.event) {\n this.droppedEvents++;\n }\n\n tooOld++;\n return false;\n });\n this.eventCount = this.items.filter((item: HeldItem): boolean => {\n return Boolean(item.event);\n }).length;\n this.metricCount = this.items.length - this.eventCount;\n\n const droppedTooOld: number = this.droppedEvents - droppedBefore;\n\n this.trimEvents();\n\n while (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {\n this.dropOldest(\"metric\");\n }\n\n this.host.onDiagnostic(\"analytics-restored\", {\n events: this.eventCount + (this.pending?.events.length ?? 0),\n metrics: this.metricCount + (this.pending?.metrics.length ?? 0),\n droppedTooOld: droppedTooOld,\n droppedOverCap: this.droppedEvents - droppedBefore - droppedTooOld,\n });\n\n /* What was left out is left out of the stored copy too. */\n if (tooOld > 0 || this.items.length < queue.items.length) {\n this.scheduleStore();\n }\n }\n\n /* A change to what is held: written once the burst it belongs to is over. */\n private scheduleStore(): void {\n if (!this.restored || this.stopReason || this.storeTimer) {\n return;\n }\n\n this.storeTimer = setTimeout((): void => {\n this.storeTimer = null;\n this.storeNow();\n }, PRODUCT_ANALYTICS_STORE_DELAY_MS);\n }\n\n /* What is held, written now, in the order the writes were asked for. */\n private storeNow(): void {\n this.cancelStoreTimer();\n\n if (!this.restored || this.revoked) {\n return;\n }\n\n const storage: ReplayStorage = this.host.storage;\n const key: string = productAnalyticsQueueKey(this.host.namespace);\n const value: string | null = buildStoredQueue(this.items, this.pending);\n\n void enqueueStoreWrite(storage, key, async (): Promise<void> => {\n if (value === null) {\n await storage.removeItem(key);\n } else {\n await storage.setItem(key, value);\n }\n });\n }\n\n private forgetStoredQueue(): void {\n this.cancelStoreTimer();\n\n const storage: ReplayStorage = this.host.storage;\n const key: string = productAnalyticsQueueKey(this.host.namespace);\n\n void enqueueStoreWrite(storage, key, async (): Promise<void> => {\n await storage.removeItem(key);\n });\n }\n\n private cancelStoreTimer(): void {\n if (this.storeTimer) {\n clearTimeout(this.storeTimer);\n this.storeTimer = null;\n }\n }\n\n private send(batch: ProductAnalyticsWireBatch): void {\n const generation: number = this.sendGeneration;\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n /*\n * sentAt is when this request goes, not when the batch was first built:\n * the server moves every time in the batch by the gap between it and\n * its own clock (receivedAt - sentAt), so a batch sent again after a\n * back-off, an hour offline or a relaunch, under the old sentAt, would\n * be filed as if it all happened at the moment it finally arrived.\n */\n const init: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"POST\",\n headers: {\n ...this.host.headers,\n \"Content-Type\": PRODUCT_ANALYTICS_CONTENT_TYPE,\n },\n body: JSON.stringify({ ...batch, sentAt: this.host.now() }),\n };\n\n if (controller) {\n init.signal = controller.signal;\n }\n\n let request: Promise<ReplayFetchResponse>;\n\n try {\n request = this.host.fetch(this.host.url, init);\n } catch {\n this.retryLater(this.host.now(), 0);\n return;\n }\n\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n timeout = setTimeout((): void => {\n controller?.abort();\n reject(new Error(\"analytics-request-timeout\"));\n }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);\n },\n );\n\n this.sending = true;\n\n Promise.race([request, deadline])\n .then((response: ReplayFetchResponse): void => {\n if (generation !== this.sendGeneration) {\n return;\n }\n\n this.sending = false;\n this.onAnswer(response, this.host.now());\n })\n .catch((): void => {\n if (generation !== this.sendGeneration) {\n return;\n }\n\n this.sending = false;\n this.retryLater(this.host.now(), 0);\n })\n .finally((): void => {\n if (timeout) {\n clearTimeout(timeout);\n }\n });\n }\n\n private onAnswer(response: ReplayFetchResponse, now: number): void {\n const status: number = response.status;\n\n if (status === 202 || status === 200) {\n this.pending = null;\n this.failures = 0;\n this.scheduleStore();\n\n if (this.items.length > 0) {\n this.flush(false);\n }\n\n return;\n }\n\n if (status === 413) {\n /* Never sendable; the next batch is smaller. */\n this.pending = null;\n this.scheduleStore();\n return;\n }\n\n if (status === 204 || status === 400 || status === 403) {\n let reason: string = \"\";\n\n try {\n reason = response.headers?.get(\"x-oneuptime-replay-reason\") || \"\";\n } catch {\n reason = \"\";\n }\n\n this.host.onDiagnostic(\"analytics-stopped\", {\n status: status,\n reason: reason.slice(0, 100),\n });\n\n this.stop(\n status === 403\n ? \"origin-not-allowed\"\n : status === 204\n ? \"not-enabled\"\n : \"refused\",\n );\n return;\n }\n\n /*\n * A 429's or a 503's Retry-After, as RFC 9110 writes it (RetryAfter):\n * whole seconds or an HTTP date, from one second to\n * RETRY_AFTER_LIMIT_SECONDS. Anything else is none, and the doubling\n * applies.\n */\n const retryAfterMs: number =\n status === 429 || status === 503\n ? RetryAfter.msFromHeaders(response.headers, {\n maxMs: RETRY_AFTER_LIMIT_SECONDS * 1000,\n nowMs: now,\n }) ?? 0\n : 0;\n\n /* 409 (consent not given), 429, 5xx: the same batch later. */\n this.retryLater(now, retryAfterMs);\n }\n\n private retryLater(now: number, delayMs: number): void {\n this.failures++;\n this.retryAtUnixMs =\n now +\n (delayMs > 0\n ? delayMs\n : Math.min(\n PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,\n PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures),\n ));\n }\n\n /*\n * The app leaving the foreground sends what is held while it still can;\n * coming back, or the device saying it is online again, sends a batch\n * that waited at once, rather than when its retry was due.\n */\n private listenToLifecycle(): void {\n const appState: ProductAnalyticsAppState | null | undefined =\n this.host.appState;\n\n if (appState && typeof appState.addEventListener === \"function\") {\n try {\n this.appStateSubscription = appState.addEventListener(\n \"change\",\n (state: string): void => {\n if (state === \"active\") {\n this.retryAtUnixMs = 0;\n this.flush(false);\n return;\n }\n\n this.flush(true);\n /*\n * In the background the system may stop the app at any moment:\n * what was not sent is written now, not after the usual wait.\n */\n this.storeNow();\n },\n );\n } catch {\n this.appStateSubscription = null;\n }\n }\n\n const connectivity: ReplayConnectivity | undefined = this.host.connectivity;\n\n if (!connectivity) {\n return;\n }\n\n try {\n const unsubscribe: unknown = connectivity.subscribe(\n (isConnected: boolean | null): void => {\n if (isConnected === false) {\n this.offline = true;\n return;\n }\n\n if (isConnected === true) {\n const wasOffline: boolean = this.offline;\n this.offline = false;\n\n if (wasOffline) {\n this.retryAtUnixMs = 0;\n this.flush(false);\n }\n }\n },\n );\n\n this.unsubscribeConnectivity =\n typeof unsubscribe === \"function\" ? (unsubscribe as () => void) : null;\n } catch {\n /* A throwing connectivity source only costs the early send. */\n this.unsubscribeConnectivity = null;\n }\n }\n}\n", "import { gzipSync, strToU8 } from \"fflate\";\nimport {\n CHUNK_PATH,\n encodeSessionReplayEnvelopeLine,\n MAX_SESSION_REPLAY_CHUNK_BYTES,\n SESSION_REPLAY_CONTENT_TYPE,\n SessionReplayChunkEnvelope,\n SessionReplayChunkResponse,\n SessionReplayDirective,\n} from \"./Contract\";\nimport {\n mobileRequestHeaders,\n ReplayFetch,\n ReplayFetchResponse,\n ValidatedStartOptions,\n} from \"./Config\";\nimport ReplayOutbox, {\n frameId,\n OutboxEntry,\n OutboxMutationResult,\n StoredReplayFrame,\n} from \"./Outbox\";\nimport RetryAfter from \"./RetryAfter\";\n\n/*\n * Attempts a frame gets against a server that ANSWERS and fails (a 5xx with\n * no Retry-After). Offline mode's rule is that nothing else costs an\n * attempt: a request that never reached the server is the device's\n * connection, and a throttle is the server asking for patience. Counting\n * either dropped a frame after three tries fifteen seconds apart - under a\n * minute of any outage lost everything recorded during it.\n */\nconst MAX_ATTEMPTS_PER_FRAME: number = 3;\nconst DEFAULT_RETRY_MS: number = 15_000;\nconst MAX_RETRY_MS: number = 5 * 60_000;\nexport const CHUNK_POST_TIMEOUT_MS: number = 10_000;\n\n/*\n * Waits after a request that never reached the server: short while a drop\n * is likely brief, then a minute for as long as it lasts. The app coming\n * to the foreground, and a connectivity source saying the network is back\n * (see MobileReplayStartOptions.connectivity), drain at once instead.\n */\nexport const OFFLINE_RETRY_MS: Array<number> = [5_000, 15_000, 30_000, 60_000];\nconst DIRECTIVE_REASON_PATTERN: RegExp = /^[A-Za-z0-9_.:-]{1,100}$/u;\n\nexport interface ReplayTransportOptions {\n startOptions: ValidatedStartOptions;\n outbox: ReplayOutbox;\n onDirective: (\n directive: SessionReplayDirective,\n reason: string | null,\n ) => void;\n onDiagnostic: (code: string, details?: Record<string, unknown>) => void;\n}\n\nexport interface EncodedReplayFrame {\n envelope: SessionReplayChunkEnvelope;\n body: Uint8Array;\n}\n\nexport function encodeReplayFrame(\n originalEnvelope: SessionReplayChunkEnvelope,\n payload: string,\n): EncodedReplayFrame {\n return encodeCompressedReplayFrame(\n originalEnvelope,\n gzipSync(strToU8(payload)),\n );\n}\n\n/*\n * The same frame from a payload the outbox already stores gzip-compressed.\n * clientSendUnixMs is stamped here, as the request is built: a frame that\n * waited out an outage tells the server how long it waited, which is what\n * keeps a recording uploaded hours late on its real timeline.\n */\nexport function encodeCompressedReplayFrame(\n originalEnvelope: SessionReplayChunkEnvelope,\n compressed: Uint8Array,\n): EncodedReplayFrame {\n const envelope: SessionReplayChunkEnvelope = {\n ...originalEnvelope,\n payloadEncoding: \"gzip\",\n payloadBytes: compressed.byteLength,\n clientSendUnixMs: Date.now(),\n };\n const prefix: Uint8Array = strToU8(encodeSessionReplayEnvelopeLine(envelope));\n const body: Uint8Array = new Uint8Array(\n prefix.byteLength + compressed.byteLength,\n );\n body.set(prefix, 0);\n body.set(compressed, prefix.byteLength);\n return { envelope, body };\n}\n\ninterface ParsedDirective {\n directive: SessionReplayDirective | null;\n reason: string | null;\n retryAfterSeconds: number | null;\n}\n\nfunction safeReason(value: unknown): string | null {\n return typeof value === \"string\" && DIRECTIVE_REASON_PATTERN.test(value)\n ? value\n : null;\n}\n\nfunction parseDirectiveValue(value: unknown): SessionReplayDirective | null {\n return value === \"continue\" || value === \"stop\" || value === \"throttle\"\n ? value\n : null;\n}\n\nasync function readDirective(\n response: ReplayFetchResponse,\n): Promise<ParsedDirective> {\n if (response.status === 204) {\n return {\n directive: parseDirectiveValue(\n response.headers?.get(\"x-oneuptime-replay-directive\"),\n ),\n reason: safeReason(response.headers?.get(\"x-oneuptime-replay-reason\")),\n retryAfterSeconds: parseRetryAfter(\n response.headers?.get(\"retry-after\") ?? null,\n ),\n };\n }\n\n try {\n const value: unknown = await response.json();\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return { directive: null, reason: null, retryAfterSeconds: null };\n }\n\n const body: Partial<SessionReplayChunkResponse> & { error?: unknown } =\n value as Partial<SessionReplayChunkResponse> & { error?: unknown };\n return {\n directive: parseDirectiveValue(body.directive),\n reason: safeReason(body.reason) ?? safeReason(body.error),\n retryAfterSeconds:\n typeof body.retryAfterSeconds === \"number\" &&\n Number.isFinite(body.retryAfterSeconds)\n ? Math.max(0, Math.min(300, body.retryAfterSeconds))\n : parseRetryAfter(response.headers?.get(\"retry-after\") ?? null),\n };\n } catch {\n return {\n directive: null,\n reason: null,\n retryAfterSeconds: parseRetryAfter(\n response.headers?.get(\"retry-after\") ?? null,\n ),\n };\n }\n}\n\n/*\n * Retry-After as RFC 9110 writes it (src/RetryAfter.ts, a copy of Common's):\n * whole seconds or an HTTP-date, from one second to 300. Null for anything\n * else, so the default wait applies: Number() read \"1.5\" as a second and a\n * half and \"\" or \" \" as 0 - a retry at once, and a server that kept\n * answering so was asked again in a loop.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n return RetryAfter.parseSeconds(value, { maxMs: 300 * 1000 }) ?? null;\n}\n\ntype PostOutcome = \"remove\" | \"remove-and-halt\" | \"retry\" | \"wait\" | \"stop\";\n\nexport default class ReplayTransport {\n private readonly options: ReplayTransportOptions;\n private readonly fetch: ReplayFetch;\n private drainPromise: Promise<void> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private stopped: boolean = false;\n private flushFailures: number = 0;\n private retryAfterDrainMs: number | null = null;\n private activeAbortController: AbortController | null = null;\n private abortCurrentRequest: (() => void) | null = null;\n\n /* Requests in a row that never reached the server. */\n private connectivityFailures: number = 0;\n\n /* What the host app's connectivity source last said, if it has one. */\n private reportedOffline: boolean = false;\n\n public constructor(options: ReplayTransportOptions) {\n this.options = options;\n this.fetch = options.startOptions.fetch;\n }\n\n /*\n * Offline, as far as uploading goes: the host app's connectivity source\n * says so, or the last request never reached the server.\n */\n public isOffline(): boolean {\n return this.reportedOffline || this.connectivityFailures > 0;\n }\n\n /*\n * The host app's connectivity source changed (NetInfo, typically). While\n * it says offline nothing is attempted. Coming back does NOT drain on its\n * own: whether this recorder may upload right now (consent) is the\n * recorder's decision, so it calls resume() itself. null means \"unknown\",\n * which blocks nothing.\n */\n public setConnectivity(isConnected: boolean | null): void {\n this.reportedOffline = isConnected === false;\n }\n\n /*\n * Drain now rather than on the retry timer: the app came to the\n * foreground, or the network came back. An offline wait ends; a server\n * throttle still stands.\n */\n public resume(): void {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n\n if (this.connectivityFailures > 0 && this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n\n if (!this.retryTimer) {\n void this.drain();\n }\n }\n\n public async enqueue(\n envelope: SessionReplayChunkEnvelope,\n payload: string,\n ): Promise<void> {\n if (this.stopped) {\n return;\n }\n\n const mutation: OutboxMutationResult = await this.options.outbox.enqueue({\n id: frameId(envelope),\n envelope,\n payload,\n attempts: 0,\n createdAtUnixMs: Date.now(),\n });\n if (mutation.dropped > 0) {\n this.options.onDiagnostic(\"outbox-overflow\", {\n dropped: mutation.dropped,\n });\n }\n\n /*\n * Stored either way; posted now only when no retry is pending. A frame\n * closes every 15 s, and posting each one into an outage, or into a\n * throttle the server asked for, is a request on the user's battery the\n * retry timer was about to make anyway.\n */\n if (!this.retryTimer) {\n await this.drain();\n }\n }\n\n public async restore(): Promise<void> {\n await this.drain();\n }\n\n public async drain(): Promise<void> {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n if (this.drainPromise) {\n return await this.drainPromise;\n }\n\n this.drainPromise = this.drainLoop().finally((): void => {\n this.drainPromise = null;\n if (this.retryAfterDrainMs !== null) {\n const delayMs: number = this.retryAfterDrainMs;\n this.retryAfterDrainMs = null;\n this.scheduleRetry(delayMs);\n }\n });\n return await this.drainPromise;\n }\n\n public destroy(): void {\n this.stopped = true;\n this.activeAbortController?.abort();\n this.abortCurrentRequest?.();\n if (this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n }\n\n public getFlushFailures(): number {\n return this.flushFailures;\n }\n\n private async drainLoop(): Promise<void> {\n /*\n * Index entries only; each frame's payload is read as it is posted, so a\n * long offline backlog is never all in memory at once.\n */\n const entries: Array<OutboxEntry> = await this.options.outbox.entries();\n for (const entry of entries) {\n if (this.stopped || this.reportedOffline) {\n return;\n }\n\n const frame: StoredReplayFrame | \"unreadable\" | null =\n await this.options.outbox.load(entry.id);\n if (frame === \"unreadable\") {\n this.options.onDiagnostic(\"outbox-frame-unreadable\");\n continue;\n }\n if (!frame) {\n continue;\n }\n\n const outcome: PostOutcome = await this.post(frame);\n if (outcome === \"remove\") {\n await this.options.outbox.remove(frame.id);\n continue;\n }\n if (outcome === \"remove-and-halt\") {\n await this.options.outbox.remove(frame.id);\n return;\n }\n if (outcome === \"stop\") {\n return;\n }\n\n this.flushFailures += 1;\n if (outcome === \"wait\") {\n /* Offline or throttled: the frame keeps its place and its attempts. */\n return;\n }\n\n const attempts: number = await this.options.outbox.incrementAttempts(\n frame.id,\n );\n if (attempts >= MAX_ATTEMPTS_PER_FRAME) {\n await this.options.outbox.remove(frame.id);\n this.options.onDiagnostic(\"chunk-retry-exhausted\", {\n chunkIndex: frame.envelope.chunkIndex,\n });\n continue;\n }\n\n if (this.retryAfterDrainMs === null) {\n this.retryAfterDrainMs = DEFAULT_RETRY_MS;\n }\n return;\n }\n }\n\n private async post(frame: StoredReplayFrame): Promise<PostOutcome> {\n const encoded: EncodedReplayFrame = encodeCompressedReplayFrame(\n frame.envelope,\n frame.compressedPayload,\n );\n if (encoded.body.byteLength > MAX_SESSION_REPLAY_CHUNK_BYTES) {\n this.options.onDiagnostic(\"chunk-too-large\", {\n chunkIndex: frame.envelope.chunkIndex,\n bytes: encoded.body.byteLength,\n });\n return \"remove\";\n }\n\n let response: ReplayFetchResponse;\n let said: ParsedDirective;\n const controller: AbortController | null =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n this.activeAbortController = controller;\n let timedOut: boolean = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let abortDeadline: (() => void) | null = null;\n try {\n const request: Promise<{\n response: ReplayFetchResponse;\n said: ParsedDirective;\n }> = (async (): Promise<{\n response: ReplayFetchResponse;\n said: ParsedDirective;\n }> => {\n const requestInit: NonNullable<Parameters<ReplayFetch>[1]> = {\n method: \"POST\",\n headers: {\n ...mobileRequestHeaders(this.options.startOptions),\n \"Content-Type\": SESSION_REPLAY_CONTENT_TYPE,\n },\n body: encoded.body,\n };\n if (controller) {\n requestInit.signal = controller.signal;\n }\n const fetched: ReplayFetchResponse = await this.fetch(\n `${this.options.startOptions.host}${CHUNK_PATH}`,\n requestInit,\n );\n return { response: fetched, said: await readDirective(fetched) };\n })();\n const deadline: Promise<never> = new Promise<never>(\n (\n _resolve: (value: never | PromiseLike<never>) => void,\n reject: (reason?: unknown) => void,\n ): void => {\n abortDeadline = (): void => {\n controller?.abort();\n reject(new Error(\"chunk-post-aborted\"));\n };\n this.abortCurrentRequest = abortDeadline;\n timeout = setTimeout((): void => {\n timedOut = true;\n abortDeadline?.();\n }, CHUNK_POST_TIMEOUT_MS);\n },\n );\n ({ response, said } = await Promise.race([request, deadline]));\n } catch {\n if (this.stopped) {\n return \"stop\";\n }\n this.options.onDiagnostic(\n timedOut ? \"chunk-post-timeout\" : \"chunk-network-failure\",\n {\n chunkIndex: frame.envelope.chunkIndex,\n },\n );\n\n /*\n * The request never reached the server: the device is offline, or on\n * a connection that goes nowhere. Not a failure of the frame - it\n * waits, with no attempt counted, for as long as the outage lasts.\n */\n this.connectivityFailures += 1;\n this.retryAfterDrainMs =\n OFFLINE_RETRY_MS[\n Math.min(this.connectivityFailures, OFFLINE_RETRY_MS.length) - 1\n ]!;\n return \"wait\";\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (this.activeAbortController === controller) {\n this.activeAbortController = null;\n }\n if (this.abortCurrentRequest === abortDeadline) {\n this.abortCurrentRequest = null;\n }\n }\n\n /* Any answer at all: the connection is back. */\n if (this.connectivityFailures > 0) {\n this.connectivityFailures = 0;\n this.options.onDiagnostic(\"back-online\");\n }\n\n if (said.directive) {\n this.options.onDirective(said.directive, said.reason);\n }\n\n if (said.directive === \"stop\") {\n this.stopped = true;\n await this.options.outbox.clear();\n return \"stop\";\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (said.directive === \"throttle\") {\n this.retryAfterDrainMs = Math.min(\n MAX_RETRY_MS,\n (said.retryAfterSeconds ?? DEFAULT_RETRY_MS / 1_000) * 1_000,\n );\n return \"remove-and-halt\";\n }\n return \"remove\";\n }\n\n if (\n response.status === 400 ||\n response.status === 413 ||\n response.status === 422\n ) {\n this.options.onDiagnostic(\"chunk-refused\", {\n status: response.status,\n chunkIndex: frame.envelope.chunkIndex,\n reason: said.reason,\n });\n return \"remove\";\n }\n\n if (\n response.status === 401 ||\n response.status === 403 ||\n response.status === 404\n ) {\n this.options.onDiagnostic(\"transport-disabled\", {\n status: response.status,\n reason: said.reason,\n });\n this.options.onDirective(\"stop\", said.reason ?? \"transport-disabled\");\n this.stopped = true;\n await this.options.outbox.clear();\n return \"stop\";\n }\n\n const retryMs: number = Math.min(\n MAX_RETRY_MS,\n (said.retryAfterSeconds ?? DEFAULT_RETRY_MS / 1_000) * 1_000,\n );\n this.retryAfterDrainMs = retryMs;\n\n /*\n * A 429, or any answer that says when to come back (a throttle directive\n * or a Retry-After): the server asking for patience, which costs the\n * frame nothing. A whole fleet reconnecting at once after an outage is\n * exactly when the project's per-minute rate is spent.\n */\n if (\n response.status === 429 ||\n said.directive === \"throttle\" ||\n said.retryAfterSeconds !== null\n ) {\n return \"wait\";\n }\n\n return \"retry\";\n }\n\n private scheduleRetry(delayMs: number): void {\n if (this.retryTimer || this.stopped) {\n return;\n }\n\n this.retryTimer = setTimeout(\n (): void => {\n this.retryTimer = null;\n void this.drain();\n },\n Math.max(0, delayMs),\n );\n }\n}\n", "import { NativeViewTreeNode } from \"./NativeViewTree\";\n\nconst MAX_PRIVACY_TREE_NODES: number = 5_000;\nconst OPAQUE_KINDS: ReadonlySet<string> = new Set<string>([\n \"image\",\n \"webview\",\n \"canvas\",\n \"masked\",\n]);\n\nexport interface OpaqueTouchRegion {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\nexport interface TouchPrivacyMap {\n regions: Array<OpaqueTouchRegion>;\n suppressAll: boolean;\n}\n\nexport const CONSERVATIVE_TOUCH_PRIVACY_MAP: TouchPrivacyMap = {\n regions: [],\n suppressAll: true,\n};\n\nfunction finite(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\nexport function deriveTouchPrivacyMap(\n root: NativeViewTreeNode,\n): TouchPrivacyMap {\n const regions: Array<OpaqueTouchRegion> = [];\n const hasRootOrigin: boolean =\n finite(root.touchOriginX) && finite(root.touchOriginY);\n const rootX: number = hasRootOrigin ? (root.touchOriginX as number) : 0;\n const rootY: number = hasRootOrigin ? (root.touchOriginY as number) : 0;\n let suppressAll: boolean =\n finite(root.truncatedNodes) && root.truncatedNodes > 0;\n let visited: number = 0;\n\n const visit: (\n node: NativeViewTreeNode,\n parentX: number,\n parentY: number,\n alignedPath: boolean,\n isRoot: boolean,\n ) => void = (\n node: NativeViewTreeNode,\n parentX: number,\n parentY: number,\n alignedPath: boolean,\n isRoot: boolean,\n ): void => {\n if (visited >= MAX_PRIVACY_TREE_NODES) {\n suppressAll = true;\n return;\n }\n visited += 1;\n\n const hasGeometry: boolean =\n finite(node.x) &&\n finite(node.y) &&\n finite(node.width) &&\n finite(node.height);\n const left: number = isRoot\n ? parentX\n : parentX + (finite(node.x) ? node.x : 0);\n const top: number = isRoot\n ? parentY\n : parentY + (finite(node.y) ? node.y : 0);\n const pathIsAligned: boolean = alignedPath && hasGeometry;\n const opaque: boolean =\n node.masked === true ||\n node.opaque === true ||\n OPAQUE_KINDS.has(typeof node.kind === \"string\" ? node.kind : \"\");\n\n if (opaque) {\n if (!pathIsAligned || !hasRootOrigin) {\n suppressAll = true;\n return;\n }\n if ((node.width as number) > 0 && (node.height as number) > 0) {\n regions.push({\n left,\n top,\n right: left + (node.width as number),\n bottom: top + (node.height as number),\n });\n }\n return;\n }\n\n if (Array.isArray(node.children)) {\n for (const child of node.children) {\n if (child && typeof child === \"object\") {\n visit(child, left, top, pathIsAligned, false);\n }\n }\n }\n };\n\n visit(root, rootX, rootY, hasRootOrigin, true);\n return { regions, suppressAll };\n}\n\nexport function isTouchPrivate(\n privacyMap: TouchPrivacyMap,\n x: number,\n y: number,\n): boolean {\n if (privacyMap.suppressAll || !finite(x) || !finite(y)) {\n return true;\n }\n return privacyMap.regions.some((region: OpaqueTouchRegion): boolean => {\n return (\n x >= region.left &&\n x <= region.right &&\n y >= region.top &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AAM,YACN,YAAY;AACd,UAAM,QAAuB;AAAA,MAC3B;AAAA,MACA,GAAG,MAAM;AAAA,MACT,GAAG,MAAM;AAAA,MACT,WAAW,KAAK,IAAI;AAAA,IACtB;AACA,QAAI,OAAO,cAAc,YAAY,OAAO,cAAc,SAAS,GAAG;AACpE,YAAM,YAAY;AAAA,IACpB;AACA,QACG,OAAO,cAAc,YAAY,OAAO,cAAc,SAAS,KAChE,OAAO,cAAc,UACrB;AACA,YAAM,YAAY;AAAA,IACpB;AACA,aAAS,YAAY,KAAK;AAAA,EAC5B;AAEA,SACE,4CAAC,cAAc,UAAd,EAAuB,OAAO,UAC7B;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,aAAa;AAAA,MACb,OAAO,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,KAAK;AAAA,MAChC,cAAc,CAAC,UAAuC;AACpD,eAAO,SAAS,KAAK;AAAA,MACvB;AAAA,MACA,aAAa,CAAC,UAAuC;AACnD,eAAO,QAAQ,KAAK;AAAA,MACtB;AAAA,MACA,YAAY,CAAC,UAAuC;AAClD,eAAO,OAAO,KAAK;AAAA,MACrB;AAAA,MAEC,gBAAM;AAAA;AAAA,EACT,GACF;AAEJ;AAEO,SAAS,qBAA2C;AACzD,aAAO,yBAAW,aAAa;AACjC;AAQO,SAAS,WAAW,OAAsC;AAC/D,SACE;AAAA,IAAC;AAAA;AAAA,MACC,aAAa;AAAA,MACb,UAAS;AAAA,MACT,QAAO;AAAA,MACP,OAAO,MAAM;AAAA,MAEZ,gBAAM;AAAA;AAAA,EACT;AAEJ;AAEO,IAAM,iBACX;;;ADxHK,IAAM,kBACX;AAEF,IAAO,gBAAQ;",
6
+ "names": ["import_react_native", "import_react_native", "SessionReplayMaskingMode", "SessionReplayConsentMode", "SessionReplayCaptureTrigger", "SessionReplayTriggerReason", "SessionReplayFidelityNotice", "CONTROL_CHARACTER_PATTERN", "x", "x", "i", "l", "i", "i2", "_a", "_b", "i", "i", "i", "_a", "bits", "AsyncStorage", "REPLAY_ID_PATTERN", "from", "batch", "x", "safeReason", "suppressed", "x"]
7
7
  }