import { n as EventPayload, r as EventSubscriber$1 } from "./event-subscriber-base-DOVIZK7N.js"; import { EventAttributes } from "autotel/event-subscriber"; //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/types.d.ts type PostHogCoreOptions = { /** * PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' * * @default 'https://us.i.posthog.com' */ host?: string; /** * The number of events to queue before sending to PostHog (flushing) * * @default 20 */ flushAt?: number; /** * The interval in milliseconds between periodic flushes * * @default 10000 */ flushInterval?: number; /** * The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) * * @default 100 */ maxBatchSize?: number; /** * The maximum number of cached messages either in memory or on the local storage (must be higher than `flushAt`) * * @default 1000 */ maxQueueSize?: number; /** * If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) * * @default false */ disabled?: boolean; /** * If set to false the SDK will not track until the `optIn` function is called. * * @default true */ defaultOptIn?: boolean; /** * Whether to track that `getFeatureFlag` was called (used by Experiments) * * @default true */ sendFeatureFlagEvent?: boolean; /** * Whether to load feature flags when initialized or not * * @default true */ preloadFeatureFlags?: boolean; /** * Whether to load remote config when initialized or not * Experimental support * * @default false */ disableRemoteConfig?: boolean; /** * Whether to load surveys when initialized or not * Experimental support * Requires the `PostHogSurveyProvider` to be used * * @default false */ disableSurveys?: boolean; /** Option to bootstrap the library with given distinctId and feature flags */ bootstrap?: { distinctId?: string; isIdentifiedId?: boolean; featureFlags?: Record; featureFlagPayloads?: Record; }; /** * How many times we will retry HTTP requests * * @default 3 */ fetchRetryCount?: number; /** * The delay between HTTP request retries in milliseconds * * @default 3000 */ fetchRetryDelay?: number; /** * Timeout in milliseconds for any calls * * @default 10000 */ requestTimeout?: number; /** * Timeout in milliseconds for feature flag calls * * @default 10000 for stateful clients, 3000 for stateless */ featureFlagsRequestTimeoutMs?: number; /** * Timeout in milliseconds for remote config calls * * @default 3000 */ remoteConfigRequestTimeoutMs?: number; /** * For Session Analysis how long before we expire a session in seconds * * @default 1800 */ sessionExpirationTimeSeconds?: number; /** * Whether to disable GZIP compression * * @default false */ disableCompression?: boolean; /** * Whether to disable GeoIP lookups * * @default false */ disableGeoip?: boolean; /** * Special flag to indicate ingested data is for a historical migration * * @default false */ historicalMigration?: boolean; /** * Evaluation contexts for feature flags. * When set, only feature flags that have at least one matching evaluation tag * will be evaluated for this SDK instance. Feature flags with no evaluation tags * will always be evaluated. * * Examples: ['production', 'web', 'mobile'] * * @default undefined */ evaluationContexts?: readonly string[]; /** * Evaluation environments for feature flags. * @deprecated Use evaluationContexts instead. This property will be removed in a future version. */ evaluationEnvironments?: readonly string[]; /** * Determines when to create Person Profiles for users. * * - 'always': Always create a person profile for every user (anonymous and identified). * - 'identified_only': Only create a person profile when the user is identified via identify(), alias(), or group(). * Events captured before identification will NOT have person profiles and will be anonymous events. * - 'never': Never create person profiles. identify(), alias(), and group() will be no-ops. * * @default 'identified_only' * * @example * ```ts * // Only create profiles when users are identified (recommended for most apps) * const posthog = new PostHog('', { * personProfiles: 'identified_only', * }) * * // Later when user logs in: * posthog.identify('user-123', { email: 'user@example.com' }) * ``` * * @example * ```ts * // Always create profiles (for apps where you want to track all users) * const posthog = new PostHog('', { * personProfiles: 'always', * }) * ``` * * @example * ```ts * // Never create profiles (anonymous analytics only) * const posthog = new PostHog('', { * personProfiles: 'never', * }) * ``` */ personProfiles?: 'always' | 'identified_only' | 'never'; /** * Allows modification or dropping of events before they're sent to PostHog. * If an array is provided, the functions are run in order. * If a function returns null, the event will be dropped. */ before_send?: BeforeSendFn$1 | BeforeSendFn$1[]; /** * A list of hostnames for which to inject PostHog tracing headers * (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID) on outgoing `fetch` requests. * * Use this to link requests made from your app to session replays and LLM traces * in PostHog. When set, the global `fetch` is patched on initialization and the * headers are added to requests whose hostname matches one of the entries. * * Requires the SDK to wire up `patchFetchForTracingHeaders` against this option * (currently supported in posthog-react-native). */ addTracingHeaders?: string[]; }; declare enum PostHogPersistedProperty { AnonymousId = "anonymous_id", DistinctId = "distinct_id", Props = "props", EnablePersonProcessing = "enable_person_processing", PersonMode = "person_mode", // 'identified' | 'anonymous' FeatureFlagDetails = "feature_flag_details", FeatureFlags = "feature_flags", FeatureFlagPayloads = "feature_flag_payloads", BootstrapFeatureFlagDetails = "bootstrap_feature_flag_details", BootstrapFeatureFlags = "bootstrap_feature_flags", BootstrapFeatureFlagPayloads = "bootstrap_feature_flag_payloads", OverrideFeatureFlags = "override_feature_flags", Queue = "queue", LogsQueue = "logs_queue", OptedOut = "opted_out", SessionId = "session_id", SessionStartTimestamp = "session_start_timestamp", SessionLastTimestamp = "session_timestamp", PersonProperties = "person_properties", GroupProperties = "group_properties", InstalledAppBuild = "installed_app_build", // only used by posthog-react-native InstalledAppVersion = "installed_app_version", // only used by posthog-react-native SessionReplay = "session_replay", // only used by posthog-react-native SurveyLastSeenDate = "survey_last_seen_date", // only used by posthog-react-native SurveysSeen = "surveys_seen", // only used by posthog-react-native Surveys = "surveys", // only used by posthog-react-native RemoteConfig = "remote_config", FlagsEndpointWasHit = "flags_endpoint_was_hit", // only used by posthog-react-native DeviceId = "device_id" } type PostHogFetchOptions = { method: 'GET' | 'POST' | 'PUT' | 'PATCH'; mode?: 'no-cors'; credentials?: 'omit'; headers: { [key: string]: string; }; body?: string | Blob; signal?: AbortSignal; }; type PostHogCaptureOptions = { /** If provided overrides the auto-generated event ID */uuid?: string; /** If provided overrides the auto-generated timestamp */ timestamp?: Date; disableGeoip?: boolean; /** * Internal flag set by captureException() to indicate this $exception * event originated from the proper exception capture path. Used to warn users who call * capture('$exception') directly. */ _originatedFromCaptureException?: boolean; }; type PostHogFetchResponse = { status: number; text: () => Promise; json: () => Promise; headers?: { get(name: string): string | null; }; body?: ReadableStream | null; }; type PostHogEventProperties = { [key: string]: JsonType; }; declare enum Compression { GZipJS = "gzip-js", Base64 = "base64" } type PostHogRemoteConfig = { sessionRecording?: boolean | { [key: string]: JsonType; }; /** * Supported compression algorithms */ supportedCompression?: Compression[]; /** * Whether surveys are enabled */ surveys?: boolean | Survey[]; /** * Indicates if the team has any flags enabled (if not we don't need to load them) */ hasFeatureFlags?: boolean; /** * Error tracking remote config. * Either a boolean (false = disabled) or a map with configuration. * When a map, `autocaptureExceptions` (boolean) controls whether automatic exception capture is enabled remotely. */ errorTracking?: boolean | { [key: string]: JsonType; }; /** * Capture performance remote config. * Either a boolean (false = disabled) or a map with configuration. * When a map, `network_timing` (boolean) controls whether network timing capture is enabled remotely. */ capturePerformance?: boolean | { [key: string]: JsonType; }; /** * Logs feature remote config. When a map, `captureConsoleLogs` (boolean) * is the local opt-in flag for `console.*` autocapture (read by the JS * SDK's `PostHogLogs` extension to decide whether to load the autocapture * bundle). */ logs?: boolean | { [key: string]: JsonType; }; }; type FeatureFlagValue = string | boolean; type PostHogFlagsResponse = Omit & { featureFlags: { [key: string]: FeatureFlagValue; }; featureFlagPayloads: { [key: string]: JsonType; }; flags: { [key: string]: FeatureFlagDetail; }; errorsWhileComputingFlags: boolean; sessionRecording?: boolean | { [key: string]: JsonType; }; quotaLimited?: string[]; requestId?: string; evaluatedAt?: number; }; type PostHogFeatureFlagsResponse = PartialWithRequired; /** * Creates a type with all properties of T, but makes only K properties required while the rest remain optional. * * @template T - The base type containing all properties * @template K - Union type of keys from T that should be required * * @example * interface User { * id: number; * name: string; * email?: string; * age?: number; * } * * // Makes 'id' and 'name' required, but 'email' and 'age' optional * type RequiredUser = PartialWithRequired; * * const user: RequiredUser = { * id: 1, // Must be provided * name: "John" // Must be provided * // email and age are optional * }; */ type PartialWithRequired = { [P in K]: T[P] } & { [P in Exclude]?: T[P] }; /** * These are the fields we care about from PostHogFlagsResponse for feature flags. */ type PostHogFeatureFlagDetails = PartialWithRequired; /** * Models legacy flags and payloads return type for many public methods. */ type PostHogFlagsAndPayloadsResponse = Partial>; type JsonType = string | number | boolean | null | { [key: string]: JsonType; } | Array | JsonType[]; /** * Represents an error that occurred during a feature flag request. */ type FeatureFlagRequestError = { type: 'timeout' | 'connection_error' | 'api_error' | 'unknown_error'; statusCode?: number; }; /** * Result type for getFlags that includes either a successful response or error information. */ type GetFlagsResult = { success: true; response: PostHogFeatureFlagsResponse; } | { success: false; error: FeatureFlagRequestError; }; type FeatureFlagDetail = { key: string; enabled: boolean; variant: string | undefined; reason: EvaluationReason | undefined; metadata: FeatureFlagMetadata | undefined; failed?: boolean; }; type FeatureFlagMetadata = { id: number | undefined; version: number | undefined; description: string | undefined; payload: string | undefined; }; type EvaluationReason = { code: string | undefined; condition_index: number | undefined; description: string | undefined; }; type SurveyAppearance = { backgroundColor?: string; textColor?: string; submitButtonColor?: string; submitButtonText?: string; submitButtonTextColor?: string; ratingButtonColor?: string; ratingButtonActiveColor?: string; inputBackground?: string; inputTextColor?: string; autoDisappear?: boolean; displayThankYouMessage?: boolean; thankYouMessageHeader?: string; thankYouMessageDescription?: string; thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType; thankYouMessageCloseButtonText?: string; borderColor?: string; position?: SurveyPosition; placeholder?: string; shuffleQuestions?: boolean; surveyPopupDelaySeconds?: number; widgetType?: SurveyWidgetType; widgetSelector?: string; widgetLabel?: string; widgetColor?: string; }; declare enum SurveyPosition { TopLeft = "top_left", TopCenter = "top_center", TopRight = "top_right", MiddleLeft = "middle_left", MiddleCenter = "middle_center", MiddleRight = "middle_right", Left = "left", Right = "right", Center = "center" } declare enum SurveyWidgetType { Button = "button", Tab = "tab", Selector = "selector" } declare enum SurveyType { Popover = "popover", API = "api", Widget = "widget", ExternalSurvey = "external_survey" } type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion; declare enum SurveyQuestionDescriptionContentType { Html = "html", Text = "text" } declare enum SurveyValidationType { MinLength = "min_length", MaxLength = "max_length" } interface SurveyValidationRule { type: SurveyValidationType; value?: number; errorMessage?: string; } interface SurveyTranslation { name?: string; thankYouMessageHeader?: string; thankYouMessageDescription?: string; thankYouMessageCloseButtonText?: string; } interface SurveyQuestionTranslation { question?: string; description?: string | null; buttonText?: string; link?: string | null; lowerBoundLabel?: string; upperBoundLabel?: string; choices?: string[]; } type SurveyQuestionBase = { question: string; id: string; description?: string | null; descriptionContentType?: SurveyQuestionDescriptionContentType; optional?: boolean; buttonText?: string; originalQuestionIndex: number; branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching; validation?: SurveyValidationRule[]; translations?: Record; }; type BasicSurveyQuestion = SurveyQuestionBase & { type: SurveyQuestionType.Open; }; type LinkSurveyQuestion = SurveyQuestionBase & { type: SurveyQuestionType.Link; link?: string | null; }; type RatingSurveyQuestion = SurveyQuestionBase & { type: SurveyQuestionType.Rating; display: SurveyRatingDisplay; scale: 2 | 3 | 5 | 7 | 10; lowerBoundLabel: string; upperBoundLabel: string; skipSubmitButton?: boolean; }; declare enum SurveyRatingDisplay { Number = "number", Emoji = "emoji" } type MultipleSurveyQuestion = SurveyQuestionBase & { type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice; choices: string[]; hasOpenChoice?: boolean; shuffleOptions?: boolean; skipSubmitButton?: boolean; }; declare enum SurveyQuestionType { Open = "open", MultipleChoice = "multiple_choice", SingleChoice = "single_choice", Rating = "rating", Link = "link" } declare enum SurveyQuestionBranchingType { NextQuestion = "next_question", End = "end", ResponseBased = "response_based", SpecificQuestion = "specific_question" } type NextQuestionBranching = { type: SurveyQuestionBranchingType.NextQuestion; }; type EndBranching = { type: SurveyQuestionBranchingType.End; }; type ResponseBasedBranching = { type: SurveyQuestionBranchingType.ResponseBased; responseValues: Record; }; type SpecificQuestionBranching = { type: SurveyQuestionBranchingType.SpecificQuestion; index: number; }; type SurveyResponse = { surveys: Survey[]; }; declare enum SurveyMatchType { Regex = "regex", NotRegex = "not_regex", Exact = "exact", IsNot = "is_not", Icontains = "icontains", NotIcontains = "not_icontains" } declare enum SurveySchedule { Once = "once", Recurring = "recurring", Always = "always" } type Survey = { id: string; name: string; description?: string; type: SurveyType; translations?: Record; feature_flag_keys?: { key: string; value?: string; }[]; linked_flag_key?: string; targeting_flag_key?: string; internal_targeting_flag_key?: string; questions: SurveyQuestion[]; appearance?: SurveyAppearance; conditions?: { url?: string; selector?: string; seenSurveyWaitPeriodInDays?: number; urlMatchType?: SurveyMatchType; events?: { repeatedActivation?: boolean; values?: { name: string; }[]; }; actions?: { values: SurveyActionType[]; }; deviceTypes?: string[]; deviceTypesMatchType?: SurveyMatchType; linkedFlagVariant?: string; }; start_date?: string; end_date?: string; current_iteration?: number; current_iteration_start_date?: string; schedule?: SurveySchedule; }; type SurveyActionType = { id: number; name?: string; steps?: ActionStepType[]; }; /** Sync with plugin-server/src/types.ts */ declare enum ActionStepStringMatching { Contains = "contains", Exact = "exact", Regex = "regex" } type ActionStepType = { event?: string; selector?: string; text?: string; /** @default StringMatching.Exact */ text_matching?: ActionStepStringMatching; href?: string; /** @default ActionStepStringMatching.Exact */ href_matching?: ActionStepStringMatching; url?: string; /** @default StringMatching.Contains */ url_matching?: ActionStepStringMatching; }; type Logger = { debug: (...args: any[]) => void; info: (...args: any[]) => void; warn: (...args: any[]) => void; error: (...args: any[]) => void; critical: (...args: any[]) => void; createLogger: (prefix: string) => Logger; }; /** * Represents an event before it's sent to PostHog. * This is the interface exposed to the `before_send` hook, matching the web SDK's `CaptureResult`. */ type CaptureEvent = { /** UUID for the event (optional to allow compatibility with Node SDK's EventMessage) */uuid?: string; /** The name of the event */ event: string; /** Properties associated with the event (optional to allow compatibility with Node SDK's EventMessage) */ properties?: PostHogEventProperties; /** Properties to set on the person (overrides existing values) */ $set?: PostHogEventProperties; /** Properties to set on the person only once (does not override existing values) */ $set_once?: PostHogEventProperties; /** Timestamp for the event */ timestamp?: Date; }; /** * Function type for the `before_send` hook. * Receives an event and can return a modified event or null to drop the event. */ type BeforeSendFn$1 = (event: CaptureEvent | null) => CaptureEvent | null; //#endregion //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/utils/index.d.ts interface RetriableOptions { retryCount: number; retryDelay: number; retryCheck: (err: unknown) => boolean; } //#endregion //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/error-tracking/types.d.ts declare const severityLevels: readonly ["fatal", "error", "warning", "log", "info", "debug"]; declare type SeverityLevel = (typeof severityLevels)[number]; interface EventHint { mechanism?: Partial; syntheticException?: Error | null; skipFirstLines?: number; } interface ErrorProperties { $exception_list: Exception[]; $exception_level?: SeverityLevel; } interface Exception { type?: string; value?: string; mechanism?: Mechanism; module?: string; thread_id?: number; stacktrace?: { frames?: StackFrame[]; type: 'raw'; }; } interface Mechanism { handled?: boolean; type?: 'generic' | 'onunhandledrejection' | 'onuncaughtexception' | 'onconsole' | 'middleware'; source?: string; synthetic?: boolean; } type StackParser = (stack: string, skipFirstLines?: number) => StackFrame[]; type StackFrameModifierFn = (frames: StackFrame[]) => Promise; type Platform = 'node:javascript' | 'web:javascript' | 'hermes'; interface StackFrame { platform: Platform; filename?: string; function?: string; module?: string; lineno?: number; colno?: number; abs_path?: string; context_line?: string; pre_context?: string[]; post_context?: string[]; in_app?: boolean; instruction_addr?: string; addr_mode?: string; vars?: { [key: string]: JsonType; }; chunk_id?: string; } interface CoercingContext extends EventHint { apply: (input: unknown) => ExceptionLike; next: (input: unknown) => ExceptionLike | undefined; } interface Coercer { match(input: unknown): input is T; coerce(input: T, ctx: C): U; } type ErrorTrackingCoercer = Coercer; interface BaseException { type: string; value: string; synthetic: boolean; } interface ExceptionLike extends BaseException { stack?: string; cause?: ExceptionLike; level?: SeverityLevel; } //#endregion //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.d.ts declare class ErrorPropertiesBuilder { private coercers; private stackParser; private modifiers; constructor(coercers: ErrorTrackingCoercer[], stackParser: StackParser, modifiers?: StackFrameModifierFn[]); buildFromUnknown(input: unknown, hint?: EventHint): ErrorProperties; modifyFrames(exceptionList: ErrorProperties['$exception_list']): Promise; private coerceFallback; private parseStacktrace; private applyChunkIds; private applyCoercers; private applyModifiers; private convertToExceptionList; private buildParsingContext; buildCoercingContext(mechanism: Mechanism, hint: EventHint, depth?: number): CoercingContext; } //#endregion //#region ../../node_modules/.pnpm/@posthog+types@1.382.0/node_modules/@posthog/types/dist/capture-log.d.ts type OtlpSeverityText = 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL'; interface OtlpAnyValue { stringValue?: string; intValue?: number; doubleValue?: number; boolValue?: boolean; arrayValue?: { values: OtlpAnyValue[]; }; } interface OtlpKeyValue { key: string; value: OtlpAnyValue; } interface OtlpLogRecord { timeUnixNano: string; observedTimeUnixNano: string; severityNumber: number; severityText: OtlpSeverityText; body: { stringValue: string; }; attributes: OtlpKeyValue[]; traceId?: string; spanId?: string; flags?: number; } interface OtlpLogsPayload { resourceLogs: Array<{ resource: { attributes: OtlpKeyValue[]; }; scopeLogs: Array<{ scope: { name: string; version?: string; }; logRecords: OtlpLogRecord[]; }>; }>; } //#endregion //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/eventemitter.d.ts declare class SimpleEventEmitter { events: { [key: string]: ((...args: any[]) => void)[]; }; constructor(); on(event: string, listener: (...args: any[]) => void): () => void; emit(event: string, payload: any): void; } //#endregion //#region ../../node_modules/.pnpm/@posthog+core@1.30.10/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts /** * Outcome of a logs batch send. Keeps HTTP error classification inside core * (single source of truth — same policy events already use in `_flush()`) so * PostHogLogs doesn't need to know about specific error types. * * - ok → records are accepted; drop them from the queue * - too-large → 413; caller should halve batch size and retry same records * - retry-later → network error; caller keeps records and retries next cycle * - fatal → anything else (auth, malformed, etc.); caller drops the * batch and surfaces the error */ type SendLogsBatchOutcome = { kind: 'ok'; } | { kind: 'too-large'; } | { kind: 'retry-later'; error: unknown; } | { kind: 'fatal'; error: unknown; }; declare abstract class PostHogCoreStateless { readonly apiKey: string; readonly host: string; readonly flushAt: number; readonly preloadFeatureFlags: boolean; readonly disableSurveys: boolean; private maxBatchSize; private maxQueueSize; private flushInterval; private flushPromise; private shutdownPromise; private requestTimeout; private featureFlagsRequestTimeoutMs; private remoteConfigRequestTimeoutMs; private removeDebugCallback?; private disableGeoip; private historicalMigration; private evaluationContexts?; protected disabled: boolean; protected disableCompression: boolean; private defaultOptIn; private promiseQueue; protected _events: SimpleEventEmitter; protected _flushTimer?: any; protected _retryOptions: RetriableOptions; protected _initPromise: Promise; protected _isInitialized: boolean; protected _remoteConfigResponsePromise?: Promise; protected _logger: Logger; private _errorPropertiesBuilder?; /** * Returns the builder used by `captureException` to coerce arbitrary inputs into a * structured `$exception_list` (with parsed stack frames). * * @internal Exposed for cross-package use within this SDK; not part of the stable public API. */ getErrorPropertiesBuilder(): ErrorPropertiesBuilder; /** * Override in subclasses to plug in platform-specific stack parsers (e.g. node, hermes), * additional coercers (DOMException, ErrorEvent, PromiseRejectionEvent), or async frame * modifiers (source maps, context lines). * * The default is intentionally JS-runtime-agnostic — no DOM-typed coercers — so any SDK * that just extends core gets parsed stack frames out of the box. */ protected createErrorPropertiesBuilder(): ErrorPropertiesBuilder; abstract fetch(url: string, options: PostHogFetchOptions): Promise; abstract getLibraryId(): string; abstract getLibraryVersion(): string; abstract getCustomUserAgent(): string | void; abstract getPersistedProperty(key: PostHogPersistedProperty): T | undefined; abstract setPersistedProperty(key: PostHogPersistedProperty, value: T | null): void; constructor(apiKey: string, options?: PostHogCoreOptions); protected logMsgIfDebug(fn: () => void): void; protected wrap(fn: () => void): void; protected getCommonEventProperties(): PostHogEventProperties; get optedOut(): boolean; optIn(): Promise; optOut(): Promise; on(event: string, cb: (...args: any[]) => void): () => void; /** * Enables or disables debug mode for detailed logging. * * @remarks * Debug mode logs all PostHog calls to the console for troubleshooting. * This is useful during development to understand what data is being sent. * * {@label Initialization} * * @example * ```js * // enable debug mode * posthog.debug(true) * ``` * * @example * ```js * // disable debug mode * posthog.debug(false) * ``` * * @public * * @param {boolean} [debug] If true, will enable debug mode. */ debug(enabled?: boolean): void; get isDebug(): boolean; get isDisabled(): boolean; private buildPayload; /** * @internal */ addPendingPromise(promise: Promise): Promise; /*** *** TRACKING ***/ protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void; protected identifyStatelessImmediate(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise; protected captureStateless(distinctId: string, event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void; protected captureStatelessImmediate(distinctId: string, event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise; protected aliasStateless(alias: string, distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void; protected aliasStatelessImmediate(alias: string, distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise; /*** *** GROUPS ***/ protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): void; protected getRemoteConfig(): Promise; /*** *** FEATURE FLAGS ***/ protected getFlags(distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, extraPayload?: Record, fetchConfig?: boolean): Promise; private categorizeRequestError; protected getFeatureFlagStateless(key: string, distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean): Promise<{ response: FeatureFlagValue | undefined; requestId: string | undefined; }>; protected getFeatureFlagDetailStateless(key: string, distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean): Promise<{ response: FeatureFlagDetail | undefined; requestId: string | undefined; evaluatedAt: number | undefined; } | undefined>; protected getFeatureFlagPayloadStateless(key: string, distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean): Promise; protected getFeatureFlagPayloadsStateless(distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise; protected getFeatureFlagsStateless(distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{ flags: PostHogFlagsResponse['featureFlags'] | undefined; payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined; requestId: PostHogFlagsResponse['requestId'] | undefined; }>; protected getFeatureFlagsAndPayloadsStateless(distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{ flags: PostHogFlagsResponse['featureFlags'] | undefined; payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined; requestId: PostHogFlagsResponse['requestId'] | undefined; }>; protected getFeatureFlagDetailsStateless(distinctId: string, groups?: Record, personProperties?: Record, groupProperties?: Record>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise; /*** *** SURVEYS ***/ getSurveysStateless(): Promise; /*** *** SUPER PROPERTIES ***/ private _props; protected get props(): PostHogEventProperties; protected set props(val: PostHogEventProperties | undefined); register(properties: PostHogEventProperties): Promise; unregister(property: string): Promise; /*** *** QUEUEING AND FLUSHING ***/ /** * Hook that allows subclasses to transform or filter a message before it's queued. * Return null to drop the message. * @param message The prepared message * @returns The transformed message, or null to drop it */ protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null; /** * Hook that allows subclasses to wait for storage operations to complete. * This is called after queue changes are persisted during flush to ensure * data is safely written to storage before considering events as sent. * * Override this in implementations with async storage (e.g., React Native) * to prevent duplicate events on app crash/restart scenarios. */ protected flushStorage(): Promise; protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void; protected sendImmediate(type: string, _message: any, options?: PostHogCaptureOptions): Promise; protected prepareMessage(type: string, _message: any, options?: PostHogCaptureOptions): PostHogEventProperties; private clearFlushTimer; /** * Helper for flushing the queue in the background * Avoids unnecessary promise errors */ private flushBackground; /** * Flushes the queue of pending events. * * This function will return a promise that will resolve when the flush is complete, * or reject if there was an error (for example if the server or network is down). * * If there is already a flush in progress, this function will wait for that flush to complete. * * It's recommended to do error handling in the callback of the promise. * * {@label Initialization} * * @example * ```js * // flush with error handling * posthog.flush().then(() => { * console.log('Flush complete') * }).catch((err) => { * console.error('Flush failed', err) * }) * ``` * * @public * * @throws PostHogFetchHttpError * @throws PostHogFetchNetworkError * @throws Error */ flush(): Promise; protected getCustomHeaders(): { [key: string]: string; }; private _flush; /** * Sends a pre-built OTLP logs payload to `/i/v1/logs`. Returns a tagged * outcome instead of throwing so PostHogLogs doesn't have to know about the * core's error class hierarchy. Error classification lives here (single * source of truth, same policy the events `_flush()` uses for its own * 413 / network / fatal handling). * * 413 is passed through as `too-large` (not auto-retried) so the caller can * shrink `maxBatchRecordsPerPost` and retry the same records. */ _sendLogsBatch(payload: OtlpLogsPayload): Promise; private fetchWithRetry; _shutdown(shutdownTimeoutMs?: number): Promise; /** * Shuts down the PostHog instance and ensures all events are sent. * * Call shutdown() once before the process exits to ensure that all events have been sent and all promises * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it. * Use flush() for per-request cleanup instead. * * {@label Initialization} * * @example * ```js * // shutdown before process exit * process.on('SIGINT', async () => { * await posthog.shutdown() * process.exit(0) * }) * ``` * * @public * * @param {number} [shutdownTimeoutMs=30000] Maximum time to wait for shutdown in milliseconds * @returns {Promise} A promise that resolves when shutdown is complete */ shutdown(shutdownTimeoutMs?: number): Promise; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/extensions/context/types.d.ts interface ContextData { distinctId?: string; sessionId?: string; properties?: Record; } interface ContextOptions { /** * If true, replaces the current context entirely. * If false, merges with the existing context (new values override existing ones). * @default false */ fresh?: boolean; } interface IPostHogContext { get(): ContextData | undefined; run(context: ContextData, fn: () => T, options?: ContextOptions): T; enter(context: ContextData, options?: ContextOptions): void; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/feature-flag-evaluations.d.ts /** * Internal per-flag record stored by a {@link FeatureFlagEvaluations} instance. * Not part of the public API. * * @internal */ type EvaluatedFlagRecord = { key: string; enabled: boolean; variant: string | undefined; payload: JsonType | undefined; id: number | undefined; version: number | undefined; reason: string | undefined; locallyEvaluated: boolean; }; /** * Parameters passed to the host when a `$feature_flag_called` event should be captured. * * @internal */ type FlagCalledEventParams = { distinctId: string; key: string; response: FeatureFlagValue | undefined; groups: Record | undefined; disableGeoip: boolean | undefined; properties: Record; }; /** * Thin interface the evaluations object uses to talk back to the PostHog client. * Keeps the class decoupled from the full client surface area. * * @internal */ interface FeatureFlagEvaluationsHost { captureFlagCalledEventIfNeeded(params: FlagCalledEventParams): void; logWarning(message: string): void; } /** * A snapshot of feature flag evaluations for a single distinctId at a point in time. * * Returned by {@link IPostHog.evaluateFlags} — branch on `isEnabled()` / `getFlag()` * and pass the same object to `capture()` via the `flags` option so the captured event * carries the exact flag values the code branched on. * * ```ts * const flags = await posthog.evaluateFlags(distinctId, { personProperties: { plan: 'enterprise' } }) * * if (flags.isEnabled('new-dashboard')) { * renderNewDashboard() * } * * posthog.capture({ distinctId, event: 'page_viewed', flags }) * ``` * * To narrow the set of flags that get attached to a captured event, use the in-memory * helpers `only([...])` and `onlyAccessed()`. To narrow the set of flags requested from * the server in the first place, pass `flagKeys` to `evaluateFlags()`. */ declare class FeatureFlagEvaluations { private readonly _host; private readonly _distinctId; private readonly _groups; private readonly _disableGeoip; private readonly _flags; private readonly _requestId; private readonly _evaluatedAt; private readonly _flagDefinitionsLoadedAt; private readonly _errorsWhileComputing; private readonly _quotaLimited; private readonly _accessed; private readonly _isSlice; /** * @internal — instances are created by the SDK via `posthog.evaluateFlags()`. */ constructor(init: { host: FeatureFlagEvaluationsHost; distinctId: string; groups?: Record; disableGeoip?: boolean; flags: Record; requestId?: string; evaluatedAt?: number; flagDefinitionsLoadedAt?: number; errorsWhileComputing?: boolean; quotaLimited?: boolean; accessed?: Set; isSlice?: boolean; }); /** * Check whether a feature flag is enabled. Fires a `$feature_flag_called` event * on the first access per (distinctId, flag, value) tuple, deduped via the SDK's * existing cache. * * Flags that were not returned from the underlying evaluation are treated as * disabled (returns `false`). */ isEnabled(key: string): boolean; /** * Get the evaluated value of a feature flag. Fires a `$feature_flag_called` event * on the first access per (distinctId, flag, value) tuple. * * Returns the variant string for multivariate flags, `true` for enabled flags * without a variant, `false` for disabled flags, and `undefined` for flags that * were not returned by the evaluation. */ getFlag(key: string): FeatureFlagValue | undefined; /** * Get the payload associated with a feature flag. Does not count as an access * for `onlyAccessed()` and does not fire any event. */ getFlagPayload(key: string): JsonType | undefined; /** * Return a filtered copy containing only flags that have been accessed via * `isEnabled()` or `getFlag()` before this call. * * Order-dependent: if nothing has been accessed yet, the returned snapshot is * empty. The method honors its name — pre-access if you want a populated result. * * **Note:** the returned snapshot is intended for `capture()`, not for further * branching. Calling `isEnabled()` / `getFlag()` on it for a key that was filtered * out is a no-op (no event is fired) — the flag wasn't actually missing, it was * excluded from the slice. */ onlyAccessed(): FeatureFlagEvaluations; /** * Return a filtered copy containing only flags with the given keys. Keys that * are not present in the evaluation are dropped and logged as a warning. * * **Note:** like `onlyAccessed()`, the returned snapshot is intended for `capture()`. * Branching on a filtered key that was excluded from the slice is a no-op. */ only(keys: string[]): FeatureFlagEvaluations; /** * Returns the flag keys that are part of this evaluation. */ get keys(): string[]; /** * Build the `$feature/*` and `$active_feature_flags` event properties derived * from the current flag set. Called by `capture()` when an event is captured * with `flags: ...`. * * @internal */ _getEventProperties(): Record; private _cloneWith; private _recordAccess; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/extensions/feature-flags/cache.d.ts /** * Represents the complete set of feature flag data needed for local evaluation. * * This includes flag definitions, group type mappings, and cohort property groups. */ interface FlagDefinitionCacheData { /** Array of feature flag definitions */ flags: PostHogFeatureFlag[]; /** Mapping of group type index to group name */ groupTypeMapping: Record; /** Cohort property groups for local evaluation */ cohorts: Record; } /** * Provider interface for caching feature flag definitions. * * Implementations can use this to control when flag definitions are fetched * and how they're cached (Redis, database, filesystem, etc.). * * This interface is designed for server-side environments where multiple workers * need to share flag definitions and coordinate fetching to reduce API calls. * * All methods may throw errors - the poller will catch and log them gracefully, * ensuring cache provider errors never break flag evaluation. * * @example * ```typescript * import type { FlagDefinitionCacheData, FlagDefinitionCacheProvider } from 'posthog-node' * * class RedisFlagCache implements FlagDefinitionCacheProvider { * constructor(private redis: Redis, private teamKey: string) { } * * async getFlagDefinitions(): Promise { * const cached = await this.redis.get(`posthog:flags:${this.teamKey}`) * return cached ? JSON.parse(cached) : undefined * } * * async shouldFetchFlagDefinitions(): Promise { * // Acquire distributed lock - only one worker fetches * const acquired = await this.redis.set(`posthog:flags:${this.teamKey}:lock`, '1', 'EX', 60, 'NX') * return acquired === 'OK' * } * * async onFlagDefinitionsReceived(data: FlagDefinitionCacheData): Promise { * await this.redis.set(`posthog:flags:${this.teamKey}`, JSON.stringify(data), 'EX', 300) * await this.redis.del(`posthog:flags:${this.teamKey}:lock`) * } * * async shutdown(): Promise { * await this.redis.del(`posthog:flags:${this.teamKey}:lock`) * } * } * ``` */ interface FlagDefinitionCacheProvider { /** * Retrieve cached flag definitions. * * Called when the poller is refreshing in-memory flag definitions. If this returns undefined * (or throws an error), the poller will fetch fresh data from the PostHog API if no flag * definitions are in memory. Otherwise, stale cache data is used until the next poll cycle. * * @returns cached definitions if available, undefined if cache is empty * @throws if an error occurs while accessing the cache (error will be logged) */ getFlagDefinitions(): Promise | FlagDefinitionCacheData | undefined; /** * Determines whether this instance should fetch new flag definitions. * * Use this to implement distributed coordination (e.g., via distributed locks) * to ensure only one instance fetches at a time in a multi-worker setup. * * When multiple workers share a cache, typically only one should fetch while * others use cached data. Implementations can use Redis locks, database locks, * or other coordination mechanisms. * * @returns true if this instance should fetch, false to skip and read cache * @throws if coordination backend is unavailable (error will be logged, fetch continues) */ shouldFetchFlagDefinitions(): Promise | boolean; /** * Called after successfully receiving new flag definitions from PostHog. * * Store the definitions in your cache backend here. This is called only * after a successful API response with valid flag data. * * If this method throws, the error is logged but flag definitions are still * stored in memory, ensuring local evaluation can still be performed. * * @param data - The complete flag definition data from PostHog * @throws if storage backend is unavailable (error will be logged) */ onFlagDefinitionsReceived(data: FlagDefinitionCacheData): Promise | void; /** * Called when the PostHog client shuts down. * * Release any held locks, close connections, or clean up resources here. * * Both sync and async cleanup are supported. Async cleanup has a timeout * (default 30s, configurable via client shutdown options) to prevent the * process shutdown from hanging indefinitely. * * @returns Promise that resolves when cleanup is complete, or void for sync cleanup */ shutdown(): Promise | void; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/types.d.ts type IdentifyMessage = { distinctId: string; properties?: Record; disableGeoip?: boolean; }; type SendFeatureFlagsOptions = { onlyEvaluateLocally?: boolean; personProperties?: Record; groupProperties?: Record>; flagKeys?: string[]; }; type EventMessage = Omit & { distinctId?: string; event: string; groups?: Record; /** * Attach feature flag values evaluated via `posthog.evaluateFlags()` to this event. * Prefer this over `sendFeatureFlags` — it guarantees the event carries the exact * values the code branched on and avoids a hidden `/flags` request on every capture. */ flags?: FeatureFlagEvaluations; /** * @deprecated Use the `flags` option with a `FeatureFlagEvaluations` object obtained * from `posthog.evaluateFlags()` instead. `sendFeatureFlags` fires a separate `/flags` * request on capture and may return different values than the ones the code branched on. */ sendFeatureFlags?: boolean | SendFeatureFlagsOptions; timestamp?: Date; uuid?: string; /** * Internal flag set by captureException() to indicate this $exception * event originated from the proper exception capture path. Used to warn users who call * capture() with '$exception' directly. */ _originatedFromCaptureException?: boolean; }; type GroupIdentifyMessage = { groupType: string; groupKey: string; properties?: Record; distinctId?: string; disableGeoip?: boolean; }; type PropertyGroup = { type: 'AND' | 'OR'; values: PropertyGroup[] | FlagProperty[]; }; type FlagProperty = { key: string; type?: string; value: FlagPropertyValue; operator?: string; negation?: boolean; dependency_chain?: string[]; }; type FlagPropertyValue = string | number | (string | number)[] | boolean; /** * Options for overriding feature flags. * * Supports multiple formats: * - `false` - Clear all overrides * - `string[]` - Enable a list of flags (sets them to `true`) * - `Record` - Set specific flag values/variants * - `FeatureFlagOverrideOptions` - Set both flag values and payloads */ type OverrideFeatureFlagsOptions = false | string[] | Record | FeatureFlagOverrideOptions; type BaseFlagEvaluationOptions = { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; disableGeoip?: boolean; }; type FlagEvaluationOptions = BaseFlagEvaluationOptions & { sendFeatureFlagEvents?: boolean; }; type AllFlagsOptions = BaseFlagEvaluationOptions & { flagKeys?: string[]; }; type FeatureFlagOverrideOptions = { /** * Flag overrides. Can be: * - `false` to clear flag overrides * - `string[]` to enable a list of flags * - `Record` to set specific values/variants */ flags?: false | string[] | Record; /** * Payload overrides for flags. * - `false` to clear payload overrides * - `Record` to set specific payloads */ payloads?: false | Record; }; type FeatureFlagCondition = { properties: FlagProperty[]; rollout_percentage?: number; variant?: string; aggregation_group_type_index?: number | null; }; type FeatureFlagBucketingIdentifier = 'distinct_id' | 'device_id' | '' | null; type BeforeSendFn = (event: EventMessage | null) => EventMessage | null; type PostHogOptions = Omit & { persistence?: 'memory'; personalApiKey?: string; privacyMode?: boolean; enableExceptionAutocapture?: boolean; featureFlagsPollingInterval?: number; maxCacheSize?: number; fetch?: (url: string, options: PostHogFetchOptions) => Promise; enableLocalEvaluation?: boolean; /** * Optional cache provider for feature flag definitions. * * Allows custom caching strategies (Redis, database, etc.) for flag definitions * in multi-worker environments. If not provided, defaults to in-memory cache. * * This enables distributed coordination where only one worker fetches flags while * others use cached data, reducing API calls and improving performance. * * @example * ```typescript * import type { FlagDefinitionCacheProvider } from 'posthog-node' * * class RedisCacheProvider implements FlagDefinitionCacheProvider { * // ... implementation * } * * const client = new PostHog('api-key', { * personalApiKey: 'personal-key', * flagDefinitionCacheProvider: new RedisCacheProvider(redis) * }) * ``` */ flagDefinitionCacheProvider?: FlagDefinitionCacheProvider; /** * Allows modification or dropping of events before they're sent to PostHog. * If an array is provided, the functions are run in order. * If a function returns null, the event will be dropped. */ before_send?: BeforeSendFn | BeforeSendFn[]; /** * Evaluation contexts for feature flags. * When set, only feature flags that have at least one matching evaluation tag * will be evaluated for this SDK instance. Feature flags with no evaluation tags * will always be evaluated. * * Examples: ['production', 'backend', 'api'] * * @default undefined */ evaluationContexts?: readonly string[]; /** * Evaluation environments for feature flags. * @deprecated Use evaluationContexts instead. This property will be removed in a future version. */ evaluationEnvironments?: readonly string[]; /** * Additional user agent strings to block from being tracked. * These are combined with the default list of blocked user agents. * * @default [] */ custom_blocked_useragents?: string[]; /** * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION * Enables collection of bot traffic as $bot_pageview events instead of dropping them. * When enabled, events with a $raw_user_agent property that matches the bot detection list * will have their $pageview event renamed to $bot_pageview. * * To use this feature, pass the user agent in event properties: * ```ts * client.capture({ * distinctId: 'user_123', * event: '$pageview', * properties: { * $raw_user_agent: req.headers['user-agent'] * } * }) * ``` */ __preview_capture_bot_pageviews?: boolean; /** * When enabled, all feature flag evaluations will use local evaluation only, * never falling back to server-side evaluation. This prevents unexpected server * requests and associated costs when using local evaluation. * * Flags that cannot be evaluated locally (e.g., those with experience continuity) * will return `undefined` instead of making a server request. * * @default false */ strictLocalEvaluation?: boolean; /** * Controls whether `FeatureFlagEvaluations` filter helpers (`onlyAccessed()` and * `only()`) log warnings when their input is unexpected — for example, calling * `onlyAccessed()` before accessing any flags, or passing unknown keys to `only()`. * * @default true */ featureFlagsLogWarnings?: boolean; /** * Provides the API to extend the lifetime of a serverless invocation until * background work (like flushing analytics events) completes after the response * is sent. * * @experimental Subject to change in a minor release. * * @example * // Vercel * import { waitUntil } from '@vercel/functions' * new PostHog('key', { waitUntil }) */ waitUntil?: (promise: Promise) => void; /** * Debounce interval in milliseconds for the `waitUntil`-based flush. * After the last event is enqueued, the SDK waits this long before flushing. * * @experimental Subject to change in a minor release. * @default 50 */ waitUntilDebounceMs?: number; /** * Maximum time in milliseconds to debounce before forcing a flush. * Prevents starvation from rapid concurrent captures. * * @experimental Subject to change in a minor release. * @default 500 */ waitUntilMaxWaitMs?: number; /** * Whether to attach the `$is_server: true` property to every captured event. * * @remarks * Defaults to `true` because this SDK is intended for server-side use, where * the property lets PostHog distinguish server events from browser and * react-native events. Set this to `false` when running the SDK as a * client/CLI so the event is attributed to the device OS normally instead of * being marked as a server event. When `false`, the `$is_server` property is * omitted entirely. * * @default true * @example * // CLI usage: don't mark events as server-side * new PostHog('key', { isServer: false }) */ isServer?: boolean; }; type PostHogFeatureFlag = { id: number; name: string; key: string; bucketing_identifier?: FeatureFlagBucketingIdentifier; filters?: { aggregation_group_type_index?: number; groups?: FeatureFlagCondition[]; multivariate?: { variants: { key: string; rollout_percentage: number; }[]; }; payloads?: Record; }; deleted: boolean; active: boolean; rollout_percentage: null | number; ensure_experience_continuity: boolean; experiment_set: number[]; }; /** * Result of evaluating a feature flag, including its value and payload. */ type FeatureFlagResult = { key: string; enabled: boolean; variant: string | undefined; payload: JsonType | undefined; }; interface IPostHog { /** * @description Capture allows you to capture anything a user does within your system, * which you can later use in PostHog to find patterns in usage, * work out which features to improve or where people are giving up. * A capture call requires: * @param distinctId which uniquely identifies your user * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on. * @param properties OPTIONAL | which can be a object with any information you'd like to add * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users. * @param flags OPTIONAL | A `FeatureFlagEvaluations` snapshot from `evaluateFlags()`. Attaches those exact flag values to the event with no extra network call. * @param sendFeatureFlags OPTIONAL | Deprecated — prefer `flags`. Fires a hidden `/flags` request on capture to enrich the event with flag values. */ capture({ distinctId, event, properties, groups, flags, sendFeatureFlags }: EventMessage): void; /** * @description Capture an event immediately. Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls. * @param distinctId which uniquely identifies your user * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on. * @param properties OPTIONAL | which can be a object with any information you'd like to add * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users. * @param flags OPTIONAL | A `FeatureFlagEvaluations` snapshot from `evaluateFlags()`. Attaches those exact flag values to the event with no extra network call. * @param sendFeatureFlags OPTIONAL | Deprecated — prefer `flags`. Fires a hidden `/flags` request on capture to enrich the event with flag values. */ captureImmediate({ distinctId, event, properties, groups, flags, sendFeatureFlags }: EventMessage): Promise; /** * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog, * and even do things like segment users by these properties. * An identify call requires: * @param distinctId which uniquely identifies your user * @param properties with a dict with any key: value pairs */ identify({ distinctId, properties }: IdentifyMessage): void; /** * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog. * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls. * @param distinctId which uniquely identifies your user * @param properties with a dict with any key: value pairs */ identifyImmediate({ distinctId, properties }: IdentifyMessage): Promise; /** * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" * or "What do users do on our website before signing up?" * In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call. * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID. * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end, * doing the identify call in the frontend will be enough.: * @param distinctId the current unique id * @param alias the unique ID of the user before */ alias(data: { distinctId: string; alias: string; }): void; /** * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls. * @param distinctId the current unique id * @param alias the unique ID of the user before */ aliasImmediate(data: { distinctId: string; alias: string; }): Promise; /** * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags) * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog, * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn * features on and off for different user groups or individual users. * @param key the unique key of your feature flag * @param distinctId the current unique id * @param options: dict with optional parameters below * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups. * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present. * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present. * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false. * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true. * * @returns true if the flag is on, false if the flag is off, undefined if there was an error. * * @deprecated Use {@link IPostHog.evaluateFlags} and call `flags.isEnabled(key)` on the * returned snapshot. Will be removed in the next major version. */ isFeatureEnabled(key: string, distinctId: string, options?: { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; }): Promise; /** * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags) * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog, * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn * features on and off for different user groups or individual users. * @param key the unique key of your feature flag * @param distinctId the current unique id * @param options: dict with optional parameters below * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups. * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present. * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present. * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false. * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true. * * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error. * * @deprecated Use {@link IPostHog.evaluateFlags} and call `flags.getFlag(key)` on the * returned snapshot. Will be removed in the next major version. */ getFeatureFlag(key: string, distinctId: string, options?: { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; }): Promise; /** * @description Retrieves payload associated with the specified flag and matched value that is passed in. * * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`. * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()` * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can * not be evaluated locally. This means that omitting `matchValue` will potentially: * - Bypass local evaluation * - Count as an additional flag evaluation against your quota * - Impact performance due to the extra network request * * Example usage: * ```js * const flagValue = await client.getFeatureFlag('my-flag', distinctId); * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue); * ``` * * @param key the unique key of your feature flag * @param distinctId the current unique id * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean. * To avoid extra network calls, pass this parameter when you can. * @param options: dict with optional parameters below * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false. * * @returns payload of a json type object * * @deprecated Use {@link IPostHog.evaluateFlags} and call `flags.getFlagPayload(key)` on * the returned snapshot. Will be removed in the next major version. */ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: { onlyEvaluateLocally?: boolean; }): Promise; /** * @description Get all feature flag values using distinctId from withContext(). */ getAllFlags(options?: AllFlagsOptions): Promise>; /** * @description Get all feature flag values for a specific user. * * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to a record of flag keys and their values */ getAllFlags(distinctId: string, options?: AllFlagsOptions): Promise>; /** * @description Get all feature flag values and payloads using distinctId from withContext(). */ getAllFlagsAndPayloads(options?: AllFlagsOptions): Promise; /** * @description Get all feature flag values and payloads for a specific user. * * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to flags and payloads */ getAllFlagsAndPayloads(distinctId: string, options?: AllFlagsOptions): Promise; /** * @description Get a feature flag result using distinctId from withContext(). */ getFeatureFlagResult(key: string, options?: FlagEvaluationOptions): Promise; /** * @description Get the result of evaluating a feature flag, including its value and payload. * This is more efficient than calling getFeatureFlag and getFeatureFlagPayload separately when you need both. * * @example * ```ts * const result = await client.getFeatureFlagResult('my-flag', 'user_123') * if (result) { * console.log('Flag enabled:', result.enabled) * console.log('Variant:', result.variant) * console.log('Payload:', result.payload) * } * ``` * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to the flag result or undefined */ getFeatureFlagResult(key: string, distinctId: string, options?: FlagEvaluationOptions): Promise; /** * @description Evaluate all feature flags for a user in a single call and return a * {@link FeatureFlagEvaluations} snapshot. Branch on `.isEnabled()` / `.getFlag()`, * then pass the same snapshot to `capture()` via the `flags` option so events carry * the exact flag values the code branched on. * * Prefer this over calling `isFeatureEnabled()` / `getFeatureFlag()` repeatedly and * over `capture({ sendFeatureFlags: true })` — it avoids multiple `/flags` requests * per incoming request. * * @example * ```ts * const flags = await posthog.evaluateFlags('user_123', { personProperties: { plan: 'enterprise' } }) * if (flags.isEnabled('new-dashboard')) { * renderNewDashboard() * } * posthog.capture({ distinctId: 'user_123', event: 'page_viewed', flags }) * ``` * * @param options - Optional configuration for flag evaluation. Pass `flagKeys` to scope the underlying `/flags` request to a subset of flags. */ evaluateFlags(options?: AllFlagsOptions): Promise; /** * @description Evaluate all feature flags for a specific user. * * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation. Pass `flagKeys` to scope the underlying `/flags` request to a subset of flags. */ evaluateFlags(distinctId: string, options?: AllFlagsOptions): Promise; /** * @description Sets a groups properties, which allows asking questions like "Who are the most active companies" * using my product in PostHog. * * @param groupType Type of group (ex: 'company'). Limited to 5 per project * @param groupKey Unique identifier for that type of group (ex: 'id:5') * @param properties OPTIONAL | which can be a object with any information you'd like to add */ groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void; /** * @description Force an immediate reload of the polled feature flags. Please note that they are * already polled automatically at a regular interval. */ reloadFeatureFlags(): Promise; /** * @description Override feature flags locally. Useful for testing and local development. * Overridden flags take precedence over both local evaluation and remote evaluation. * * @example * ```ts * // Clear all overrides * posthog.overrideFeatureFlags(false) * * // Enable a list of flags (sets them to true) * posthog.overrideFeatureFlags(['flag-a', 'flag-b']) * * // Set specific flag values/variants * posthog.overrideFeatureFlags({ 'my-flag': 'variant-a', 'other-flag': true }) * * // Set both flags and payloads * posthog.overrideFeatureFlags({ * flags: { 'my-flag': 'variant-a' }, * payloads: { 'my-flag': { discount: 20 } } * }) * ``` * * @param overrides - Flag overrides configuration */ overrideFeatureFlags(overrides: OverrideFeatureFlagsOptions): void; /** * @description Run a function with specific context that will be applied to all events captured within that context. * @param data Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture) * @param fn Function to run with the context * @param options Context options (fresh) * @returns The return value of the function */ withContext(data: Partial, fn: () => T, options?: ContextOptions): T; /** * @description Set context without a callback wrapper. Must be called in the same * async scope that makes PostHog calls. Prefer `withContext()` when you can wrap * code in a callback. * @param data Context data to apply (distinctId, sessionId, properties) * @param options Context options (fresh) */ enterContext(data: Partial, options?: ContextOptions): void; /** * @description Get the current context data. * @returns The current context data, or undefined if no context is set */ getContext(): ContextData | undefined; /** * @description Flushes the events still in the queue and clears the feature flags poller to allow for * a clean shutdown. * * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s). */ shutdown(shutdownTimeoutMs?: number): void; /** * @description Waits for local evaluation to be ready, with an optional timeout. * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds. * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached. */ waitForLocalEvaluationReady(timeoutMs?: number): Promise; /** * @description Returns true if local evaluation is ready, false if it's not. * @returns true if local evaluation is ready, false if it's not. */ isLocalEvaluationReady(): boolean; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/extensions/error-tracking/index.d.ts declare class ErrorTracking { private client; private _exceptionAutocaptureEnabled; private _rateLimiter; private _logger; constructor(client: PostHogBackendClient, options: PostHogOptions, _logger: Logger); static isPreviouslyCapturedError(x: unknown): boolean; static buildEventMessage(builder: ErrorPropertiesBuilder, error: unknown, hint: EventHint, distinctId?: string, additionalProperties?: Record): Promise; private startAutocaptureIfEnabled; private onException; private onFatalError; isEnabled(): boolean; shutdown(): void; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/client.d.ts declare abstract class PostHogBackendClient extends PostHogCoreStateless implements IPostHog { private _memoryStorage; private featureFlagsPoller?; protected errorTracking: ErrorTracking; private maxCacheSize; readonly options: PostHogOptions; protected readonly context?: IPostHogContext; private _flagOverrides?; private _payloadOverrides?; distinctIdHasSentFlagCalls: Record>; private _waitUntilCycle?; /** * Initialize a new PostHog client instance. * * @example * ```ts * // Basic initialization * const client = new PostHogBackendClient( * 'your-api-key', * { host: 'https://app.posthog.com' } * ) * ``` * * @example * ```ts * // With personal API key * const client = new PostHogBackendClient( * 'your-api-key', * { * host: 'https://app.posthog.com', * personalApiKey: 'your-personal-api-key' * } * ) * ``` * * {@label Initialization} * * @param apiKey - Your PostHog project API key * @param options - Configuration options for the client */ constructor(apiKey: string, options?: PostHogOptions); protected enqueue(type: string, message: any, options?: PostHogCaptureOptions): void; flush(): Promise; private scheduleDebouncedFlush; private _consumeWaitUntilCycle; private resolveWaitUntilFlush; /** * Get a persisted property value from memory storage. * * @example * ```ts * // Get user ID * const userId = client.getPersistedProperty('userId') * ``` * * @example * ```ts * // Get session ID * const sessionId = client.getPersistedProperty('sessionId') * ``` * * {@label Initialization} * * @param key - The property key to retrieve * @returns The stored property value or undefined if not found */ getPersistedProperty(key: PostHogPersistedProperty): any | undefined; /** * Set a persisted property value in memory storage. * * @example * ```ts * // Set user ID * client.setPersistedProperty('userId', 'user_123') * ``` * * @example * ```ts * // Set session ID * client.setPersistedProperty('sessionId', 'session_456') * ``` * * {@label Initialization} * * @param key - The property key to set * @param value - The value to store (null to remove) */ setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void; /** * Make an HTTP request using the configured fetch function or default fetch. * * @example * ```ts * // POST request * const response = await client.fetch('/api/endpoint', { * method: 'POST', * headers: { 'Content-Type': 'application/json' }, * body: JSON.stringify(data) * }) * ``` * * @internal * * {@label Initialization} * * @param url - The URL to fetch * @param options - Fetch options * @returns Promise resolving to the fetch response */ fetch(url: string, options: PostHogFetchOptions): Promise; /** * Get the library version from package.json. * * @example * ```ts * // Get version * const version = client.getLibraryVersion() * console.log(`Using PostHog SDK version: ${version}`) * ``` * * {@label Initialization} * * @returns The current library version string */ getLibraryVersion(): string; /** * Get the custom user agent string for this client. * * @example * ```ts * // Get user agent * const userAgent = client.getCustomUserAgent() * // Returns: "posthog-node/5.7.0" * ``` * * {@label Identification} * * @returns The formatted user agent string */ getCustomUserAgent(): string; /** * Returns the common properties attached to every captured event. * * @remarks * Extends the shared core properties (`$lib`, `$lib_version`) with * `$is_server: true` so that events emitted from the server-side SDKs * (posthog-node and posthog-edge, which both extend this class) are * distinguishable from browser and react-native events. Browser and * react-native clients do not extend `PostHogBackendClient`, so they * never receive this property. * * This is controlled by the `isServer` option, which defaults to `true`. * When `isServer` is `false` (e.g. when using the SDK as a client/CLI), the * `$is_server` property is omitted entirely so the device OS is attributed * normally. * * @returns The common event properties, including `$is_server: true` when * the `isServer` option is enabled. */ protected getCommonEventProperties(): PostHogEventProperties; /** * Enable the PostHog client (opt-in). * * @example * ```ts * // Enable client * await client.enable() * // Client is now enabled and will capture events * ``` * * {@label Privacy} * * @returns Promise that resolves when the client is enabled */ enable(): Promise; /** * Disable the PostHog client (opt-out). * * @example * ```ts * // Disable client * await client.disable() * // Client is now disabled and will not capture events * ``` * * {@label Privacy} * * @returns Promise that resolves when the client is disabled */ disable(): Promise; /** * Enable or disable debug logging. * * @example * ```ts * // Enable debug logging * client.debug(true) * ``` * * @example * ```ts * // Disable debug logging * client.debug(false) * ``` * * {@label Initialization} * * @param enabled - Whether to enable debug logging */ debug(enabled?: boolean): void; /** * Capture an event manually. * * @example * ```ts * // Basic capture * client.capture({ * distinctId: 'user_123', * event: 'button_clicked', * properties: { button_color: 'red' } * }) * ``` * * {@label Capture} * * @param props - The event properties * @returns void */ capture(props: EventMessage): void; /** * Capture an event immediately (synchronously). * * @example * ```ts * // Basic immediate capture * await client.captureImmediate({ * distinctId: 'user_123', * event: 'button_clicked', * properties: { button_color: 'red' } * }) * ``` * * @example * ```ts * // With feature flags * await client.captureImmediate({ * distinctId: 'user_123', * event: 'user_action', * sendFeatureFlags: true * }) * ``` * * @example * ```ts * // With custom feature flags options * await client.captureImmediate({ * distinctId: 'user_123', * event: 'user_action', * sendFeatureFlags: { * onlyEvaluateLocally: true, * personProperties: { plan: 'premium' }, * groupProperties: { org: { tier: 'enterprise' } } * flagKeys: ['flag1', 'flag2'] * } * }) * ``` * * {@label Capture} * * @param props - The event properties * @returns Promise that resolves when the event is captured */ captureImmediate(props: EventMessage): Promise; /** * Identify a user and set their properties. * * @example * ```ts * // Basic identify with properties * client.identify({ * distinctId: 'user_123', * properties: { * name: 'John Doe', * email: 'john@example.com', * plan: 'premium' * } * }) * ``` * * @example * ```ts * // Using $set and $set_once * client.identify({ * distinctId: 'user_123', * properties: { * $set: { name: 'John Doe', email: 'john@example.com' }, * $set_once: { first_login: new Date().toISOString() } * $anon_distinct_id: 'anonymous_user_456' * } * }) * ``` * * {@label Identification} * * @param data - The identify data containing distinctId and properties */ identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void; /** * Identify a user and set their properties immediately (synchronously). * * @example * ```ts * // Basic immediate identify * await client.identifyImmediate({ * distinctId: 'user_123', * properties: { * name: 'John Doe', * email: 'john@example.com' * } * }) * ``` * * {@label Identification} * * @param data - The identify data containing distinctId and properties * @returns Promise that resolves when the identify is processed */ identifyImmediate({ distinctId, properties, disableGeoip }: IdentifyMessage): Promise; /** * Create an alias to link two distinct IDs together. * * @example * ```ts * // Link an anonymous user to an identified user * client.alias({ * distinctId: 'anonymous_123', * alias: 'user_456' * }) * ``` * * {@label Identification} * * @param data - The alias data containing distinctId and alias */ alias(data: { distinctId: string; alias: string; disableGeoip?: boolean; }): void; /** * Create an alias to link two distinct IDs together immediately (synchronously). * * @example * ```ts * // Link an anonymous user to an identified user immediately * await client.aliasImmediate({ * distinctId: 'anonymous_123', * alias: 'user_456' * }) * ``` * * {@label Identification} * * @param data - The alias data containing distinctId and alias * @returns Promise that resolves when the alias is processed */ aliasImmediate(data: { distinctId: string; alias: string; disableGeoip?: boolean; }): Promise; /** * Check if local evaluation of feature flags is ready. * * @example * ```ts * // Check if ready * if (client.isLocalEvaluationReady()) { * // Local evaluation is ready, can evaluate flags locally * const flag = await client.getFeatureFlag('flag-key', 'user_123') * } else { * // Local evaluation not ready, will use remote evaluation * const flag = await client.getFeatureFlag('flag-key', 'user_123') * } * ``` * * {@label Feature flags} * * @returns true if local evaluation is ready, false otherwise */ isLocalEvaluationReady(): boolean; /** * Wait for local evaluation of feature flags to be ready. * * @example * ```ts * // Wait for local evaluation * const isReady = await client.waitForLocalEvaluationReady() * if (isReady) { * console.log('Local evaluation is ready') * } else { * console.log('Local evaluation timed out') * } * ``` * * @example * ```ts * // Wait with custom timeout * const isReady = await client.waitForLocalEvaluationReady(10000) // 10 seconds * ``` * * {@label Feature flags} * * @param timeoutMs - Timeout in milliseconds (default: 30000) * @returns Promise that resolves to true if ready, false if timed out */ waitForLocalEvaluationReady(timeoutMs?: number): Promise; private _resolveDistinctId; /** * Internal method that handles feature flag evaluation with full details. * Used by getFeatureFlag, getFeatureFlagPayload, and getFeatureFlagResult. * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param options - Evaluation options (includes sendFeatureFlagEvents, defaults to true) * @param matchValue - Optional match value for payload lookup (used by getFeatureFlagPayload) * @returns Promise that resolves to the flag result or undefined */ private _getFeatureFlagResult; /** * Get the value of a feature flag for a specific user. * * @example * ```ts * // Basic feature flag check * const flagValue = await client.getFeatureFlag('new-feature', 'user_123') * if (flagValue === 'variant-a') { * // Show variant A * } else if (flagValue === 'variant-b') { * // Show variant B * } else { * // Flag is disabled or not found * } * ``` * * @example * ```ts * // With groups and properties * const flagValue = await client.getFeatureFlag('org-feature', 'user_123', { * groups: { organization: 'acme-corp' }, * personProperties: { plan: 'enterprise' }, * groupProperties: { organization: { tier: 'premium' } } * }) * ``` * * @example * ```ts * // Only evaluate locally * const flagValue = await client.getFeatureFlag('local-flag', 'user_123', { * onlyEvaluateLocally: true * }) * ``` * * {@label Feature flags} * * @deprecated Use {@link evaluateFlags} and call `flags.getFlag(key)` on the returned snapshot. * This consolidates flag evaluation into a single `/flags` request per incoming request and * avoids drift between the values your code branched on and the values attached to events. * Will be removed in the next major version. * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to the flag value or undefined */ getFeatureFlag(key: string, distinctId: string, options?: { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }): Promise; /** * Get the payload for a feature flag. * * @example * ```ts * // Get payload for a feature flag * const payload = await client.getFeatureFlagPayload('flag-key', 'user_123') * if (payload) { * console.log('Flag payload:', payload) * } * ``` * * @example * ```ts * // Get payload with specific match value * const payload = await client.getFeatureFlagPayload('flag-key', 'user_123', 'variant-a') * ``` * * @example * ```ts * // With groups and properties * const payload = await client.getFeatureFlagPayload('org-flag', 'user_123', undefined, { * groups: { organization: 'acme-corp' }, * personProperties: { plan: 'enterprise' } * }) * ``` * * {@label Feature flags} * * @deprecated Use {@link evaluateFlags} and call `flags.getFlagPayload(key)` on the returned * snapshot. This consolidates flag evaluation into a single `/flags` request per incoming * request. Will be removed in the next major version. * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param matchValue - Optional match value to get payload for * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to the flag payload or undefined */ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; /** @deprecated THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. */ sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }): Promise; /** * Get the result of evaluating a feature flag, including its value and payload. * This is more efficient than calling getFeatureFlag and getFeatureFlagPayload separately when you need both. * * @example * ```ts * // Get flag result * const result = await client.getFeatureFlagResult('my-flag', 'user_123') * if (result) { * console.log('Flag enabled:', result.enabled) * console.log('Variant:', result.variant) * console.log('Payload:', result.payload) * } * ``` * * @example * ```ts * // With groups and properties * const result = await client.getFeatureFlagResult('org-feature', 'user_123', { * groups: { organization: 'acme-corp' }, * personProperties: { plan: 'enterprise' } * }) * ``` * * {@label Feature flags} * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to the flag result or undefined */ getFeatureFlagResult(key: string, options?: FlagEvaluationOptions): Promise; getFeatureFlagResult(key: string, distinctId: string, options?: FlagEvaluationOptions): Promise; /** * Get the remote config payload for a feature flag. * * @example * ```ts * // Get remote config payload * const payload = await client.getRemoteConfigPayload('flag-key') * if (payload) { * console.log('Remote config payload:', payload) * } * ``` * * {@label Feature flags} * * @param flagKey - The feature flag key * @returns Promise that resolves to the remote config payload or undefined * @throws Error if personal API key is not provided */ getRemoteConfigPayload(flagKey: string): Promise; /** * Check if a feature flag is enabled for a specific user. * * @example * ```ts * // Basic feature flag check * const isEnabled = await client.isFeatureEnabled('new-feature', 'user_123') * if (isEnabled) { * // Feature is enabled * console.log('New feature is active') * } else { * // Feature is disabled * console.log('New feature is not active') * } * ``` * * @example * ```ts * // With groups and properties * const isEnabled = await client.isFeatureEnabled('org-feature', 'user_123', { * groups: { organization: 'acme-corp' }, * personProperties: { plan: 'enterprise' } * }) * ``` * * {@label Feature flags} * * @deprecated Use {@link evaluateFlags} and call `flags.isEnabled(key)` on the returned snapshot. * This consolidates flag evaluation into a single `/flags` request per incoming request. * Will be removed in the next major version. * * @param key - The feature flag key * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to true if enabled, false if disabled, undefined if not found */ isFeatureEnabled(key: string, distinctId: string, options?: { groups?: Record; personProperties?: Record; groupProperties?: Record>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }): Promise; /** * Get all feature flag values for a specific user. * * @example * ```ts * // Get all flags for a user * const allFlags = await client.getAllFlags('user_123') * console.log('User flags:', allFlags) * // Output: { 'flag-1': 'variant-a', 'flag-2': false, 'flag-3': 'variant-b' } * ``` * * @example * ```ts * // With specific flag keys * const specificFlags = await client.getAllFlags('user_123', { * flagKeys: ['flag-1', 'flag-2'] * }) * ``` * * @example * ```ts * // With groups and properties * const orgFlags = await client.getAllFlags('user_123', { * groups: { organization: 'acme-corp' }, * personProperties: { plan: 'enterprise' } * }) * ``` * * {@label Feature flags} * * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to a record of flag keys and their values */ getAllFlags(options?: AllFlagsOptions): Promise>; getAllFlags(distinctId: string, options?: AllFlagsOptions): Promise>; /** * Get all feature flag values and payloads for a specific user. * * @example * ```ts * // Get all flags and payloads for a user * const result = await client.getAllFlagsAndPayloads('user_123') * console.log('Flags:', result.featureFlags) * console.log('Payloads:', result.featureFlagPayloads) * ``` * * @example * ```ts * // With specific flag keys * const result = await client.getAllFlagsAndPayloads('user_123', { * flagKeys: ['flag-1', 'flag-2'] * }) * ``` * * @example * ```ts * // Only evaluate locally * const result = await client.getAllFlagsAndPayloads('user_123', { * onlyEvaluateLocally: true * }) * ``` * * {@label Feature flags} * * @param distinctId - The user's distinct ID * @param options - Optional configuration for flag evaluation * @returns Promise that resolves to flags and payloads */ getAllFlagsAndPayloads(options?: AllFlagsOptions): Promise; getAllFlagsAndPayloads(distinctId: string, options?: AllFlagsOptions): Promise; /** * Evaluate all feature flags for a user in a single call and return a * {@link FeatureFlagEvaluations} snapshot. Branch on `.isEnabled()` / `.getFlag()`, * then pass the same snapshot to `capture()` via the `flags` option so the * captured event carries the exact flag values the code branched on. * * Prefer this over repeated `isFeatureEnabled()` / `getFeatureFlag()` calls and * over `capture({ sendFeatureFlags: true })` — it consolidates flag evaluation * into a single `/flags` request per incoming request. * * **Local evaluation is transparent.** When the poller can resolve a flag from * cached definitions, no network call is made and the snapshot's `$feature_flag_called` * events are tagged `locally_evaluated: true`. * * **Trim the request.** Pass `flagKeys` to scope the underlying `/flags` request * to a subset of flags — useful when you only need a few flags and want to reduce * the response payload. * * **Trim the event payload.** Use `flags.only([...])` or `flags.onlyAccessed()` * to filter which flags get attached to a captured event without re-fetching. * * @example * Basic usage: * ```ts * const flags = await client.evaluateFlags('user_123', { * personProperties: { plan: 'enterprise' }, * }) * if (flags.isEnabled('new-dashboard')) { * renderNewDashboard() * } * client.capture({ distinctId: 'user_123', event: 'page_viewed', flags }) * ``` * * @example * Scope the `/flags` request to specific keys: * ```ts * const flags = await client.evaluateFlags('user_123', { * flagKeys: ['new-dashboard', 'checkout-flow'], * personProperties: { plan: 'enterprise' }, * }) * ``` * * @example * Attach only the flags the developer actually checked: * ```ts * const flags = await client.evaluateFlags('user_123') * if (flags.isEnabled('new-dashboard')) { ... } * client.capture({ distinctId: 'user_123', event: 'page_viewed', flags: flags.onlyAccessed() }) * ``` * * @example * Use `withContext()` to avoid repeating the distinctId: * ```ts * await client.withContext({ distinctId: 'user_123' }, async () => { * const flags = await client.evaluateFlags() * if (flags.isEnabled('new-dashboard')) { ... } * client.capture({ event: 'page_viewed', flags }) * }) * ``` * * {@label Feature flags} * * @param distinctIdOrOptions - The user's distinct ID, or options when the distinctId comes from `withContext()` * @param options - Optional configuration for flag evaluation. Supports the same fields as `getAllFlags()`, including `flagKeys` to scope the `/flags` request. * @returns Promise that resolves to a `FeatureFlagEvaluations` snapshot */ evaluateFlags(options?: AllFlagsOptions): Promise; evaluateFlags(distinctId: string, options?: AllFlagsOptions): Promise; /** * Fires a `$feature_flag_called` event for the given flag if the (distinctId, flag, response) * triple hasn't already been reported for this client. Shared by the single-flag evaluation * path and `FeatureFlagEvaluations.isEnabled() / getFlag()` so both paths dedupe identically. * * @internal */ protected _captureFlagCalledEventIfNeeded(params: FlagCalledEventParams): void; private _featureFlagEvaluationsHost?; private _getFeatureFlagEvaluationsHost; /** * Create or update a group and its properties. * * @example * ```ts * // Create a company group * client.groupIdentify({ * groupType: 'company', * groupKey: 'acme-corp', * properties: { * name: 'Acme Corporation', * industry: 'Technology', * employee_count: 500 * }, * distinctId: 'user_123' * }) * ``` * * @example * ```ts * // Update organization properties * client.groupIdentify({ * groupType: 'organization', * groupKey: 'org-456', * properties: { * plan: 'enterprise', * region: 'US-West' * } * }) * ``` * * {@label Identification} * * @param data - The group identify data */ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void; /** * Reload feature flag definitions from the server for local evaluation. * * @example * ```ts * // Force reload of feature flags * await client.reloadFeatureFlags() * console.log('Feature flags reloaded') * ``` * * @example * ```ts * // Reload before checking a specific flag * await client.reloadFeatureFlags() * const flag = await client.getFeatureFlag('flag-key', 'user_123') * ``` * * {@label Feature flags} * * @returns Promise that resolves when flags are reloaded */ reloadFeatureFlags(): Promise; /** * Override feature flags locally. Useful for testing and local development. * Overridden flags take precedence over both local evaluation and remote evaluation. * * @example * ```ts * // Clear all overrides * client.overrideFeatureFlags(false) * * // Enable a list of flags (sets them to true) * client.overrideFeatureFlags(['flag-a', 'flag-b']) * * // Set specific flag values/variants * client.overrideFeatureFlags({ 'my-flag': 'variant-a', 'other-flag': true }) * * // Set both flags and payloads * client.overrideFeatureFlags({ * flags: { 'my-flag': 'variant-a' }, * payloads: { 'my-flag': { discount: 20 } } * }) * ``` * * {@label Feature flags} * * @param overrides - Flag overrides configuration */ overrideFeatureFlags(overrides: OverrideFeatureFlagsOptions): void; /** * Type guard to check if overrides is a FeatureFlagOverrideOptions object. * * This distinguishes between: * - { flags: { 'flag-a': true } } -> FeatureFlagOverrideOptions (flags is an object/array/false) * - { flags: true } -> Record (a flag named "flags" with value true) */ private _isFeatureFlagOverrideOptions; protected abstract initializeContext(): IPostHogContext | undefined; /** * Run a function with specific context that will be applied to all events captured within that context. * It propagates the context to all subsequent calls down the call stack. * Context properties like tags and sessionId will be automatically attached to all events. * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context. * * @example * ```ts * posthog.withContext({ distinctId: 'user_123' }, () => { * posthog.capture({ event: 'button clicked' }) * }) * ``` * * {@label Context} * * @param data - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture) * @param fn - Function to run with the context * @param options - Context options (fresh: true to start with clean context instead of inheriting) * @returns The return value of the function */ withContext(data: Partial, fn: () => T, options?: ContextOptions): T; /** * Get the current context data. * * @example * ```ts * // Get current context within a withContext block * posthog.withContext({ distinctId: 'user_123' }, () => { * const context = posthog.getContext() * console.log(context?.distinctId) // 'user_123' * }) * ``` * * {@label Context} * * @returns The current context data, or undefined if no context is set */ getContext(): ContextData | undefined; /** * Set context without a callback wrapper. * * Uses `AsyncLocalStorage.enterWith()` to attach context to the current * async execution context. The context lives until that async context ends. * * Must be called in the same async scope that makes PostHog calls. * Calling this outside a request-scoped async context will leak context * across unrelated work. Prefer `withContext()` when you can wrap code * in a callback — it creates an isolated scope that cleans up automatically. * * @param data - Context data to apply (distinctId, sessionId, properties) * @param options - Context options (fresh: true to start with clean context instead of inheriting) */ enterContext(data: Partial, options?: ContextOptions): void; /** * Shutdown the PostHog client gracefully. * * @example * ```ts * // Shutdown with default timeout * await client._shutdown() * ``` * * @example * ```ts * // Shutdown with custom timeout * await client._shutdown(5000) // 5 seconds * ``` * * {@label Shutdown} * * @param shutdownTimeoutMs - Timeout in milliseconds for shutdown * @returns Promise that resolves when shutdown is complete */ _shutdown(shutdownTimeoutMs?: number): Promise; private _requestRemoteConfigPayload; private extractPropertiesFromEvent; private getFeatureFlagsForEvent; private addLocalPersonAndGroupProperties; private createFeatureFlagEvaluationContext; /** * Capture an error exception as an event. * * @example * ```ts * // Capture an error with user ID * try { * // Some risky operation * riskyOperation() * } catch (error) { * client.captureException(error, 'user_123') * } * ``` * * @example * ```ts * // Capture with additional properties * try { * apiCall() * } catch (error) { * client.captureException(error, 'user_123', { * endpoint: '/api/users', * method: 'POST', * status_code: 500 * }) * } * ``` * * {@label Error tracking} * * @param error - The error to capture * @param distinctId - Optional user distinct ID * @param additionalProperties - Optional additional properties to include * @param uuid - Optional event UUID * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events */ captureException(error: unknown, distinctId?: string, additionalProperties?: Record, uuid?: EventMessage['uuid'], flags?: FeatureFlagEvaluations): void; /** * Capture an error exception as an event immediately (synchronously). * * @example * ```ts * // Capture an error immediately with user ID * try { * // Some risky operation * riskyOperation() * } catch (error) { * await client.captureExceptionImmediate(error, 'user_123') * } * ``` * * @example * ```ts * // Capture with additional properties * try { * apiCall() * } catch (error) { * await client.captureExceptionImmediate(error, 'user_123', { * endpoint: '/api/users', * method: 'POST', * status_code: 500 * }) * } * ``` * * {@label Error tracking} * * @param error - The error to capture * @param distinctId - Optional user distinct ID * @param additionalProperties - Optional additional properties to include * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events * @returns Promise that resolves when the error is captured */ captureExceptionImmediate(error: unknown, distinctId?: string, additionalProperties?: Record, flags?: FeatureFlagEvaluations): Promise; prepareEventMessage(props: EventMessage): Promise<{ distinctId: string; event: string; properties: PostHogEventProperties; options: PostHogCaptureOptions; }>; private _runBeforeSend; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/extensions/context/context.d.ts declare class PostHogContext implements IPostHogContext { private storage; constructor(); get(): ContextData | undefined; run(context: ContextData, fn: () => T, options?: ContextOptions): T; enter(context: ContextData, options?: ContextOptions): void; private resolve; } //#endregion //#region ../../node_modules/.pnpm/posthog-node@5.36.4_rxjs@7.8.2/node_modules/posthog-node/dist/entrypoints/index.node.d.ts declare class PostHog extends PostHogBackendClient { getLibraryId(): string; protected initializeContext(): PostHogContext; protected createErrorPropertiesBuilder(): ErrorPropertiesBuilder; } //#endregion //#region src/posthog.d.ts /** * Error context for enhanced error handling * * Provides detailed context about the event that caused an error. */ interface ErrorContext { /** The error that occurred */ error: Error; /** Event name (if applicable) */ eventName?: string; /** Event type (event, funnel, outcome, value) */ eventType?: 'event' | 'funnel' | 'outcome' | 'value'; /** Event attributes (filtered) */ attributes?: EventAttributes; /** Subscriber name */ subscriberName: string; } type StringRedactor = (value: string) => string; interface PostHogConfig { /** PostHog API key (starts with phc_) - required if not providing custom client */ apiKey?: string; /** PostHog host (defaults to US cloud) */ host?: string; /** Enable/disable the subscriber */ enabled?: boolean; /** Custom PostHog client instance (bypasses apiKey/host) */ client?: PostHog; /** * Use global browser client (window.posthog) * * When true, uses the PostHog client already loaded on the page via script tag. * This is useful for Next.js apps that initialize PostHog in _app.tsx. * * @example * ```typescript * // Browser - uses window.posthog * const subscriber = new PostHogSubscriber({ * useGlobalClient: true, * }); * ``` */ useGlobalClient?: boolean; /** * Serverless mode preset (AWS Lambda, Vercel Functions, Next.js API routes) * * When true, auto-configures for serverless environments: * - flushAt: 1 (send immediately, don't batch) * - flushInterval: 0 (disable interval-based flushing) * - requestTimeout: 3000 (shorter timeout for fast responses) * * @example * ```typescript * // Vercel / Next.js API route * const subscriber = new PostHogSubscriber({ * apiKey: 'phc_...', * serverless: true, * }); * ``` */ serverless?: boolean; /** Flush batch when it reaches this size (default: 20, set to 1 for immediate send) */ flushAt?: number; /** Flush interval in milliseconds (default: 10000, set to 0 to disable) */ flushInterval?: number; /** Disable geoip lookup to reduce request size (default: false) */ disableGeoip?: boolean; /** Request timeout in milliseconds (default: 10000) */ requestTimeout?: number; /** Send feature flag evaluation events (default: true) */ sendFeatureFlags?: boolean; /** * Automatically filter out undefined and null values from attributes * * When true (default), undefined and null values are removed before sending. * This improves DX when passing objects with optional properties. * * @default true * * @example * ```typescript * // With filterUndefinedValues: true (default) * subscriber.trackEvent('user.action', { * userId: user.id, * email: user.email, // might be undefined - will be filtered * plan: user.subscription, // might be null - will be filtered * }); * ``` */ filterUndefinedValues?: boolean; /** Error callback for debugging and monitoring */ onError?: (error: Error) => void; /** * Enhanced error callback with event context * * Provides detailed context about the event that caused the error. * If both onError and onErrorWithContext are provided, both are called. * * @example * ```typescript * const subscriber = new PostHogSubscriber({ * apiKey: 'phc_...', * onErrorWithContext: (ctx) => { * console.error(`Failed to track ${ctx.eventType}: ${ctx.eventName}`, ctx.error); * Sentry.captureException(ctx.error, { extra: ctx }); * } * }); * ``` */ onErrorWithContext?: (context: ErrorContext) => void; /** Known attribute paths to redact using slow-redact (path-based, immutable). */ redactPaths?: string[]; /** String redactor for value-based PII scanning. Applied after path-based redaction. */ stringRedactor?: StringRedactor; /** Enable debug logging (default: false) */ debug?: boolean; } /** * PostHog feature flag options */ interface FeatureFlagOptions { /** Group context for group-based feature flags */ groups?: Record; /** Group properties for feature flag evaluation */ groupProperties?: Record>; /** Person properties for feature flag evaluation */ personProperties?: Record; /** Only evaluate locally, don't send $feature_flag_called event */ onlyEvaluateLocally?: boolean; /** Send feature flag events even if disabled globally */ sendFeatureFlagEvents?: boolean; } /** * Person properties for identify calls */ interface PersonProperties { /** Set properties (will update existing values) */ $set?: Record; /** Set properties only if they don't exist */ $set_once?: Record; /** Any custom properties */ [key: string]: any; } declare class PostHogSubscriber extends EventSubscriber$1 { readonly name = "PostHogSubscriber"; readonly version = "2.0.0"; private posthog; private config; private initPromise; /** True when using browser's window.posthog (different API signature) */ private isBrowserClient; private pathRedactor; private stringRedactor; constructor(config: PostHogConfig); private initialize; private setupErrorHandling; private ensureInitialized; private extractDistinctId; private redactProperties; private redactStringValues; private redactArray; /** * Set the string redactor. Called by autotel init() when attributeRedactor is configured. * Can also be called manually. */ setStringRedactor(redactor: StringRedactor): void; /** * Send payload to PostHog * * Maps autotel context to PostHog-specific field names: * - autotel.trace_id → $trace_id * - autotel.span_id → $span_id * - autotel.correlation_id → $correlation_id * - autotel.trace_url → $trace_url */ protected sendToDestination(payload: EventPayload): Promise; /** * Check if a feature flag is enabled for a user * * @param flagKey - Feature flag key * @param distinctId - User ID or anonymous ID * @param options - Feature flag evaluation options * @returns true if enabled, false otherwise * * @example * ```typescript * const isEnabled = await subscriber.isFeatureEnabled('new-checkout', 'user-123'); * * // With groups * const isEnabled = await subscriber.isFeatureEnabled('beta-features', 'user-123', { * groups: { company: 'acme-corp' } * }); * ``` */ isFeatureEnabled(flagKey: string, distinctId: string, options?: FeatureFlagOptions): Promise; /** * Get feature flag value for a user * * @param flagKey - Feature flag key * @param distinctId - User ID or anonymous ID * @param options - Feature flag evaluation options * @returns Flag value (string, boolean, or undefined) * * @example * ```typescript * const variant = await subscriber.getFeatureFlag('experiment-variant', 'user-123'); * // Returns: 'control' | 'test' | 'test-2' | undefined * * // With person properties * const variant = await subscriber.getFeatureFlag('premium-feature', 'user-123', { * personProperties: { plan: 'premium' } * }); * ``` */ getFeatureFlag(flagKey: string, distinctId: string, options?: FeatureFlagOptions): Promise; /** * Get all feature flags for a user * * @param distinctId - User ID or anonymous ID * @param options - Feature flag evaluation options * @returns Object mapping flag keys to their values * * @example * ```typescript * const flags = await subscriber.getAllFlags('user-123'); * // Returns: { 'new-checkout': true, 'experiment-variant': 'test', ... } * ``` */ getAllFlags(distinctId: string, options?: FeatureFlagOptions): Promise>; /** * Reload feature flags from PostHog server * * Call this to refresh feature flag definitions without restarting. * * @example * ```typescript * await subscriber.reloadFeatureFlags(); * ``` */ reloadFeatureFlags(): Promise; /** * Identify a user and set their properties * * @param distinctId - User ID * @param properties - Person properties ($set, $set_once, or custom properties) * * @example * ```typescript * // Set properties (will update existing values) * await subscriber.identify('user-123', { * $set: { * email: 'user@example.com', * plan: 'premium' * } * }); * * // Set properties only once (won't update if already exists) * await subscriber.identify('user-123', { * $set_once: { * signup_date: '2025-01-17' * } * }); * ``` */ identify(distinctId: string, properties?: PersonProperties): Promise; /** * Identify a group and set its properties * * Groups are useful for B2B SaaS to track organizations, teams, or accounts. * * @param groupType - Type of group (e.g., 'company', 'organization', 'team') * @param groupKey - Unique identifier for the group * @param properties - Group properties * * @example * ```typescript * await subscriber.groupIdentify('company', 'acme-corp', { * $set: { * name: 'Acme Corporation', * industry: 'saas', * employees: 500, * plan: 'enterprise' * } * }); * ``` */ groupIdentify(groupType: string, groupKey: string | number, properties?: Record): Promise; /** * Track an event with group context * * Use this to associate events with groups (e.g., organizations). * * @param name - Event name * @param attributes - Event attributes * @param groups - Group context (e.g., { company: 'acme-corp' }) * * @example * ```typescript * await subscriber.trackEventWithGroups('feature.used', { * userId: 'user-123', * feature: 'advanced-events' * }, { * company: 'acme-corp' * }); * ``` */ trackEventWithGroups(name: string, attributes?: EventAttributes, groups?: Record): Promise; /** * Capture an exception and send to PostHog error tracking. * * If using browser client (window.posthog), delegates to its captureException. * Otherwise, formats and sends via posthog-node capture API. */ captureException(error: unknown, options?: { distinctId?: string; additionalProperties?: Record; }): Promise; /** * Flush pending events and clean up resources */ shutdown(): Promise; /** * Handle errors with custom error handler */ protected handleError(error: Error, payload: EventPayload): void; } //#endregion export { PostHogSubscriber as a, PostHogConfig as i, FeatureFlagOptions as n, PersonProperties as r, ErrorContext as t }; //# sourceMappingURL=posthog-DLBf2UJJ.d.ts.map