@posthog/electron 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.cjs","names":["PostHogCore","PostHogPersistedProperty","app","release","session","isPostHogFetchNetworkError","BucketedRateLimiter","resolveExceptionRateLimiterConfig","createLogger","hostname","randomUUID","join","fs","readFileSync","openSync","randomUUID","createHash","join","app","PostHogPersistedProperty","flagDetailsToResults"],"sources":["../src/version.ts","../src/shared/protocol.ts","../src/shared/autocapture.ts","../src/main/client.ts","../src/shared/exception-autocapture.ts","../src/main/exception-autocapture.ts","../src/main/storage.ts","../src/utility/protocol.ts","../src/utility/attach.ts","../src/main/index.ts"],"sourcesContent":["export const version = \"0.1.1\"\n","import type { FeatureFlagValue, FeatureFlagResult, JsonType, PostHogEventProperties } from '@posthog/core'\n\nimport type { AutocaptureState } from './autocapture'\n\nexport const COMMAND_CHANNEL = 'posthog:command:v1'\nexport const STATE_CHANNEL = 'posthog:state:v1'\nexport const BRIDGE_KEY = '__POSTHOG_ELECTRON__'\nexport const PROTOCOL_VERSION = 1\nexport const MAX_MESSAGE_BYTES = 256 * 1024\n\nexport type Properties = PostHogEventProperties\nexport type { FeatureFlagValue, FeatureFlagResult, JsonType }\n\nexport interface FeatureFlagReadOptions {\n /** Report a deduplicated exposure by default; false suppresses it. Takes precedence over sendEvent. */\n sendFeatureFlagEvent?: boolean\n /** Compatibility option; prefer sendFeatureFlagEvent. */\n sendEvent?: boolean\n}\n\nexport interface IsFeatureEnabledOptions extends FeatureFlagReadOptions {\n /** Fallback for unknown or unavailable flags; never overrides a known false or empty variant. */\n defaultValue?: boolean\n}\n\n// Core currently marks empty variants enabled; normalize reads without changing exposure values.\nexport function normalizeFlagResult(result: FeatureFlagResult): FeatureFlagResult {\n return structuredClone({ ...result, enabled: result.variant === '' ? false : result.enabled })\n}\n\nexport interface State {\n revision: number\n generation: number\n distinctId: string\n anonymousId: string\n sessionId: string\n optedOut: boolean\n disabled?: boolean\n autocapture?: AutocaptureState\n featureFlags: Record<string, FeatureFlagValue>\n flagsLoaded?: boolean\n flagRevision: number\n featureFlagPayloads: Record<string, JsonType>\n}\n\nexport type Command =\n | { type: 'hello' }\n | { type: 'capture'; event: string; properties?: Properties }\n | { type: 'alias'; alias: string }\n | { type: 'screen'; name: string; properties?: Properties }\n | { type: 'setPersonProperties'; properties?: Properties; propertiesOnce?: Properties }\n | { type: 'setPersonPropertiesForFlags'; properties: Properties; reloadFeatureFlags: boolean }\n | { type: 'setGroupPropertiesForFlags'; properties: Record<string, Properties>; reloadFeatureFlags: boolean }\n | { type: 'resetPersonPropertiesForFlags' | 'resetGroupPropertiesForFlags'; reloadFeatureFlags: boolean }\n | { type: 'identify'; distinctId: string; properties?: Properties }\n | { type: 'reset' }\n | { type: 'group'; groupType: string; groupKey: string | number; properties?: Properties }\n | { type: 'register'; properties: Properties }\n | { type: 'unregister'; key: string }\n | { type: 'optIn' }\n | { type: 'optOut' }\n | { type: 'flag'; key: string; flagRevision: number; value: FeatureFlagValue | null }\n | { type: 'reloadFeatureFlags' }\n | { type: 'loadAutocaptureConfig' }\n | { type: 'flush' }\n | { type: 'exception'; properties: Properties }\n\nexport function isFlagContextCommand(command: Command): command is Extract<Command, { reloadFeatureFlags: boolean }> {\n return (\n command.type === 'setPersonPropertiesForFlags' ||\n command.type === 'setGroupPropertiesForFlags' ||\n command.type === 'resetPersonPropertiesForFlags' ||\n command.type === 'resetGroupPropertiesForFlags'\n )\n}\n\nexport interface Request {\n version: number\n sequence: number\n generation: number\n command: Command\n}\n\nexport type Response = { ok: true; state: State } | { ok: false; error: string }\n\nexport interface Bridge {\n request(request: Request): Promise<Response>\n subscribe(callback: (state: State) => void): () => void\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function assertJson(value: unknown, depth = 0, allowReservedKeys = false): void {\n let remaining = MAX_MESSAGE_BYTES\n const spend = (size: number): void => {\n remaining -= size\n if (remaining < 0) throw new Error('PostHog message exceeds 256 KiB')\n }\n const visit = (item: unknown, level: number): void => {\n if (level > 20) throw new Error('PostHog payload is too deeply nested')\n // Count each occurrence, including shared references, against a lower bound on JSON size.\n spend(typeof item === 'string' ? item.length + 2 : 1)\n if (item === null || typeof item === 'string' || typeof item === 'boolean') return\n if (typeof item === 'number' && Number.isFinite(item)) return\n if (Array.isArray(item)) {\n for (const element of item) visit(element, level + 1)\n return\n }\n if (\n isRecord(item) &&\n (Object.getPrototypeOf(item) === Object.prototype || Object.getPrototypeOf(item) === null)\n ) {\n for (const key in item) {\n if (!Object.hasOwn(item, key)) continue\n spend(key.length + 3)\n if (!allowReservedKeys && ['__proto__', 'constructor', 'prototype'].includes(key))\n throw new Error('Unsafe PostHog property key')\n visit(item[key], level + 1)\n }\n return\n }\n throw new Error('PostHog properties must be JSON serializable')\n }\n visit(value, depth)\n}\n\nexport function validateRequest(value: unknown): asserts value is Request {\n assertJson(value)\n if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_MESSAGE_BYTES) {\n throw new Error('PostHog message exceeds 256 KiB')\n }\n if (\n !isRecord(value) ||\n value.version !== PROTOCOL_VERSION ||\n !Number.isSafeInteger(value.sequence) ||\n (value.sequence as number) < 1 ||\n !Number.isSafeInteger(value.generation) ||\n !isRecord(value.command)\n ) {\n throw new Error('Invalid PostHog request')\n }\n const command = value.command\n const string = (key: string): boolean =>\n typeof command[key] === 'string' && (command[key] as string).trim().length > 0\n const properties = (): boolean => command.properties === undefined || isRecord(command.properties)\n switch (command.type) {\n case 'hello':\n case 'reset':\n case 'optIn':\n case 'optOut':\n case 'reloadFeatureFlags':\n case 'loadAutocaptureConfig':\n case 'flush':\n return\n case 'capture':\n if (string('event') && !['$snapshot', '$exception'].includes(command.event as string) && properties())\n return\n break\n case 'alias':\n if (string('alias')) return\n break\n case 'screen':\n if (string('name') && properties()) return\n break\n case 'setPersonProperties':\n if (properties() && (command.propertiesOnce === undefined || isRecord(command.propertiesOnce))) return\n break\n case 'setPersonPropertiesForFlags':\n if (isRecord(command.properties) && typeof command.reloadFeatureFlags === 'boolean') return\n break\n case 'setGroupPropertiesForFlags':\n if (\n isRecord(command.properties) &&\n Object.values(command.properties).every(isRecord) &&\n typeof command.reloadFeatureFlags === 'boolean'\n )\n return\n break\n case 'resetPersonPropertiesForFlags':\n case 'resetGroupPropertiesForFlags':\n if (typeof command.reloadFeatureFlags === 'boolean') return\n break\n case 'identify':\n if (string('distinctId') && properties()) return\n break\n case 'group':\n if (string('groupType') && (string('groupKey') || typeof command.groupKey === 'number') && properties())\n return\n break\n case 'register':\n if (isRecord(command.properties)) return\n break\n case 'exception':\n if (\n isRecord(command.properties) &&\n Array.isArray(command.properties.$exception_list) &&\n command.properties.$exception_list.length > 0 &&\n command.properties.$exception_list.every(\n (exception) =>\n isRecord(exception) && typeof exception.type === 'string' && typeof exception.value === 'string'\n )\n )\n return\n break\n case 'unregister':\n if (string('key')) return\n break\n case 'flag':\n if (\n string('key') &&\n Number.isSafeInteger(command.flagRevision) &&\n (command.value === null || typeof command.value === 'boolean' || typeof command.value === 'string')\n )\n return\n break\n }\n throw new Error('Invalid PostHog command')\n}\n\nexport function trustedUrl(url: string, allowedUrls: readonly string[]): boolean {\n try {\n const target = new URL(url)\n target.hash = ''\n // Windows pathToFileURL escapes tildes in short paths, while Electron loadFile leaves them literal.\n if (target.protocol === 'file:') target.pathname = target.pathname.replace(/%7e/gi, '~')\n return allowedUrls.some((allowed) => {\n const candidate = new URL(allowed)\n candidate.hash = ''\n if (candidate.protocol === 'file:') candidate.pathname = candidate.pathname.replace(/%7e/gi, '~')\n return candidate.href === target.href\n })\n } catch {\n return false\n }\n}\n","import { isRecord } from './protocol'\n\nexport interface AutocaptureRemoteConfig {\n autocapture_opt_out?: boolean\n elementsChainAsString?: boolean\n}\n\nexport interface AutocaptureState extends AutocaptureRemoteConfig {\n status: 'pending' | 'loaded' | 'failed' | 'disabled'\n}\n\n/** Only these project settings may cross the bridge or enter Electron's config cache. */\nexport function sanitizeAutocaptureConfig(value: unknown): AutocaptureRemoteConfig {\n if (!isRecord(value)) return {}\n return {\n ...(typeof value.autocapture_opt_out === 'boolean' ? { autocapture_opt_out: value.autocapture_opt_out } : {}),\n ...(typeof value.elementsChainAsString === 'boolean'\n ? { elementsChainAsString: value.elementsChainAsString }\n : {}),\n }\n}\n","import { app, session } from 'electron'\nimport { release } from 'node:os'\nimport {\n PostHogCore,\n PostHogPersistedProperty,\n isPostHogFetchNetworkError,\n type PostHogCoreOptions,\n type PostHogEventProperties,\n type PostHogFetchOptions,\n type PostHogFetchResponse,\n type PostHogCaptureOptions,\n type GetFlagsResult,\n} from '@posthog/core'\nimport { version } from '../version'\nimport { ElectronStorage } from './storage'\nimport { isRecord } from '../shared/protocol'\nimport { sanitizeAutocaptureConfig, type AutocaptureState } from '../shared/autocapture'\n\nconst AUTOCAPTURE_CONFIG_MAX_AGE_MS = 60_000\n\nclass RetryLaterError extends Error {}\n\nexport class ElectronCore extends PostHogCore {\n private _autocaptureStatus: AutocaptureState['status'] = 'pending'\n private _autocaptureLoad?: Promise<void>\n private _autocaptureLoadedAt?: number\n private _disableRemoteConfig: boolean\n private _stopped = false\n private _suspended = false\n private _identityEpoch = 0\n private _controllers = new Set<AbortController>()\n private _retryAt = 0\n private _failures = 0\n private _initialization: Promise<void>\n private _eventContext: PostHogEventProperties = {}\n private _appBuild?: string\n private _maxQueueAgeMs: number\n private _flagsResponseTimeoutMs: number\n\n constructor(\n token: string,\n options: PostHogCoreOptions & { appBuild?: string; maxQueueAgeMs?: number },\n private _storage: ElectronStorage,\n private _notify: () => void,\n private _report: (error: unknown) => void\n ) {\n super(token, { ...options, flushInterval: 0, disableSurveys: true })\n this._disableRemoteConfig = options.disableRemoteConfig ?? false\n this._appBuild = options.appBuild\n this._maxQueueAgeMs = options.maxQueueAgeMs ?? 7 * 24 * 60 * 60 * 1000\n this._flagsResponseTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 10000\n this._isInitialized = false\n this._initialization = this._initPromise = this._storage.load().then(() => {\n if (this._stopped) return\n if (!this._storage.isOwned) {\n this.disabled = true\n return\n }\n this._isInitialized = true\n const cached = this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig)\n if (cached !== undefined)\n this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, sanitizeAutocaptureConfig(cached))\n this.setupBootstrap(options)\n this.resetSessionId()\n this.getDistinctId()\n this.getSessionId()\n })\n this.on('error', this._report)\n }\n\n ready(): Promise<void> {\n return this._initialization\n }\n\n canIdentify(): boolean {\n return !this.isDisabled && this._personProfiles !== 'never'\n }\n\n getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined {\n return this._storage.get<T>(key)\n }\n\n setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void {\n if (this._stopped || key === PostHogPersistedProperty.SessionReplay) return\n this._storage.set(\n key,\n key === PostHogPersistedProperty.RemoteConfig && value !== null ? sanitizeAutocaptureConfig(value) : value\n )\n if (\n this._isInitialized &&\n key !== PostHogPersistedProperty.Queue &&\n key !== PostHogPersistedProperty.SessionLastTimestamp\n ) {\n this._notify()\n }\n }\n\n getAutocaptureState(): AutocaptureState {\n return {\n ...sanitizeAutocaptureConfig(this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig)),\n status: this._disableRemoteConfig ? 'disabled' : this._autocaptureStatus,\n ...(this.isDisabled ? { autocapture_opt_out: true } : {}),\n }\n }\n\n loadAutocaptureConfig(forceRefresh = false): Promise<void> {\n if (this._stopped || this.isDisabled || this.optedOut || this._disableRemoteConfig) return Promise.resolve()\n if (this._autocaptureLoad) return this._autocaptureLoad\n if (\n !forceRefresh &&\n this._autocaptureStatus === 'loaded' &&\n this._autocaptureLoadedAt !== undefined &&\n Date.now() - this._autocaptureLoadedAt < AUTOCAPTURE_CONFIG_MAX_AGE_MS\n )\n return Promise.resolve()\n // Status starts 'pending' and only the first request waits on it; a warm refresh or a retry after an\n // outcome keeps the last known state so already-enabled capture is not paused.\n // These whitelisted project settings are identity-independent, unlike flag responses.\n this._autocaptureLoad = this.getRemoteConfig()\n .then((response) => {\n if (this._stopped) return\n if (this.optedOut || this.isDisabled) {\n this._autocaptureStatus = 'failed'\n return\n }\n this._autocaptureStatus = response ? 'loaded' : 'failed'\n if (response) {\n this._autocaptureLoadedAt = Date.now()\n this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, {\n ...sanitizeAutocaptureConfig(this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig)),\n ...sanitizeAutocaptureConfig(response),\n })\n }\n })\n .finally(() => {\n this._autocaptureLoad = undefined\n if (!this._stopped) this._notify()\n })\n return this._autocaptureLoad\n }\n\n capture(event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {\n if (this.optedOut || this._stopped) return\n super.capture(event, properties, options)\n }\n\n group(...args: Parameters<PostHogCore['group']>): void {\n if (this.optedOut || this._stopped) return\n super.group(...args)\n }\n\n protected async getFlagsForContext(\n ...args: Parameters<PostHogCore['getFlagsForContext']>\n ): Promise<GetFlagsResult | undefined> {\n const epoch = this._identityEpoch\n const result = await super.getFlagsForContext(...args)\n return this._stopped || epoch !== this._identityEpoch ? undefined : result\n }\n\n getLibraryId(): string {\n return 'posthog-electron'\n }\n getLibraryVersion(): string {\n return version\n }\n getCustomUserAgent(): string {\n return `posthog-electron/${version}`\n }\n protected getEvaluationRuntime(): 'client' {\n return 'client'\n }\n\n protected getCommonEventProperties(): PostHogEventProperties {\n return {\n ...super.getCommonEventProperties(),\n $electron_process: 'main',\n $app_name: app.getName(),\n $app_version: app.getVersion(),\n $os_name: process.platform === 'darwin' ? 'macOS' : process.platform === 'win32' ? 'Windows' : 'Linux',\n $os_version: process.getSystemVersion?.() ?? release(),\n $device_type: 'Desktop',\n ...(this._appBuild ? { $app_build: this._appBuild } : {}),\n ...this._eventContext,\n }\n }\n\n withContext<T>(context: PostHogEventProperties, operation: () => T): T {\n const previous = this._eventContext\n this._eventContext = context\n try {\n return operation()\n } finally {\n this._eventContext = previous\n }\n }\n\n invalidateIdentity(): void {\n this._identityEpoch++\n for (const key of [\n PostHogPersistedProperty.FeatureFlagDetails,\n PostHogPersistedProperty.BootstrapFeatureFlagDetails,\n PostHogPersistedProperty.FeatureFlags,\n PostHogPersistedProperty.FeatureFlagPayloads,\n PostHogPersistedProperty.FlagsEndpointWasHit,\n ])\n this.setPersistedProperty(key, null)\n }\n\n async fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {\n if (this._stopped || !this._storage.isOwned || this._suspended) throw new Error('PostHog delivery is inactive')\n const target = new URL(url)\n const host = new URL(this.host)\n const configHost =\n host.hostname === 'us.i.posthog.com'\n ? 'us-assets.i.posthog.com'\n : host.hostname === 'eu.i.posthog.com'\n ? 'eu-assets.i.posthog.com'\n : undefined\n const assetConfig =\n configHost &&\n host.protocol === 'https:' &&\n !host.port &&\n host.pathname === '/' &&\n target.href === `https://${configHost}/array/${this.projectToken}/config` &&\n options.method === 'GET'\n if (\n !assetConfig &&\n (target.origin !== host.origin || !target.pathname.startsWith(host.pathname.replace(/\\/$/, '') + '/'))\n ) {\n throw new Error('PostHog request outside configured host')\n }\n const flagsRequest = target.pathname.endsWith('/flags/') || target.pathname.endsWith('/flags')\n const started = Date.now()\n const controller = new AbortController()\n let responseTimer: ReturnType<typeof setTimeout> | undefined\n const abort = (): void => controller.abort(options.signal?.reason)\n options.signal?.addEventListener('abort', abort, { once: true })\n if (options.signal?.aborted) abort()\n this._controllers.add(controller)\n const cleanup = (): void => {\n clearTimeout(responseTimer)\n options.signal?.removeEventListener('abort', abort)\n controller.signal.removeEventListener('abort', cleanup)\n this._controllers.delete(controller)\n }\n controller.signal.addEventListener('abort', cleanup, { once: true })\n try {\n await app.whenReady()\n if (this._stopped || controller.signal.aborted) throw new Error('PostHog request cancelled')\n const response = await session.fromPartition('posthog-electron').fetch(url, {\n method: options.method,\n headers: options.headers,\n body: options.body,\n signal: controller.signal,\n credentials: 'omit',\n redirect: 'error',\n })\n if (!response.body) cleanup()\n else if (response.status < 200 || response.status >= 300) {\n // Core permits lazy diagnostics until this attempt's deadline, not until shutdown.\n const timeout = flagsRequest ? this._flagsResponseTimeoutMs : this.requestTimeout\n responseTimer = setTimeout(\n () => {\n controller.abort(new Error('PostHog error response body deadline exceeded'))\n void response.body?.cancel().catch(() => {})\n cleanup()\n },\n Math.max(0, timeout - (Date.now() - started)) + 1\n )\n responseTimer.unref()\n }\n return {\n status: response.status,\n headers: response.headers,\n body: response.body\n ? new ReadableStream({\n cancel: async (reason) => {\n try {\n await response.body?.cancel(reason)\n } finally {\n cleanup()\n }\n },\n })\n : null,\n text: async () => {\n try {\n return await response.text()\n } finally {\n cleanup()\n }\n },\n json: async () => {\n try {\n return await response.json()\n } finally {\n cleanup()\n }\n },\n }\n } catch (error) {\n cleanup()\n throw error\n }\n }\n\n protected shouldRetainBatchOnError(error: unknown): boolean {\n if (error instanceof RetryLaterError) return true\n const status = isRecord(error) ? error.status : undefined\n return (\n isPostHogFetchNetworkError(error) ||\n status === 407 ||\n status === 408 ||\n status === 429 ||\n (typeof status === 'number' && status >= 500)\n )\n }\n\n protected async sendBatch(...args: Parameters<PostHogCore['sendBatch']>): Promise<void> {\n if (this._stopped || this._suspended || !this._storage.isOwned || Date.now() < this._retryAt)\n throw new RetryLaterError('PostHog delivery paused')\n try {\n await this._storage.flush()\n } catch (error) {\n throw new RetryLaterError('PostHog storage write failed', { cause: error })\n }\n if (this._stopped || this._suspended) throw new RetryLaterError('PostHog delivery paused')\n try {\n const cutoff = Date.now() - this._maxQueueAgeMs\n const eligible = args[0].filter((message) => {\n const timestamp = message?.timestamp\n return (\n (typeof timestamp === 'string' || timestamp instanceof Date) &&\n new Date(timestamp).getTime() >= cutoff\n )\n })\n if (eligible.length) await super.sendBatch(eligible, args[1], args[2])\n this._failures = 0\n this._retryAt = 0\n } catch (error) {\n if (this.shouldRetainBatchOnError(error)) {\n this._failures++\n const retryAfter = isRecord(error) && typeof error.retryAfterMs === 'number' ? error.retryAfterMs : 0\n const delay = Math.min(60_000, 1000 * 2 ** Math.min(this._failures, 6)) * (0.5 + Math.random() * 0.5)\n this._retryAt = Date.now() + Math.max(retryAfter, delay)\n }\n throw error\n }\n }\n\n protected flushStorage(): Promise<void> {\n return this._storage.flush()\n }\n persist(): Promise<void> {\n return this._storage.flush()\n }\n\n suspend(): void {\n this._suspended = true\n for (const controller of this._controllers) controller.abort()\n }\n\n resume(): void {\n this._suspended = false\n }\n\n stop(): Promise<void> {\n this._stopped = true\n this.disabled = true\n clearTimeout(this._flushTimer)\n for (const controller of this._controllers) controller.abort()\n this._controllers.clear()\n return this._storage.stop()\n }\n}\n","import { BucketedRateLimiter, createLogger, resolveExceptionRateLimiterConfig } from '@posthog/core/utils'\nimport type { EventHint } from '@posthog/core/error-tracking'\n\nexport type ExceptionCapture = (\n error: unknown,\n properties: { $exception_source: string },\n hint: EventHint\n) => Promise<void>\n\n/** Never let reporting failures escape a runtime's global error dispatch. */\nexport function createExceptionObserver(\n canCapture: () => boolean,\n capture: ExceptionCapture,\n isIgnored: (error: unknown, mechanism: string) => boolean = () => false\n): (error: unknown, mechanism: string, source: string) => void {\n const limiter = new BucketedRateLimiter({\n ...resolveExceptionRateLimiterConfig(),\n refillInterval: 1000,\n _logger: createLogger('[PostHog]', () => {}),\n })\n let capturing = false\n return (error, mechanism, source) => {\n try {\n // Check consent before inspecting any part of the error, even its type or message.\n if (capturing || !canCapture()) return\n capturing = true\n try {\n // Ignored errors don't spend the rate limit. isIgnored can run application getters, so it runs\n // inside the reentrancy guard.\n if (isIgnored(error, mechanism) || limiter.consumeRateLimit('exceptions')) return\n void capture(\n error,\n { $exception_source: source },\n { mechanism: { type: mechanism, handled: false } }\n ).catch(() => {})\n } finally {\n capturing = false\n }\n } catch {\n // Error accessors, IPC and consumer hooks may all fail while reporting.\n }\n }\n}\n","import type { ExceptionCapture } from '../shared/exception-autocapture'\nimport { createExceptionObserver } from '../shared/exception-autocapture'\n\n/**\n * Monitor only by default: a rejection listener would change Node's default throw/exit behavior.\n * `captureUnhandledRejections` opts in to that listener anyway, because Electron's main process\n * only warns about rejections and never escalates them to the monitor.\n */\nexport function startProcessExceptionAutocapture(\n canCapture: () => boolean,\n capture: ExceptionCapture,\n captureUnhandledRejections = false\n): () => void {\n const observe = createExceptionObserver(\n canCapture,\n capture,\n (error, mechanism) => mechanism === 'onunhandledrejection' && isAbortError(error)\n )\n const monitor = (error: Error, origin: NodeJS.UncaughtExceptionOrigin): void => {\n const rejection = origin === 'unhandledRejection'\n // The rejection listener reports every rejection, including any Node also escalates here.\n if (rejection && captureUnhandledRejections) return\n observe(\n error,\n rejection ? 'onunhandledrejection' : 'onuncaughtexception',\n rejection ? 'node.process_unhandled_rejection' : 'node.process_uncaught_exception'\n )\n }\n const rejection = (reason: unknown): void =>\n observe(reason, 'onunhandledrejection', 'node.process_unhandled_rejection')\n process.on('uncaughtExceptionMonitor', monitor)\n if (captureUnhandledRejections) process.on('unhandledRejection', rejection)\n return () => {\n process.removeListener('uncaughtExceptionMonitor', monitor)\n process.removeListener('unhandledRejection', rejection)\n }\n}\n\n// An abort the app started itself and never awaited, such as a cancelled fetch. posthog-node ignores these too.\nfunction isAbortError(reason: unknown): boolean {\n try {\n return (\n (typeof reason === 'object' || typeof reason === 'function') &&\n reason !== null &&\n (reason as { name?: unknown }).name === 'AbortError'\n )\n } catch {\n return false\n }\n}\n","import {\n closeSync,\n ftruncateSync,\n openSync,\n promises as fs,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { hostname } from 'node:os'\n\nconst DEFAULT_MAX_STORAGE_BYTES = 5 * 1024 * 1024\nconst DEFAULT_MAX_QUEUE_AGE_MS = 7 * 24 * 60 * 60 * 1000\n\ntype StorageOptions = {\n maxStorageBytes?: number\n maxQueueAgeMs?: number\n onError?: (error: unknown) => void\n}\n\ntype Values = Record<string, unknown>\ntype QueueItem = { message: { timestamp: string | Date } }\n\nfunction isObject(value: unknown): value is Values {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction eventTime(item: QueueItem): number {\n return new Date(item.message.timestamp).getTime()\n}\n\nfunction isQueueItem(value: unknown): value is QueueItem {\n if (!isObject(value) || !Object.hasOwn(value, 'message') || !isObject(value.message)) {\n return false\n }\n const message = value.message\n return (\n Object.hasOwn(message, 'timestamp') &&\n (typeof message.timestamp === 'string' || message.timestamp instanceof Date) &&\n Number.isFinite(new Date(message.timestamp).getTime()) &&\n Object.hasOwn(message, 'event') &&\n typeof message.event === 'string' &&\n Object.hasOwn(message, 'distinct_id') &&\n typeof message.distinct_id === 'string' &&\n Object.hasOwn(message, 'properties') &&\n isObject(message.properties)\n )\n}\n\n/** Exclusively owned local storage. Call load before use; mutations must go through set. */\nexport class ElectronStorage {\n private stopped = false\n private owned = false\n private readonly owner = JSON.stringify({ host: hostname(), pid: process.pid, token: randomUUID() })\n private stopping?: Promise<void>\n private values: Values = Object.create(null)\n private serialized = JSON.stringify({ version: 1, values: {} })\n private revision = 0\n private queueExpiresAt = Infinity\n private persistedRevision = 0\n private pending?: Promise<void>\n private failure?: { error: unknown }\n private loading?: Promise<void>\n private loaded = false\n // Temp file whose rename has been submitted and may still land after the final exit write.\n private renaming?: string\n private finalized = false\n private readonly maxStorageBytes: number\n private readonly maxQueueAgeMs: number\n private readonly file: string\n\n constructor(\n private readonly directory: string,\n private readonly options: StorageOptions = {}\n ) {\n this.file = join(directory, 'state.json')\n this.maxStorageBytes = options.maxStorageBytes ?? DEFAULT_MAX_STORAGE_BYTES\n this.maxQueueAgeMs = options.maxQueueAgeMs ?? DEFAULT_MAX_QUEUE_AGE_MS\n if (!Number.isFinite(this.maxStorageBytes) || this.maxStorageBytes <= 0) {\n throw new RangeError('maxStorageBytes must be positive and finite')\n }\n if (!Number.isFinite(this.maxQueueAgeMs) || this.maxQueueAgeMs < 0) {\n throw new RangeError('maxQueueAgeMs must be nonnegative and finite')\n }\n }\n\n async load(): Promise<void> {\n this.loading ??= this.loadState().finally(() => {\n this.loaded = true\n })\n await this.loading\n }\n\n get isLoaded(): boolean {\n return this.loaded\n }\n\n get isOwned(): boolean {\n return this.owned && !this.stopped\n }\n\n private async acquire(): Promise<void> {\n await fs.mkdir(this.directory, { recursive: true, mode: 0o700 })\n await fs.chmod(this.directory, 0o700)\n const lock = join(this.directory, '.owner')\n try {\n await fs.writeFile(lock, this.owner, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const previous = await fs.readFile(lock, 'utf8')\n const owner: unknown = JSON.parse(previous)\n if (\n !isObject(owner) ||\n owner.host !== hostname() ||\n !Number.isSafeInteger(owner.pid) ||\n (owner.pid as number) <= 0 ||\n typeof owner.token !== 'string' ||\n !/^[a-f0-9-]{36}$/.test(owner.token)\n )\n throw new Error('Unverifiable Electron storage ownership')\n try {\n process.kill(owner.pid as number, 0)\n throw new Error('Electron storage is already owned by another process')\n } catch (probeError) {\n if ((probeError as NodeJS.ErrnoException).code !== 'ESRCH') throw probeError\n }\n // Never delete this tombstone: only one reclaimer may remove this owner generation.\n // A crashed reclaimer requires manual recovery with all application processes stopped.\n await fs.writeFile(join(this.directory, `.reclaim-${owner.token}`), '', { mode: 0o600, flag: 'wx' })\n if ((await fs.readFile(lock, 'utf8')) !== previous) throw new Error('Electron storage owner changed')\n await fs.unlink(lock)\n await fs.writeFile(lock, this.owner, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n }\n this.owned = true\n }\n\n private async loadState(): Promise<void> {\n try {\n if (this.stopped) return\n await this.acquire()\n if (this.stopped) return\n } catch (error) {\n this.values = Object.assign(Object.create(null), { opted_out: true })\n this.report(error)\n return\n }\n let text: string\n try {\n text = await fs.readFile(this.file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return\n }\n this.recover(error)\n return\n }\n if (this.stopped) return\n try {\n const state: unknown = JSON.parse(text)\n if (\n !isObject(state) ||\n !Object.hasOwn(state, 'version') ||\n state.version !== 1 ||\n !Object.hasOwn(state, 'values') ||\n !isObject(state.values) ||\n (Object.hasOwn(state.values, 'opted_out') && typeof state.values.opted_out !== 'boolean')\n ) {\n throw new Error('Invalid Electron storage schema')\n }\n const bounded = this.bound(state.values)\n this.values = bounded.values\n this.serialized = bounded.serialized\n this.queueExpiresAt = bounded.expiresAt\n if (this.serialized !== text) {\n this.revision++\n this.scheduleWrite()\n }\n } catch (error) {\n this.recover(error)\n }\n }\n\n private recover(error: unknown): void {\n if (this.stopped) return\n // Consent cannot safely be inferred from unreadable state. Discard all analytics.\n this.values = Object.assign(Object.create(null), { opted_out: true })\n this.queueExpiresAt = Infinity\n this.serialized = JSON.stringify({ version: 1, values: this.values })\n this.revision++\n this.report(error)\n this.scheduleWrite()\n }\n\n get<T>(key: string): T | undefined {\n if (key === 'queue' && this.isOwned && Date.now() > this.queueExpiresAt) {\n const bounded = this.bound(this.values)\n if (bounded.serialized !== this.serialized) {\n this.values = bounded.values\n this.serialized = bounded.serialized\n this.queueExpiresAt = bounded.expiresAt\n this.revision++\n this.scheduleWrite()\n }\n }\n if (!Object.hasOwn(this.values, key)) return undefined\n const value = this.values[key]\n return (key === 'queue' && Array.isArray(value) ? value.slice() : structuredClone(value)) as T\n }\n\n set<T>(key: string, value: T | null): void {\n if (!this.isOwned) return\n const next: Values = Object.assign(Object.create(null), this.values)\n try {\n if (value === null) {\n delete next[key]\n } else {\n next[key] = structuredClone(value)\n }\n const bounded = this.bound(next)\n this.values = bounded.values\n this.serialized = bounded.serialized\n this.queueExpiresAt = bounded.expiresAt\n } catch (error) {\n this.report(error)\n // In particular, callers must not mistake rejected consent changes for durable ones.\n throw error\n }\n this.revision++\n this.scheduleWrite()\n }\n\n /** Waits for atomic write completion, not an fsync/power-loss durability barrier. */\n async flush(): Promise<void> {\n if (!this.isOwned) return\n // Retention also applies when the queue has been idle since the last write.\n if (Date.now() > this.queueExpiresAt) {\n const bounded = this.bound(this.values)\n this.values = bounded.values\n this.serialized = bounded.serialized\n this.queueExpiresAt = bounded.expiresAt\n this.revision++\n this.scheduleWrite()\n }\n if (!this.pending && this.persistedRevision < this.revision) {\n this.scheduleWrite()\n }\n while (this.pending) {\n await this.pending\n }\n if (this.persistedRevision < this.revision && this.failure) {\n throw this.failure.error\n }\n }\n\n private bound(input: Values): { values: Values; serialized: string; expiresAt: number } {\n const values: Values = Object.assign(Object.create(null), input)\n let queue: QueueItem[] | undefined\n if (Object.hasOwn(values, 'queue')) {\n if (!Array.isArray(values.queue) || !values.queue.every(isQueueItem)) {\n throw new Error('Invalid Electron event queue')\n }\n const cutoff = Date.now() - this.maxQueueAgeMs\n queue = values.queue.filter((item) => eventTime(item) >= cutoff)\n values.queue = queue\n }\n let serialized = JSON.stringify({ version: 1, values })\n let bytes = Buffer.byteLength(serialized, 'utf8')\n if (bytes > this.maxStorageBytes && queue?.length) {\n const oldest = queue\n .map((item, index) => ({ item, index }))\n .sort((a, b) => eventTime(a.item) - eventTime(b.item))\n const removed = new Set<number>()\n for (const { item, index } of oldest) {\n if (bytes <= this.maxStorageBytes) {\n break\n }\n bytes -= Buffer.byteLength(JSON.stringify(item), 'utf8') + (queue.length - removed.size > 1 ? 1 : 0)\n removed.add(index)\n }\n queue = queue.filter((_, index) => !removed.has(index))\n values.queue = queue\n serialized = JSON.stringify({ version: 1, values })\n }\n if (Buffer.byteLength(serialized, 'utf8') > this.maxStorageBytes) {\n throw new RangeError('Electron storage exceeds maxStorageBytes after removing queued events')\n }\n const expiresAt =\n queue?.reduce((next, item) => Math.min(next, eventTime(item) + this.maxQueueAgeMs), Infinity) ?? Infinity\n return { values, serialized, expiresAt }\n }\n\n /** Final process-exit only: never race asynchronous loading, writing or ownership release. */\n releaseOnExit(): void {\n if (!this.owned || !this.loaded || this.stopping || this.stopped) return\n // The SDK never blocks quit, so persist unsaved state (notably consent) with a blocking write.\n if (this.persistedRevision < this.revision) this.writeOnExit()\n // An older async rename may still land after this; keep ownership as before.\n if (this.pending) return\n this.stopped = true\n const lock = join(this.directory, '.owner')\n try {\n if (readFileSync(lock, 'utf8') === this.owner) unlinkSync(lock)\n } catch (error) {\n this.report(error)\n } finally {\n this.owned = false\n }\n }\n\n stop(): Promise<void> {\n this.stopped = true\n return (this.stopping ??= (async () => {\n await this.loading\n await this.pending?.catch(() => {})\n if (!this.owned) return\n const lock = join(this.directory, '.owner')\n try {\n if ((await fs.readFile(lock, 'utf8')) === this.owner) await fs.unlink(lock)\n } catch (error) {\n this.report(error)\n } finally {\n this.owned = false\n }\n })())\n }\n\n private scheduleWrite(): void {\n if (!this.isOwned || this.pending) {\n return\n }\n this.failure = undefined\n let attemptedRevision = this.persistedRevision\n const pending = Promise.resolve().then(async () => {\n while (!this.stopped && this.persistedRevision < this.revision) {\n attemptedRevision = this.revision\n const serialized = this.serialized\n await this.write(serialized)\n this.persistedRevision = Math.max(this.persistedRevision, attemptedRevision)\n }\n })\n this.pending = pending\n // Attach a rejection handler even when the caller does not ask for a durability ack.\n void pending.then(\n () => {\n this.pending = undefined\n // A set can land between the worker returning and this settlement handler.\n if (this.persistedRevision < this.revision) {\n this.scheduleWrite()\n }\n },\n (error: unknown) => {\n this.failure = { error }\n this.pending = undefined\n this.report(error)\n if (attemptedRevision < this.revision) {\n this.scheduleWrite()\n }\n }\n )\n }\n\n private writeOnExit(): void {\n if (Buffer.byteLength(this.serialized, 'utf8') > this.maxStorageBytes) {\n this.report(new RangeError('Electron storage exceeds maxStorageBytes'))\n return\n }\n // A submitted rename cannot be cancelled. Overwrite its source in place first (never create it):\n // if it already landed, the rename below replaces it; otherwise it now carries the final state.\n if (this.renaming) {\n let fd: number | undefined\n try {\n fd = openSync(this.renaming, 'r+')\n ftruncateSync(fd, 0)\n writeSync(fd, this.serialized, 0, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') this.report(error)\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n }\n const temporary = join(this.directory, `.state-${randomUUID()}.tmp`)\n try {\n writeFileSync(temporary, this.serialized, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n renameSync(temporary, this.file)\n this.persistedRevision = this.revision\n this.finalized = true\n } catch (error) {\n this.report(error)\n try {\n unlinkSync(temporary)\n } catch {}\n }\n }\n\n private async write(serialized: string): Promise<void> {\n if (Buffer.byteLength(serialized, 'utf8') > this.maxStorageBytes) {\n throw new RangeError('Electron storage exceeds maxStorageBytes')\n }\n await fs.mkdir(this.directory, { recursive: true, mode: 0o700 })\n await fs.chmod(this.directory, 0o700)\n const temporary = join(this.directory, `.state-${randomUUID()}.tmp`)\n try {\n await fs.writeFile(temporary, serialized, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n if (this.finalized) return\n // stop() retains ownership until this already-started write settles.\n this.renaming = temporary\n await fs.rename(temporary, this.file)\n } finally {\n if (this.renaming === temporary) this.renaming = undefined\n await fs.unlink(temporary).catch((error: NodeJS.ErrnoException) => {\n if (error.code !== 'ENOENT') {\n this.report(error)\n }\n })\n }\n }\n\n private report(error: unknown): void {\n try {\n this.options.onError?.(error)\n } catch {\n // Error reporting must never break storage recovery or background writes.\n }\n }\n}\n","import {\n assertJson,\n isRecord,\n MAX_MESSAGE_BYTES,\n PROTOCOL_VERSION,\n type Response,\n type State,\n} from '../shared/protocol'\n\nexport const UTILITY_CHANNEL = 'posthog:utility:v1'\nexport const UTILITY_TIMEOUT_MS = 10_000\n\nexport function envelope(message: Record<string, unknown>): Record<string, unknown> {\n return { channel: UTILITY_CHANNEL, version: PROTOCOL_VERSION, ...message }\n}\n\n// Application messages may share parentPort, but never enter the SDK command path.\nexport function readEnvelope(\n value: unknown,\n direction: 'to-main' | 'to-utility' = 'to-main'\n): Record<string, unknown> | undefined {\n if (!isRecord(value) || value.channel !== UTILITY_CHANNEL) return\n assertJson(value, 0, direction === 'to-utility')\n if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_MESSAGE_BYTES) {\n throw new Error('PostHog utility message exceeds 256 KiB')\n }\n if (value.version !== PROTOCOL_VERSION) throw new Error('Unsupported PostHog utility protocol')\n return value\n}\n\nexport function isState(value: unknown): value is State {\n return (\n isRecord(value) &&\n ['revision', 'generation', 'flagRevision'].every(\n (key) => Number.isSafeInteger(value[key]) && (value[key] as number) >= 0\n ) &&\n ['distinctId', 'anonymousId', 'sessionId'].every((key) => typeof value[key] === 'string') &&\n typeof value.optedOut === 'boolean' &&\n (value.flagsLoaded === undefined || typeof value.flagsLoaded === 'boolean') &&\n isRecord(value.featureFlags) &&\n Object.values(value.featureFlags).every((flag) => typeof flag === 'boolean' || typeof flag === 'string') &&\n isRecord(value.featureFlagPayloads)\n )\n}\n\nexport function isResponse(value: unknown): value is Response {\n return (\n isRecord(value) &&\n ((value.ok === true && isState(value.state)) || (value.ok === false && typeof value.error === 'string'))\n )\n}\n","import type { UtilityProcess } from 'electron'\nimport { randomUUID } from 'node:crypto'\nimport { validateRequest, type Command, type Properties, type Response, type State } from '../shared/protocol'\nimport { envelope, readEnvelope, UTILITY_TIMEOUT_MS } from './protocol'\n\nexport interface UtilityRegistration {\n publish(state: State): void\n dispose(): void\n}\n\nexport function attachUtilityProcess(\n child: UtilityProcess,\n execute: (command: Command, context: Properties, generation: number, authorize: () => void) => Promise<void>,\n getState: () => State,\n removed: () => void\n): UtilityRegistration {\n const token = randomUUID()\n const context: Properties = { $electron_process: 'utility', $utility_process_id: randomUUID() }\n let active = true\n let connected = false\n let sequence = 0\n let requests = 0\n let period = performance.now()\n const pending = new Set<(error: Error) => void>()\n const authorize = (): void => {\n if (!active) throw new Error('PostHog utility process disconnected')\n }\n const send = (message: Record<string, unknown>): void => {\n if (!active) return\n try {\n const value = envelope(message)\n // Bound outbound state too: never flood a child with a large flag cache.\n readEnvelope(value, 'to-utility')\n child.postMessage(value)\n } catch {\n dispose()\n }\n }\n const dispose = (): void => {\n if (!active) return\n try {\n child.postMessage(envelope({ kind: 'closed', token }))\n } catch {}\n active = false\n clearTimeout(handshakeTimer)\n child.removeListener('message', message)\n child.removeListener('exit', dispose)\n for (const reject of pending) reject(new Error('PostHog utility process disconnected'))\n pending.clear()\n removed()\n }\n const message = (value: unknown): void => {\n if (!active) return\n let requestSequence: number | undefined\n try {\n const data = readEnvelope(value)\n if (!data) return\n if (performance.now() - period >= 1000) {\n period = performance.now()\n requests = 0\n }\n const rateLimited = ++requests > 100\n if (data.kind === 'connect') {\n if (rateLimited) throw new Error('PostHog utility rate limit exceeded')\n connected = true\n send({ kind: 'connected', token })\n return\n }\n if (!connected || data.kind !== 'request' || data.token !== token)\n throw new Error('Invalid PostHog utility connection')\n validateRequest(data.request)\n const request = data.request\n requestSequence = request.sequence\n if (request.sequence !== sequence + 1) throw new Error('Out-of-order PostHog utility request')\n if (request.sequence !== 1 && request.command.type === 'hello')\n throw new Error('Duplicate PostHog utility handshake')\n if (request.sequence === 1 && request.command.type !== 'hello')\n throw new Error('PostHog utility handshake required')\n sequence = request.sequence\n // Authenticated overload rejections consume their sequence so later work can recover.\n if (rateLimited) throw new Error('PostHog utility rate limit exceeded')\n if (pending.size >= 100) throw new Error('Too many pending PostHog utility requests')\n clearTimeout(handshakeTimer)\n let rejectClosed!: (error: Error) => void\n const closed = new Promise<never>((_resolve, reject) => {\n rejectClosed = reject\n })\n pending.add(rejectClosed)\n void Promise.race([execute(request.command, context, request.generation, authorize), closed])\n .then(() => {\n authorize()\n const response: Response = { ok: true, state: getState() }\n send({ kind: 'response', token, sequence: request.sequence, response })\n })\n .catch((error: unknown) => {\n send({\n kind: 'response',\n token,\n sequence: request.sequence,\n response: {\n ok: false,\n error: error instanceof Error ? error.message : 'PostHog utility request failed',\n },\n })\n })\n .finally(() => pending.delete(rejectClosed))\n } catch (error) {\n if (requestSequence !== undefined) {\n send({\n kind: 'response',\n token,\n sequence: requestSequence,\n response: {\n ok: false,\n error: error instanceof Error ? error.message : 'Invalid PostHog utility request',\n },\n })\n } else dispose()\n }\n }\n // pid is undefined both before spawn and after exit; a bounded handshake handles both.\n const handshakeTimer = setTimeout(dispose, UTILITY_TIMEOUT_MS)\n handshakeTimer.unref()\n child.on('message', message)\n child.once('exit', dispose)\n return {\n publish: (state) => {\n if (connected) send({ kind: 'state', token, state })\n },\n dispose,\n }\n}\n","import {\n app,\n powerMonitor,\n ipcMain,\n type BrowserWindow,\n type IpcMainInvokeEvent,\n type WebContents,\n type UtilityProcess,\n} from 'electron'\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport {\n PostHogPersistedProperty,\n flagDetailsToResults,\n type PostHogCoreOptions,\n type PostHogFeatureFlagDetails,\n type FeatureFlagValue,\n type JsonType,\n} from '@posthog/core'\nimport type { EventHint } from '@posthog/core/error-tracking'\nimport { ElectronCore } from './client'\nimport { startProcessExceptionAutocapture } from './exception-autocapture'\nimport { ElectronStorage } from './storage'\nimport { attachUtilityProcess, type UtilityRegistration } from '../utility/attach'\nimport {\n COMMAND_CHANNEL,\n STATE_CHANNEL,\n validateRequest,\n trustedUrl,\n normalizeFlagResult,\n isFlagContextCommand,\n type FeatureFlagReadOptions,\n type IsFeatureEnabledOptions,\n type FeatureFlagResult,\n type Command,\n type Properties,\n type Response,\n type State,\n} from '../shared/protocol'\n\nexport type {\n State,\n Properties,\n FeatureFlagValue,\n FeatureFlagResult,\n FeatureFlagReadOptions,\n IsFeatureEnabledOptions,\n JsonType,\n}\n\nexport interface PostHogOptions extends Pick<\n PostHogCoreOptions,\n | 'host'\n | 'flushAt'\n | 'flushInterval'\n | 'maxBatchSize'\n | 'maxQueueSize'\n | 'requestTimeout'\n | 'fetchRetryCount'\n | 'fetchRetryDelay'\n | 'preloadFeatureFlags'\n | 'disableRemoteFeatureFlags'\n | 'disableRemoteConfig'\n | 'remoteConfigRequestTimeoutMs'\n | 'defaultOptIn'\n | 'disabled'\n | 'bootstrap'\n | 'before_send'\n | 'personProfiles'\n | 'sessionExpirationTimeSeconds'\n | 'disableGeoip'\n | 'disableCompression'\n | 'featureFlagsRequestTimeoutMs'\n | 'featureFlagsRequestMaxRetries'\n> {\n projectToken: string\n storageDirectory?: string\n maxStorageBytes?: number\n maxQueueAgeMs?: number\n captureAppLifecycleEvents?: boolean\n enableExceptionAutocapture?: boolean\n /**\n * Also installs a `process.on('unhandledRejection')` listener to capture main-process rejections.\n * Requires `enableExceptionAutocapture`. While the listener is installed, Node skips its default\n * handling: an unhandled rejection no longer prints `UnhandledPromiseRejectionWarning` or sets\n * `process.exitCode = 1`. This lasts until shutdown, even while the user is opted out. Off by default.\n */\n captureUnhandledRejections?: boolean\n appBuild?: string\n onError?: (error: unknown) => void\n}\n\ninterface RegisteredWindow {\n contents: WebContents\n allowedUrls: readonly string[]\n sequence: number\n frame: number | undefined\n requests: number\n period: number\n dispose: () => void\n}\n\nlet singleton: PostHog | undefined\nlet singletonOptions: Pick<PostHogOptions, 'projectToken' | 'host'> | undefined\n\n// Copy caller data with JSON semantics so a caller's toJSON() redaction applies, matching the renderer.\n// structuredClone still runs first so non-cloneable input keeps rejecting.\nfunction snapshot<T>(value: T): T {\n structuredClone(value)\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport class PostHog {\n private _core: ElectronCore\n private _ready: Promise<void>\n private _windows = new Map<number, RegisteredWindow>()\n private _utilities = new Map<UtilityProcess, UtilityRegistration>()\n private _revision = 0\n private _generation = 0\n private _closed = false\n private _closing = false\n private _shutdownPromise?: Promise<void>\n private _notifyPending = false\n private _lastPublished = ''\n private _flagRevision = 0\n private _lastFlags = ''\n private _reportedPayloadErrors = new Map<string, string>()\n private _focusTimer?: ReturnType<typeof setTimeout>\n private _timer?: ReturnType<typeof setInterval>\n private _foreground = false\n private _stopExceptionAutocapture?: () => void\n private _cancelReady!: () => void\n private _cleanups: (() => void)[] = []\n private _tail: Promise<unknown> = Promise.resolve()\n private _readyForSnapshots = false\n private _pendingConsent = 0\n // Latest consent change requested but not yet applied by the mutation queue.\n private _requestedConsent?: { optedOut: boolean; token: number }\n private _consentToken = 0\n\n constructor(private _options: PostHogOptions) {\n if (singleton) throw new Error('PostHog Electron is already initialized; use init()')\n if (!this._options.projectToken?.trim()) throw new Error('PostHog projectToken is required')\n const host = new URL(this._options.host ?? 'https://us.i.posthog.com')\n if (\n !['http:', 'https:'].includes(host.protocol) ||\n host.username ||\n host.password ||\n host.search ||\n host.hash\n ) {\n throw new Error('PostHog host must be an HTTP(S) URL without credentials, query or fragment')\n }\n const namespace = createHash('sha256')\n .update(this._options.projectToken.trim() + host.href)\n .digest('hex')\n .slice(0, 24)\n const directory = join(this._options.storageDirectory ?? join(app.getPath('userData'), 'posthog'), namespace)\n const storage = new ElectronStorage(directory, {\n maxStorageBytes: this._options.maxStorageBytes,\n maxQueueAgeMs: this._options.maxQueueAgeMs,\n onError: (error) => this._report(error),\n })\n this._core = new ElectronCore(\n this._options.projectToken,\n { ...this._options, host: host.href },\n storage,\n () => this._scheduleState(),\n (error) => this._report(error)\n )\n const exit = (): void => {\n // Quit is never delayed, so a queued consent change is applied before the final blocking write.\n if (this._requestedConsent && storage.isLoaded) {\n this._core.setPersistedProperty(PostHogPersistedProperty.OptedOut, this._requestedConsent.optedOut)\n }\n storage.releaseOnExit()\n }\n process.once('exit', exit)\n this._cleanups.push(() => process.removeListener('exit', exit))\n singleton = this\n singletonOptions = { projectToken: this._options.projectToken, host: this._options.host }\n ipcMain.handle(COMMAND_CHANNEL, (event, request: unknown) => this._handle(event, request))\n this._ready = Promise.race([\n this._initialize(),\n new Promise<void>((resolve) => {\n this._cancelReady = resolve\n }),\n ]).then(() => {\n this._readyForSnapshots = true\n })\n }\n\n private _report(error: unknown): void {\n try {\n this._options.onError?.(error)\n } catch {}\n }\n\n private async _initialize(): Promise<void> {\n await this._core.ready()\n if (this._closing || this._core.isDisabled) return\n await app.whenReady()\n if (this._closing) return\n if (!this._closing && this._options.enableExceptionAutocapture === true) {\n this._stopExceptionAutocapture = startProcessExceptionAutocapture(\n () => !this._closing && !this._core.isDisabled && !this._core.optedOut,\n (error, properties, hint) => this._captureException(error, properties, hint),\n this._options.captureUnhandledRejections === true\n )\n }\n if (!this._core.isDisabled && this._options.captureAppLifecycleEvents !== false) {\n const previous = this._core.getPersistedProperty<string>(PostHogPersistedProperty.InstalledAppVersion)\n const previousBuild = this._core.getPersistedProperty<string>(PostHogPersistedProperty.InstalledAppBuild)\n const version = app.getVersion()\n const build = this._options.appBuild\n const properties = {\n $electron_version: process.versions.electron,\n $node_version: process.versions.node,\n $chromium_version: process.versions.chrome,\n ...(build ? { $app_build: build } : {}),\n }\n if (!previous) this._core.capture('Application Installed', properties)\n else if (previous !== version || previousBuild !== build)\n this._core.capture('Application Updated', {\n ...properties,\n previous_version: previous,\n ...(previousBuild ? { previous_build: previousBuild } : {}),\n })\n this._core.setPersistedProperty(PostHogPersistedProperty.InstalledAppVersion, version)\n this._core.setPersistedProperty(PostHogPersistedProperty.InstalledAppBuild, build ?? null)\n this._core.capture('Application Opened', { from_background: false })\n this._foreground = true\n }\n const interval = this._options.flushInterval ?? 10_000\n if (interval > 0) {\n this._timer = setInterval(() => {\n if (!this._closing) void this._core.flush().catch((error) => this._report(error))\n }, interval)\n this._timer.unref()\n }\n const suspend = (): void => this._core.suspend()\n const resume = (): void => {\n this._core.resume()\n if (!this._closing) void this.flush().catch((error) => this._report(error))\n }\n powerMonitor.on('suspend', suspend)\n powerMonitor.on('resume', resume)\n this._cleanups.push(() => {\n powerMonitor.removeListener('suspend', suspend)\n powerMonitor.removeListener('resume', resume)\n })\n const quit = (event: Electron.Event): void => {\n if (this._closed || event.defaultPrevented) return\n // Observe cancellation by other will-quit listeners too. Do not force a second quit.\n queueMicrotask(() => {\n if (event.defaultPrevented) return\n void this.flush().catch((error) => this._report(error))\n })\n }\n app.on('will-quit', quit)\n this._cleanups.push(() => app.removeListener('will-quit', quit))\n if (this._core.preloadFeatureFlags && !this._core.isDisabled) {\n void this._core.reloadFeatureFlagsAsync().catch((error) => this._report(error))\n }\n // Storage already reports failed writes and retries on later mutations. Readiness is not a write receipt.\n await this._core.persist().catch(() => {})\n this._scheduleState()\n }\n\n ready(): Promise<void> {\n return this._ready\n }\n\n private async _run(\n operation: () => void | Promise<unknown>,\n generation?: number,\n authorize?: () => void,\n changesConsent = false,\n shouldRun?: () => boolean\n ): Promise<void> {\n if (this._closing) throw new Error('PostHog is shut down')\n if (changesConsent) this._pendingConsent++\n const pending = this._tail\n .then(async () => {\n await this._ready\n if (this._closed) throw new Error('PostHog is shut down')\n if (generation !== undefined && generation !== this._generation)\n throw new Error('Stale PostHog identity')\n authorize?.()\n if (shouldRun && !shouldRun()) return\n await operation()\n await this._core.persist()\n this._scheduleState()\n })\n .finally(() => {\n if (changesConsent) this._pendingConsent--\n })\n this._tail = pending.catch(() => {})\n return pending\n }\n\n /**\n * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; captures\n * after shutdown are dropped. A capture after an unawaited `identify()` or `reset()` uses the new identity.\n */\n capture(event: string, properties?: Properties): void {\n if (typeof event !== 'string' || !event.trim() || event === '$snapshot') return\n this._captureEvent(event, properties)\n }\n private _captureEvent(event: string, properties: Properties | undefined, screenName?: string): void {\n let copy: Properties | undefined\n try {\n // The caller can't await capture, so copy properties now rather than when the queued work runs.\n copy = this._snapshotEventProperties(properties)\n } catch (error) {\n this._report(error)\n return\n }\n void this._run(() => {\n if (this._core.optedOut || this._core.isDisabled) return\n let captured: Properties | undefined\n try {\n // copy may still be the caller's object when inspection was deferred; apply toJSON before capturing.\n captured = copy === undefined ? undefined : snapshot(copy)\n } catch (error) {\n this._report(error)\n return\n }\n // A screen name wins over a supplied $screen_name.\n this._core.capture(event, screenName === undefined ? captured : { ...captured, $screen_name: screenName })\n }).catch(() => {\n // Storage reports its own write failures through onError; shutdown and identity changes drop the event.\n })\n }\n /**\n * Link the current distinct ID to an alias without switching identity or reloading flags.\n * Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.\n */\n alias(alias: string): Promise<void> {\n if (!alias?.trim()) return Promise.resolve()\n return this._run(() => this._alias(alias))\n }\n private _alias(alias: string): void {\n if (!this._core.optedOut) this._core.alias(alias)\n }\n private _snapshotEventProperties(properties?: Properties): Properties | undefined {\n // Unknown persisted consent and queued consent changes must settle before inspecting caller data.\n if (\n this._closing ||\n !this._readyForSnapshots ||\n this._pendingConsent ||\n this._core.optedOut ||\n this._core.isDisabled\n ) {\n return properties\n }\n return properties === undefined ? undefined : snapshot(properties)\n }\n /**\n * Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.\n * Fire-and-forget: never throws or rejects; ignored when opted out.\n */\n screen(name: string, properties?: Properties): void {\n if (typeof name !== 'string' || !name.trim()) return\n this._captureEvent('$screen', properties, name)\n }\n /**\n * Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.\n * Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.\n * Ignored when opted out or personProfiles is 'never'.\n */\n async setPersonProperties(properties?: Properties, propertiesOnce?: Properties): Promise<void> {\n const set = this._snapshotEventProperties(properties)\n const once = this._snapshotEventProperties(propertiesOnce)\n return this._run(() => this._setPersonProperties(set, once))\n }\n private _setPersonProperties(properties?: Properties, propertiesOnce?: Properties): void {\n if (this._core.optedOut || this._core.isDisabled) return\n const set = properties === undefined ? undefined : snapshot(properties)\n const once = propertiesOnce === undefined ? undefined : snapshot(propertiesOnce)\n this._core.setPersonProperties(set, once)\n }\n /**\n * Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.\n * Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.\n * With false, only saves context; cached flag values stay unchanged until a reload.\n */\n async setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags = true): Promise<void> {\n const copy = snapshot(properties)\n return this._runFlagContext(() => this._setPersonPropertiesForFlags(copy, reloadFeatureFlags))\n }\n private async _setPersonPropertiesForFlags(properties: Properties, reload: boolean): Promise<void> {\n if (!Object.keys(properties).length) return\n this._core.setPersonPropertiesForFlags(properties, false)\n if (reload) await this._core.reloadFeatureFlagsAsync()\n }\n /**\n * Merge a call-time copy of local overrides by group type, without changing profiles or group membership.\n * Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.\n * With false, only saves context; cached flag values stay unchanged until a reload.\n */\n async setGroupPropertiesForFlags(properties: Record<string, Properties>, reloadFeatureFlags = true): Promise<void> {\n const copy = snapshot(properties)\n return this._runFlagContext(() => this._setGroupPropertiesForFlags(copy, reloadFeatureFlags))\n }\n private async _setGroupPropertiesForFlags(properties: Record<string, Properties>, reload: boolean): Promise<void> {\n if (!Object.keys(properties).length) return\n this._core.setGroupPropertiesForFlags(properties)\n if (reload) await this._core.reloadFeatureFlagsAsync()\n }\n /**\n * Clear all local person flag overrides, not profile data or identity. Resolves after persistence.\n * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.\n */\n resetPersonPropertiesForFlags(reloadFeatureFlags = false): Promise<void> {\n return this._runFlagContext(() => this._resetPersonPropertiesForFlags(reloadFeatureFlags))\n }\n private async _resetPersonPropertiesForFlags(reload: boolean): Promise<void> {\n this._core.resetPersonPropertiesForFlags()\n if (reload) await this._core.reloadFeatureFlagsAsync()\n }\n /**\n * Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.\n * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.\n */\n resetGroupPropertiesForFlags(reloadFeatureFlags = false): Promise<void> {\n return this._runFlagContext(() => this._resetGroupPropertiesForFlags(reloadFeatureFlags))\n }\n private async _resetGroupPropertiesForFlags(reload: boolean): Promise<void> {\n this._core.resetGroupPropertiesForFlags()\n if (reload) await this._core.reloadFeatureFlagsAsync()\n }\n private async _runFlagContext(\n operation: () => void | Promise<unknown>,\n generation?: number,\n authorize?: () => void\n ): Promise<void> {\n let reloading: Promise<unknown> = Promise.resolve()\n await this._run(\n () => {\n reloading = Promise.resolve(operation())\n // Observe a rejection while persistence is pending, without holding the mutation tail on networking.\n void reloading.catch(() => {})\n },\n generation,\n authorize\n )\n await reloading\n await this._core.persist()\n this._scheduleState()\n }\n identify(distinctId: string, properties?: Properties): Promise<void> {\n if (!distinctId?.trim()) return Promise.resolve()\n return this._run(() => this._identify(distinctId, properties))\n }\n private _identify(distinctId: string, properties?: Properties): void {\n if (!this._core.canIdentify()) {\n this._core.identify(distinctId, properties)\n return\n }\n if (distinctId !== this._core.getDistinctId()) {\n this._generation++\n this._core.invalidateIdentity()\n }\n this._core.identify(distinctId, properties)\n }\n reset(): Promise<void> {\n return this._run(() => this._reset())\n }\n private _reset(): void {\n this._generation++\n this._core.invalidateIdentity()\n const optedOut = this._core.optedOut\n this._core.reset([\n PostHogPersistedProperty.OptedOut,\n PostHogPersistedProperty.RemoteConfig,\n PostHogPersistedProperty.InstalledAppVersion,\n PostHogPersistedProperty.InstalledAppBuild,\n ])\n this._core.setPersistedProperty(PostHogPersistedProperty.OptedOut, optedOut)\n this._core.getDistinctId()\n this._core.getSessionId()\n }\n group(type: string, key: string | number, properties?: Properties): Promise<void> {\n return this._run(() => this._core.group(type, key, properties))\n }\n register(properties: Properties): Promise<void> {\n return this._run(() => this._core.register(properties))\n }\n unregister(key: string): Promise<void> {\n return this._run(() => this._core.unregister(key))\n }\n optIn(): Promise<void> {\n return this._changeConsent(false)\n }\n optOut(): Promise<void> {\n return this._changeConsent(true)\n }\n private _changeConsent(optedOut: boolean, generation?: number, authorize?: () => void): Promise<void> {\n const requested = { optedOut, token: ++this._consentToken }\n if (!this._closing) this._requestedConsent = requested\n return this._run(() => (optedOut ? this._optOut() : this._core.optIn()), generation, authorize, true).finally(\n () => {\n if (this._requestedConsent === requested) this._requestedConsent = undefined\n }\n )\n }\n private async _optOut(): Promise<void> {\n this._generation++\n await this._core.optOut()\n }\n /**\n * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; reports after\n * shutdown or across an identity change are dropped.\n */\n captureException(error: unknown, properties?: Properties): void {\n void this._captureException(error, properties).catch(() => {})\n }\n protected _captureException(error: unknown, properties?: Properties, hint?: EventHint): Promise<void> {\n const canCapture = (): boolean => !this._core.isDisabled && !this._core.optedOut\n if (!canCapture()) return Promise.resolve()\n return this._run(\n () => {\n if (this._core.optedOut || this._core.isDisabled) return\n try {\n const exception = this._core.getErrorPropertiesBuilder().buildFromUnknown(error, hint)\n this._core.capture('$exception', { ...properties, ...exception } as unknown as Properties, {\n _originatedFromCaptureException: true,\n })\n } catch (captureError) {\n this._report(captureError)\n }\n },\n this._generation,\n undefined,\n false,\n canCapture\n )\n }\n getDistinctId(): string {\n return this._core.getDistinctId()\n }\n /** Return the shared anonymous ID, stable across identify and rotated by reset; await ready() first. */\n getAnonymousId(): string {\n return this._core.getAnonymousId()\n }\n /** Read cached consent; await ready() before relying on persisted consent. */\n hasOptedOutCapturing(): boolean {\n return this._core.optedOut\n }\n getSessionId(): string {\n return this._core.isDisabled ? '' : this._core.getSessionId()\n }\n /**\n * Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.\n * Reports a deduplicated exposure by default; sendFeatureFlagEvent: false suppresses it.\n */\n getFeatureFlag(key: string, options?: FeatureFlagReadOptions): FeatureFlagValue | undefined {\n return this._core.getFeatureFlag(key, { sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent })\n }\n /**\n * Read cached enabled state without fetching; empty variants are disabled. defaultValue applies only to\n * unknown/unavailable flags. Without it, missing-key behavior matches getFeatureFlag().\n * Reports exposure by default; sendFeatureFlagEvent: false suppresses it.\n */\n isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & { defaultValue: boolean }): boolean\n /**\n * Read cached enabled state without fetching; empty variants are disabled. Missing keys follow getFeatureFlag()\n * unless defaultValue is supplied. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.\n */\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined\n isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined {\n return this._core.isFeatureEnabled(key, {\n sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent,\n defaultValue: options?.defaultValue,\n })\n }\n /**\n * Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.\n * Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.\n */\n getFeatureFlagResult(key: string, options?: FeatureFlagReadOptions): FeatureFlagResult | undefined {\n const result = this._core.getFeatureFlagResult(key, {\n sendEvent: options?.sendFeatureFlagEvent ?? options?.sendEvent,\n })\n return result === undefined ? undefined : this._copyFlagResult(result)\n }\n private _copyFlagResult(result: FeatureFlagResult): FeatureFlagResult {\n return normalizeFlagResult({ ...result, payload: this.getFeatureFlagPayload(result.key) ?? null })\n }\n /** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */\n getAllFeatureFlags(): FeatureFlagResult[] {\n const details = this._core.getFeatureFlagDetails()\n this._prunePayloadErrors(details)\n return flagDetailsToResults(details?.flags ?? {}).map((result) =>\n normalizeFlagResult({ ...result, payload: this._decodeFlagPayload(result.key, details) ?? null })\n )\n }\n /**\n * Read a copied, decoded cached payload without fetching or reporting exposure.\n * Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.\n */\n getFeatureFlagPayload(key: string): JsonType | undefined {\n const details = this._core.getFeatureFlagDetails()\n this._prunePayloadErrors(details)\n return this._decodeFlagPayload(key, details)\n }\n private _prunePayloadErrors(details: PostHogFeatureFlagDetails | undefined): void {\n // Retain only the current malformed value per current flag, not a history of raw payloads.\n for (const [reportedKey, reportedRaw] of this._reportedPayloadErrors) {\n if (\n !details ||\n !Object.prototype.hasOwnProperty.call(details.flags, reportedKey) ||\n details.flags[reportedKey].metadata?.payload !== reportedRaw\n ) {\n this._reportedPayloadErrors.delete(reportedKey)\n }\n }\n }\n private _decodeFlagPayload(key: string, details: PostHogFeatureFlagDetails | undefined): JsonType | undefined {\n if (!details) return undefined\n const raw = Object.prototype.hasOwnProperty.call(details.flags, key)\n ? details.flags[key].metadata?.payload\n : undefined\n if (raw === undefined) return null\n // Decode raw metadata once; never reparse a decoded string in the renderer or result adapters.\n try {\n return JSON.parse(raw) as JsonType\n } catch (error) {\n if (this._reportedPayloadErrors.get(key) !== raw) {\n // Mark before invoking application code, which may capture this SDK error.\n this._reportedPayloadErrors.set(key, raw)\n this._report(new Error(`PostHog could not decode payload for flag \"${key}\"`, { cause: error }))\n }\n return null\n }\n }\n get optedOut(): boolean {\n return this._core.optedOut\n }\n /**\n * Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.\n * A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.\n */\n reloadFeatureFlags(): Promise<void> {\n return this._reloadFeatureFlags()\n }\n /** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */\n reloadFeatureFlagsAsync(): Promise<void> {\n return this.reloadFeatureFlags()\n }\n private async _reloadFeatureFlags(generation?: number, authorize?: () => void): Promise<void> {\n await this._ready\n await this._tail\n if (this._closing) return\n if (generation !== undefined && generation !== this._generation) throw new Error('Stale PostHog identity')\n authorize?.()\n await this._core.reloadFeatureFlagsAsync()\n await this._core.persist()\n this._scheduleState()\n }\n flush(): Promise<void> {\n return this._flush()\n }\n private async _flush(authorize?: () => void): Promise<void> {\n await this._ready\n await this._tail\n if (this._closed) return\n authorize?.()\n await this._core.flush()\n await this._core.persist()\n }\n\n getState(): State {\n const details = this._core.getFeatureFlagDetails()\n this._prunePayloadErrors(details)\n const flags = details?.featureFlags ?? {}\n const payloads: Record<string, JsonType> = Object.create(null)\n for (const key of Object.keys(flags)) {\n const payload = this._decodeFlagPayload(key, details)\n if (payload !== undefined) payloads[key] = payload\n }\n return structuredClone({\n revision: this._revision,\n generation: this._generation,\n distinctId: this._core.getDistinctId(),\n anonymousId: this._core.getAnonymousId(),\n sessionId: this._core.getPersistedProperty<string>(PostHogPersistedProperty.SessionId) ?? '',\n optedOut: this._core.optedOut,\n disabled: this._core.isDisabled,\n autocapture: this._core.getAutocaptureState(),\n featureFlags: flags,\n flagsLoaded: details !== undefined,\n flagRevision: this._flagRevision,\n featureFlagPayloads: payloads,\n })\n }\n\n private _scheduleState(): void {\n if (this._notifyPending || this._closed) return\n this._notifyPending = true\n queueMicrotask(() => {\n this._notifyPending = false\n if (this._closed) return\n const flags = JSON.stringify([\n this._core.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails),\n this._core.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),\n ])\n if (flags !== this._lastFlags) {\n this._lastFlags = flags\n this._flagRevision++\n }\n const state = this.getState()\n const serialized = JSON.stringify({ ...state, revision: 0 })\n if (serialized === this._lastPublished) return\n this._lastPublished = serialized\n state.revision = ++this._revision\n for (const registered of this._utilities.values()) registered.publish(state)\n for (const registered of this._windows.values()) {\n if (\n !registered.contents.isDestroyed() &&\n registered.frame !== undefined &&\n trustedUrl(registered.contents.getURL(), registered.allowedUrls)\n ) {\n registered.contents.mainFrame.send(STATE_CHANNEL, state)\n }\n }\n })\n }\n\n registerWindow(window: BrowserWindow, options: { allowedUrls: readonly string[] }): () => void {\n if (!options.allowedUrls.length || options.allowedUrls.some((url) => !trustedUrl(url, [url]))) {\n throw new Error('PostHog requires explicit trusted window URLs')\n }\n const contents = window.webContents\n this._windows.get(contents.id)?.dispose()\n const registration: RegisteredWindow = {\n contents,\n allowedUrls: [...options.allowedUrls],\n sequence: 0,\n frame: undefined,\n requests: 0,\n period: performance.now(),\n dispose: () => {},\n }\n const navigation = (): void => {\n registration.sequence = 0\n registration.frame = undefined\n }\n const focus = (): void => {\n clearTimeout(this._focusTimer)\n this._updateFocus()\n }\n const blur = (): void => {\n clearTimeout(this._focusTimer)\n this._focusTimer = setTimeout(() => this._updateFocus(), 50)\n this._focusTimer.unref()\n }\n const dispose = (): void => {\n contents.removeListener('did-navigate', navigation)\n contents.removeListener('destroyed', dispose)\n window.removeListener('focus', focus)\n window.removeListener('blur', blur)\n this._windows.delete(contents.id)\n this._updateFocus()\n }\n registration.dispose = dispose\n contents.on('did-navigate', navigation)\n contents.once('destroyed', dispose)\n window.on('focus', focus)\n window.on('blur', blur)\n this._windows.set(contents.id, registration)\n return dispose\n }\n\n /** Register only a trusted utilityProcess.fork() result, immediately after forking. */\n registerUtilityProcess(child: UtilityProcess): () => void {\n if (this._closing) throw new Error('PostHog is shut down')\n if (this._utilities.has(child)) throw new Error('PostHog utility process is already registered')\n const registration = attachUtilityProcess(\n child,\n (command, context, generation, authorize) => this._execute(command, context, generation, authorize),\n () => this.getState(),\n () => this._utilities.delete(child)\n )\n this._utilities.set(child, registration)\n return registration.dispose\n }\n\n private _updateFocus(): void {\n if (this._closing || this._options.captureAppLifecycleEvents === false) return\n const active = [...this._windows.values()].some(\n ({ contents }) => !contents.isDestroyed() && contents.isFocused()\n )\n if (this._foreground === active) return\n const previous = this._foreground\n this._foreground = active\n if (active) {\n if (previous === false) this.capture('Application Opened', { from_background: true })\n } else this.capture('Application Backgrounded')\n }\n\n private async _handle(event: IpcMainInvokeEvent, value: unknown): Promise<Response> {\n try {\n const registered = this._windows.get(event.sender.id)\n if (\n !registered ||\n !event.senderFrame ||\n event.senderFrame !== event.sender.mainFrame ||\n !trustedUrl(event.senderFrame.url, registered.allowedUrls)\n )\n throw new Error('Unauthorized PostHog sender')\n if (performance.now() - registered.period >= 1000) {\n registered.period = performance.now()\n registered.requests = 0\n }\n if (++registered.requests > 100) throw new Error('PostHog renderer rate limit exceeded')\n validateRequest(value)\n if (value.command.type === 'hello') {\n if (registered.frame === event.senderFrame.routingId && value.sequence <= registered.sequence)\n throw new Error('Duplicate PostHog request')\n registered.frame = event.senderFrame.routingId\n } else if (registered.frame !== event.senderFrame.routingId) throw new Error('PostHog handshake required')\n if (value.sequence <= registered.sequence) throw new Error('Out-of-order PostHog request')\n registered.sequence = value.sequence\n await this._ready\n if (this._closing) throw new Error('PostHog is shut down')\n const command = value.command\n if (\n command.type !== 'hello' &&\n command.type !== 'flush' &&\n command.type !== 'optOut' &&\n value.generation !== this._generation\n ) {\n throw new Error('Stale PostHog identity; synchronize before capturing')\n }\n const context: Properties = { $electron_process: 'renderer', $window_id: String(event.sender.id) }\n const authorize = (): void => {\n if (\n this._windows.get(event.sender.id) !== registered ||\n registered.frame !== event.senderFrame?.routingId ||\n !trustedUrl(event.sender.getURL(), registered.allowedUrls)\n )\n throw new Error('PostHog sender navigated or disconnected')\n }\n authorize()\n await this._execute(command, context, value.generation, authorize)\n return { ok: true, state: this.getState() }\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : 'PostHog request failed' }\n }\n }\n\n private async _execute(\n command: Command,\n context: Properties,\n generation: number,\n authorize: () => void\n ): Promise<void> {\n if (command.type === 'hello') return this._run(() => {}, undefined, authorize)\n if (command.type === 'flush') return this._flush(authorize)\n if (command.type === 'reloadFeatureFlags') return this._reloadFeatureFlags(generation, authorize)\n // Withdrawal from any window must survive an immediate quit, like a main-process optOut().\n if (command.type === 'optOut') return this._changeConsent(true, undefined, authorize)\n if (command.type === 'loadAutocaptureConfig') {\n await this._ready\n await this._tail\n if (this._closing) return\n if (generation !== this._generation) throw new Error('Stale PostHog identity')\n authorize()\n await this._core.loadAutocaptureConfig()\n if (!this._closing) await this._core.persist()\n this._scheduleState()\n return\n }\n const operation = () =>\n this._core.withContext(context, () => {\n switch (command.type) {\n case 'capture':\n return this._core.capture(command.event, { ...command.properties, ...context })\n case 'alias':\n return this._alias(command.alias)\n case 'screen':\n return this._core.capture('$screen', {\n ...command.properties,\n ...context,\n $screen_name: command.name,\n })\n case 'setPersonProperties':\n return this._setPersonProperties(command.properties, command.propertiesOnce)\n case 'setPersonPropertiesForFlags':\n return this._setPersonPropertiesForFlags(command.properties, command.reloadFeatureFlags)\n case 'setGroupPropertiesForFlags':\n return this._setGroupPropertiesForFlags(command.properties, command.reloadFeatureFlags)\n case 'resetPersonPropertiesForFlags':\n return this._resetPersonPropertiesForFlags(command.reloadFeatureFlags)\n case 'resetGroupPropertiesForFlags':\n return this._resetGroupPropertiesForFlags(command.reloadFeatureFlags)\n case 'identify':\n return this._identify(command.distinctId, command.properties)\n case 'reset':\n return this._reset()\n case 'group':\n return this._core.group(command.groupType, command.groupKey, command.properties)\n case 'register':\n return this._core.register(command.properties)\n case 'unregister':\n return this._core.unregister(command.key)\n case 'optIn':\n return this._core.optIn()\n case 'flag': {\n if (\n command.flagRevision === this._flagRevision &&\n this._core.getFeatureFlag(command.key, { sendEvent: false }) ===\n (command.value ?? undefined)\n ) {\n this._core.getFeatureFlag(command.key)\n }\n return\n }\n case 'exception':\n return this._core.capture(\n '$exception',\n { ...command.properties, ...context },\n { _originatedFromCaptureException: true }\n )\n }\n })\n if (isFlagContextCommand(command)) {\n return this._runFlagContext(operation, generation, authorize)\n }\n return this._run(operation, generation, authorize, command.type === 'optIn')\n }\n\n shutdown(timeoutMs = 2000): Promise<void> {\n if (this._shutdownPromise) return this._shutdownPromise\n this._closing = true\n for (const registration of this._utilities.values()) registration.dispose()\n this._stopExceptionAutocapture?.()\n this._stopExceptionAutocapture = undefined\n clearInterval(this._timer)\n clearTimeout(this._focusTimer)\n let timer: ReturnType<typeof setTimeout> | undefined\n let cleanupPromise: Promise<void> | undefined\n const cleanup = (): Promise<void> => {\n if (cleanupPromise) return cleanupPromise\n this._closed = true\n this._cancelReady()\n const stopped = this._core.stop()\n ipcMain.removeHandler(COMMAND_CHANNEL)\n for (const cleanup of this._cleanups) cleanup()\n for (const registration of this._windows.values()) registration.dispose()\n if (singleton === this) singleton = undefined\n return (cleanupPromise = stopped)\n }\n const drain = async (): Promise<void> => {\n await this._ready\n if (this._closed) return\n await this._tail\n if (this._closed) return\n await this._core.shutdown(timeoutMs)\n if (!this._closed) await this._core.persist()\n await cleanup()\n }\n this._shutdownPromise = Promise.race([\n drain().catch(async (error) => {\n this._report(error)\n await cleanup()\n }),\n new Promise<void>((resolve) => {\n timer = setTimeout(\n () => {\n this._report(new Error('PostHog shutdown timed out; unsent events remain in storage'))\n resolve()\n },\n Math.max(0, timeoutMs)\n )\n }),\n ]).finally(() => {\n clearTimeout(timer)\n // Filesystem work cannot be cancelled safely. Keep ownership until it settles,\n // without extending the caller's shutdown budget.\n void cleanup().catch((error) => this._report(error))\n })\n return this._shutdownPromise\n }\n}\n\nexport function init(options: PostHogOptions): PostHog {\n if (singleton) {\n if (singletonOptions?.projectToken !== options.projectToken || singletonOptions?.host !== options.host) {\n throw new Error('PostHog Electron is already initialized for a different project')\n }\n return singleton\n }\n return new PostHog(options)\n}\n"],"mappings":";;;;;;;;;AAAA,MAAa,UAAU;;;ACIvB,MAAa,kBAAkB;AAC/B,MAAa,gBAAgB;AAG7B,MAAa,oBAAoB;AAkBjC,SAAgB,oBAAoB,QAA8C;CAC9E,OAAO,gBAAgB;EAAE,GAAG;EAAQ,SAAS,OAAO,YAAY,KAAK,QAAQ,OAAO;CAAQ,CAAC;AACjG;AAuCA,SAAgB,qBAAqB,SAAgF;CACjH,OACI,QAAQ,SAAS,iCACjB,QAAQ,SAAS,gCACjB,QAAQ,SAAS,mCACjB,QAAQ,SAAS;AAEzB;AAgBA,SAAgB,SAAS,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;AAEA,SAAgB,WAAW,OAAgB,QAAQ,GAAG,oBAAoB,OAAa;CACnF,IAAI,YAAY;CAChB,MAAM,SAAS,SAAuB;EAClC,aAAa;EACb,IAAI,YAAY,GAAG,MAAM,IAAI,MAAM,iCAAiC;CACxE;CACA,MAAM,SAAS,MAAe,UAAwB;EAClD,IAAI,QAAQ,IAAI,MAAM,IAAI,MAAM,sCAAsC;EAEtE,MAAM,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,CAAC;EACpD,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,OAAO,SAAS,WAAW;EAC5E,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI,GAAG;EACvD,IAAI,MAAM,QAAQ,IAAI,GAAG;GACrB,KAAK,MAAM,WAAW,MAAM,MAAM,SAAS,QAAQ,CAAC;GACpD;EACJ;EACA,IACI,SAAS,IAAI,MACZ,OAAO,eAAe,IAAI,MAAM,OAAO,aAAa,O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,GAAG,SAAS,CACzB;EACJ,CAAC,CACL,CAAC,CAAC,CAAC,cAAc;GACb,aAAa,KAAK;GAGlB,QAAa,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ,KAAK,CAAC;EACvD,CAAC;EACD,OAAO,KAAK;CAChB;AACJ;AAEA,SAAgB,KAAK,SAAkC;CACnD,IAAI,WAAW;EACX,IAAI,kBAAkB,iBAAiB,QAAQ,gBAAgB,kBAAkB,SAAS,QAAQ,MAC9F,MAAM,IAAI,MAAM,iEAAiE;EAErF,OAAO;CACX;CACA,OAAO,IAAI,QAAQ,OAAO;AAC9B"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,224 @@
1
+ import { BrowserWindow, UtilityProcess } from "electron";
2
+ import { FeatureFlagResult, FeatureFlagValue, FeatureFlagValue as FeatureFlagValue$1, JsonType, JsonType as JsonType$1, PostHogCoreOptions, PostHogEventProperties } from "@posthog/core";
3
+ import { EventHint } from "@posthog/core/error-tracking";
4
+ //#region src/shared/autocapture.d.ts
5
+ interface AutocaptureRemoteConfig {
6
+ autocapture_opt_out?: boolean;
7
+ elementsChainAsString?: boolean;
8
+ }
9
+ interface AutocaptureState extends AutocaptureRemoteConfig {
10
+ status: 'pending' | 'loaded' | 'failed' | 'disabled';
11
+ }
12
+ //#endregion
13
+ //#region src/shared/protocol.d.ts
14
+ type Properties = PostHogEventProperties;
15
+ interface FeatureFlagReadOptions {
16
+ /** Report a deduplicated exposure by default; false suppresses it. Takes precedence over sendEvent. */
17
+ sendFeatureFlagEvent?: boolean;
18
+ /** Compatibility option; prefer sendFeatureFlagEvent. */
19
+ sendEvent?: boolean;
20
+ }
21
+ interface IsFeatureEnabledOptions extends FeatureFlagReadOptions {
22
+ /** Fallback for unknown or unavailable flags; never overrides a known false or empty variant. */
23
+ defaultValue?: boolean;
24
+ }
25
+ interface State {
26
+ revision: number;
27
+ generation: number;
28
+ distinctId: string;
29
+ anonymousId: string;
30
+ sessionId: string;
31
+ optedOut: boolean;
32
+ disabled?: boolean;
33
+ autocapture?: AutocaptureState;
34
+ featureFlags: Record<string, FeatureFlagValue$1>;
35
+ flagsLoaded?: boolean;
36
+ flagRevision: number;
37
+ featureFlagPayloads: Record<string, JsonType$1>;
38
+ }
39
+ //#endregion
40
+ //#region src/main/index.d.ts
41
+ interface PostHogOptions extends Pick<PostHogCoreOptions, 'host' | 'flushAt' | 'flushInterval' | 'maxBatchSize' | 'maxQueueSize' | 'requestTimeout' | 'fetchRetryCount' | 'fetchRetryDelay' | 'preloadFeatureFlags' | 'disableRemoteFeatureFlags' | 'disableRemoteConfig' | 'remoteConfigRequestTimeoutMs' | 'defaultOptIn' | 'disabled' | 'bootstrap' | 'before_send' | 'personProfiles' | 'sessionExpirationTimeSeconds' | 'disableGeoip' | 'disableCompression' | 'featureFlagsRequestTimeoutMs' | 'featureFlagsRequestMaxRetries'> {
42
+ projectToken: string;
43
+ storageDirectory?: string;
44
+ maxStorageBytes?: number;
45
+ maxQueueAgeMs?: number;
46
+ captureAppLifecycleEvents?: boolean;
47
+ enableExceptionAutocapture?: boolean;
48
+ /**
49
+ * Also installs a `process.on('unhandledRejection')` listener to capture main-process rejections.
50
+ * Requires `enableExceptionAutocapture`. While the listener is installed, Node skips its default
51
+ * handling: an unhandled rejection no longer prints `UnhandledPromiseRejectionWarning` or sets
52
+ * `process.exitCode = 1`. This lasts until shutdown, even while the user is opted out. Off by default.
53
+ */
54
+ captureUnhandledRejections?: boolean;
55
+ appBuild?: string;
56
+ onError?: (error: unknown) => void;
57
+ }
58
+ declare class PostHog {
59
+ private _options;
60
+ private _core;
61
+ private _ready;
62
+ private _windows;
63
+ private _utilities;
64
+ private _revision;
65
+ private _generation;
66
+ private _closed;
67
+ private _closing;
68
+ private _shutdownPromise?;
69
+ private _notifyPending;
70
+ private _lastPublished;
71
+ private _flagRevision;
72
+ private _lastFlags;
73
+ private _reportedPayloadErrors;
74
+ private _focusTimer?;
75
+ private _timer?;
76
+ private _foreground;
77
+ private _stopExceptionAutocapture?;
78
+ private _cancelReady;
79
+ private _cleanups;
80
+ private _tail;
81
+ private _readyForSnapshots;
82
+ private _pendingConsent;
83
+ private _requestedConsent?;
84
+ private _consentToken;
85
+ constructor(_options: PostHogOptions);
86
+ private _report;
87
+ private _initialize;
88
+ ready(): Promise<void>;
89
+ private _run;
90
+ /**
91
+ * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; captures
92
+ * after shutdown are dropped. A capture after an unawaited `identify()` or `reset()` uses the new identity.
93
+ */
94
+ capture(event: string, properties?: Properties): void;
95
+ private _captureEvent;
96
+ /**
97
+ * Link the current distinct ID to an alias without switching identity or reloading flags.
98
+ * Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.
99
+ */
100
+ alias(alias: string): Promise<void>;
101
+ private _alias;
102
+ private _snapshotEventProperties;
103
+ /**
104
+ * Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.
105
+ * Fire-and-forget: never throws or rejects; ignored when opted out.
106
+ */
107
+ screen(name: string, properties?: Properties): void;
108
+ /**
109
+ * Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.
110
+ * Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.
111
+ * Ignored when opted out or personProfiles is 'never'.
112
+ */
113
+ setPersonProperties(properties?: Properties, propertiesOnce?: Properties): Promise<void>;
114
+ private _setPersonProperties;
115
+ /**
116
+ * Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.
117
+ * Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.
118
+ * With false, only saves context; cached flag values stay unchanged until a reload.
119
+ */
120
+ setPersonPropertiesForFlags(properties: Properties, reloadFeatureFlags?: boolean): Promise<void>;
121
+ private _setPersonPropertiesForFlags;
122
+ /**
123
+ * Merge a call-time copy of local overrides by group type, without changing profiles or group membership.
124
+ * Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.
125
+ * With false, only saves context; cached flag values stay unchanged until a reload.
126
+ */
127
+ setGroupPropertiesForFlags(properties: Record<string, Properties>, reloadFeatureFlags?: boolean): Promise<void>;
128
+ private _setGroupPropertiesForFlags;
129
+ /**
130
+ * Clear all local person flag overrides, not profile data or identity. Resolves after persistence.
131
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
132
+ */
133
+ resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): Promise<void>;
134
+ private _resetPersonPropertiesForFlags;
135
+ /**
136
+ * Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.
137
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
138
+ */
139
+ resetGroupPropertiesForFlags(reloadFeatureFlags?: boolean): Promise<void>;
140
+ private _resetGroupPropertiesForFlags;
141
+ private _runFlagContext;
142
+ identify(distinctId: string, properties?: Properties): Promise<void>;
143
+ private _identify;
144
+ reset(): Promise<void>;
145
+ private _reset;
146
+ group(type: string, key: string | number, properties?: Properties): Promise<void>;
147
+ register(properties: Properties): Promise<void>;
148
+ unregister(key: string): Promise<void>;
149
+ optIn(): Promise<void>;
150
+ optOut(): Promise<void>;
151
+ private _changeConsent;
152
+ private _optOut;
153
+ /**
154
+ * Fire-and-forget: never throws or rejects. Storage failures are reported through `onError`; reports after
155
+ * shutdown or across an identity change are dropped.
156
+ */
157
+ captureException(error: unknown, properties?: Properties): void;
158
+ protected _captureException(error: unknown, properties?: Properties, hint?: EventHint): Promise<void>;
159
+ getDistinctId(): string;
160
+ /** Return the shared anonymous ID, stable across identify and rotated by reset; await ready() first. */
161
+ getAnonymousId(): string;
162
+ /** Read cached consent; await ready() before relying on persisted consent. */
163
+ hasOptedOutCapturing(): boolean;
164
+ getSessionId(): string;
165
+ /**
166
+ * Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.
167
+ * Reports a deduplicated exposure by default; sendFeatureFlagEvent: false suppresses it.
168
+ */
169
+ getFeatureFlag(key: string, options?: FeatureFlagReadOptions): FeatureFlagValue | undefined;
170
+ /**
171
+ * Read cached enabled state without fetching; empty variants are disabled. defaultValue applies only to
172
+ * unknown/unavailable flags. Without it, missing-key behavior matches getFeatureFlag().
173
+ * Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
174
+ */
175
+ isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & {
176
+ defaultValue: boolean;
177
+ }): boolean;
178
+ /**
179
+ * Read cached enabled state without fetching; empty variants are disabled. Missing keys follow getFeatureFlag()
180
+ * unless defaultValue is supplied. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
181
+ */
182
+ isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined;
183
+ /**
184
+ * Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.
185
+ * Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
186
+ */
187
+ getFeatureFlagResult(key: string, options?: FeatureFlagReadOptions): FeatureFlagResult | undefined;
188
+ private _copyFlagResult;
189
+ /** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */
190
+ getAllFeatureFlags(): FeatureFlagResult[];
191
+ /**
192
+ * Read a copied, decoded cached payload without fetching or reporting exposure.
193
+ * Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.
194
+ */
195
+ getFeatureFlagPayload(key: string): JsonType | undefined;
196
+ private _prunePayloadErrors;
197
+ private _decodeFlagPayload;
198
+ get optedOut(): boolean;
199
+ /**
200
+ * Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.
201
+ * A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.
202
+ */
203
+ reloadFeatureFlags(): Promise<void>;
204
+ /** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */
205
+ reloadFeatureFlagsAsync(): Promise<void>;
206
+ private _reloadFeatureFlags;
207
+ flush(): Promise<void>;
208
+ private _flush;
209
+ getState(): State;
210
+ private _scheduleState;
211
+ registerWindow(window: BrowserWindow, options: {
212
+ allowedUrls: readonly string[];
213
+ }): () => void;
214
+ /** Register only a trusted utilityProcess.fork() result, immediately after forking. */
215
+ registerUtilityProcess(child: UtilityProcess): () => void;
216
+ private _updateFocus;
217
+ private _handle;
218
+ private _execute;
219
+ shutdown(timeoutMs?: number): Promise<void>;
220
+ }
221
+ declare function init(options: PostHogOptions): PostHog;
222
+ //#endregion
223
+ export { type FeatureFlagReadOptions, type FeatureFlagResult, type FeatureFlagValue, type IsFeatureEnabledOptions, type JsonType, PostHog, PostHogOptions, type Properties, type State, init };
224
+ //# sourceMappingURL=main.d.ts.map