posthog-node 4.16.0 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/lib/edge/index.cjs.js +3919 -0
  3. package/lib/edge/index.cjs.js.map +1 -0
  4. package/lib/edge/index.esm.js +3893 -0
  5. package/lib/edge/index.esm.js.map +1 -0
  6. package/lib/index.d.ts +921 -859
  7. package/lib/{index.cjs.js → node/index.cjs.js} +3575 -3594
  8. package/lib/node/index.cjs.js.map +1 -0
  9. package/lib/{index.esm.js → node/index.esm.js} +3576 -3592
  10. package/lib/node/index.esm.js.map +1 -0
  11. package/package.json +31 -4
  12. package/src/{posthog-node.ts → client.ts} +10 -28
  13. package/src/entrypoints/index.edge.ts +15 -0
  14. package/src/entrypoints/index.node.ts +17 -0
  15. package/src/exports.ts +3 -0
  16. package/src/extensions/error-tracking/autocapture.ts +1 -1
  17. package/src/extensions/error-tracking/{context-lines.ts → context-lines.node.ts} +64 -97
  18. package/src/extensions/error-tracking/error-conversion.ts +22 -5
  19. package/src/extensions/error-tracking/get-module.node.ts +57 -0
  20. package/src/{error-tracking.ts → extensions/error-tracking/index.ts} +12 -10
  21. package/src/extensions/error-tracking/{stack-trace.ts → stack-parser.ts} +7 -64
  22. package/src/extensions/error-tracking/types.ts +4 -0
  23. package/src/extensions/express.ts +3 -3
  24. package/src/{crypto-helpers.ts → extensions/feature-flags/crypto-helpers.ts} +1 -1
  25. package/src/{feature-flags.ts → extensions/feature-flags/feature-flags.ts} +7 -6
  26. package/src/extensions/sentry-integration.ts +13 -5
  27. package/src/fetch.ts +2 -2
  28. package/src/storage-memory.ts +13 -0
  29. package/src/types.ts +19 -1
  30. package/test/crypto.spec.ts +2 -2
  31. package/test/extensions/error-conversion.spec.ts +2 -2
  32. package/test/extensions/sentry-integration.spec.ts +1 -2
  33. package/test/feature-flags.decide.spec.ts +2 -1
  34. package/test/feature-flags.spec.ts +7 -4
  35. package/test/lazy.spec.ts +1 -1
  36. package/test/posthog-node.spec.ts +3 -3
  37. package/tsconfig.json +1 -0
  38. package/index.ts +0 -3
  39. package/lib/index.cjs.js.map +0 -1
  40. package/lib/index.esm.js.map +0 -1
  41. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  42. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  43. package/lib/posthog-core/src/index.d.ts +0 -259
  44. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  45. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  46. package/lib/posthog-core/src/types.d.ts +0 -422
  47. package/lib/posthog-core/src/utils.d.ts +0 -20
  48. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  49. package/lib/posthog-node/index.d.ts +0 -3
  50. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  51. package/lib/posthog-node/src/crypto.d.ts +0 -2
  52. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  53. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  54. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  55. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  56. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  57. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  58. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  59. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  60. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  61. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  62. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  63. package/lib/posthog-node/src/fetch.d.ts +0 -11
  64. package/lib/posthog-node/src/lazy.d.ts +0 -23
  65. package/lib/posthog-node/src/posthog-node.d.ts +0 -98
  66. package/lib/posthog-node/src/types.d.ts +0 -229
  67. package/lib/posthog-node/test/test-utils.d.ts +0 -18
  68. /package/src/{crypto.ts → extensions/feature-flags/crypto.ts} +0 -0
  69. /package/src/{lazy.ts → extensions/feature-flags/lazy.ts} +0 -0
package/lib/index.d.ts CHANGED
@@ -1,880 +1,942 @@
1
- /// <reference types="node" />
2
- import { SeverityLevel } from 'posthog-node/src/extensions/error-tracking/types';
3
1
  import * as http from 'node:http';
4
2
 
5
- type PostHogCoreOptions = {
6
- /** PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' */
7
- host?: string;
8
- /** The number of events to queue before sending to PostHog (flushing) */
9
- flushAt?: number;
10
- /** The interval in milliseconds between periodic flushes */
11
- flushInterval?: number;
12
- /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */
13
- maxBatchSize?: number;
14
- /** The maximum number of cached messages either in memory or on the local storage.
15
- * Defaults to 1000, (must be higher than `flushAt`)
16
- */
17
- maxQueueSize?: number;
18
- /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */
19
- disabled?: boolean;
20
- /** If set to false the SDK will not track until the `optIn` function is called. */
21
- defaultOptIn?: boolean;
22
- /** Whether to track that `getFeatureFlag` was called (used by Experiments) */
23
- sendFeatureFlagEvent?: boolean;
24
- /** Whether to load feature flags when initialized or not */
25
- preloadFeatureFlags?: boolean;
26
- /**
27
- * Whether to load remote config when initialized or not
28
- * Experimental support
29
- * Default: false - Remote config is loaded by default
30
- */
31
- disableRemoteConfig?: boolean;
32
- /**
33
- * Whether to load surveys when initialized or not
34
- * Experimental support
35
- * Default: false - Surveys are loaded by default, but requires the `PostHogSurveyProvider` to be used
36
- */
37
- disableSurveys?: boolean;
38
- /** Option to bootstrap the library with given distinctId and feature flags */
39
- bootstrap?: {
40
- distinctId?: string;
41
- isIdentifiedId?: boolean;
42
- featureFlags?: Record<string, FeatureFlagValue>;
43
- featureFlagPayloads?: Record<string, JsonType>;
44
- };
45
- /** How many times we will retry HTTP requests. Defaults to 3. */
46
- fetchRetryCount?: number;
47
- /** The delay between HTTP request retries, Defaults to 3 seconds. */
48
- fetchRetryDelay?: number;
49
- /** Timeout in milliseconds for any calls. Defaults to 10 seconds. */
50
- requestTimeout?: number;
51
- /** Timeout in milliseconds for feature flag calls. Defaults to 10 seconds for stateful clients, and 3 seconds for stateless. */
52
- featureFlagsRequestTimeoutMs?: number;
53
- /** Timeout in milliseconds for remote config calls. Defaults to 3 seconds. */
54
- remoteConfigRequestTimeoutMs?: number;
55
- /** For Session Analysis how long before we expire a session (defaults to 30 mins) */
56
- sessionExpirationTimeSeconds?: number;
57
- /** Whether to post events to PostHog in JSON or compressed format. Defaults to 'json' */
58
- captureMode?: 'json' | 'form';
59
- disableGeoip?: boolean;
60
- /** Special flag to indicate ingested data is for a historical migration. */
61
- historicalMigration?: boolean;
62
- };
63
- declare enum PostHogPersistedProperty {
64
- AnonymousId = "anonymous_id",
65
- DistinctId = "distinct_id",
66
- Props = "props",
67
- FeatureFlagDetails = "feature_flag_details",
68
- FeatureFlags = "feature_flags",
69
- FeatureFlagPayloads = "feature_flag_payloads",
70
- BootstrapFeatureFlagDetails = "bootstrap_feature_flag_details",
71
- BootstrapFeatureFlags = "bootstrap_feature_flags",
72
- BootstrapFeatureFlagPayloads = "bootstrap_feature_flag_payloads",
73
- OverrideFeatureFlags = "override_feature_flags",
74
- Queue = "queue",
75
- OptedOut = "opted_out",
76
- SessionId = "session_id",
77
- SessionLastTimestamp = "session_timestamp",
78
- PersonProperties = "person_properties",
79
- GroupProperties = "group_properties",
80
- InstalledAppBuild = "installed_app_build",
81
- InstalledAppVersion = "installed_app_version",
82
- SessionReplay = "session_replay",
83
- DecideEndpointWasHit = "decide_endpoint_was_hit",
84
- SurveyLastSeenDate = "survey_last_seen_date",
85
- SurveysSeen = "surveys_seen",
86
- Surveys = "surveys",
87
- RemoteConfig = "remote_config"
88
- }
89
- type PostHogFetchOptions = {
90
- method: 'GET' | 'POST' | 'PUT' | 'PATCH';
91
- mode?: 'no-cors';
92
- credentials?: 'omit';
93
- headers: {
94
- [key: string]: string;
95
- };
96
- body?: string;
97
- signal?: AbortSignal;
98
- };
99
- type PostHogCaptureOptions = {
100
- /** If provided overrides the auto-generated event ID */
101
- uuid?: string;
102
- /** If provided overrides the auto-generated timestamp */
103
- timestamp?: Date;
104
- disableGeoip?: boolean;
105
- };
106
- type PostHogFetchResponse = {
107
- status: number;
108
- text: () => Promise<string>;
109
- json: () => Promise<any>;
110
- };
111
- type PostHogEventProperties = {
112
- [key: string]: any;
113
- };
114
- type PostHogRemoteConfig = {
115
- sessionRecording?: boolean | {
116
- [key: string]: JsonType;
117
- };
118
- /**
119
- * Whether surveys are enabled
120
- */
121
- surveys?: boolean | Survey[];
122
- /**
123
- * Indicates if the team has any flags enabled (if not we don't need to load them)
124
- */
125
- hasFeatureFlags?: boolean;
126
- };
127
- type FeatureFlagValue = string | boolean;
128
- type PostHogDecideResponse = Omit<PostHogRemoteConfig, 'surveys' | 'hasFeatureFlags'> & {
129
- featureFlags: {
130
- [key: string]: FeatureFlagValue;
131
- };
132
- featureFlagPayloads: {
133
- [key: string]: JsonType;
134
- };
135
- flags: {
136
- [key: string]: FeatureFlagDetail;
137
- };
138
- errorsWhileComputingFlags: boolean;
139
- sessionRecording?: boolean | {
140
- [key: string]: JsonType;
141
- };
142
- quotaLimited?: string[];
143
- requestId?: string;
144
- };
145
- /**
146
- * Creates a type with all properties of T, but makes only K properties required while the rest remain optional.
147
- *
148
- * @template T - The base type containing all properties
149
- * @template K - Union type of keys from T that should be required
150
- *
151
- * @example
152
- * interface User {
153
- * id: number;
154
- * name: string;
155
- * email?: string;
156
- * age?: number;
157
- * }
158
- *
159
- * // Makes 'id' and 'name' required, but 'email' and 'age' optional
160
- * type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;
161
- *
162
- * const user: RequiredUser = {
163
- * id: 1, // Must be provided
164
- * name: "John" // Must be provided
165
- * // email and age are optional
166
- * };
167
- */
168
- type PartialWithRequired<T, K extends keyof T> = {
169
- [P in K]: T[P];
170
- } & {
171
- [P in Exclude<keyof T, K>]?: T[P];
172
- };
173
- /**
174
- * These are the fields we care about from PostHogDecideResponse for feature flags.
175
- */
176
- type PostHogFeatureFlagDetails = PartialWithRequired<PostHogDecideResponse, 'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'>;
177
- /**
178
- * Models legacy flags and payloads return type for many public methods.
179
- */
180
- type PostHogFlagsAndPayloadsResponse = Partial<Pick<PostHogDecideResponse, 'featureFlags' | 'featureFlagPayloads'>>;
181
- type JsonType = string | number | boolean | null | {
182
- [key: string]: JsonType;
183
- } | Array<JsonType>;
184
- type FeatureFlagDetail = {
185
- key: string;
186
- enabled: boolean;
187
- variant: string | undefined;
188
- reason: EvaluationReason | undefined;
189
- metadata: FeatureFlagMetadata | undefined;
190
- };
191
- type FeatureFlagMetadata = {
192
- id: number | undefined;
193
- version: number | undefined;
194
- description: string | undefined;
195
- payload: string | undefined;
196
- };
197
- type EvaluationReason = {
198
- code: string | undefined;
199
- condition_index: number | undefined;
200
- description: string | undefined;
201
- };
202
- type SurveyAppearance = {
203
- backgroundColor?: string;
204
- submitButtonColor?: string;
205
- submitButtonText?: string;
206
- submitButtonTextColor?: string;
207
- ratingButtonColor?: string;
208
- ratingButtonActiveColor?: string;
209
- autoDisappear?: boolean;
210
- displayThankYouMessage?: boolean;
211
- thankYouMessageHeader?: string;
212
- thankYouMessageDescription?: string;
213
- thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType;
214
- thankYouMessageCloseButtonText?: string;
215
- borderColor?: string;
216
- position?: SurveyPosition;
217
- placeholder?: string;
218
- shuffleQuestions?: boolean;
219
- surveyPopupDelaySeconds?: number;
220
- widgetType?: SurveyWidgetType;
221
- widgetSelector?: string;
222
- widgetLabel?: string;
223
- widgetColor?: string;
224
- };
225
- declare enum SurveyPosition {
226
- Left = "left",
227
- Right = "right",
228
- Center = "center"
229
- }
230
- declare enum SurveyWidgetType {
231
- Button = "button",
232
- Tab = "tab",
233
- Selector = "selector"
234
- }
235
- declare enum SurveyType {
236
- Popover = "popover",
237
- API = "api",
238
- Widget = "widget"
239
- }
240
- type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion;
241
- declare enum SurveyQuestionDescriptionContentType {
242
- Html = "html",
243
- Text = "text"
244
- }
245
- type SurveyQuestionBase = {
246
- question: string;
247
- id?: string;
248
- description?: string;
249
- descriptionContentType?: SurveyQuestionDescriptionContentType;
250
- optional?: boolean;
251
- buttonText?: string;
252
- originalQuestionIndex: number;
253
- branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching;
254
- };
255
- type BasicSurveyQuestion = SurveyQuestionBase & {
256
- type: SurveyQuestionType.Open;
257
- };
258
- type LinkSurveyQuestion = SurveyQuestionBase & {
259
- type: SurveyQuestionType.Link;
260
- link?: string;
261
- };
262
- type RatingSurveyQuestion = SurveyQuestionBase & {
263
- type: SurveyQuestionType.Rating;
264
- display: SurveyRatingDisplay;
265
- scale: 3 | 5 | 7 | 10;
266
- lowerBoundLabel: string;
267
- upperBoundLabel: string;
268
- };
269
- declare enum SurveyRatingDisplay {
270
- Number = "number",
271
- Emoji = "emoji"
272
- }
273
- type MultipleSurveyQuestion = SurveyQuestionBase & {
274
- type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice;
275
- choices: string[];
276
- hasOpenChoice?: boolean;
277
- shuffleOptions?: boolean;
278
- };
279
- declare enum SurveyQuestionType {
280
- Open = "open",
281
- MultipleChoice = "multiple_choice",
282
- SingleChoice = "single_choice",
283
- Rating = "rating",
284
- Link = "link"
285
- }
286
- declare enum SurveyQuestionBranchingType {
287
- NextQuestion = "next_question",
288
- End = "end",
289
- ResponseBased = "response_based",
290
- SpecificQuestion = "specific_question"
291
- }
292
- type NextQuestionBranching = {
293
- type: SurveyQuestionBranchingType.NextQuestion;
294
- };
295
- type EndBranching = {
296
- type: SurveyQuestionBranchingType.End;
297
- };
298
- type ResponseBasedBranching = {
299
- type: SurveyQuestionBranchingType.ResponseBased;
300
- responseValues: Record<string, any>;
301
- };
302
- type SpecificQuestionBranching = {
303
- type: SurveyQuestionBranchingType.SpecificQuestion;
304
- index: number;
305
- };
306
- type SurveyResponse = {
307
- surveys: Survey[];
308
- };
309
- declare enum SurveyMatchType {
310
- Regex = "regex",
311
- NotRegex = "not_regex",
312
- Exact = "exact",
313
- IsNot = "is_not",
314
- Icontains = "icontains",
315
- NotIcontains = "not_icontains"
316
- }
317
- type Survey = {
318
- id: string;
319
- name: string;
320
- description?: string;
321
- type: SurveyType;
322
- feature_flag_keys?: {
323
- key: string;
324
- value?: string;
325
- }[];
326
- linked_flag_key?: string;
327
- targeting_flag_key?: string;
328
- internal_targeting_flag_key?: string;
329
- questions: SurveyQuestion[];
330
- appearance?: SurveyAppearance;
331
- conditions?: {
332
- url?: string;
333
- selector?: string;
334
- seenSurveyWaitPeriodInDays?: number;
335
- urlMatchType?: SurveyMatchType;
336
- events?: {
337
- repeatedActivation?: boolean;
338
- values?: {
339
- name: string;
340
- }[];
341
- };
342
- actions?: {
343
- values: SurveyActionType[];
344
- };
345
- deviceTypes?: string[];
346
- deviceTypesMatchType?: SurveyMatchType;
347
- };
348
- start_date?: string;
349
- end_date?: string;
350
- current_iteration?: number;
351
- current_iteration_start_date?: string;
352
- };
353
- type SurveyActionType = {
354
- id: number;
355
- name?: string;
356
- steps?: ActionStepType[];
357
- };
358
- /** Sync with plugin-server/src/types.ts */
359
- declare enum ActionStepStringMatching {
360
- Contains = "contains",
361
- Exact = "exact",
362
- Regex = "regex"
363
- }
364
- type ActionStepType = {
365
- event?: string;
366
- selector?: string;
367
- /** @deprecated Only `selector` should be used now. */
368
- tag_name?: string;
369
- text?: string;
370
- /** @default StringMatching.Exact */
371
- text_matching?: ActionStepStringMatching;
372
- href?: string;
373
- /** @default ActionStepStringMatching.Exact */
374
- href_matching?: ActionStepStringMatching;
375
- url?: string;
376
- /** @default StringMatching.Contains */
377
- url_matching?: ActionStepStringMatching;
3
+ declare const severityLevels: readonly ["fatal", "error", "warning", "log", "info", "debug"];
4
+ declare type SeverityLevel = (typeof severityLevels)[number];
5
+ interface EventHint {
6
+ mechanism?: Partial<Mechanism>;
7
+ syntheticException?: Error | null;
8
+ }
9
+ interface Mechanism {
10
+ handled?: boolean;
11
+ type?: string;
12
+ source?: string;
13
+ synthetic?: boolean;
14
+ }
15
+ type StackParser = (stack: string, skipFirstLines?: number) => StackFrame[];
16
+ type StackFrameModifierFn = (frames: StackFrame[]) => Promise<StackFrame[]>;
17
+ interface StackFrame {
18
+ platform: string;
19
+ filename?: string;
20
+ function?: string;
21
+ module?: string;
22
+ lineno?: number;
23
+ colno?: number;
24
+ abs_path?: string;
25
+ context_line?: string;
26
+ pre_context?: string[];
27
+ post_context?: string[];
28
+ in_app?: boolean;
29
+ instruction_addr?: string;
30
+ addr_mode?: string;
31
+ vars?: {
32
+ [key: string]: any;
33
+ };
34
+ debug_id?: string;
35
+ }
36
+
37
+ type PostHogCoreOptions = {
38
+ /** PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' */
39
+ host?: string;
40
+ /** The number of events to queue before sending to PostHog (flushing) */
41
+ flushAt?: number;
42
+ /** The interval in milliseconds between periodic flushes */
43
+ flushInterval?: number;
44
+ /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */
45
+ maxBatchSize?: number;
46
+ /** The maximum number of cached messages either in memory or on the local storage.
47
+ * Defaults to 1000, (must be higher than `flushAt`)
48
+ */
49
+ maxQueueSize?: number;
50
+ /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */
51
+ disabled?: boolean;
52
+ /** If set to false the SDK will not track until the `optIn` function is called. */
53
+ defaultOptIn?: boolean;
54
+ /** Whether to track that `getFeatureFlag` was called (used by Experiments) */
55
+ sendFeatureFlagEvent?: boolean;
56
+ /** Whether to load feature flags when initialized or not */
57
+ preloadFeatureFlags?: boolean;
58
+ /**
59
+ * Whether to load remote config when initialized or not
60
+ * Experimental support
61
+ * Default: false - Remote config is loaded by default
62
+ */
63
+ disableRemoteConfig?: boolean;
64
+ /**
65
+ * Whether to load surveys when initialized or not
66
+ * Experimental support
67
+ * Default: false - Surveys are loaded by default, but requires the `PostHogSurveyProvider` to be used
68
+ */
69
+ disableSurveys?: boolean;
70
+ /** Option to bootstrap the library with given distinctId and feature flags */
71
+ bootstrap?: {
72
+ distinctId?: string;
73
+ isIdentifiedId?: boolean;
74
+ featureFlags?: Record<string, FeatureFlagValue>;
75
+ featureFlagPayloads?: Record<string, JsonType>;
76
+ };
77
+ /** How many times we will retry HTTP requests. Defaults to 3. */
78
+ fetchRetryCount?: number;
79
+ /** The delay between HTTP request retries, Defaults to 3 seconds. */
80
+ fetchRetryDelay?: number;
81
+ /** Timeout in milliseconds for any calls. Defaults to 10 seconds. */
82
+ requestTimeout?: number;
83
+ /** Timeout in milliseconds for feature flag calls. Defaults to 10 seconds for stateful clients, and 3 seconds for stateless. */
84
+ featureFlagsRequestTimeoutMs?: number;
85
+ /** Timeout in milliseconds for remote config calls. Defaults to 3 seconds. */
86
+ remoteConfigRequestTimeoutMs?: number;
87
+ /** For Session Analysis how long before we expire a session (defaults to 30 mins) */
88
+ sessionExpirationTimeSeconds?: number;
89
+ /** Whether to post events to PostHog in JSON or compressed format. Defaults to 'json' */
90
+ captureMode?: 'json' | 'form';
91
+ disableGeoip?: boolean;
92
+ /** Special flag to indicate ingested data is for a historical migration. */
93
+ historicalMigration?: boolean;
94
+ };
95
+ declare enum PostHogPersistedProperty {
96
+ AnonymousId = "anonymous_id",
97
+ DistinctId = "distinct_id",
98
+ Props = "props",
99
+ FeatureFlagDetails = "feature_flag_details",
100
+ FeatureFlags = "feature_flags",
101
+ FeatureFlagPayloads = "feature_flag_payloads",
102
+ BootstrapFeatureFlagDetails = "bootstrap_feature_flag_details",
103
+ BootstrapFeatureFlags = "bootstrap_feature_flags",
104
+ BootstrapFeatureFlagPayloads = "bootstrap_feature_flag_payloads",
105
+ OverrideFeatureFlags = "override_feature_flags",
106
+ Queue = "queue",
107
+ OptedOut = "opted_out",
108
+ SessionId = "session_id",
109
+ SessionLastTimestamp = "session_timestamp",
110
+ PersonProperties = "person_properties",
111
+ GroupProperties = "group_properties",
112
+ InstalledAppBuild = "installed_app_build",
113
+ InstalledAppVersion = "installed_app_version",
114
+ SessionReplay = "session_replay",
115
+ DecideEndpointWasHit = "decide_endpoint_was_hit",
116
+ SurveyLastSeenDate = "survey_last_seen_date",
117
+ SurveysSeen = "surveys_seen",
118
+ Surveys = "surveys",
119
+ RemoteConfig = "remote_config"
120
+ }
121
+ type PostHogFetchOptions = {
122
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH';
123
+ mode?: 'no-cors';
124
+ credentials?: 'omit';
125
+ headers: {
126
+ [key: string]: string;
127
+ };
128
+ body?: string;
129
+ signal?: AbortSignal;
130
+ };
131
+ type PostHogCaptureOptions = {
132
+ /** If provided overrides the auto-generated event ID */
133
+ uuid?: string;
134
+ /** If provided overrides the auto-generated timestamp */
135
+ timestamp?: Date;
136
+ disableGeoip?: boolean;
137
+ };
138
+ type PostHogFetchResponse = {
139
+ status: number;
140
+ text: () => Promise<string>;
141
+ json: () => Promise<any>;
142
+ };
143
+ type PostHogEventProperties = {
144
+ [key: string]: any;
145
+ };
146
+ type PostHogRemoteConfig = {
147
+ sessionRecording?: boolean | {
148
+ [key: string]: JsonType;
149
+ };
150
+ /**
151
+ * Whether surveys are enabled
152
+ */
153
+ surveys?: boolean | Survey[];
154
+ /**
155
+ * Indicates if the team has any flags enabled (if not we don't need to load them)
156
+ */
157
+ hasFeatureFlags?: boolean;
158
+ };
159
+ type FeatureFlagValue = string | boolean;
160
+ type PostHogDecideResponse = Omit<PostHogRemoteConfig, 'surveys' | 'hasFeatureFlags'> & {
161
+ featureFlags: {
162
+ [key: string]: FeatureFlagValue;
163
+ };
164
+ featureFlagPayloads: {
165
+ [key: string]: JsonType;
166
+ };
167
+ flags: {
168
+ [key: string]: FeatureFlagDetail;
169
+ };
170
+ errorsWhileComputingFlags: boolean;
171
+ sessionRecording?: boolean | {
172
+ [key: string]: JsonType;
173
+ };
174
+ quotaLimited?: string[];
175
+ requestId?: string;
176
+ };
177
+ /**
178
+ * Creates a type with all properties of T, but makes only K properties required while the rest remain optional.
179
+ *
180
+ * @template T - The base type containing all properties
181
+ * @template K - Union type of keys from T that should be required
182
+ *
183
+ * @example
184
+ * interface User {
185
+ * id: number;
186
+ * name: string;
187
+ * email?: string;
188
+ * age?: number;
189
+ * }
190
+ *
191
+ * // Makes 'id' and 'name' required, but 'email' and 'age' optional
192
+ * type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;
193
+ *
194
+ * const user: RequiredUser = {
195
+ * id: 1, // Must be provided
196
+ * name: "John" // Must be provided
197
+ * // email and age are optional
198
+ * };
199
+ */
200
+ type PartialWithRequired<T, K extends keyof T> = {
201
+ [P in K]: T[P];
202
+ } & {
203
+ [P in Exclude<keyof T, K>]?: T[P];
204
+ };
205
+ /**
206
+ * These are the fields we care about from PostHogDecideResponse for feature flags.
207
+ */
208
+ type PostHogFeatureFlagDetails = PartialWithRequired<PostHogDecideResponse, 'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'>;
209
+ /**
210
+ * Models legacy flags and payloads return type for many public methods.
211
+ */
212
+ type PostHogFlagsAndPayloadsResponse = Partial<Pick<PostHogDecideResponse, 'featureFlags' | 'featureFlagPayloads'>>;
213
+ type JsonType = string | number | boolean | null | {
214
+ [key: string]: JsonType;
215
+ } | Array<JsonType>;
216
+ type FeatureFlagDetail = {
217
+ key: string;
218
+ enabled: boolean;
219
+ variant: string | undefined;
220
+ reason: EvaluationReason | undefined;
221
+ metadata: FeatureFlagMetadata | undefined;
222
+ };
223
+ type FeatureFlagMetadata = {
224
+ id: number | undefined;
225
+ version: number | undefined;
226
+ description: string | undefined;
227
+ payload: string | undefined;
228
+ };
229
+ type EvaluationReason = {
230
+ code: string | undefined;
231
+ condition_index: number | undefined;
232
+ description: string | undefined;
233
+ };
234
+ type SurveyAppearance = {
235
+ backgroundColor?: string;
236
+ submitButtonColor?: string;
237
+ submitButtonText?: string;
238
+ submitButtonTextColor?: string;
239
+ ratingButtonColor?: string;
240
+ ratingButtonActiveColor?: string;
241
+ autoDisappear?: boolean;
242
+ displayThankYouMessage?: boolean;
243
+ thankYouMessageHeader?: string;
244
+ thankYouMessageDescription?: string;
245
+ thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType;
246
+ thankYouMessageCloseButtonText?: string;
247
+ borderColor?: string;
248
+ position?: SurveyPosition;
249
+ placeholder?: string;
250
+ shuffleQuestions?: boolean;
251
+ surveyPopupDelaySeconds?: number;
252
+ widgetType?: SurveyWidgetType;
253
+ widgetSelector?: string;
254
+ widgetLabel?: string;
255
+ widgetColor?: string;
256
+ };
257
+ declare enum SurveyPosition {
258
+ Left = "left",
259
+ Right = "right",
260
+ Center = "center"
261
+ }
262
+ declare enum SurveyWidgetType {
263
+ Button = "button",
264
+ Tab = "tab",
265
+ Selector = "selector"
266
+ }
267
+ declare enum SurveyType {
268
+ Popover = "popover",
269
+ API = "api",
270
+ Widget = "widget"
271
+ }
272
+ type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion;
273
+ declare enum SurveyQuestionDescriptionContentType {
274
+ Html = "html",
275
+ Text = "text"
276
+ }
277
+ type SurveyQuestionBase = {
278
+ question: string;
279
+ id?: string;
280
+ description?: string;
281
+ descriptionContentType?: SurveyQuestionDescriptionContentType;
282
+ optional?: boolean;
283
+ buttonText?: string;
284
+ originalQuestionIndex: number;
285
+ branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching;
286
+ };
287
+ type BasicSurveyQuestion = SurveyQuestionBase & {
288
+ type: SurveyQuestionType.Open;
289
+ };
290
+ type LinkSurveyQuestion = SurveyQuestionBase & {
291
+ type: SurveyQuestionType.Link;
292
+ link?: string;
293
+ };
294
+ type RatingSurveyQuestion = SurveyQuestionBase & {
295
+ type: SurveyQuestionType.Rating;
296
+ display: SurveyRatingDisplay;
297
+ scale: 3 | 5 | 7 | 10;
298
+ lowerBoundLabel: string;
299
+ upperBoundLabel: string;
300
+ };
301
+ declare enum SurveyRatingDisplay {
302
+ Number = "number",
303
+ Emoji = "emoji"
304
+ }
305
+ type MultipleSurveyQuestion = SurveyQuestionBase & {
306
+ type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice;
307
+ choices: string[];
308
+ hasOpenChoice?: boolean;
309
+ shuffleOptions?: boolean;
310
+ };
311
+ declare enum SurveyQuestionType {
312
+ Open = "open",
313
+ MultipleChoice = "multiple_choice",
314
+ SingleChoice = "single_choice",
315
+ Rating = "rating",
316
+ Link = "link"
317
+ }
318
+ declare enum SurveyQuestionBranchingType {
319
+ NextQuestion = "next_question",
320
+ End = "end",
321
+ ResponseBased = "response_based",
322
+ SpecificQuestion = "specific_question"
323
+ }
324
+ type NextQuestionBranching = {
325
+ type: SurveyQuestionBranchingType.NextQuestion;
326
+ };
327
+ type EndBranching = {
328
+ type: SurveyQuestionBranchingType.End;
329
+ };
330
+ type ResponseBasedBranching = {
331
+ type: SurveyQuestionBranchingType.ResponseBased;
332
+ responseValues: Record<string, any>;
333
+ };
334
+ type SpecificQuestionBranching = {
335
+ type: SurveyQuestionBranchingType.SpecificQuestion;
336
+ index: number;
337
+ };
338
+ type SurveyResponse = {
339
+ surveys: Survey[];
340
+ };
341
+ declare enum SurveyMatchType {
342
+ Regex = "regex",
343
+ NotRegex = "not_regex",
344
+ Exact = "exact",
345
+ IsNot = "is_not",
346
+ Icontains = "icontains",
347
+ NotIcontains = "not_icontains"
348
+ }
349
+ type Survey = {
350
+ id: string;
351
+ name: string;
352
+ description?: string;
353
+ type: SurveyType;
354
+ feature_flag_keys?: {
355
+ key: string;
356
+ value?: string;
357
+ }[];
358
+ linked_flag_key?: string;
359
+ targeting_flag_key?: string;
360
+ internal_targeting_flag_key?: string;
361
+ questions: SurveyQuestion[];
362
+ appearance?: SurveyAppearance;
363
+ conditions?: {
364
+ url?: string;
365
+ selector?: string;
366
+ seenSurveyWaitPeriodInDays?: number;
367
+ urlMatchType?: SurveyMatchType;
368
+ events?: {
369
+ repeatedActivation?: boolean;
370
+ values?: {
371
+ name: string;
372
+ }[];
373
+ };
374
+ actions?: {
375
+ values: SurveyActionType[];
376
+ };
377
+ deviceTypes?: string[];
378
+ deviceTypesMatchType?: SurveyMatchType;
379
+ };
380
+ start_date?: string;
381
+ end_date?: string;
382
+ current_iteration?: number;
383
+ current_iteration_start_date?: string;
384
+ };
385
+ type SurveyActionType = {
386
+ id: number;
387
+ name?: string;
388
+ steps?: ActionStepType[];
389
+ };
390
+ /** Sync with plugin-server/src/types.ts */
391
+ declare enum ActionStepStringMatching {
392
+ Contains = "contains",
393
+ Exact = "exact",
394
+ Regex = "regex"
395
+ }
396
+ type ActionStepType = {
397
+ event?: string;
398
+ selector?: string;
399
+ /** @deprecated Only `selector` should be used now. */
400
+ tag_name?: string;
401
+ text?: string;
402
+ /** @default StringMatching.Exact */
403
+ text_matching?: ActionStepStringMatching;
404
+ href?: string;
405
+ /** @default ActionStepStringMatching.Exact */
406
+ href_matching?: ActionStepStringMatching;
407
+ url?: string;
408
+ /** @default StringMatching.Contains */
409
+ url_matching?: ActionStepStringMatching;
378
410
  };
379
411
 
380
- interface RetriableOptions {
381
- retryCount: number;
382
- retryDelay: number;
383
- retryCheck: (err: unknown) => boolean;
412
+ interface RetriableOptions {
413
+ retryCount: number;
414
+ retryDelay: number;
415
+ retryCheck: (err: unknown) => boolean;
384
416
  }
385
417
 
386
- declare class SimpleEventEmitter {
387
- events: {
388
- [key: string]: ((...args: any[]) => void)[];
389
- };
390
- constructor();
391
- on(event: string, listener: (...args: any[]) => void): () => void;
392
- emit(event: string, payload: any): void;
418
+ declare class SimpleEventEmitter {
419
+ events: {
420
+ [key: string]: ((...args: any[]) => void)[];
421
+ };
422
+ constructor();
423
+ on(event: string, listener: (...args: any[]) => void): () => void;
424
+ emit(event: string, payload: any): void;
393
425
  }
394
426
 
395
- declare abstract class PostHogCoreStateless {
396
- readonly apiKey: string;
397
- readonly host: string;
398
- readonly flushAt: number;
399
- readonly preloadFeatureFlags: boolean;
400
- readonly disableSurveys: boolean;
401
- private maxBatchSize;
402
- private maxQueueSize;
403
- private flushInterval;
404
- private flushPromise;
405
- private shutdownPromise;
406
- private requestTimeout;
407
- private featureFlagsRequestTimeoutMs;
408
- private remoteConfigRequestTimeoutMs;
409
- private captureMode;
410
- private removeDebugCallback?;
411
- private disableGeoip;
412
- private historicalMigration;
413
- protected disabled: boolean;
414
- private defaultOptIn;
415
- private pendingPromises;
416
- protected _events: SimpleEventEmitter;
417
- protected _flushTimer?: any;
418
- protected _retryOptions: RetriableOptions;
419
- protected _initPromise: Promise<void>;
420
- protected _isInitialized: boolean;
421
- protected _remoteConfigResponsePromise?: Promise<PostHogRemoteConfig | undefined>;
422
- abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
423
- abstract getLibraryId(): string;
424
- abstract getLibraryVersion(): string;
425
- abstract getCustomUserAgent(): string | void;
426
- abstract getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined;
427
- abstract setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void;
428
- constructor(apiKey: string, options?: PostHogCoreOptions);
429
- protected logMsgIfDebug(fn: () => void): void;
430
- protected wrap(fn: () => void): void;
431
- protected getCommonEventProperties(): any;
432
- get optedOut(): boolean;
433
- optIn(): Promise<void>;
434
- optOut(): Promise<void>;
435
- on(event: string, cb: (...args: any[]) => void): () => void;
436
- debug(enabled?: boolean): void;
437
- get isDebug(): boolean;
438
- get isDisabled(): boolean;
439
- private buildPayload;
440
- protected addPendingPromise<T>(promise: Promise<T>): Promise<T>;
441
- /***
442
- *** TRACKING
443
- ***/
444
- protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
445
- protected identifyStatelessImmediate(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void>;
446
- protected captureStateless(distinctId: string, event: string, properties?: {
447
- [key: string]: any;
448
- }, options?: PostHogCaptureOptions): void;
449
- protected captureStatelessImmediate(distinctId: string, event: string, properties?: {
450
- [key: string]: any;
451
- }, options?: PostHogCaptureOptions): Promise<void>;
452
- protected aliasStateless(alias: string, distinctId: string, properties?: {
453
- [key: string]: any;
454
- }, options?: PostHogCaptureOptions): void;
455
- protected aliasStatelessImmediate(alias: string, distinctId: string, properties?: {
456
- [key: string]: any;
457
- }, options?: PostHogCaptureOptions): Promise<void>;
458
- /***
459
- *** GROUPS
460
- ***/
461
- protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): void;
462
- protected getRemoteConfig(): Promise<PostHogRemoteConfig | undefined>;
463
- /***
464
- *** FEATURE FLAGS
465
- ***/
466
- protected getDecide(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, extraPayload?: Record<string, any>): Promise<PostHogDecideResponse | undefined>;
467
- protected getFeatureFlagStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
468
- response: FeatureFlagValue | undefined;
469
- requestId: string | undefined;
470
- }>;
471
- protected getFeatureFlagDetailStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
472
- response: FeatureFlagDetail | undefined;
473
- requestId: string | undefined;
474
- } | undefined>;
475
- protected getFeatureFlagPayloadStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<JsonType | undefined>;
476
- protected getFeatureFlagPayloadsStateless(distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogDecideResponse['featureFlagPayloads'] | undefined>;
477
- protected getFeatureFlagsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
478
- flags: PostHogDecideResponse['featureFlags'] | undefined;
479
- payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
480
- requestId: PostHogDecideResponse['requestId'] | undefined;
481
- }>;
482
- protected getFeatureFlagsAndPayloadsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
483
- flags: PostHogDecideResponse['featureFlags'] | undefined;
484
- payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
485
- requestId: PostHogDecideResponse['requestId'] | undefined;
486
- }>;
487
- protected getFeatureFlagDetailsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogFeatureFlagDetails | undefined>;
488
- /***
489
- *** SURVEYS
490
- ***/
491
- getSurveysStateless(): Promise<SurveyResponse['surveys']>;
492
- /***
493
- *** SUPER PROPERTIES
494
- ***/
495
- private _props;
496
- protected get props(): PostHogEventProperties;
497
- protected set props(val: PostHogEventProperties | undefined);
498
- register(properties: {
499
- [key: string]: any;
500
- }): Promise<void>;
501
- unregister(property: string): Promise<void>;
502
- /***
503
- *** QUEUEING AND FLUSHING
504
- ***/
505
- protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void;
506
- protected sendImmediate(type: string, _message: any, options?: PostHogCaptureOptions): Promise<void>;
507
- private prepareMessage;
508
- private clearFlushTimer;
509
- /**
510
- * Helper for flushing the queue in the background
511
- * Avoids unnecessary promise errors
512
- */
513
- private flushBackground;
514
- flush(): Promise<any[]>;
515
- protected getCustomHeaders(): {
516
- [key: string]: string;
517
- };
518
- private _flush;
519
- private fetchWithRetry;
520
- _shutdown(shutdownTimeoutMs?: number): Promise<void>;
521
- /**
522
- * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
523
- * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
524
- * @param shutdownTimeoutMs
525
- */
526
- shutdown(shutdownTimeoutMs?: number): Promise<void>;
427
+ declare abstract class PostHogCoreStateless {
428
+ readonly apiKey: string;
429
+ readonly host: string;
430
+ readonly flushAt: number;
431
+ readonly preloadFeatureFlags: boolean;
432
+ readonly disableSurveys: boolean;
433
+ private maxBatchSize;
434
+ private maxQueueSize;
435
+ private flushInterval;
436
+ private flushPromise;
437
+ private shutdownPromise;
438
+ private requestTimeout;
439
+ private featureFlagsRequestTimeoutMs;
440
+ private remoteConfigRequestTimeoutMs;
441
+ private captureMode;
442
+ private removeDebugCallback?;
443
+ private disableGeoip;
444
+ private historicalMigration;
445
+ protected disabled: boolean;
446
+ private defaultOptIn;
447
+ private pendingPromises;
448
+ protected _events: SimpleEventEmitter;
449
+ protected _flushTimer?: any;
450
+ protected _retryOptions: RetriableOptions;
451
+ protected _initPromise: Promise<void>;
452
+ protected _isInitialized: boolean;
453
+ protected _remoteConfigResponsePromise?: Promise<PostHogRemoteConfig | undefined>;
454
+ abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
455
+ abstract getLibraryId(): string;
456
+ abstract getLibraryVersion(): string;
457
+ abstract getCustomUserAgent(): string | void;
458
+ abstract getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined;
459
+ abstract setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void;
460
+ constructor(apiKey: string, options?: PostHogCoreOptions);
461
+ protected logMsgIfDebug(fn: () => void): void;
462
+ protected wrap(fn: () => void): void;
463
+ protected getCommonEventProperties(): any;
464
+ get optedOut(): boolean;
465
+ optIn(): Promise<void>;
466
+ optOut(): Promise<void>;
467
+ on(event: string, cb: (...args: any[]) => void): () => void;
468
+ debug(enabled?: boolean): void;
469
+ get isDebug(): boolean;
470
+ get isDisabled(): boolean;
471
+ private buildPayload;
472
+ protected addPendingPromise<T>(promise: Promise<T>): Promise<T>;
473
+ /***
474
+ *** TRACKING
475
+ ***/
476
+ protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
477
+ protected identifyStatelessImmediate(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void>;
478
+ protected captureStateless(distinctId: string, event: string, properties?: {
479
+ [key: string]: any;
480
+ }, options?: PostHogCaptureOptions): void;
481
+ protected captureStatelessImmediate(distinctId: string, event: string, properties?: {
482
+ [key: string]: any;
483
+ }, options?: PostHogCaptureOptions): Promise<void>;
484
+ protected aliasStateless(alias: string, distinctId: string, properties?: {
485
+ [key: string]: any;
486
+ }, options?: PostHogCaptureOptions): void;
487
+ protected aliasStatelessImmediate(alias: string, distinctId: string, properties?: {
488
+ [key: string]: any;
489
+ }, options?: PostHogCaptureOptions): Promise<void>;
490
+ /***
491
+ *** GROUPS
492
+ ***/
493
+ protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): void;
494
+ protected getRemoteConfig(): Promise<PostHogRemoteConfig | undefined>;
495
+ /***
496
+ *** FEATURE FLAGS
497
+ ***/
498
+ protected getDecide(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, extraPayload?: Record<string, any>): Promise<PostHogDecideResponse | undefined>;
499
+ protected getFeatureFlagStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
500
+ response: FeatureFlagValue | undefined;
501
+ requestId: string | undefined;
502
+ }>;
503
+ protected getFeatureFlagDetailStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
504
+ response: FeatureFlagDetail | undefined;
505
+ requestId: string | undefined;
506
+ } | undefined>;
507
+ protected getFeatureFlagPayloadStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<JsonType | undefined>;
508
+ protected getFeatureFlagPayloadsStateless(distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogDecideResponse['featureFlagPayloads'] | undefined>;
509
+ protected getFeatureFlagsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
510
+ flags: PostHogDecideResponse['featureFlags'] | undefined;
511
+ payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
512
+ requestId: PostHogDecideResponse['requestId'] | undefined;
513
+ }>;
514
+ protected getFeatureFlagsAndPayloadsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
515
+ flags: PostHogDecideResponse['featureFlags'] | undefined;
516
+ payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
517
+ requestId: PostHogDecideResponse['requestId'] | undefined;
518
+ }>;
519
+ protected getFeatureFlagDetailsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogFeatureFlagDetails | undefined>;
520
+ /***
521
+ *** SURVEYS
522
+ ***/
523
+ getSurveysStateless(): Promise<SurveyResponse['surveys']>;
524
+ /***
525
+ *** SUPER PROPERTIES
526
+ ***/
527
+ private _props;
528
+ protected get props(): PostHogEventProperties;
529
+ protected set props(val: PostHogEventProperties | undefined);
530
+ register(properties: {
531
+ [key: string]: any;
532
+ }): Promise<void>;
533
+ unregister(property: string): Promise<void>;
534
+ /***
535
+ *** QUEUEING AND FLUSHING
536
+ ***/
537
+ protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void;
538
+ protected sendImmediate(type: string, _message: any, options?: PostHogCaptureOptions): Promise<void>;
539
+ private prepareMessage;
540
+ private clearFlushTimer;
541
+ /**
542
+ * Helper for flushing the queue in the background
543
+ * Avoids unnecessary promise errors
544
+ */
545
+ private flushBackground;
546
+ flush(): Promise<any[]>;
547
+ protected getCustomHeaders(): {
548
+ [key: string]: string;
549
+ };
550
+ private _flush;
551
+ private fetchWithRetry;
552
+ _shutdown(shutdownTimeoutMs?: number): Promise<void>;
553
+ /**
554
+ * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
555
+ * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
556
+ * @param shutdownTimeoutMs
557
+ */
558
+ shutdown(shutdownTimeoutMs?: number): Promise<void>;
527
559
  }
528
560
 
529
- interface IdentifyMessage {
530
- distinctId: string;
531
- properties?: Record<string | number, any>;
532
- disableGeoip?: boolean;
533
- }
534
- interface EventMessage extends IdentifyMessage {
535
- event: string;
536
- groups?: Record<string, string | number>;
537
- sendFeatureFlags?: boolean;
538
- timestamp?: Date;
539
- uuid?: string;
540
- }
541
- interface GroupIdentifyMessage {
542
- groupType: string;
543
- groupKey: string;
544
- properties?: Record<string | number, any>;
545
- distinctId?: string;
546
- disableGeoip?: boolean;
547
- }
548
- type PostHogNodeV1 = {
549
- /**
550
- * @description Capture allows you to capture anything a user does within your system,
551
- * which you can later use in PostHog to find patterns in usage,
552
- * work out which features to improve or where people are giving up.
553
- * A capture call requires:
554
- * @param distinctId which uniquely identifies your user
555
- * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
556
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
557
- * @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.
558
- * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
559
- */
560
- capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void;
561
- /**
562
- * @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.
563
- * @param distinctId which uniquely identifies your user
564
- * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
565
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
566
- * @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.
567
- * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
568
- */
569
- captureImmediate({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): Promise<void>;
570
- /**
571
- * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
572
- * and even do things like segment users by these properties.
573
- * An identify call requires:
574
- * @param distinctId which uniquely identifies your user
575
- * @param properties with a dict with any key: value pairs
576
- */
577
- identify({ distinctId, properties }: IdentifyMessage): void;
578
- /**
579
- * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog.
580
- * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
581
- * @param distinctId which uniquely identifies your user
582
- * @param properties with a dict with any key: value pairs
583
- */
584
- identifyImmediate({ distinctId, properties }: IdentifyMessage): Promise<void>;
585
- /**
586
- * @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.
587
- * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
588
- * or "What do users do on our website before signing up?"
589
- * 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.
590
- * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
591
- * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
592
- * doing the identify call in the frontend will be enough.:
593
- * @param distinctId the current unique id
594
- * @param alias the unique ID of the user before
595
- */
596
- alias(data: {
597
- distinctId: string;
598
- alias: string;
599
- }): void;
600
- /**
601
- * @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.
602
- * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
603
- * @param distinctId the current unique id
604
- * @param alias the unique ID of the user before
605
- */
606
- aliasImmediate(data: {
607
- distinctId: string;
608
- alias: string;
609
- }): Promise<void>;
610
- /**
611
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
612
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
613
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
614
- * features on and off for different user groups or individual users.
615
- * @param key the unique key of your feature flag
616
- * @param distinctId the current unique id
617
- * @param options: dict with optional parameters below
618
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
619
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
620
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
621
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
622
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
623
- *
624
- * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
625
- */
626
- isFeatureEnabled(key: string, distinctId: string, options?: {
627
- groups?: Record<string, string>;
628
- personProperties?: Record<string, string>;
629
- groupProperties?: Record<string, Record<string, string>>;
630
- onlyEvaluateLocally?: boolean;
631
- sendFeatureFlagEvents?: boolean;
632
- }): Promise<boolean | undefined>;
633
- /**
634
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
635
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
636
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
637
- * features on and off for different user groups or individual users.
638
- * @param key the unique key of your feature flag
639
- * @param distinctId the current unique id
640
- * @param options: dict with optional parameters below
641
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
642
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
643
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
644
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
645
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
646
- *
647
- * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
648
- */
649
- getFeatureFlag(key: string, distinctId: string, options?: {
650
- groups?: Record<string, string>;
651
- personProperties?: Record<string, string>;
652
- groupProperties?: Record<string, Record<string, string>>;
653
- onlyEvaluateLocally?: boolean;
654
- sendFeatureFlagEvents?: boolean;
655
- }): Promise<FeatureFlagValue | undefined>;
656
- /**
657
- * @description Retrieves payload associated with the specified flag and matched value that is passed in.
658
- *
659
- * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
660
- * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
661
- * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
662
- * not be evaluated locally. This means that omitting `matchValue` will potentially:
663
- * - Bypass local evaluation
664
- * - Count as an additional flag evaluation against your quota
665
- * - Impact performance due to the extra network request
666
- *
667
- * Example usage:
668
- * ```js
669
- * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
670
- * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
671
- * ```
672
- *
673
- * @param key the unique key of your feature flag
674
- * @param distinctId the current unique id
675
- * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
676
- * To avoid extra network calls, pass this parameter when you can.
677
- * @param options: dict with optional parameters below
678
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
679
- *
680
- * @returns payload of a json type object
681
- */
682
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
683
- onlyEvaluateLocally?: boolean;
684
- }): Promise<JsonType | undefined>;
685
- /**
686
- * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
687
- * using my product in PostHog.
688
- *
689
- * @param groupType Type of group (ex: 'company'). Limited to 5 per project
690
- * @param groupKey Unique identifier for that type of group (ex: 'id:5')
691
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
692
- */
693
- groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void;
694
- /**
695
- * @description Force an immediate reload of the polled feature flags. Please note that they are
696
- * already polled automatically at a regular interval.
697
- */
698
- reloadFeatureFlags(): Promise<void>;
699
- /**
700
- * @description Flushes the events still in the queue and clears the feature flags poller to allow for
701
- * a clean shutdown.
702
- *
703
- * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
704
- */
705
- shutdown(shutdownTimeoutMs?: number): void;
706
- /**
707
- * @description Waits for local evaluation to be ready, with an optional timeout.
708
- * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
709
- * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
710
- */
711
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
712
- /**
713
- * @description Returns true if local evaluation is ready, false if it's not.
714
- * @returns true if local evaluation is ready, false if it's not.
715
- */
716
- isLocalEvaluationReady(): boolean;
561
+ interface IdentifyMessage {
562
+ distinctId: string;
563
+ properties?: Record<string | number, any>;
564
+ disableGeoip?: boolean;
565
+ }
566
+ interface EventMessage extends IdentifyMessage {
567
+ event: string;
568
+ groups?: Record<string, string | number>;
569
+ sendFeatureFlags?: boolean;
570
+ timestamp?: Date;
571
+ uuid?: string;
572
+ }
573
+ interface GroupIdentifyMessage {
574
+ groupType: string;
575
+ groupKey: string;
576
+ properties?: Record<string | number, any>;
577
+ distinctId?: string;
578
+ disableGeoip?: boolean;
579
+ }
580
+ type PropertyGroup = {
581
+ type: 'AND' | 'OR';
582
+ values: PropertyGroup[] | FlagProperty[];
583
+ };
584
+ type FlagProperty = {
585
+ key: string;
586
+ type?: string;
587
+ value: string | number | (string | number)[];
588
+ operator?: string;
589
+ negation?: boolean;
590
+ };
591
+ type FeatureFlagCondition = {
592
+ properties: FlagProperty[];
593
+ rollout_percentage?: number;
594
+ variant?: string;
595
+ };
596
+ type PostHogOptions = PostHogCoreOptions & {
597
+ persistence?: 'memory';
598
+ personalApiKey?: string;
599
+ privacyMode?: boolean;
600
+ enableExceptionAutocapture?: boolean;
601
+ featureFlagsPollingInterval?: number;
602
+ maxCacheSize?: number;
603
+ fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
604
+ };
605
+ type PostHogFeatureFlag = {
606
+ id: number;
607
+ name: string;
608
+ key: string;
609
+ filters?: {
610
+ aggregation_group_type_index?: number;
611
+ groups?: FeatureFlagCondition[];
612
+ multivariate?: {
613
+ variants: {
614
+ key: string;
615
+ rollout_percentage: number;
616
+ }[];
617
+ };
618
+ payloads?: Record<string, string>;
619
+ };
620
+ deleted: boolean;
621
+ active: boolean;
622
+ /** @deprecated This field will be removed in a future version. **/
623
+ is_simple_flag: boolean;
624
+ rollout_percentage: null | number;
625
+ ensure_experience_continuity: boolean;
626
+ experiment_set: number[];
627
+ };
628
+ type PostHogNodeV1 = {
629
+ /**
630
+ * @description Capture allows you to capture anything a user does within your system,
631
+ * which you can later use in PostHog to find patterns in usage,
632
+ * work out which features to improve or where people are giving up.
633
+ * A capture call requires:
634
+ * @param distinctId which uniquely identifies your user
635
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
636
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
637
+ * @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.
638
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
639
+ */
640
+ capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void;
641
+ /**
642
+ * @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.
643
+ * @param distinctId which uniquely identifies your user
644
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
645
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
646
+ * @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.
647
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
648
+ */
649
+ captureImmediate({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): Promise<void>;
650
+ /**
651
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
652
+ * and even do things like segment users by these properties.
653
+ * An identify call requires:
654
+ * @param distinctId which uniquely identifies your user
655
+ * @param properties with a dict with any key: value pairs
656
+ */
657
+ identify({ distinctId, properties }: IdentifyMessage): void;
658
+ /**
659
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog.
660
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
661
+ * @param distinctId which uniquely identifies your user
662
+ * @param properties with a dict with any key: value pairs
663
+ */
664
+ identifyImmediate({ distinctId, properties }: IdentifyMessage): Promise<void>;
665
+ /**
666
+ * @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.
667
+ * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
668
+ * or "What do users do on our website before signing up?"
669
+ * 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.
670
+ * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
671
+ * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
672
+ * doing the identify call in the frontend will be enough.:
673
+ * @param distinctId the current unique id
674
+ * @param alias the unique ID of the user before
675
+ */
676
+ alias(data: {
677
+ distinctId: string;
678
+ alias: string;
679
+ }): void;
680
+ /**
681
+ * @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.
682
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
683
+ * @param distinctId the current unique id
684
+ * @param alias the unique ID of the user before
685
+ */
686
+ aliasImmediate(data: {
687
+ distinctId: string;
688
+ alias: string;
689
+ }): Promise<void>;
690
+ /**
691
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
692
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
693
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
694
+ * features on and off for different user groups or individual users.
695
+ * @param key the unique key of your feature flag
696
+ * @param distinctId the current unique id
697
+ * @param options: dict with optional parameters below
698
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
699
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
700
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
701
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
702
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
703
+ *
704
+ * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
705
+ */
706
+ isFeatureEnabled(key: string, distinctId: string, options?: {
707
+ groups?: Record<string, string>;
708
+ personProperties?: Record<string, string>;
709
+ groupProperties?: Record<string, Record<string, string>>;
710
+ onlyEvaluateLocally?: boolean;
711
+ sendFeatureFlagEvents?: boolean;
712
+ }): Promise<boolean | undefined>;
713
+ /**
714
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
715
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
716
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
717
+ * features on and off for different user groups or individual users.
718
+ * @param key the unique key of your feature flag
719
+ * @param distinctId the current unique id
720
+ * @param options: dict with optional parameters below
721
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
722
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
723
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
724
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
725
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
726
+ *
727
+ * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
728
+ */
729
+ getFeatureFlag(key: string, distinctId: string, options?: {
730
+ groups?: Record<string, string>;
731
+ personProperties?: Record<string, string>;
732
+ groupProperties?: Record<string, Record<string, string>>;
733
+ onlyEvaluateLocally?: boolean;
734
+ sendFeatureFlagEvents?: boolean;
735
+ }): Promise<FeatureFlagValue | undefined>;
736
+ /**
737
+ * @description Retrieves payload associated with the specified flag and matched value that is passed in.
738
+ *
739
+ * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
740
+ * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
741
+ * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
742
+ * not be evaluated locally. This means that omitting `matchValue` will potentially:
743
+ * - Bypass local evaluation
744
+ * - Count as an additional flag evaluation against your quota
745
+ * - Impact performance due to the extra network request
746
+ *
747
+ * Example usage:
748
+ * ```js
749
+ * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
750
+ * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
751
+ * ```
752
+ *
753
+ * @param key the unique key of your feature flag
754
+ * @param distinctId the current unique id
755
+ * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
756
+ * To avoid extra network calls, pass this parameter when you can.
757
+ * @param options: dict with optional parameters below
758
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
759
+ *
760
+ * @returns payload of a json type object
761
+ */
762
+ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
763
+ onlyEvaluateLocally?: boolean;
764
+ }): Promise<JsonType | undefined>;
765
+ /**
766
+ * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
767
+ * using my product in PostHog.
768
+ *
769
+ * @param groupType Type of group (ex: 'company'). Limited to 5 per project
770
+ * @param groupKey Unique identifier for that type of group (ex: 'id:5')
771
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
772
+ */
773
+ groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void;
774
+ /**
775
+ * @description Force an immediate reload of the polled feature flags. Please note that they are
776
+ * already polled automatically at a regular interval.
777
+ */
778
+ reloadFeatureFlags(): Promise<void>;
779
+ /**
780
+ * @description Flushes the events still in the queue and clears the feature flags poller to allow for
781
+ * a clean shutdown.
782
+ *
783
+ * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
784
+ */
785
+ shutdown(shutdownTimeoutMs?: number): void;
786
+ /**
787
+ * @description Waits for local evaluation to be ready, with an optional timeout.
788
+ * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
789
+ * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
790
+ */
791
+ waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
792
+ /**
793
+ * @description Returns true if local evaluation is ready, false if it's not.
794
+ * @returns true if local evaluation is ready, false if it's not.
795
+ */
796
+ isLocalEvaluationReady(): boolean;
717
797
  };
718
798
 
719
- interface EventHint {
720
- mechanism?: Partial<Mechanism>;
721
- syntheticException?: Error | null;
722
- }
723
- interface Mechanism {
724
- handled?: boolean;
725
- type?: string;
726
- source?: string;
727
- synthetic?: boolean;
799
+ declare class ErrorTracking {
800
+ private client;
801
+ private _exceptionAutocaptureEnabled;
802
+ static stackParser: StackParser;
803
+ static frameModifiers: StackFrameModifierFn[];
804
+ static captureException(client: PostHogBackendClient, error: unknown, hint: EventHint, distinctId?: string, additionalProperties?: Record<string | number, any>): Promise<void>;
805
+ constructor(client: PostHogBackendClient, options: PostHogOptions);
806
+ private startAutocaptureIfEnabled;
807
+ private onException;
808
+ private onFatalError;
809
+ isEnabled(): boolean;
728
810
  }
729
811
 
730
- declare class ErrorTracking {
731
- private client;
732
- private _exceptionAutocaptureEnabled;
733
- static captureException(client: PostHog, error: unknown, hint: EventHint, distinctId?: string, additionalProperties?: Record<string | number, any>): Promise<void>;
734
- constructor(client: PostHog, options: PostHogOptions);
735
- private startAutocaptureIfEnabled;
736
- private onException;
737
- private onFatalError;
738
- isEnabled(): boolean;
812
+ declare abstract class PostHogBackendClient extends PostHogCoreStateless implements PostHogNodeV1 {
813
+ private _memoryStorage;
814
+ private featureFlagsPoller?;
815
+ protected errorTracking: ErrorTracking;
816
+ private maxCacheSize;
817
+ readonly options: PostHogOptions;
818
+ distinctIdHasSentFlagCalls: Record<string, string[]>;
819
+ constructor(apiKey: string, options?: PostHogOptions);
820
+ getPersistedProperty(key: PostHogPersistedProperty): any | undefined;
821
+ setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
822
+ fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
823
+ getLibraryVersion(): string;
824
+ getCustomUserAgent(): string;
825
+ enable(): Promise<void>;
826
+ disable(): Promise<void>;
827
+ debug(enabled?: boolean): void;
828
+ capture(props: EventMessage): void;
829
+ captureImmediate(props: EventMessage): Promise<void>;
830
+ identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void;
831
+ identifyImmediate({ distinctId, properties, disableGeoip }: IdentifyMessage): Promise<void>;
832
+ alias(data: {
833
+ distinctId: string;
834
+ alias: string;
835
+ disableGeoip?: boolean;
836
+ }): void;
837
+ aliasImmediate(data: {
838
+ distinctId: string;
839
+ alias: string;
840
+ disableGeoip?: boolean;
841
+ }): Promise<void>;
842
+ isLocalEvaluationReady(): boolean;
843
+ waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
844
+ getFeatureFlag(key: string, distinctId: string, options?: {
845
+ groups?: Record<string, string>;
846
+ personProperties?: Record<string, string>;
847
+ groupProperties?: Record<string, Record<string, string>>;
848
+ onlyEvaluateLocally?: boolean;
849
+ sendFeatureFlagEvents?: boolean;
850
+ disableGeoip?: boolean;
851
+ }): Promise<FeatureFlagValue | undefined>;
852
+ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
853
+ groups?: Record<string, string>;
854
+ personProperties?: Record<string, string>;
855
+ groupProperties?: Record<string, Record<string, string>>;
856
+ onlyEvaluateLocally?: boolean;
857
+ sendFeatureFlagEvents?: boolean;
858
+ disableGeoip?: boolean;
859
+ }): Promise<JsonType | undefined>;
860
+ getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
861
+ isFeatureEnabled(key: string, distinctId: string, options?: {
862
+ groups?: Record<string, string>;
863
+ personProperties?: Record<string, string>;
864
+ groupProperties?: Record<string, Record<string, string>>;
865
+ onlyEvaluateLocally?: boolean;
866
+ sendFeatureFlagEvents?: boolean;
867
+ disableGeoip?: boolean;
868
+ }): Promise<boolean | undefined>;
869
+ getAllFlags(distinctId: string, options?: {
870
+ groups?: Record<string, string>;
871
+ personProperties?: Record<string, string>;
872
+ groupProperties?: Record<string, Record<string, string>>;
873
+ onlyEvaluateLocally?: boolean;
874
+ disableGeoip?: boolean;
875
+ }): Promise<Record<string, FeatureFlagValue>>;
876
+ getAllFlagsAndPayloads(distinctId: string, options?: {
877
+ groups?: Record<string, string>;
878
+ personProperties?: Record<string, string>;
879
+ groupProperties?: Record<string, Record<string, string>>;
880
+ onlyEvaluateLocally?: boolean;
881
+ disableGeoip?: boolean;
882
+ }): Promise<PostHogFlagsAndPayloadsResponse>;
883
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void;
884
+ /**
885
+ * Reloads the feature flag definitions from the server for local evaluation.
886
+ * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
887
+ */
888
+ reloadFeatureFlags(): Promise<void>;
889
+ _shutdown(shutdownTimeoutMs?: number): Promise<void>;
890
+ private addLocalPersonAndGroupProperties;
891
+ captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void;
739
892
  }
740
893
 
741
- type PostHogOptions = PostHogCoreOptions & {
742
- persistence?: 'memory';
743
- personalApiKey?: string;
744
- privacyMode?: boolean;
745
- enableExceptionAutocapture?: boolean;
746
- featureFlagsPollingInterval?: number;
747
- maxCacheSize?: number;
748
- fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
749
- };
750
- declare const MINIMUM_POLLING_INTERVAL = 100;
751
- declare const THIRTY_SECONDS: number;
752
- declare const SIXTY_SECONDS: number;
753
- declare class PostHog extends PostHogCoreStateless implements PostHogNodeV1 {
754
- private _memoryStorage;
755
- private featureFlagsPoller?;
756
- protected errorTracking: ErrorTracking;
757
- private maxCacheSize;
758
- readonly options: PostHogOptions;
759
- distinctIdHasSentFlagCalls: Record<string, string[]>;
760
- constructor(apiKey: string, options?: PostHogOptions);
761
- getPersistedProperty(key: PostHogPersistedProperty): any | undefined;
762
- setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
763
- fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
764
- getLibraryId(): string;
765
- getLibraryVersion(): string;
766
- getCustomUserAgent(): string;
767
- enable(): Promise<void>;
768
- disable(): Promise<void>;
769
- debug(enabled?: boolean): void;
770
- capture(props: EventMessage): void;
771
- captureImmediate(props: EventMessage): Promise<void>;
772
- identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void;
773
- identifyImmediate({ distinctId, properties, disableGeoip }: IdentifyMessage): Promise<void>;
774
- alias(data: {
775
- distinctId: string;
776
- alias: string;
777
- disableGeoip?: boolean;
778
- }): void;
779
- aliasImmediate(data: {
780
- distinctId: string;
781
- alias: string;
782
- disableGeoip?: boolean;
783
- }): Promise<void>;
784
- isLocalEvaluationReady(): boolean;
785
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
786
- getFeatureFlag(key: string, distinctId: string, options?: {
787
- groups?: Record<string, string>;
788
- personProperties?: Record<string, string>;
789
- groupProperties?: Record<string, Record<string, string>>;
790
- onlyEvaluateLocally?: boolean;
791
- sendFeatureFlagEvents?: boolean;
792
- disableGeoip?: boolean;
793
- }): Promise<FeatureFlagValue | undefined>;
794
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
795
- groups?: Record<string, string>;
796
- personProperties?: Record<string, string>;
797
- groupProperties?: Record<string, Record<string, string>>;
798
- onlyEvaluateLocally?: boolean;
799
- sendFeatureFlagEvents?: boolean;
800
- disableGeoip?: boolean;
801
- }): Promise<JsonType | undefined>;
802
- getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
803
- isFeatureEnabled(key: string, distinctId: string, options?: {
804
- groups?: Record<string, string>;
805
- personProperties?: Record<string, string>;
806
- groupProperties?: Record<string, Record<string, string>>;
807
- onlyEvaluateLocally?: boolean;
808
- sendFeatureFlagEvents?: boolean;
809
- disableGeoip?: boolean;
810
- }): Promise<boolean | undefined>;
811
- getAllFlags(distinctId: string, options?: {
812
- groups?: Record<string, string>;
813
- personProperties?: Record<string, string>;
814
- groupProperties?: Record<string, Record<string, string>>;
815
- onlyEvaluateLocally?: boolean;
816
- disableGeoip?: boolean;
817
- }): Promise<Record<string, FeatureFlagValue>>;
818
- getAllFlagsAndPayloads(distinctId: string, options?: {
819
- groups?: Record<string, string>;
820
- personProperties?: Record<string, string>;
821
- groupProperties?: Record<string, Record<string, string>>;
822
- onlyEvaluateLocally?: boolean;
823
- disableGeoip?: boolean;
824
- }): Promise<PostHogFlagsAndPayloadsResponse>;
825
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void;
826
- /**
827
- * Reloads the feature flag definitions from the server for local evaluation.
828
- * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
829
- */
830
- reloadFeatureFlags(): Promise<void>;
831
- _shutdown(shutdownTimeoutMs?: number): Promise<void>;
832
- private addLocalPersonAndGroupProperties;
833
- captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void;
834
- }
894
+ /**
895
+ * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
896
+ */
835
897
 
836
- /**
837
- * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
838
- */
839
-
840
- type _SentryEvent = any;
841
- type _SentryEventProcessor = any;
842
- type _SentryHub = any;
843
- interface _SentryIntegration {
844
- name: string;
845
- processEvent(event: _SentryEvent): _SentryEvent;
846
- }
847
- interface _SentryIntegrationClass {
848
- name: string;
849
- setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void;
850
- }
851
- type SentryIntegrationOptions = {
852
- organization?: string;
853
- projectId?: number;
854
- prefix?: string;
855
- severityAllowList?: SeverityLevel[] | '*';
856
- };
857
- declare function createEventProcessor(_posthog: PostHog, { organization, projectId, prefix, severityAllowList }?: SentryIntegrationOptions): (event: _SentryEvent) => _SentryEvent;
858
- declare function sentryIntegration(_posthog: PostHog, options?: SentryIntegrationOptions): _SentryIntegration;
859
- declare class PostHogSentryIntegration implements _SentryIntegrationClass {
860
- readonly name = "posthog-node";
861
- static readonly POSTHOG_ID_TAG = "posthog_distinct_id";
862
- setupOnce: (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub) => void;
863
- constructor(_posthog: PostHog, organization?: string, prefix?: string, severityAllowList?: SeverityLevel[] | '*');
898
+ type _SentryEvent = any;
899
+ type _SentryEventProcessor = any;
900
+ type _SentryHub = any;
901
+ interface _SentryIntegration {
902
+ name: string;
903
+ processEvent(event: _SentryEvent): _SentryEvent;
904
+ }
905
+ interface _SentryIntegrationClass {
906
+ name: string;
907
+ setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void;
908
+ }
909
+ type SentryIntegrationOptions = {
910
+ organization?: string;
911
+ projectId?: number;
912
+ prefix?: string;
913
+ severityAllowList?: SeverityLevel[] | '*';
914
+ };
915
+ declare function createEventProcessor(_posthog: PostHogBackendClient, { organization, projectId, prefix, severityAllowList }?: SentryIntegrationOptions): (event: _SentryEvent) => _SentryEvent;
916
+ declare function sentryIntegration(_posthog: PostHogBackendClient, options?: SentryIntegrationOptions): _SentryIntegration;
917
+ declare class PostHogSentryIntegration implements _SentryIntegrationClass {
918
+ readonly name = "posthog-node";
919
+ static readonly POSTHOG_ID_TAG = "posthog_distinct_id";
920
+ setupOnce: (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub) => void;
921
+ constructor(_posthog: PostHogBackendClient, organization?: string, prefix?: string, severityAllowList?: SeverityLevel[] | '*');
864
922
  }
865
923
 
866
- type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void;
867
- type ExpressErrorMiddleware = (error: MiddlewareError, req: http.IncomingMessage, res: http.ServerResponse, next: (error: MiddlewareError) => void) => void;
868
- interface MiddlewareError extends Error {
869
- status?: number | string;
870
- statusCode?: number | string;
871
- status_code?: number | string;
872
- output?: {
873
- statusCode?: number | string;
874
- };
875
- }
876
- declare function setupExpressErrorHandler(_posthog: PostHog, app: {
877
- use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown;
924
+ type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void;
925
+ type ExpressErrorMiddleware = (error: MiddlewareError, req: http.IncomingMessage, res: http.ServerResponse, next: (error: MiddlewareError) => void) => void;
926
+ interface MiddlewareError extends Error {
927
+ status?: number | string;
928
+ statusCode?: number | string;
929
+ status_code?: number | string;
930
+ output?: {
931
+ statusCode?: number | string;
932
+ };
933
+ }
934
+ declare function setupExpressErrorHandler(_posthog: PostHogBackendClient, app: {
935
+ use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown;
878
936
  }): void;
879
937
 
880
- export { MINIMUM_POLLING_INTERVAL, PostHog, PostHogOptions, PostHogSentryIntegration, SIXTY_SECONDS, SentryIntegrationOptions, THIRTY_SECONDS, createEventProcessor, sentryIntegration, setupExpressErrorHandler };
938
+ declare class PostHog extends PostHogBackendClient {
939
+ getLibraryId(): string;
940
+ }
941
+
942
+ export { EventMessage, FeatureFlagCondition, FlagProperty, GroupIdentifyMessage, IdentifyMessage, PostHog, PostHogFeatureFlag, PostHogNodeV1, PostHogOptions, PostHogSentryIntegration, PropertyGroup, SentryIntegrationOptions, createEventProcessor, sentryIntegration, setupExpressErrorHandler };