posthog-node 5.73.1 → 6.0.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 (156) hide show
  1. package/MIGRATION.md +556 -0
  2. package/README.md +3 -1
  3. package/dist/ai-capture/routing.d.ts +0 -3
  4. package/dist/ai-capture/routing.d.ts.map +1 -1
  5. package/dist/ai-capture/routing.js +2 -14
  6. package/dist/ai-capture/routing.mjs +1 -4
  7. package/dist/capture-lane/lane.d.ts +109 -0
  8. package/dist/capture-lane/lane.d.ts.map +1 -0
  9. package/dist/capture-lane/lane.js +308 -0
  10. package/dist/capture-lane/lane.mjs +270 -0
  11. package/dist/capture-lane/limits.d.ts +7 -0
  12. package/dist/capture-lane/limits.d.ts.map +1 -0
  13. package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
  14. package/dist/capture-lane/limits.mjs +4 -0
  15. package/dist/capture-lane/settings.d.ts +30 -0
  16. package/dist/capture-lane/settings.d.ts.map +1 -0
  17. package/dist/capture-lane/settings.js +100 -0
  18. package/dist/capture-lane/settings.mjs +47 -0
  19. package/dist/capture-v1/compression.d.ts +18 -0
  20. package/dist/capture-v1/compression.d.ts.map +1 -0
  21. package/dist/capture-v1/compression.js +70 -0
  22. package/dist/capture-v1/compression.mjs +26 -0
  23. package/dist/capture-v1/errors.d.ts +23 -7
  24. package/dist/capture-v1/errors.d.ts.map +1 -1
  25. package/dist/capture-v1/errors.js +37 -8
  26. package/dist/capture-v1/errors.mjs +29 -6
  27. package/dist/capture-v1/sender.d.ts +63 -23
  28. package/dist/capture-v1/sender.d.ts.map +1 -1
  29. package/dist/capture-v1/sender.js +281 -74
  30. package/dist/capture-v1/sender.mjs +275 -77
  31. package/dist/capture-v1/serialize.d.ts +28 -0
  32. package/dist/capture-v1/serialize.d.ts.map +1 -0
  33. package/dist/capture-v1/serialize.js +82 -0
  34. package/dist/capture-v1/serialize.mjs +38 -0
  35. package/dist/capture-v1/transform.d.ts +10 -25
  36. package/dist/capture-v1/transform.d.ts.map +1 -1
  37. package/dist/capture-v1/transform.js +33 -64
  38. package/dist/capture-v1/transform.mjs +28 -53
  39. package/dist/capture-v1/types.d.ts +16 -14
  40. package/dist/capture-v1/types.d.ts.map +1 -1
  41. package/dist/capture-v1/types.js +27 -1
  42. package/dist/capture-v1/types.mjs +3 -1
  43. package/dist/capture-v1/uuid.d.ts +9 -0
  44. package/dist/capture-v1/uuid.d.ts.map +1 -0
  45. package/dist/capture-v1/uuid.js +75 -0
  46. package/dist/capture-v1/uuid.mjs +34 -0
  47. package/dist/client.d.ts +201 -94
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +485 -246
  50. package/dist/client.mjs +485 -246
  51. package/dist/compression.node.d.ts +13 -0
  52. package/dist/compression.node.d.ts.map +1 -0
  53. package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
  54. package/dist/compression.node.mjs +18 -0
  55. package/dist/entrypoints/index.node.d.ts +2 -0
  56. package/dist/entrypoints/index.node.d.ts.map +1 -1
  57. package/dist/entrypoints/index.node.js +11 -4
  58. package/dist/entrypoints/index.node.mjs +4 -0
  59. package/dist/event-defaults.d.ts +46 -0
  60. package/dist/event-defaults.d.ts.map +1 -0
  61. package/dist/event-defaults.js +141 -0
  62. package/dist/event-defaults.mjs +79 -0
  63. package/dist/exports.d.ts +3 -0
  64. package/dist/exports.d.ts.map +1 -1
  65. package/dist/exports.js +22 -11
  66. package/dist/exports.mjs +1 -0
  67. package/dist/extensions/context/context.d.ts +0 -1
  68. package/dist/extensions/context/context.d.ts.map +1 -1
  69. package/dist/extensions/context/context.js +4 -3
  70. package/dist/extensions/context/context.mjs +4 -3
  71. package/dist/extensions/context/event-context.d.ts.map +1 -1
  72. package/dist/extensions/context/event-context.js +3 -0
  73. package/dist/extensions/context/event-context.mjs +3 -0
  74. package/dist/extensions/context/types.d.ts +9 -1
  75. package/dist/extensions/context/types.d.ts.map +1 -1
  76. package/dist/extensions/error-tracking/index.d.ts +1 -1
  77. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  78. package/dist/extensions/error-tracking/index.js +71 -7
  79. package/dist/extensions/error-tracking/index.mjs +75 -11
  80. package/dist/extensions/express.d.ts +8 -0
  81. package/dist/extensions/express.d.ts.map +1 -1
  82. package/dist/extensions/express.js +3 -3
  83. package/dist/extensions/express.mjs +4 -4
  84. package/dist/extensions/fetch-request.d.ts.map +1 -1
  85. package/dist/extensions/fetch-request.js +2 -2
  86. package/dist/extensions/fetch-request.mjs +3 -3
  87. package/dist/extensions/nestjs.d.ts.map +1 -1
  88. package/dist/extensions/nestjs.js +7 -4
  89. package/dist/extensions/nestjs.mjs +8 -5
  90. package/dist/extensions/tracing-headers.d.ts +7 -0
  91. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  92. package/dist/extensions/tracing-headers.js +11 -1
  93. package/dist/extensions/tracing-headers.mjs +9 -2
  94. package/dist/feature-flag-evaluations.d.ts +5 -5
  95. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  96. package/dist/feature-flag-evaluations.js +16 -9
  97. package/dist/feature-flag-evaluations.mjs +16 -9
  98. package/dist/flag-events.d.ts +1 -1
  99. package/dist/flag-events.d.ts.map +1 -1
  100. package/dist/flag-events.js +2 -2
  101. package/dist/flag-events.mjs +2 -2
  102. package/dist/flags-response.d.ts +2 -0
  103. package/dist/flags-response.d.ts.map +1 -1
  104. package/dist/flags-response.js +6 -0
  105. package/dist/flags-response.mjs +4 -1
  106. package/dist/types.d.ts +192 -27
  107. package/dist/types.d.ts.map +1 -1
  108. package/dist/types.js +1 -0
  109. package/dist/types.mjs +1 -0
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.d.ts.map +1 -1
  112. package/dist/version.js +1 -1
  113. package/dist/version.mjs +1 -1
  114. package/package.json +5 -4
  115. package/src/ai-capture/routing.ts +0 -6
  116. package/src/capture-lane/lane.ts +414 -0
  117. package/src/capture-lane/limits.ts +8 -0
  118. package/src/capture-lane/settings.ts +119 -0
  119. package/src/capture-v1/compression.ts +50 -0
  120. package/src/capture-v1/errors.ts +50 -11
  121. package/src/capture-v1/sender.ts +405 -111
  122. package/src/capture-v1/serialize.ts +77 -0
  123. package/src/capture-v1/transform.ts +59 -92
  124. package/src/capture-v1/types.ts +19 -15
  125. package/src/capture-v1/uuid.ts +53 -0
  126. package/src/client.ts +885 -446
  127. package/src/compression.node.ts +30 -0
  128. package/src/entrypoints/index.node.ts +6 -0
  129. package/src/event-defaults.ts +177 -0
  130. package/src/exports.ts +3 -0
  131. package/src/extensions/context/context.ts +4 -4
  132. package/src/extensions/context/event-context.ts +3 -1
  133. package/src/extensions/context/types.ts +10 -1
  134. package/src/extensions/error-tracking/index.ts +51 -7
  135. package/src/extensions/express.ts +12 -3
  136. package/src/extensions/fetch-request.ts +7 -3
  137. package/src/extensions/nestjs.ts +9 -5
  138. package/src/extensions/tracing-headers.ts +26 -7
  139. package/src/feature-flag-evaluations.ts +31 -23
  140. package/src/flag-events.ts +5 -2
  141. package/src/flags-response.ts +6 -1
  142. package/src/types.ts +212 -44
  143. package/src/version.ts +1 -1
  144. package/dist/ai-capture/batching.d.ts +0 -11
  145. package/dist/ai-capture/batching.d.ts.map +0 -1
  146. package/dist/ai-capture/batching.js +0 -77
  147. package/dist/ai-capture/batching.mjs +0 -36
  148. package/dist/capture-v1/config.d.ts +0 -11
  149. package/dist/capture-v1/config.d.ts.map +0 -1
  150. package/dist/capture-v1/config.mjs +0 -8
  151. package/dist/capture-v1/routing.d.ts +0 -21
  152. package/dist/capture-v1/routing.d.ts.map +0 -1
  153. package/dist/capture-v1/routing.mjs +0 -7
  154. package/src/ai-capture/batching.ts +0 -47
  155. package/src/capture-v1/config.ts +0 -18
  156. package/src/capture-v1/routing.ts +0 -28
package/src/client.ts CHANGED
@@ -2,11 +2,11 @@ import { version } from './version'
2
2
 
3
3
  import {
4
4
  allSettled,
5
+ ErrorTracking as CoreErrorTracking,
6
+ EVENT_OPTION_LEGACY_PROPERTIES,
5
7
  FeatureFlagValue,
6
- getEventUuid,
7
8
  isBlockedUA,
8
9
  isPlainObject,
9
- isPostHogFetchContentTooLargeError,
10
10
  JsonType,
11
11
  minimizeFlagCalledEventProperties,
12
12
  PostHogCaptureOptions,
@@ -28,11 +28,9 @@ import {
28
28
  resolveMetricsConfig,
29
29
  resolveTracesConfig,
30
30
  runWithActiveSpan,
31
- RetriableOptions,
32
31
  raceWithTimeout,
33
32
  safeSetTimeout,
34
33
  SyncSpanContextManager,
35
- uuidv7,
36
34
  } from '@posthog/core'
37
35
  import type {
38
36
  Metrics,
@@ -45,7 +43,9 @@ import type {
45
43
  } from '@posthog/core'
46
44
  import {
47
45
  AllFlagsOptions,
46
+ CaptureExceptionOptions,
48
47
  EventMessage,
48
+ EventOptions,
49
49
  FeatureFlagError,
50
50
  FeatureFlagErrorType,
51
51
  FeatureFlagEvaluationRuntime,
@@ -57,6 +57,7 @@ import {
57
57
  IPostHog,
58
58
  OverrideFeatureFlagsOptions,
59
59
  PostHogOptions,
60
+ PreparedEventMessage,
60
61
  SendFeatureFlagsOptions,
61
62
  SetPersonPropertiesMessage,
62
63
  UnsetPersonPropertiesMessage,
@@ -69,6 +70,7 @@ import {
69
70
  } from './feature-flag-evaluations'
70
71
  import {
71
72
  FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE,
73
+ isServerFailedFlagRecord,
72
74
  isUnreadableFlagRecord,
73
75
  ParsedFlagRecord,
74
76
  parsedFlagRecordOf,
@@ -91,13 +93,28 @@ import ErrorTracking from './extensions/error-tracking'
91
93
  import { getActiveTraceProperties } from './extensions/error-tracking/trace-context'
92
94
  import { PostHogMemoryStorage } from './storage-memory'
93
95
  import { ContextData, ContextOptions, IPostHogContext } from './extensions/context/types'
96
+ import { V1CaptureSender, type V1CaptureSenderConfig } from './capture-v1/sender'
97
+ import { AI_CAPTURE_ENDPOINT, ANALYTICS_CAPTURE_ENDPOINT, type CaptureEndpoint } from './capture-v1/types'
98
+ import type { CaptureError } from './capture-v1/errors'
99
+ import { CaptureLane, type CaptureLaneConfig } from './capture-lane/lane'
100
+ import { AI_MAX_PROPERTIES_BYTES, ANALYTICS_MAX_EVENT_BYTES, CAPTURE_BATCH_TARGET_BYTES } from './capture-lane/limits'
101
+ import { type CaptureSettings, resolveCaptureSettings } from './capture-lane/settings'
102
+ import { type CaptureCompressor, resolveCaptureCodec, webCompressor } from './capture-v1/compression'
103
+ import { canonicalizeUuid, eventUuidv7 } from './capture-v1/uuid'
104
+ import { readEventOptions } from './capture-v1/transform'
105
+ import {
106
+ dropIdentifyStyleLegacyPersonProfile,
107
+ fillIdentifyStylePersonProfile,
108
+ fillLibraryProperties,
109
+ fillOptions,
110
+ fillProperties,
111
+ isMergeableObject,
112
+ isUnsetProperty,
113
+ snapshotLayer,
114
+ } from './event-defaults'
115
+ import { AI_CAPTURE_ROUTE } from './ai-capture/routing'
94
116
  import { notifyContextListeners } from './extensions/context/listeners'
95
117
  import { getEventContext } from './extensions/context/event-context'
96
- import { type CaptureMode, resolveCaptureMode } from './capture-v1/config'
97
- import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from './capture-v1/routing'
98
- import { V1CaptureSender } from './capture-v1/sender'
99
- import { eventByteSize, partitionAiBatch } from './ai-capture/batching'
100
- import { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from './ai-capture/routing'
101
118
  import { DEFAULT_EMAIL_REQUEST_MAX_RETRIES, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS, EmailSender } from './emails/emails'
102
119
  import type { Emails } from './emails/types'
103
120
  import { resolveNodeLogsConfig } from './logs-config'
@@ -112,28 +129,16 @@ const WAITUNTIL_DEBOUNCE_MS = 50
112
129
  const WAITUNTIL_MAX_WAIT_MS = 500
113
130
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com'
114
131
 
115
- // Internal options of one event's trip through the capture pipeline.
116
- type PrepareEventOptions = {
117
- includeContextProperties?: boolean
118
- /** How a config version 2 flag event fixes its properties; see `flag-events.ts`. */
119
- flagEvent?: FlagEventCapture
120
- /**
121
- * Called when capture fails: `before_send` throws, or the event cannot be prepared or queued.
122
- * Not called when `before_send` discards the event.
123
- */
124
- onCaptureFailed?: () => void
125
- }
126
-
127
132
  // Process-wide dedup for deprecation warnings — without this, calling a deprecated
128
133
  // method in a loop would spam logs. Matches Python's `warnings.warn` default-dedup behavior.
129
134
  const _emittedDeprecations = new Set<string>()
130
135
 
131
- function emitDeprecationWarningOnce(id: string, message: string): void {
136
+ function emitDeprecationWarningOnce(id: string, message: string, log: (message: string) => void = console.warn): void {
132
137
  if (_emittedDeprecations.has(id)) {
133
138
  return
134
139
  }
135
140
  _emittedDeprecations.add(id)
136
- console.warn(`[PostHog] ${message}`)
141
+ log(`[PostHog] ${message}`)
137
142
  }
138
143
 
139
144
  /**
@@ -147,16 +152,210 @@ function normalizeApiKey(value?: unknown): string {
147
152
  return typeof value === 'string' ? value.trim() : ''
148
153
  }
149
154
 
155
+ /** Why a project API key disables the client, or undefined when it is usable. Never includes the key. */
156
+ function apiKeyProblem(apiKey: string): string | undefined {
157
+ if (!apiKey) {
158
+ return 'No project API key was passed'
159
+ }
160
+ if (apiKey.startsWith('phx_')) {
161
+ return 'A personal API key ("phx_...") was passed where the project API key ("phc_...") belongs'
162
+ }
163
+ return undefined
164
+ }
165
+
166
+ /** A content-free summary of an emitted event's payload for debug logs: names, uuids and counts only. */
167
+ function summarizeForDebugLog(payload: unknown): unknown {
168
+ if (Array.isArray(payload)) {
169
+ return `${payload.length} item(s)`
170
+ }
171
+ if (payload instanceof Error) {
172
+ return `${payload.name}: ${payload.message}`
173
+ }
174
+ if (payload && typeof payload === 'object' && typeof (payload as { event?: unknown }).event === 'string') {
175
+ const { event, uuid } = payload as { event: string; uuid?: unknown }
176
+ return uuid === undefined ? { event } : { event, uuid }
177
+ }
178
+ return undefined
179
+ }
180
+
150
181
  function normalizePersonalApiKey(value?: unknown): string | undefined {
151
182
  const normalizedValue = typeof value === 'string' ? value.trim() : ''
152
183
  return normalizedValue || undefined
153
184
  }
154
185
 
186
+ /** Capture options plus a flag that the caller's uuid was already replaced, with its one warning. */
187
+ type LaneCaptureOptions = PostHogCaptureOptions & { _invalidUuidWarned?: boolean }
188
+
189
+ function isUnsetUuid(uuid: unknown): boolean {
190
+ return uuid === undefined || uuid === null || uuid === ''
191
+ }
192
+
193
+ function isInvalidUuid(uuid: unknown): boolean {
194
+ return !isUnsetUuid(uuid) && (typeof uuid !== 'string' || canonicalizeUuid(uuid) === undefined)
195
+ }
196
+
155
197
  function normalizeHost(value?: unknown): string {
156
198
  const normalizedValue = typeof value === 'string' ? value.trim() : ''
157
199
  return normalizedValue || DEFAULT_NODE_HOST
158
200
  }
159
201
 
202
+ /** Properties that set an option or a session field, kept on a minimal `$feature_flag_called` event. */
203
+ const FLAG_CALLED_OPTION_SOURCE_PROPERTIES = [
204
+ '$cookieless_mode',
205
+ '$ignore_sent_at',
206
+ '$product_tour_id',
207
+ '$process_person_profile',
208
+ '$session_id',
209
+ '$window_id',
210
+ ]
211
+
212
+ /**
213
+ * The options of a `captureException()` or `captureExceptionImmediate()` call. A string second
214
+ * argument, or extra arguments after one that is not an object, is the 5.x positional form
215
+ * `(error, distinctId, properties, uuid, flags)` (no `uuid` for the immediate variant): it still
216
+ * works and logs one deprecation error per process.
217
+ */
218
+ function readCaptureExceptionArgs(
219
+ method: string,
220
+ second: unknown,
221
+ rest: unknown[],
222
+ legacyHasUuid: boolean
223
+ ): CaptureExceptionOptions {
224
+ if (typeof second !== 'string' && (rest.length === 0 || isPlainObject(second))) {
225
+ if (rest.length > 0) {
226
+ emitDeprecationWarningOnce(
227
+ `${method} extra arguments`,
228
+ `${method}(error, options) ignores the arguments after the options object.`
229
+ )
230
+ }
231
+ return isPlainObject(second) ? (second as CaptureExceptionOptions) : {}
232
+ }
233
+ emitDeprecationWarningOnce(
234
+ `${method} positional arguments`,
235
+ `${method}(error, distinctId, properties) is deprecated: pass an object instead, e.g. ` +
236
+ `${method}(error, { distinctId, properties }). The old form will be removed in the next major version.`,
237
+ console.error
238
+ )
239
+ const [properties, ...tail] = rest
240
+ const [uuid, flags] = legacyHasUuid ? tail : [undefined, tail[0]]
241
+ return {
242
+ distinctId: (second ?? undefined) as string | undefined,
243
+ properties: properties as CaptureExceptionOptions['properties'],
244
+ uuid: uuid as string | undefined,
245
+ flags: flags as FeatureFlagEvaluations | undefined,
246
+ }
247
+ }
248
+
249
+ /**
250
+ * A caller value threw while the client read the event, so the event is dropped as
251
+ * `unserializable`. `original` only lets `prepareEventMessage()` reject as it did before; the drop
252
+ * report never uses it, because its message can hold event data.
253
+ */
254
+ class UnreadableEventError extends Error {
255
+ constructor(readonly original: unknown) {
256
+ super('A value in the event threw while it was read')
257
+ }
258
+ }
259
+
260
+ /** Runs `read` over caller values; a throw becomes an `UnreadableEventError`. */
261
+ function readCallerValues<T>(read: () => T): T {
262
+ try {
263
+ return read()
264
+ } catch (error) {
265
+ throw new UnreadableEventError(error)
266
+ }
267
+ }
268
+
269
+ /**
270
+ * A copy of the event for `beforeSend`, so a hook that mutates it cannot change the caller's
271
+ * objects or the `register()` and context defaults. Plain objects and arrays are copied all the
272
+ * way down; class instances (`Date`, `Buffer`, custom classes) stay shared. The hook always gets
273
+ * an `options` object it can write to.
274
+ */
275
+ function isolateForBeforeSend(eventMessage: EventMessage): EventMessage {
276
+ const isolated = copyPlainValues(eventMessage, new WeakMap()) as EventMessage
277
+ isolated.options ??= {}
278
+ return isolated
279
+ }
280
+
281
+ /** Only objects with no prototype or `Object.prototype`: a copy keeps no class or `toJSON` method. */
282
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
283
+ if (value === null || typeof value !== 'object') {
284
+ return false
285
+ }
286
+ const prototype = Object.getPrototypeOf(value)
287
+ return prototype === Object.prototype || prototype === null
288
+ }
289
+
290
+ // `seen` keeps a circular value circular, so it serializes as it would without a hook.
291
+ function copyPlainValues(value: unknown, seen: WeakMap<object, unknown>): unknown {
292
+ if (!Array.isArray(value) && !isPlainRecord(value)) {
293
+ return value
294
+ }
295
+ const known = seen.get(value)
296
+ if (known !== undefined) {
297
+ return known
298
+ }
299
+ if (Array.isArray(value)) {
300
+ const copy: unknown[] = new Array(value.length)
301
+ seen.set(value, copy)
302
+ value.forEach((item, index) => {
303
+ copy[index] = copyPlainValues(item, seen)
304
+ })
305
+ return copy
306
+ }
307
+ const copy: Record<string, unknown> = Object.getPrototypeOf(value) === null ? Object.create(null) : {}
308
+ seen.set(value, copy)
309
+ for (const key of Object.keys(value)) {
310
+ copy[key] = copyPlainValues(value[key], seen)
311
+ }
312
+ return copy
313
+ }
314
+
315
+ /**
316
+ * The `$identify` properties: `$set` is the caller's `$set`, or every other property when there is
317
+ * none; `$set_once` only when the caller gave one.
318
+ */
319
+ function identifyEventProperties(properties: Record<string | number, any>): PostHogEventProperties {
320
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties
321
+ return {
322
+ $set: $set || rest,
323
+ ...($set_once !== undefined && $set_once !== null ? { $set_once } : {}),
324
+ $anon_distinct_id: $anon_distinct_id ?? undefined,
325
+ }
326
+ }
327
+
328
+ /** How one message type resolves identity and which layers may set which keys. */
329
+ type PrepareEventOptions = {
330
+ /** The distinct id when neither the call nor the context gives one; otherwise a personless id is generated. */
331
+ fallbackDistinctId?: string
332
+ /** Whether the context session id fills `$session_id`. */
333
+ contextSession?: boolean
334
+ /** Properties that only the call sets: no layer fills them. */
335
+ callOnlyProperties?: readonly string[]
336
+ /** Set the `distinct_id` property to the resolved distinct id. */
337
+ distinctIdProperty?: boolean
338
+ /** How a config version 2 flag event fixes its properties; see `flag-events.ts`. */
339
+ flagEvent?: FlagEventCapture
340
+ /**
341
+ * Called when capture fails: `beforeSend` throws, or the event cannot be prepared or queued.
342
+ * Not called when `beforeSend` discards the event.
343
+ */
344
+ onCaptureFailed?: () => void
345
+ }
346
+
347
+ /** `alias` never takes its target from a context or default, and reports the resolved id. */
348
+ const ALIAS_PREPARE_OPTIONS: PrepareEventOptions = { callOnlyProperties: ['alias'], distinctIdProperty: true }
349
+
350
+ /** The id, or undefined when it is missing, empty or only whitespace. */
351
+ function presentDistinctId(value: unknown): string | undefined {
352
+ if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {
353
+ return undefined
354
+ }
355
+ // Stringified before beforeSend, so a hook that leaves the id alone never sends a non-string.
356
+ return typeof value === 'string' ? value : String(value)
357
+ }
358
+
160
359
  function positiveNumberOr(value: unknown, fallback: number): number {
161
360
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
162
361
  }
@@ -210,15 +409,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
210
409
  private _serviceName?: string | null
211
410
  private _spanContext?: SpanContextManager
212
411
 
213
- private readonly captureMode: CaptureMode
214
- private _v1Sender?: V1CaptureSender
412
+ // Created on first use, so a client that never calls captureAi has no AI lane.
413
+ private readonly _captureLanes = new Map<CaptureEndpoint, CaptureLane>()
414
+ private readonly _captureSettings: CaptureSettings
215
415
  private _emails?: EmailSender
216
416
  private _isShutdown = false
217
417
  /** Whether this client captures full AI content: see `enableFullAiCapture` in `PostHogOptions`. */
218
418
  public readonly enableFullAiCapture: boolean
219
419
  /** Whether PostHog AI integrations redact content: see `privacyMode` in `PostHogOptions`. */
220
420
  public readonly privacyMode: boolean
221
- private _aiCaptureRouteActive = false
421
+
422
+ // Options from registerOptions(). Replaced, never mutated, so an event can keep the object it read.
423
+ private _globalOptions: Record<string, unknown> = {}
222
424
 
223
425
  // Feature flag overrides for local testing/development
224
426
  private _flagOverrides?: Record<string, FeatureFlagValue>
@@ -294,8 +496,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
294
496
  */
295
497
  constructor(apiKey: string, options: PostHogOptions = {}) {
296
498
  const normalizedApiKey = normalizeApiKey(apiKey)
499
+ const keyProblem = apiKeyProblem(normalizedApiKey)
297
500
  const normalizedOptions = {
298
501
  ...options,
502
+ disabled: options.disabled || keyProblem !== undefined,
299
503
  // Node's default is higher than the shared core default (1000) because backend
300
504
  // workloads are more likely to burst-enqueue synchronously ahead of a flush.
301
505
  // Applied after the spread with a nullish fallback so a wrapper forwarding
@@ -309,7 +513,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
309
513
  super(normalizedApiKey, normalizedOptions)
310
514
 
311
515
  this.options = normalizedOptions
312
- this.captureMode = resolveCaptureMode()
516
+ if (keyProblem) {
517
+ // console.error, not this._logger: the logger only prints in debug mode, and the client sends nothing.
518
+ console.error(`[PostHog] ${keyProblem}, so the client is disabled.`)
519
+ }
520
+ this.warnIfCaptureModeSet()
521
+ // console.error, not this._logger: the logger only prints in debug mode, and a bad option changes delivery.
522
+ this._captureSettings = resolveCaptureSettings(normalizedOptions, (message) =>
523
+ console.error(`[PostHog] ${message}`)
524
+ )
313
525
  this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true
314
526
  this.privacyMode = normalizedOptions.privacyMode === true
315
527
  this.context = this.initializeContext()
@@ -368,23 +580,93 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
368
580
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE
369
581
  }
370
582
 
583
+ /** Queues the event on its capture lane instead of the core queue. */
371
584
  protected override enqueue(
372
585
  type: string,
373
586
  message: any,
374
587
  options?: PostHogCaptureOptions,
375
588
  explicitRoute?: string
376
589
  ): void {
377
- super.enqueue(type, message, options, explicitRoute)
590
+ this.wrap(() => {
591
+ if (this.optedOut) {
592
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`)
593
+ return
594
+ }
595
+ const prepared = this._prepareLaneMessage(message, options)
596
+ if (prepared === null) {
597
+ return
598
+ }
599
+ this._captureLane(explicitRoute).enqueue(prepared)
600
+ this._events.emit(type, prepared)
601
+ })
378
602
  this.scheduleDebouncedFlush()
379
603
  }
380
604
 
605
+ /** Sends the event through its capture lane's sender, without queueing it. */
606
+ protected override async sendImmediate(
607
+ type: string,
608
+ message: any,
609
+ options?: PostHogCaptureOptions,
610
+ explicitRoute?: string
611
+ ): Promise<void> {
612
+ if (this.disabled) {
613
+ this._logger.warn('The client is disabled')
614
+ return
615
+ }
616
+ if (!this._isInitialized) {
617
+ await this._initPromise
618
+ }
619
+ if (this.optedOut) {
620
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`)
621
+ return
622
+ }
623
+ const prepared = this._prepareLaneMessage(message, options)
624
+ if (prepared === null) {
625
+ return
626
+ }
627
+ try {
628
+ await this._captureLane(explicitRoute).sendImmediate(prepared)
629
+ } catch (err) {
630
+ this._events.emit('error', err)
631
+ }
632
+ }
633
+
634
+ private _prepareLaneMessage(message: any, options?: PostHogCaptureOptions): PostHogEventProperties | null {
635
+ const { _invalidUuidWarned, ...captureOptions } = (options ?? {}) as LaneCaptureOptions
636
+ // beforeSend already ran, so this is the hook's uuid; check it again, warning at most once per call.
637
+ // A missing uuid is generated here, not by core's generator.
638
+ const uuid = this._canonicalEventUuid(captureOptions.uuid, !_invalidUuidWarned) ?? eventUuidv7()
639
+ const prepared = this.processBeforeEnqueue(this.prepareMessage(message, { ...captureOptions, uuid }))
640
+ return prepared === null ? null : this.normalizeMessage(prepared)
641
+ }
642
+
643
+ /**
644
+ * The canonical form of a caller's event uuid, or undefined when there is none to keep. An
645
+ * invalid uuid is replaced with a generated one and a warning that never repeats the value.
646
+ */
647
+ private _canonicalEventUuid(uuid: unknown, warnIfInvalid = true): string | undefined {
648
+ if (isUnsetUuid(uuid)) {
649
+ return undefined
650
+ }
651
+ const canonical = typeof uuid === 'string' ? canonicalizeUuid(uuid) : undefined
652
+ if (canonical !== undefined) {
653
+ return canonical
654
+ }
655
+ if (warnIfInvalid) {
656
+ // console.warn, not this._logger: the logger only prints in debug mode, and the event loses its uuid.
657
+ console.warn('[PostHog] Replaced an invalid event uuid with a generated one; uuids must be RFC 4122 strings')
658
+ }
659
+ return eventUuidv7()
660
+ }
661
+
381
662
  /**
382
663
  * Concurrent so a serverless handler waits for one round trip, not two. A
383
664
  * failed span export leaves the spans queued rather than rejecting, since
384
665
  * callers already treat `flush()` as safe to leave unwrapped.
385
666
  */
386
667
  private _flushEventsAndSpans(skipThrottledSpans = false): Promise<void> {
387
- const events = this.flushWithPendingPromises()
668
+ // Pending captures land on their lanes first, so this flush sends them too.
669
+ const events = this.flushWithPendingPromises().then(() => this._flushCaptureLanes())
388
670
  const others: Promise<unknown>[] = []
389
671
  if (this._traces && !(skipThrottledSpans && this._traces.throttled)) {
390
672
  others.push(this._traces.flush().catch(() => {}))
@@ -408,20 +690,53 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
408
690
  })
409
691
  }
410
692
 
411
- protected override flushAutomatic(): Promise<void> {
412
- // The events timer must not drag spans through a `Retry-After` window the
413
- // traces queue is honouring; its own timer picks them up when it closes.
414
- return this._flushKeepingRuntimeAlive(true)
415
- }
416
-
693
+ /**
694
+ * Sends all queued events and spans, and resolves when every send has finished.
695
+ * It does not reject when delivery fails: those failures arrive on the `'error'` event.
696
+ *
697
+ * It has no overall timeout. In an AWS Lambda handler, race it against the time the invocation
698
+ * has left, and keep 100 ms to return. The race limits the wait. It does not cancel the flush.
699
+ *
700
+ * @example
701
+ * ```ts
702
+ * const remainingMs = Math.max(0, context.getRemainingTimeInMillis() - 100)
703
+ * let timer: ReturnType<typeof setTimeout> | undefined
704
+ * try {
705
+ * await Promise.race([
706
+ * client.flush(),
707
+ * new Promise((_, reject) => {
708
+ * timer = setTimeout(() => reject(new Error('PostHog flush timed out')), remainingMs)
709
+ * }),
710
+ * ])
711
+ * } catch (err) {
712
+ * console.error('PostHog flush failed', err)
713
+ * } finally {
714
+ * clearTimeout(timer)
715
+ * }
716
+ * ```
717
+ */
417
718
  override async flush(): Promise<void> {
418
719
  // An app's crash handler often flushes and exits before the end of the turn, when autocapture would capture.
419
720
  this.errorTracking.capturePendingExceptions()
420
- return this._flushKeepingRuntimeAlive(false)
721
+ return this._keepRuntimeAlive(this._flushEventsAndSpans())
722
+ }
723
+
724
+ /** Every lane flushes concurrently, so a slow lane only delays this promise, not the other lanes' sends. */
725
+ private _flushCaptureLanes(): Promise<void> {
726
+ return Promise.all([...this._captureLanes.values()].map((lane) => lane.flush())).then(() => {})
727
+ }
728
+
729
+ /** A flush a lane started on its own, from its timer or `flushAt`. */
730
+ private _onLaneBackgroundFlush(laneFlush: Promise<void>): void {
731
+ // Spans ride along, except while the traces queue is honouring a `Retry-After`
732
+ // window; its own timer picks them up when the window closes.
733
+ const traces = this._traces
734
+ const flush =
735
+ traces && !traces.throttled ? allSettled([laneFlush, traces.flush().catch(() => {})]).then(() => {}) : laneFlush
736
+ void this._keepRuntimeAlive(flush)
421
737
  }
422
738
 
423
- private _flushKeepingRuntimeAlive(skipThrottledSpans: boolean): Promise<void> {
424
- const flushPromise = this._flushEventsAndSpans(skipThrottledSpans)
739
+ private _keepRuntimeAlive(flushPromise: Promise<void>): Promise<void> {
425
740
  const waitUntil = this.options.waitUntil
426
741
  // Only register when no debounce promise is already keeping runtime alive
427
742
  if (waitUntil && !this._waitUntilCycle) {
@@ -592,127 +907,96 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
592
907
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options)
593
908
  }
594
909
 
595
- /**
596
- * Route an event to its queue. In v1 mode `$ai_*` events go to the isolated {@link AI_ROUTE}
597
- * (legacy transport) and everything else to {@link ANALYTICS_ROUTE} (Capture V1); in v0 mode
598
- * every event stays on {@link ANALYTICS_ROUTE}, which maps to the historical queue. Routing runs
599
- * on the post-`before_send`, normalized event name (core calls this after `processBeforeEnqueue`).
600
- */
601
- protected getQueueRouteKey(message: PostHogEventProperties): string {
602
- return this.captureMode === 'v1' && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE
603
- }
604
-
605
- protected persistedQueueKeyForRoute(route: string): PostHogPersistedProperty {
606
- if (route === AI_CAPTURE_ROUTE) {
607
- return PostHogPersistedProperty.AiCaptureQueue
910
+ /** The lane for `route`; `captureAi` events use the AI lane, every other event the analytics lane. */
911
+ private _captureLane(route?: string): CaptureLane {
912
+ const endpoint = route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT : ANALYTICS_CAPTURE_ENDPOINT
913
+ let lane = this._captureLanes.get(endpoint)
914
+ if (!lane) {
915
+ const compressor = this.captureCompressor()
916
+ lane = new CaptureLane(this._captureLaneConfig(endpoint), {
917
+ sender: new V1CaptureSender(this.captureSenderConfig(endpoint, compressor), {
918
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
919
+ onError: (error, summary) => this._reportCaptureLoss([error], summary),
920
+ compress: (payload, codec) => compressor.compress(payload, codec),
921
+ }),
922
+ onLocalDrops: (errors, summary) => this._reportCaptureLoss(errors, summary),
923
+ onError: (error) => this._events.emit('error', error),
924
+ onFlush: (messages) => this._events.emit('flush', messages),
925
+ onBackgroundFlush: (flush) => this._onLaneBackgroundFlush(flush),
926
+ logger: this._logger,
927
+ })
928
+ this._captureLanes.set(endpoint, lane)
608
929
  }
609
- return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue
930
+ return lane
610
931
  }
611
932
 
612
- protected getActiveQueueRoutes(): string[] {
613
- const routes = this.captureMode === 'v1' ? [ANALYTICS_ROUTE, AI_ROUTE] : [ANALYTICS_ROUTE]
614
- if (this._aiCaptureRouteActive) {
615
- routes.push(AI_CAPTURE_ROUTE)
933
+ private _captureLaneConfig(endpoint: CaptureEndpoint): CaptureLaneConfig {
934
+ const isAi = endpoint === AI_CAPTURE_ENDPOINT
935
+ // The AI queue cap bounds memory for large events, so it is kept as set and the AI lane flushes no later than when
936
+ // its queue is full. The analytics queue keeps its floor at flushAt, so the flushAt trigger can always fire.
937
+ const flushAt = isAi ? Math.min(this.flushAt, this._captureSettings.ai.maxQueueSize) : this.flushAt
938
+ return {
939
+ endpoint,
940
+ flushAt,
941
+ flushIntervalMs: this.options.flushInterval ?? 5000,
942
+ maxBatchSize: Math.max(flushAt, this.options.maxBatchSize ?? 100),
943
+ maxQueueSize: isAi
944
+ ? this._captureSettings.ai.maxQueueSize
945
+ : Math.max(this.flushAt, this.options.maxQueueSize ?? 10000),
946
+ targetBatchBytes: CAPTURE_BATCH_TARGET_BYTES,
947
+ maxEventBytes: isAi ? AI_MAX_PROPERTIES_BYTES : ANALYTICS_MAX_EVENT_BYTES,
948
+ maxEventBytesOf: isAi ? 'properties' : 'event',
616
949
  }
617
- return routes
618
- }
619
-
620
- protected getBatchEndpointPath(route: string): string {
621
- return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route)
622
950
  }
623
951
 
624
- /**
625
- * Capture submission seam shared by the batched (`_flush`) and immediate (`sendImmediate`)
626
- * paths. Events are routed to homogeneous per-route queues at enqueue time, so a batch here is
627
- * never mixed: the {@link AI_ROUTE} (and all of v0 mode) uses the legacy `/batch/` transport,
628
- * which throws so `_flush` can shrink/persist/retry its own queue; the {@link ANALYTICS_ROUTE}
629
- * in v1 mode uses the Capture V1 endpoint. Because the routes flush independently, a v0/AI leg
630
- * failure can never re-send analytics events already accepted on the V1 leg.
631
- */
632
- protected async sendBatch(
633
- batchMessages: (PostHogEventProperties | undefined)[],
634
- retryOptions?: Partial<RetriableOptions>,
635
- route: string = ANALYTICS_ROUTE
636
- ): Promise<void> {
637
- if (route === AI_CAPTURE_ROUTE) {
638
- return this.sendAiCaptureBatch(batchMessages, retryOptions)
952
+ /** Emits each error; with no `'error'` listener, logs `summary` once instead, since the events are lost. */
953
+ private _reportCaptureLoss(errors: CaptureError[], summary: string): void {
954
+ const errorListeners = this._events.events['error']?.length ?? 0
955
+ for (const error of errors) {
956
+ this._events.emit('error', error)
639
957
  }
640
-
641
- if (this.captureMode !== 'v1' || route === AI_ROUTE) {
642
- return super.sendBatch(batchMessages, retryOptions, route)
958
+ if (errorListeners === 0) {
959
+ // console.warn, not this._logger: the logger only prints in debug mode.
960
+ console.warn(`[PostHog] ${summary}`)
643
961
  }
644
-
645
- // Analytics route in v1 mode: homogeneous (no `$ai_*`, routed away at enqueue) and never
646
- // undefined for a freshly-enqueued event; drop any legacy undefined queue artifacts.
647
- const v1Events = batchMessages.filter((message): message is PostHogEventProperties => message !== undefined)
648
- await this.getV1Sender().sendV1Batch(v1Events)
649
962
  }
650
963
 
651
- private async sendAiCaptureBatch(
652
- batchMessages: (PostHogEventProperties | undefined)[],
653
- retryOptions?: Partial<RetriableOptions>
654
- ): Promise<void> {
655
- const { batches, dropped } = partitionAiBatch(batchMessages)
656
- for (const { event, bytes } of dropped) {
657
- const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / (1024 * 1024)}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`
658
- this._logger.error(message)
659
- this._events.emit('error', new Error(message))
660
- }
661
- for (const batch of batches) {
662
- await this.sendAiSubBatch(batch, retryOptions)
663
- }
964
+ /**
965
+ * Compresses capture request bodies. The edge build uses CompressionStream; the Node
966
+ * entrypoint overrides this with node:zlib.
967
+ *
968
+ * @internal
969
+ */
970
+ protected captureCompressor(): CaptureCompressor {
971
+ return webCompressor
664
972
  }
665
973
 
666
- // A single-event 413 means the server's cap is below that event's size, so no split can save it.
667
- private async sendAiSubBatch(
668
- batch: PostHogEventProperties[],
669
- retryOptions?: Partial<RetriableOptions>
670
- ): Promise<void> {
671
- try {
672
- await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE)
673
- } catch (err) {
674
- if (!isPostHogFetchContentTooLargeError(err)) {
675
- throw err
676
- }
677
- if (batch.length === 1) {
678
- const [event] = batch
679
- const eventName = typeof event.event === 'string' ? event.event : 'unknown'
680
- const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`
681
- this._logger.error(message)
682
- this._events.emit('error', new Error(message))
683
- return
684
- }
685
- const mid = Math.ceil(batch.length / 2)
686
- await this.sendAiSubBatch(batch.slice(0, mid), retryOptions)
687
- await this.sendAiSubBatch(batch.slice(mid), retryOptions)
974
+ private captureSenderConfig(path: CaptureEndpoint, compressor: CaptureCompressor): V1CaptureSenderConfig {
975
+ const laneSettings = path === AI_CAPTURE_ENDPOINT ? this._captureSettings.ai : this._captureSettings.analytics
976
+ const compression = resolveCaptureCodec(laneSettings.compression, compressor, (fallback) =>
977
+ this._logger.debug(`zstd compression is not available in this runtime; ${path} uses ${fallback} instead`)
978
+ )
979
+ return {
980
+ host: this.host,
981
+ path,
982
+ apiKey: this.apiKey,
983
+ libraryId: this.getLibraryId(),
984
+ libraryVersion: this.getLibraryVersion(),
985
+ userAgent: this.getCustomUserAgent() || undefined,
986
+ historicalMigration: this.historicalMigration,
987
+ compression,
988
+ requestTimeoutMs: laneSettings.requestTimeoutMs,
989
+ maxRetries: this._captureSettings.maxRetries,
990
+ isDebug: this.isDebug,
688
991
  }
689
992
  }
690
993
 
691
- private getV1Sender(): V1CaptureSender {
692
- if (!this._v1Sender) {
693
- this._v1Sender = new V1CaptureSender(
694
- {
695
- host: this.host,
696
- apiKey: this.apiKey,
697
- libraryId: this.getLibraryId(),
698
- libraryVersion: this.getLibraryVersion(),
699
- userAgent: this.getCustomUserAgent() || undefined,
700
- historicalMigration: this.historicalMigration,
701
- compressionEnabled: !this.disableCompression,
702
- requestTimeoutMs: this.requestTimeout,
703
- // Reuse the existing v0 retry knobs: 1 initial attempt + fetchRetryCount retries.
704
- maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
705
- initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
706
- isDebug: this.isDebug,
707
- },
708
- {
709
- fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
710
- onError: (error) => this._events.emit('error', error),
711
- compress: (payload) => this.compressPayload(payload),
712
- }
713
- )
994
+ private warnIfCaptureModeSet(): void {
995
+ const captureMode = typeof process !== 'undefined' ? process.env?.POSTHOG_CAPTURE_MODE : undefined
996
+ if (captureMode !== undefined) {
997
+ // console.warn, not this._logger: the logger only prints in debug mode, which cannot be on yet.
998
+ console.warn('[PostHog] POSTHOG_CAPTURE_MODE is no longer read. Capture always uses capture v1.')
714
999
  }
715
- return this._v1Sender
716
1000
  }
717
1001
 
718
1002
  /**
@@ -1111,38 +1395,100 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1111
1395
  this._loggedFlagsResponseWithoutTypedValues = true
1112
1396
  this._logger.info(FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE)
1113
1397
  }
1114
- return shared.read(body)
1398
+ const normalized = shared.read(body)
1399
+ // Parser failures keep their legacy disabled value; only server failures are unevaluated.
1400
+ if (isPlainObject(normalized.flags)) {
1401
+ for (const [key, detail] of Object.entries(normalized.flags)) {
1402
+ if (isUnreadableFlagRecord(detail)) {
1403
+ normalized.featureFlags[key] = false
1404
+ }
1405
+ }
1406
+ }
1407
+ return normalized
1115
1408
  },
1116
1409
  }
1117
1410
  }
1118
1411
 
1119
1412
  /**
1120
- * Returns the common properties attached to every captured event.
1121
- *
1122
- * @remarks
1123
- * Extends the shared core properties (`$lib`, `$lib_version`) with
1124
- * `$is_server: true` so that events emitted from the server-side SDKs
1125
- * (posthog-node and posthog-edge, which both extend this class) are
1126
- * distinguishable from browser and react-native events. Browser and
1127
- * react-native clients do not extend `PostHogBackendClient`, so they
1128
- * never receive this property.
1129
- *
1130
- * This is controlled by the `isServer` option, which defaults to `true`.
1131
- * When `isServer` is `false` (e.g. when using the SDK as a client/CLI), the
1132
- * `$is_server` property is omitted entirely so the device OS is attributed
1133
- * normally.
1134
- *
1135
- * @returns The common event properties, including `$is_server: true` when
1136
- * the `isServer` option is enabled.
1413
+ * The properties the SDK adds to an event: `$is_server` (unless the `isServer` option is
1414
+ * `false`), `$geoip_disable` (when the `disableGeoip` option is on), feature flag properties,
1415
+ * and for `$exception` events the active OpenTelemetry trace ids and the injected release id.
1416
+ * They fill only the keys every other layer left unset.
1137
1417
  */
1138
- protected override getCommonEventProperties(): PostHogEventProperties {
1139
- const commonProperties = super.getCommonEventProperties()
1140
-
1418
+ private async _sdkEventProperties(
1419
+ event: string,
1420
+ properties: PostHogEventProperties,
1421
+ distinctId: string,
1422
+ flagInputs: Pick<EventMessage, 'groups' | 'flags' | 'sendFeatureFlags' | 'disableGeoip'>
1423
+ ): Promise<PostHogEventProperties> {
1424
+ const sdkProperties: PostHogEventProperties = {
1425
+ ...this._serviceNameProperties(),
1426
+ ...(await this._flagEventProperties(distinctId, flagInputs)),
1427
+ }
1141
1428
  if (this.options.isServer ?? true) {
1142
- commonProperties.$is_server = true
1429
+ sdkProperties.$is_server = true
1430
+ }
1431
+ if (this.options.disableGeoip ?? true) {
1432
+ sdkProperties.$geoip_disable = true
1433
+ }
1434
+ if (event === '$exception') {
1435
+ // Both ids or neither, so a trace id is never paired with another trace's span id.
1436
+ if (isUnsetProperty(properties, '$trace_id') && isUnsetProperty(properties, '$span_id')) {
1437
+ Object.assign(sdkProperties, await getActiveTraceProperties())
1438
+ }
1439
+ const releaseId = CoreErrorTracking.getInjectedReleaseId()
1440
+ if (releaseId) {
1441
+ sdkProperties.$release_id = releaseId
1442
+ }
1443
+ }
1444
+ return sdkProperties
1445
+ }
1446
+
1447
+ /**
1448
+ * `$feature/<key>` and `$active_feature_flags` from a `flags` snapshot or, when there is none,
1449
+ * from `sendFeatureFlags`. Any failure gives no flag properties, and the event is still sent.
1450
+ */
1451
+ private async _flagEventProperties(
1452
+ distinctId: string,
1453
+ {
1454
+ groups,
1455
+ flags,
1456
+ sendFeatureFlags,
1457
+ disableGeoip,
1458
+ }: Pick<EventMessage, 'groups' | 'flags' | 'sendFeatureFlags' | 'disableGeoip'>
1459
+ ): Promise<PostHogEventProperties> {
1460
+ try {
1461
+ // An explicit `flags` snapshot always wins: the event carries the values the code branched
1462
+ // on, with no additional network call.
1463
+ if (flags) {
1464
+ if (sendFeatureFlags) {
1465
+ console.warn(
1466
+ '[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.'
1467
+ )
1468
+ }
1469
+ return flags._getEventProperties()
1470
+ }
1471
+
1472
+ if (sendFeatureFlags) {
1473
+ emitDeprecationWarningOnce(
1474
+ 'sendFeatureFlags',
1475
+ '`sendFeatureFlags` is deprecated and will be removed in a future major version. ' +
1476
+ 'Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a ' +
1477
+ 'second `/flags` request per capture and guarantees the event carries the exact ' +
1478
+ 'flag values your code branched on.'
1479
+ )
1480
+ // If we are sending feature flags, we evaluate them locally if the user prefers it, otherwise we fall back to remote evaluation
1481
+ const sendFeatureFlagsOptions = typeof sendFeatureFlags === 'object' ? sendFeatureFlags : undefined
1482
+ const flagValues = await this.getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions)
1483
+ return buildFlagEventProperties(flagValues)
1484
+ }
1485
+ } catch {
1486
+ return {}
1143
1487
  }
1144
1488
 
1145
- return commonProperties
1489
+ // $feature_flag_called events are not enriched with cached flags — the flags
1490
+ // on that event should reflect the specific call, not a potentially stale snapshot.
1491
+ return {}
1146
1492
  }
1147
1493
 
1148
1494
  /**
@@ -1205,6 +1551,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1205
1551
  this.featureFlagsPoller?.debug(enabled)
1206
1552
  }
1207
1553
 
1554
+ protected describeDebugPayload(payload: unknown): unknown {
1555
+ return summarizeForDebugLog(payload)
1556
+ }
1557
+
1208
1558
  private _warnIfInvalidCapture(
1209
1559
  props: EventMessage,
1210
1560
  stringArgumentWarning: string,
@@ -1225,34 +1575,44 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1225
1575
  prepareOptions?: PrepareEventOptions,
1226
1576
  explicitRoute?: string
1227
1577
  ): Promise<void> {
1578
+ const invalidUuidWarned = isInvalidUuid(props.uuid)
1579
+ const uuid = this._canonicalEventUuid(props.uuid)
1580
+ if (uuid !== props.uuid) {
1581
+ props = { ...props, uuid }
1582
+ }
1228
1583
  return this.addPendingPromise(
1229
1584
  this._prepareEventMessage(props, prepareOptions)
1230
- .then(({ distinctId, event, properties, options }) => {
1585
+ .then(({ distinctId, event, properties, options, uuid, timestamp }) => {
1231
1586
  // The queue drops the event without an error when the client was disabled or opted out
1232
1587
  // while the event was prepared, so a flag event's dedupe key is released here.
1233
1588
  if (this.disabled || this.optedOut) {
1234
1589
  prepareOptions?.onCaptureFailed?.()
1235
1590
  }
1236
- const captureOptions: PostHogCaptureOptions = {
1237
- timestamp: options.timestamp,
1238
- disableGeoip: options.disableGeoip,
1239
- uuid: options.uuid,
1591
+ const captureOptions: LaneCaptureOptions = {
1592
+ timestamp,
1593
+ // `$geoip_disable` is already set before beforeSend; core must not add it after.
1594
+ disableGeoip: false,
1595
+ uuid,
1596
+ _invalidUuidWarned: invalidUuidWarned,
1240
1597
  }
1241
1598
  const message = {
1242
- distinctId,
1599
+ // Set directly, not as `distinctId`: core drops a falsy `distinctId`, which would hide what beforeSend left.
1600
+ distinct_id: distinctId,
1243
1601
  event,
1244
- properties: {
1245
- ...properties,
1246
- ...this.getCommonEventProperties(),
1247
- },
1602
+ properties,
1603
+ ...(options !== undefined ? { options } : {}),
1248
1604
  }
1249
1605
  return immediate
1250
1606
  ? this.sendImmediate(type, message, captureOptions, explicitRoute)
1251
1607
  : this.enqueue(type, message, captureOptions, explicitRoute)
1252
1608
  })
1253
1609
  .catch((err) => {
1254
- // A `before_send` discard rejects with null; it is not a failure.
1255
- if (err) {
1610
+ // A `beforeSend` discard rejects with null; it is not a failure.
1611
+ // Only a caller value that threw is a local drop; anything else is an SDK failure.
1612
+ if (err instanceof UnreadableEventError) {
1613
+ this._dropUnreadableEvent(uuid, immediate, explicitRoute)
1614
+ prepareOptions?.onCaptureFailed?.()
1615
+ } else if (err) {
1256
1616
  console.error(err)
1257
1617
  prepareOptions?.onCaptureFailed?.()
1258
1618
  }
@@ -1260,6 +1620,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1260
1620
  )
1261
1621
  }
1262
1622
 
1623
+ private _dropUnreadableEvent(uuid: string | undefined, immediate: boolean, explicitRoute?: string): void {
1624
+ if (this.disabled || this.optedOut) {
1625
+ return
1626
+ }
1627
+ this._captureLane(explicitRoute).dropUnserializable(uuid, immediate)
1628
+ if (!immediate) {
1629
+ // The next flush reports the drop, so a serverless host must stay alive for it.
1630
+ this.scheduleDebouncedFlush()
1631
+ }
1632
+ }
1633
+
1263
1634
  _capturePreparedEvent(props: EventMessage, immediate: boolean): Promise<void> {
1264
1635
  return this._sendPreparedEvent('capture', props, immediate)
1265
1636
  }
@@ -1359,7 +1730,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1359
1730
  if (this.disabled) {
1360
1731
  return undefined
1361
1732
  }
1362
- const uuid = getEventUuid(props.uuid, uuidv7)
1733
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7()
1363
1734
  void this._sendPreparedAiEvent({ ...props, uuid }, false)
1364
1735
  return uuid
1365
1736
  }
@@ -1378,7 +1749,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1378
1749
  if (this.disabled) {
1379
1750
  return undefined
1380
1751
  }
1381
- const uuid = getEventUuid(props.uuid, uuidv7)
1752
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7()
1382
1753
  await this._sendPreparedAiEvent({ ...props, uuid }, true)
1383
1754
  return uuid
1384
1755
  }
@@ -1387,7 +1758,6 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1387
1758
  if (typeof props?.event === 'string' && !props.event.startsWith('$ai_')) {
1388
1759
  this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`)
1389
1760
  }
1390
- this._aiCaptureRouteActive = true
1391
1761
  return this._sendPreparedEvent('capture', props, immediate, undefined, AI_CAPTURE_ROUTE)
1392
1762
  }
1393
1763
 
@@ -1424,22 +1794,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1424
1794
  *
1425
1795
  * @param data - The identify data containing distinctId and properties
1426
1796
  */
1427
- identify({ distinctId, properties = {}, disableGeoip }: IdentifyMessage): void {
1428
- // Catch properties passed as $set and move them to the top level
1429
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties
1430
- // if no $set is provided we assume all rest properties are $set
1431
- const setProps = $set || rest
1432
- const setOnceProps = $set_once || {}
1433
- const eventProperties = {
1434
- $set: setProps,
1435
- $set_once: setOnceProps,
1436
- $anon_distinct_id: $anon_distinct_id ?? undefined,
1437
- }
1797
+ identify({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): void {
1798
+ const eventProperties = identifyEventProperties(properties)
1438
1799
  this._sendPreparedEvent(
1439
1800
  'identify',
1440
- { distinctId, event: '$identify', properties: eventProperties, disableGeoip },
1441
- false,
1442
- { includeContextProperties: false }
1801
+ { distinctId, event: '$identify', properties: eventProperties, disableGeoip, options },
1802
+ false
1443
1803
  )
1444
1804
  }
1445
1805
 
@@ -1463,22 +1823,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1463
1823
  * @param data - The identify data containing distinctId and properties
1464
1824
  * @returns Promise that resolves when the identify is processed
1465
1825
  */
1466
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }: IdentifyMessage): Promise<void> {
1467
- // Catch properties passed as $set and move them to the top level
1468
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties
1469
- // if no $set is provided we assume all rest properties are $set
1470
- const setProps = $set || rest
1471
- const setOnceProps = $set_once || {}
1472
- const eventProperties = {
1473
- $set: setProps,
1474
- $set_once: setOnceProps,
1475
- $anon_distinct_id: $anon_distinct_id ?? undefined,
1476
- }
1826
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): Promise<void> {
1827
+ const eventProperties = identifyEventProperties(properties)
1477
1828
  await this._sendPreparedEvent(
1478
1829
  'identify',
1479
- { distinctId, event: '$identify', properties: eventProperties, disableGeoip },
1480
- true,
1481
- { includeContextProperties: false }
1830
+ { distinctId, event: '$identify', properties: eventProperties, disableGeoip, options },
1831
+ true
1482
1832
  )
1483
1833
  }
1484
1834
 
@@ -1498,7 +1848,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1498
1848
  *
1499
1849
  * @param data - The data containing distinctId and properties to set
1500
1850
  */
1501
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }: SetPersonPropertiesMessage): void {
1851
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }: SetPersonPropertiesMessage): void {
1502
1852
  if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0) {
1503
1853
  return
1504
1854
  }
@@ -1515,6 +1865,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1515
1865
  distinctId,
1516
1866
  event: '$set',
1517
1867
  properties: eventProperties,
1868
+ options,
1518
1869
  })
1519
1870
  }
1520
1871
 
@@ -1533,13 +1884,13 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1533
1884
  *
1534
1885
  * @param data - The data containing distinctId and property names to unset
1535
1886
  */
1536
- unsetPersonProperties({ distinctId, properties }: UnsetPersonPropertiesMessage): void {
1887
+ unsetPersonProperties({ distinctId, properties, options }: UnsetPersonPropertiesMessage): void {
1537
1888
  const propertyNames = normalizeUnsetPersonProperties(properties)
1538
1889
  if (propertyNames.length === 0) {
1539
1890
  return
1540
1891
  }
1541
1892
 
1542
- this.capture({ distinctId, event: '$set', properties: { $unset: propertyNames } })
1893
+ this.capture({ distinctId, event: '$set', properties: { $unset: propertyNames }, options })
1543
1894
  }
1544
1895
 
1545
1896
  /**
@@ -1558,17 +1909,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1558
1909
  *
1559
1910
  * @param data - The alias data containing distinctId and alias
1560
1911
  */
1561
- alias(data: { distinctId: string; alias: string; disableGeoip?: boolean }): void {
1912
+ alias(data: { distinctId: string; alias: string; disableGeoip?: boolean; options?: EventOptions }): void {
1562
1913
  this._sendPreparedEvent(
1563
1914
  'alias',
1564
1915
  {
1565
1916
  distinctId: data.distinctId,
1566
1917
  event: '$create_alias',
1567
- properties: { distinct_id: data.distinctId, alias: data.alias },
1918
+ properties: { alias: data.alias },
1568
1919
  disableGeoip: data.disableGeoip,
1920
+ options: data.options,
1569
1921
  },
1570
1922
  false,
1571
- { includeContextProperties: false }
1923
+ ALIAS_PREPARE_OPTIONS
1572
1924
  )
1573
1925
  }
1574
1926
 
@@ -1589,17 +1941,23 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1589
1941
  * @param data - The alias data containing distinctId and alias
1590
1942
  * @returns Promise that resolves when the alias is processed
1591
1943
  */
1592
- async aliasImmediate(data: { distinctId: string; alias: string; disableGeoip?: boolean }): Promise<void> {
1944
+ async aliasImmediate(data: {
1945
+ distinctId: string
1946
+ alias: string
1947
+ disableGeoip?: boolean
1948
+ options?: EventOptions
1949
+ }): Promise<void> {
1593
1950
  await this._sendPreparedEvent(
1594
1951
  'alias',
1595
1952
  {
1596
1953
  distinctId: data.distinctId,
1597
1954
  event: '$create_alias',
1598
- properties: { distinct_id: data.distinctId, alias: data.alias },
1955
+ properties: { alias: data.alias },
1599
1956
  disableGeoip: data.disableGeoip,
1957
+ options: data.options,
1600
1958
  },
1601
1959
  true,
1602
- { includeContextProperties: false }
1960
+ ALIAS_PREPARE_OPTIONS
1603
1961
  )
1604
1962
  }
1605
1963
 
@@ -1840,8 +2198,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1840
2198
  let flagVersion: number | undefined = undefined
1841
2199
  let flagReason: string | undefined = undefined
1842
2200
  let flagHasExperiment: boolean | undefined = undefined
1843
- // The parsed /flags record when it supplied the result. Only such a read can carry config
1844
- // version 2 attribution and send $experiment_exposure.
2201
+ // The parsed record supplies the value or failure diagnostics. Only a successful
2202
+ // experiment split sends $experiment_exposure.
1845
2203
  let flagRecord: ParsedFlagRecord | undefined = undefined
1846
2204
 
1847
2205
  // Try local evaluation first
@@ -1920,27 +2278,31 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1920
2278
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code
1921
2279
  flagHasExperiment = flagDetail.metadata?.has_experiment
1922
2280
 
1923
- // Parse payload once from the API response
1924
- let parsedPayload: JsonType | undefined = undefined
1925
- if (flagDetail.metadata?.payload !== undefined) {
1926
- try {
1927
- parsedPayload = JSON.parse(flagDetail.metadata.payload)
1928
- } catch {
1929
- // If parsing fails, return the raw string (matches parsePayload behavior)
1930
- parsedPayload = flagDetail.metadata.payload
2281
+ flagRecord = parsedFlagRecordOf(flagDetail)
2282
+ if (isServerFailedFlagRecord(flagRecord)) {
2283
+ errors.push(FeatureFlagError.EVALUATION_FAILED)
2284
+ } else {
2285
+ // Parse payload once from the API response
2286
+ let parsedPayload: JsonType | undefined = undefined
2287
+ if (flagDetail.metadata?.payload !== undefined) {
2288
+ try {
2289
+ parsedPayload = JSON.parse(flagDetail.metadata.payload)
2290
+ } catch {
2291
+ // If parsing fails, return the raw string (matches parsePayload behavior)
2292
+ parsedPayload = flagDetail.metadata.payload
2293
+ }
1931
2294
  }
1932
- }
1933
2295
 
1934
- result = {
1935
- key,
1936
- enabled: flagDetail.enabled,
1937
- // The flags API serializes missing variants as null
1938
- variant: flagDetail.variant ?? undefined,
1939
- payload: parsedPayload,
1940
- reason: flagReason,
1941
- reasonCode: flagDetail.reason?.code,
2296
+ result = {
2297
+ key,
2298
+ enabled: flagDetail.enabled,
2299
+ // The flags API serializes missing variants as null
2300
+ variant: flagDetail.variant ?? undefined,
2301
+ payload: parsedPayload,
2302
+ reason: flagReason,
2303
+ reasonCode: flagDetail.reason?.code,
2304
+ }
1942
2305
  }
1943
- flagRecord = parsedFlagRecordOf(flagDetail)
1944
2306
  }
1945
2307
 
1946
2308
  if (flagDetail !== undefined && isUnreadableFlagRecord(flagDetail)) {
@@ -2737,8 +3099,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2737
3099
  if (locallyEvaluatedKeys.has(key)) {
2738
3100
  continue
2739
3101
  }
3102
+ const parsed = parsedFlagRecordOf(detail)
2740
3103
  let parsedPayload: JsonType | undefined = undefined
2741
- if (detail.metadata?.payload !== undefined) {
3104
+ if (!isServerFailedFlagRecord(parsed) && detail.metadata?.payload !== undefined) {
2742
3105
  try {
2743
3106
  parsedPayload = JSON.parse(detail.metadata.payload)
2744
3107
  } catch {
@@ -2755,7 +3118,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2755
3118
  reason: detail.reason?.description ?? detail.reason?.code,
2756
3119
  locallyEvaluated: false,
2757
3120
  hasExperiment: detail.metadata?.has_experiment,
2758
- parsed: parsedFlagRecordOf(detail),
3121
+ parsed,
2759
3122
  }
2760
3123
  }
2761
3124
  }
@@ -2804,7 +3167,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2804
3167
  // A flag a remote fallback or override resolved has a value, so it is not unresolved.
2805
3168
  const unresolvedFlags: Record<string, UnresolvedFlagReason> = {}
2806
3169
  for (const [key, reason] of Object.entries(localResult?.unresolved ?? {})) {
2807
- if (!Object.prototype.hasOwnProperty.call(records, key)) {
3170
+ const parsed = records[key]?.parsed
3171
+ if (!Object.prototype.hasOwnProperty.call(records, key) || (parsed && isServerFailedFlagRecord(parsed))) {
2808
3172
  unresolvedFlags[key] = reason
2809
3173
  }
2810
3174
  }
@@ -2934,7 +3298,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2934
3298
  * The key is reserved before capture and stays reserved while capture runs, so a read during
2935
3299
  * capture does not send the event again. It is released when capture fails, so a later read
2936
3300
  * sends the event: the capture call throws, the client is disabled or opted out (also while the
2937
- * event is prepared), `before_send` throws, or the event cannot be prepared or queued. An event that `before_send` discards keeps
3301
+ * event is prepared), `beforeSend` throws, or the event cannot be prepared or queued. An event that `beforeSend` discards keeps
2938
3302
  * its key: the application chose to drop it, and later reads would be dropped the same way.
2939
3303
  * A failure is logged and never reaches the read.
2940
3304
  */
@@ -3041,11 +3405,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3041
3405
  *
3042
3406
  * @param data - The group identify data
3043
3407
  */
3044
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void {
3408
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }: GroupIdentifyMessage): void {
3045
3409
  this._sendPreparedEvent(
3046
3410
  'capture',
3047
3411
  {
3048
- distinctId: distinctId || `$${groupType}_${groupKey}`,
3412
+ distinctId,
3049
3413
  event: '$groupidentify',
3050
3414
  properties: {
3051
3415
  $group_type: groupType,
@@ -3053,9 +3417,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3053
3417
  $group_set: properties || {},
3054
3418
  },
3055
3419
  disableGeoip,
3420
+ options,
3056
3421
  },
3057
3422
  false,
3058
- { includeContextProperties: false }
3423
+ { fallbackDistinctId: `$${groupType}_${groupKey}`, contextSession: false }
3059
3424
  )
3060
3425
  }
3061
3426
 
@@ -3087,11 +3452,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3087
3452
  properties,
3088
3453
  distinctId,
3089
3454
  disableGeoip,
3455
+ options,
3090
3456
  }: GroupIdentifyMessage): Promise<void> {
3091
3457
  await this._sendPreparedEvent(
3092
3458
  'capture',
3093
3459
  {
3094
- distinctId: distinctId || `$${groupType}_${groupKey}`,
3460
+ distinctId,
3095
3461
  event: '$groupidentify',
3096
3462
  properties: {
3097
3463
  $group_type: groupType,
@@ -3099,9 +3465,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3099
3465
  $group_set: properties || {},
3100
3466
  },
3101
3467
  disableGeoip,
3468
+ options,
3102
3469
  },
3103
3470
  true,
3104
- { includeContextProperties: false }
3471
+ { fallbackDistinctId: `$${groupType}_${groupKey}`, contextSession: false }
3105
3472
  )
3106
3473
  }
3107
3474
 
@@ -3240,6 +3607,86 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3240
3607
  return false
3241
3608
  }
3242
3609
 
3610
+ /**
3611
+ * Register properties that every event sent by this client carries.
3612
+ *
3613
+ * @remarks
3614
+ * Each event fills the keys it left unset in this order: the event's own values, then context
3615
+ * properties, then these, then the values the SDK adds (such as `$is_server` and
3616
+ * `$geoip_disable`). `beforeSend` sees the result and can change it.
3617
+ *
3618
+ * A `$process_person_profile` registered here never reaches `$identify`, `$create_alias`,
3619
+ * `$merge_dangerously`, `$groupidentify`, `$set` or `$set_once` events (see `registerOptions()`).
3620
+ *
3621
+ * @example
3622
+ * ```ts
3623
+ * await client.register({ service: 'billing' })
3624
+ * ```
3625
+ *
3626
+ * {@label Capture}
3627
+ *
3628
+ * @param properties - The properties to add to every event
3629
+ */
3630
+ override register(properties: PostHogEventProperties): Promise<void> {
3631
+ return super.register(properties)
3632
+ }
3633
+
3634
+ /**
3635
+ * Remove a property added with `register()`.
3636
+ *
3637
+ * {@label Capture}
3638
+ *
3639
+ * @param property - The property name to remove
3640
+ */
3641
+ override unregister(property: string): Promise<void> {
3642
+ return super.unregister(property)
3643
+ }
3644
+
3645
+ /**
3646
+ * Register options that every event sent by this client carries.
3647
+ *
3648
+ * @remarks
3649
+ * Each event fills the options it left unset (missing or `null`) in this order: the event's own
3650
+ * `options`, then context options, then these, then the options the SDK adds (such as
3651
+ * `process_person_profile: false` for an event with no distinct id). `beforeSend` sees the
3652
+ * result and can change it. Values are sent to capture unchanged. Capture drops an event whose
3653
+ * option value it cannot read, so a bad value registered here drops every event.
3654
+ *
3655
+ * A `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` or `$set_once`
3656
+ * event whose call leaves `process_person_profile` unset gets `true` instead of a value registered
3657
+ * here, unless its distinct id is generated.
3658
+ *
3659
+ * @example
3660
+ * ```ts
3661
+ * await client.registerOptions({ cookieless_mode: true })
3662
+ * ```
3663
+ *
3664
+ * {@label Capture}
3665
+ *
3666
+ * @param options - The options to add to every event
3667
+ */
3668
+ async registerOptions(options: EventOptions): Promise<void> {
3669
+ if (!isPlainObject(options)) {
3670
+ // console.error, not this._logger: the logger only prints in debug mode, and the options are lost.
3671
+ console.error('[PostHog] registerOptions takes an object; ignoring the value')
3672
+ return
3673
+ }
3674
+ this._globalOptions = { ...this._globalOptions, ...options }
3675
+ }
3676
+
3677
+ /**
3678
+ * Remove an option added with `registerOptions()`.
3679
+ *
3680
+ * {@label Capture}
3681
+ *
3682
+ * @param key - The option name to remove
3683
+ */
3684
+ async unregisterOptions(key: string): Promise<void> {
3685
+ const remaining = { ...this._globalOptions }
3686
+ delete remaining[key]
3687
+ this._globalOptions = remaining
3688
+ }
3689
+
3243
3690
  protected abstract initializeContext(): IPostHogContext | undefined
3244
3691
 
3245
3692
  /**
@@ -3248,6 +3695,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3248
3695
  * Context properties like tags and sessionId will be automatically attached to all events.
3249
3696
  * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context.
3250
3697
  *
3698
+ * @remarks
3699
+ * Context `properties` and `options` fill only what an event left unset: the event's own values
3700
+ * win, and context values beat `register()` and `registerOptions()` values and the values the SDK
3701
+ * adds. `beforeSend` sees the result and can change it.
3702
+ *
3703
+ * On `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` and `$set_once`
3704
+ * events, a context `process_person_profile` option applies only when the distinct id is
3705
+ * generated, and a `$process_person_profile` property never applies (see `registerOptions()`).
3706
+ *
3251
3707
  * @example
3252
3708
  * ```ts
3253
3709
  * posthog.withContext({ distinctId: 'user_123' }, () => {
@@ -3257,7 +3713,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3257
3713
  *
3258
3714
  * {@label Context}
3259
3715
  *
3260
- * @param data - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture)
3716
+ * @param data - Context data to apply (sessionId, distinctId, properties, options)
3261
3717
  * @param fn - Function to run with the context
3262
3718
  * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3263
3719
  * @returns The return value of the function
@@ -3298,25 +3754,6 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3298
3754
  return this.context?.get()
3299
3755
  }
3300
3756
 
3301
- /**
3302
- * Set context without a callback wrapper.
3303
- *
3304
- * Uses `AsyncLocalStorage.enterWith()` to attach context to the current
3305
- * async execution context. The context lives until that async context ends.
3306
- *
3307
- * Must be called in the same async scope that makes PostHog calls.
3308
- * Calling this outside a request-scoped async context will leak context
3309
- * across unrelated work. Prefer `withContext()` when you can wrap code
3310
- * in a callback — it creates an isolated scope that cleans up automatically.
3311
- *
3312
- * @param data - Context data to apply (distinctId, sessionId, properties)
3313
- * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3314
- */
3315
- enterContext(data: Partial<ContextData>, options?: ContextOptions): void {
3316
- this.context?.enter(data as ContextData, options)
3317
- notifyContextListeners(this)
3318
- }
3319
-
3320
3757
  /**
3321
3758
  * Shutdown the PostHog client gracefully.
3322
3759
  *
@@ -3409,8 +3846,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3409
3846
  // Wait for the email sends next to the core flush, not before it, so a slow send can't use up the budget for events.
3410
3847
  const emailsSettled = emailsDrained ? raceWithTimeout(emailsDrained, remainingMs) : undefined
3411
3848
  try {
3412
- return await super._shutdown(remainingMs)
3849
+ // The core shutdown waits for pending captures to land on their lanes; the lanes drain meanwhile,
3850
+ // then once more for whatever those captures added.
3851
+ await Promise.all([super._shutdown(remainingMs), this._drainCaptureLanes(shutdownDeadlineMs)])
3852
+ await this._drainCaptureLanes(shutdownDeadlineMs)
3413
3853
  } finally {
3854
+ for (const lane of this._captureLanes.values()) {
3855
+ lane.finishShutdown()
3856
+ }
3414
3857
  await emailsSettled
3415
3858
  await logsDrained
3416
3859
  this._distinctIdHasSentFlagCalls.clear()
@@ -3419,6 +3862,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3419
3862
  }
3420
3863
  }
3421
3864
 
3865
+ private _drainCaptureLanes(deadlineMs: number): Promise<void> {
3866
+ return Promise.all([...this._captureLanes.values()].map((lane) => lane.drain(deadlineMs))).then(() => {})
3867
+ }
3868
+
3422
3869
  private async _requestRemoteConfigPayload(flagKey: string): Promise<PostHogFetchResponse | undefined> {
3423
3870
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) {
3424
3871
  return undefined
@@ -3601,6 +4048,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3601
4048
  /**
3602
4049
  * Capture an error exception as an event.
3603
4050
  *
4051
+ * @remarks
4052
+ * The 5.x positional form `captureException(error, distinctId, properties, uuid, flags)` still
4053
+ * works in 6.x but logs a deprecation error once per process, and will be removed in the next
4054
+ * major version.
4055
+ *
3604
4056
  * @example
3605
4057
  * ```ts
3606
4058
  * // Capture an error with user ID
@@ -3608,20 +4060,20 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3608
4060
  * // Some risky operation
3609
4061
  * riskyOperation()
3610
4062
  * } catch (error) {
3611
- * client.captureException(error, 'user_123')
4063
+ * client.captureException(error, { distinctId: 'user_123' })
3612
4064
  * }
3613
4065
  * ```
3614
4066
  *
3615
4067
  * @example
3616
4068
  * ```ts
3617
- * // Capture with additional properties
4069
+ * // Capture with additional properties and a level
3618
4070
  * try {
3619
4071
  * apiCall()
3620
4072
  * } catch (error) {
3621
- * client.captureException(error, 'user_123', {
3622
- * endpoint: '/api/users',
3623
- * method: 'POST',
3624
- * status_code: 500
4073
+ * client.captureException(error, {
4074
+ * distinctId: 'user_123',
4075
+ * properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
4076
+ * level: 'warning',
3625
4077
  * })
3626
4078
  * }
3627
4079
  * ```
@@ -3629,29 +4081,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3629
4081
  * {@label Error tracking}
3630
4082
  *
3631
4083
  * @param error - The error to capture
3632
- * @param distinctId - Optional user distinct ID
3633
- * @param additionalProperties - Optional additional properties to include
3634
- * @param uuid - Optional event UUID
3635
- * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events
4084
+ * @param options - Optional distinct id, properties, options, uuid, flags snapshot and level
3636
4085
  */
3637
- captureException(
3638
- error: unknown,
3639
- distinctId?: string,
3640
- additionalProperties?: Record<string | number, any>,
3641
- uuid?: EventMessage['uuid'],
3642
- flags?: FeatureFlagEvaluations
3643
- ): void {
4086
+ captureException(error: unknown, options?: CaptureExceptionOptions): void
4087
+ captureException(error: unknown, options?: unknown, ...legacyArgs: unknown[]): void {
4088
+ const exceptionOptions = readCaptureExceptionArgs('captureException', options, legacyArgs, true)
3644
4089
  if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3645
4090
  const syntheticException = new Error('PostHog syntheticException')
3646
4091
  this.addPendingPromise(
3647
- ErrorTracking.buildEventMessage(
3648
- this.getErrorPropertiesBuilder(),
3649
- error,
3650
- { syntheticException },
3651
- distinctId,
3652
- additionalProperties,
3653
- this.getContext()
3654
- ).then((msg) => this._capturePreparedEvent({ ...msg, uuid, flags }, false))
4092
+ this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg) =>
4093
+ this._capturePreparedEvent(msg, false)
4094
+ )
3655
4095
  )
3656
4096
  }
3657
4097
  }
@@ -3659,6 +4099,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3659
4099
  /**
3660
4100
  * Capture an error exception as an event immediately (synchronously).
3661
4101
  *
4102
+ * @remarks
4103
+ * The 5.x positional form `captureExceptionImmediate(error, distinctId, properties, flags)` still
4104
+ * works in 6.x but logs a deprecation error once per process, and will be removed in the next
4105
+ * major version.
4106
+ *
3662
4107
  * @example
3663
4108
  * ```ts
3664
4109
  * // Capture an error immediately with user ID
@@ -3666,7 +4111,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3666
4111
  * // Some risky operation
3667
4112
  * riskyOperation()
3668
4113
  * } catch (error) {
3669
- * await client.captureExceptionImmediate(error, 'user_123')
4114
+ * await client.captureExceptionImmediate(error, { distinctId: 'user_123' })
3670
4115
  * }
3671
4116
  * ```
3672
4117
  *
@@ -3676,10 +4121,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3676
4121
  * try {
3677
4122
  * apiCall()
3678
4123
  * } catch (error) {
3679
- * await client.captureExceptionImmediate(error, 'user_123', {
3680
- * endpoint: '/api/users',
3681
- * method: 'POST',
3682
- * status_code: 500
4124
+ * await client.captureExceptionImmediate(error, {
4125
+ * distinctId: 'user_123',
4126
+ * properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
3683
4127
  * })
3684
4128
  * }
3685
4129
  * ```
@@ -3687,39 +4131,35 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3687
4131
  * {@label Error tracking}
3688
4132
  *
3689
4133
  * @param error - The error to capture
3690
- * @param distinctId - Optional user distinct ID
3691
- * @param additionalProperties - Optional additional properties to include
3692
- * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events
4134
+ * @param options - Optional distinct id, properties, options, uuid, flags snapshot and level
3693
4135
  * @returns Promise that resolves when the error is captured
3694
4136
  */
3695
- async captureExceptionImmediate(
3696
- error: unknown,
3697
- distinctId?: string,
3698
- additionalProperties?: Record<string | number, any>,
3699
- flags?: FeatureFlagEvaluations
3700
- ): Promise<void> {
4137
+ captureExceptionImmediate(error: unknown, options?: CaptureExceptionOptions): Promise<void>
4138
+ async captureExceptionImmediate(error: unknown, options?: unknown, ...legacyArgs: unknown[]): Promise<void> {
4139
+ const exceptionOptions = readCaptureExceptionArgs('captureExceptionImmediate', options, legacyArgs, false)
3701
4140
  if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3702
4141
  const syntheticException = new Error('PostHog syntheticException')
3703
4142
  return this.addPendingPromise(
3704
- ErrorTracking.buildEventMessage(
3705
- this.getErrorPropertiesBuilder(),
3706
- error,
3707
- { syntheticException },
3708
- distinctId,
3709
- additionalProperties,
3710
- this.getContext()
3711
- ).then((msg) => this.captureImmediate({ ...msg, flags }))
4143
+ this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg) => this.captureImmediate(msg))
3712
4144
  )
3713
4145
  }
3714
4146
  }
3715
4147
 
3716
- public async prepareEventMessage(props: EventMessage): Promise<{
3717
- distinctId: string
3718
- event: string
3719
- properties: PostHogEventProperties
3720
- options: PostHogCaptureOptions
3721
- }> {
3722
- return this._prepareEventMessage(props)
4148
+ private async _buildExceptionEvent(
4149
+ error: unknown,
4150
+ syntheticException: Error,
4151
+ { distinctId, properties, options, uuid, flags, level }: CaptureExceptionOptions
4152
+ ): Promise<EventMessage> {
4153
+ const msg = await ErrorTracking.buildEventMessage(
4154
+ this.getErrorPropertiesBuilder(),
4155
+ error,
4156
+ { syntheticException },
4157
+ distinctId,
4158
+ properties,
4159
+ level,
4160
+ this.getContext()
4161
+ )
4162
+ return { ...msg, options, uuid, flags }
3723
4163
  }
3724
4164
 
3725
4165
  /**
@@ -3749,15 +4189,43 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3749
4189
  return this._serviceName
3750
4190
  }
3751
4191
 
4192
+ /**
4193
+ * Build an event as `capture()` would send it, without sending it.
4194
+ *
4195
+ * @remarks
4196
+ * The result has the same shape as the message passed in: `options` holds the event's options
4197
+ * after every layer filled them, and `uuid`, `timestamp` and `disableGeoip` are top-level fields.
4198
+ * Rejects with `null` when `beforeSend` drops the event.
4199
+ *
4200
+ * @example
4201
+ * ```ts
4202
+ * const message = await client.prepareEventMessage({ distinctId: 'user_123', event: 'button_clicked' })
4203
+ * console.log(message.properties.$is_server, message.options)
4204
+ * ```
4205
+ *
4206
+ * {@label Capture}
4207
+ *
4208
+ * @param props - The event to build
4209
+ * @returns The event with its properties and options filled, after `beforeSend`
4210
+ */
4211
+ public async prepareEventMessage(props: EventMessage): Promise<PreparedEventMessage> {
4212
+ try {
4213
+ return await this._prepareEventMessage(props)
4214
+ } catch (error) {
4215
+ throw error instanceof UnreadableEventError ? error.original : error
4216
+ }
4217
+ }
4218
+
4219
+ /**
4220
+ * Build an event in the canonical order: identity, the call's own values, then the values it left
4221
+ * unset from context, then `register()` / `registerOptions()`, then the SDK, then the SDK's own
4222
+ * `$lib` / `$lib_version`, then the minimal `$feature_flag_called` allowlist, then `beforeSend`,
4223
+ * which has the final say.
4224
+ */
3752
4225
  private async _prepareEventMessage(
3753
4226
  props: EventMessage,
3754
- options: PrepareEventOptions = {}
3755
- ): Promise<{
3756
- distinctId: string
3757
- event: string
3758
- properties: PostHogEventProperties
3759
- options: PostHogCaptureOptions
3760
- }> {
4227
+ prepareOptions: PrepareEventOptions = {}
4228
+ ): Promise<PreparedEventMessage> {
3761
4229
  const {
3762
4230
  distinctId,
3763
4231
  event,
@@ -3769,55 +4237,93 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3769
4237
  disableGeoip,
3770
4238
  uuid,
3771
4239
  }: EventMessage = props
4240
+ const callOptions = readEventOptions(props.options)
3772
4241
 
4242
+ // Read every layer now, before the first await, so later changes never reach this event.
3773
4243
  const contextData = getEventContext(props, this.context?.get())
3774
- const includeContextProperties = options.includeContextProperties ?? true
3775
-
3776
- let mergedDistinctId = distinctId || contextData?.distinctId
3777
-
3778
- const mergedProperties = includeContextProperties
3779
- ? {
3780
- ...this._serviceNameProperties(),
3781
- ...this.props,
3782
- ...(contextData?.properties || {}),
3783
- ...(properties || {}),
3784
- }
3785
- : { ...this._serviceNameProperties(), ...(properties || {}) }
3786
-
3787
- if (event === '$exception' && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) {
3788
- Object.assign(mergedProperties, await getActiveTraceProperties())
4244
+ const contextProperties = snapshotLayer(contextData?.properties)
4245
+ const contextOptions = snapshotLayer(contextData?.options)
4246
+ const globalProperties = snapshotLayer(this.props)
4247
+ const globalOptions = this._globalOptions
4248
+ // A relabel after capture(), such as `@posthog/mcp`'s `instrument()`, does not reach this event.
4249
+ // captureException() gets here only after building its event, so a relabel in between does.
4250
+ const libraryId = this.getLibraryId()
4251
+ const libraryVersion = this.getLibraryVersion()
4252
+
4253
+ const resolvedDistinctId =
4254
+ presentDistinctId(distinctId) ?? presentDistinctId(contextData?.distinctId) ?? prepareOptions.fallbackDistinctId
4255
+ const eventDistinctId = resolvedDistinctId ?? eventUuidv7()
4256
+
4257
+ const eventProperties: PostHogEventProperties = readCallerValues(() => ({ ...(properties || {}) }))
4258
+ // Read before any layer fills properties, so only the caller's own value counts.
4259
+ const callerPersonProfile = eventProperties[EVENT_OPTION_LEGACY_PROPERTIES.process_person_profile]
4260
+ if (prepareOptions.distinctIdProperty) {
4261
+ eventProperties.distinct_id = eventDistinctId
3789
4262
  }
3790
-
3791
- if (!mergedDistinctId) {
3792
- mergedDistinctId = uuidv7()
3793
- mergedProperties.$process_person_profile = false
4263
+ if (
4264
+ (prepareOptions.contextSession ?? true) &&
4265
+ contextData?.sessionId &&
4266
+ isUnsetProperty(eventProperties, '$session_id')
4267
+ ) {
4268
+ eventProperties.$session_id = contextData.sessionId
3794
4269
  }
3795
-
3796
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) {
3797
- mergedProperties.$session_id = contextData.sessionId
4270
+ if (isPlainObject(groups) && Object.keys(groups).length > 0) {
4271
+ const existingGroups = eventProperties.$groups
4272
+ eventProperties.$groups = isMergeableObject(existingGroups) ? { ...existingGroups, ...groups } : { ...groups }
4273
+ }
4274
+ if (disableGeoip !== undefined && disableGeoip !== null) {
4275
+ fillProperties(eventProperties, [{ $geoip_disable: disableGeoip }])
3798
4276
  }
3799
4277
 
3800
- // A config version 2 flag event fixes its attribution after super and context properties are
3801
- // merged, so neither can change it or add a field the event never carries.
3802
- const flagEvent = options.flagEvent
3803
- const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties
3804
-
3805
- // Minimal $feature_flag_called events: rebuild from the strict allowlist before before_send
3806
- // runs, so a customer hook may deliberately re-add stripped properties. Everything the SDK
3807
- // itself adds after this point ($groups, $lib/$lib_version/$is_server, $geoip_disable) is
3808
- // allowlisted — no SDK enrichment may reintroduce stripped properties. A config version 2
3809
- // event also keeps its attribution.
4278
+ fillProperties(eventProperties, [contextProperties, globalProperties], prepareOptions.callOnlyProperties)
4279
+ fillProperties(eventProperties, [
4280
+ await this._sdkEventProperties(event, eventProperties, eventDistinctId, {
4281
+ groups,
4282
+ flags,
4283
+ sendFeatureFlags,
4284
+ disableGeoip,
4285
+ }),
4286
+ ])
4287
+ fillLibraryProperties(eventProperties, libraryId, libraryVersion)
4288
+
4289
+ const filledOptions: Record<string, JsonType> = { ...callOptions }
4290
+ fillIdentifyStylePersonProfile(event, filledOptions, callerPersonProfile, resolvedDistinctId !== undefined)
4291
+ fillOptions(filledOptions, [
4292
+ contextOptions,
4293
+ globalOptions,
4294
+ resolvedDistinctId !== undefined ? undefined : { process_person_profile: false },
4295
+ ])
4296
+ dropIdentifyStyleLegacyPersonProfile(event, filledOptions, eventProperties)
4297
+ const eventOptions = callOptions !== undefined || Object.keys(filledOptions).length > 0 ? filledOptions : undefined
4298
+
4299
+ // A config version 2 flag event fixes its attribution after every layer is filled, so no layer
4300
+ // can change it or add a field the event never carries.
4301
+ const flagEvent = prepareOptions.flagEvent
4302
+ const enrichedProperties = flagEvent ? applyFlagEventCapture(eventProperties, flagEvent) : eventProperties
4303
+
4304
+ // Runs after every fill and before beforeSend, so no default can re-add a stripped property
4305
+ // but a hook still can. A config version 2 event also keeps its attribution.
3810
4306
  const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties)
3811
4307
  ? flagEvent
3812
- ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties)
3813
- : minimizeFlagCalledEventProperties(enrichedProperties)
4308
+ ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES)
4309
+ : minimizeFlagCalledEventProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES)
3814
4310
  : enrichedProperties
3815
4311
 
3816
- // Run before_send if configured
4312
+ let finalEvent = event
4313
+ if (
4314
+ event === '$pageview' &&
4315
+ this.options.__previewCaptureBotPageviews &&
4316
+ typeof finalProperties.$raw_user_agent === 'string' &&
4317
+ isBlockedUA(finalProperties.$raw_user_agent, this.options.customBlockedUserAgents || [])
4318
+ ) {
4319
+ finalEvent = '$bot_pageview'
4320
+ finalProperties.$browser_type = 'bot'
4321
+ }
4322
+
3817
4323
  const eventMessage = this._runBeforeSend(
3818
4324
  {
3819
- distinctId: mergedDistinctId,
3820
- event,
4325
+ distinctId: eventDistinctId,
4326
+ event: finalEvent,
3821
4327
  properties: finalProperties,
3822
4328
  groups,
3823
4329
  flags,
@@ -3825,106 +4331,36 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3825
4331
  timestamp,
3826
4332
  disableGeoip,
3827
4333
  uuid,
4334
+ options: eventOptions,
3828
4335
  },
3829
- options.onCaptureFailed
4336
+ prepareOptions.onCaptureFailed
3830
4337
  )
3831
4338
 
3832
4339
  if (!eventMessage) {
3833
4340
  return Promise.reject(null)
3834
4341
  }
3835
4342
 
3836
- // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush
3837
- const eventProperties = await Promise.resolve()
3838
- .then(async () => {
3839
- // Precedence: an explicit `flags` snapshot always wins, regardless of
3840
- // `sendFeatureFlags`. The snapshot guarantees the event carries the same
3841
- // values the developer branched on with no additional network call. The
3842
- // `sendFeatureFlags` path only runs when no snapshot is provided.
3843
- if (flags) {
3844
- if (sendFeatureFlags) {
3845
- console.warn(
3846
- '[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.'
3847
- )
3848
- }
3849
- return flags._getEventProperties()
3850
- }
3851
-
3852
- if (sendFeatureFlags) {
3853
- emitDeprecationWarningOnce(
3854
- 'sendFeatureFlags',
3855
- '`sendFeatureFlags` is deprecated and will be removed in a future major version. ' +
3856
- 'Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a ' +
3857
- 'second `/flags` request per capture and guarantees the event carries the exact ' +
3858
- 'flag values your code branched on.'
3859
- )
3860
- // If we are sending feature flags, we evaluate them locally if the user prefers it, otherwise we fall back to remote evaluation
3861
- const sendFeatureFlagsOptions = typeof sendFeatureFlags === 'object' ? sendFeatureFlags : undefined
3862
- const flagValues = await this.getFeatureFlagsForEvent(
3863
- eventMessage.distinctId!,
3864
- groups,
3865
- disableGeoip,
3866
- sendFeatureFlagsOptions
3867
- )
3868
- return buildFlagEventProperties(flagValues)
3869
- }
3870
-
3871
- // $feature_flag_called events are not enriched with cached flags — the flags
3872
- // on that event should reflect the specific call, not a potentially stale snapshot.
3873
- return {}
3874
- })
3875
- .catch(() => {
3876
- // Something went wrong getting the flag info - we should capture the event anyways
3877
- return {}
3878
- })
3879
- .then((additionalProperties): PostHogEventProperties => {
3880
- // No matter what - capture the event
3881
- const resolvedGroups = eventMessage.groups || groups
3882
-
3883
- return {
3884
- ...additionalProperties,
3885
- ...(eventMessage.properties || {}),
3886
- // Only stamp $groups from the top-level `groups` when present — otherwise a
3887
- // caller-provided properties.$groups would be clobbered with undefined (#3888).
3888
- ...(resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0
3889
- ? { $groups: resolvedGroups }
3890
- : {}),
3891
- }
3892
- })
3893
-
3894
- // Handle bot pageview collection based on preview flag
3895
- if (
3896
- eventMessage.event === '$pageview' &&
3897
- this.options.__preview_capture_bot_pageviews &&
3898
- typeof eventProperties.$raw_user_agent === 'string'
3899
- ) {
3900
- if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
3901
- eventMessage.event = '$bot_pageview'
3902
- eventProperties.$browser_type = 'bot'
3903
- }
3904
- }
3905
-
3906
4343
  return {
3907
4344
  distinctId: eventMessage.distinctId!,
3908
4345
  event: eventMessage.event,
3909
- properties: eventProperties,
3910
- options: {
3911
- timestamp: eventMessage.timestamp,
3912
- disableGeoip: eventMessage.disableGeoip,
3913
- uuid: eventMessage.uuid,
3914
- },
4346
+ properties: eventMessage.properties || {},
4347
+ options: eventMessage.options,
4348
+ uuid: eventMessage.uuid,
4349
+ timestamp: eventMessage.timestamp,
4350
+ disableGeoip: eventMessage.disableGeoip,
3915
4351
  }
3916
4352
  }
3917
4353
 
3918
4354
  // `onError` is called when a hook throws. A hook that returns null discards the event, which
3919
4355
  // is not an error.
3920
4356
  private _runBeforeSend(eventMessage: EventMessage, onError?: () => void): EventMessage | null {
3921
- const beforeSend = this.options.before_send
4357
+ const beforeSend = this.options.beforeSend
3922
4358
  if (!beforeSend) {
3923
4359
  return eventMessage
3924
4360
  }
3925
4361
 
3926
4362
  const fns = Array.isArray(beforeSend) ? beforeSend : [beforeSend]
3927
- let result: EventMessage | null = eventMessage
4363
+ let result: EventMessage | null = readCallerValues(() => isolateForBeforeSend(eventMessage))
3928
4364
 
3929
4365
  for (const fn of fns) {
3930
4366
  try {
@@ -3938,7 +4374,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3938
4374
  this._logger.warn(message)
3939
4375
  }
3940
4376
  } catch (error) {
3941
- this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error)
4377
+ // The error's message can carry the data the hook was redacting, so only its type is logged.
4378
+ const errorType = error instanceof Error ? error.name : typeof error
4379
+ // console.error, not this._logger: the logger only prints in debug mode, and the event is lost.
4380
+ console.error(`[PostHog] Error in beforeSend function for event '${eventMessage.event}' (${errorType})`)
3942
4381
  onError?.()
3943
4382
  return null
3944
4383
  }