posthog-node 5.74.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) 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 +203 -96
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +456 -228
  50. package/dist/client.mjs +455 -227
  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/flag-events.d.ts +1 -1
  95. package/dist/flag-events.d.ts.map +1 -1
  96. package/dist/flag-events.js +2 -2
  97. package/dist/flag-events.mjs +2 -2
  98. package/dist/types.d.ts +191 -27
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/version.d.ts +1 -1
  101. package/dist/version.d.ts.map +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/version.mjs +1 -1
  104. package/package.json +3 -2
  105. package/src/ai-capture/routing.ts +0 -6
  106. package/src/capture-lane/lane.ts +414 -0
  107. package/src/capture-lane/limits.ts +8 -0
  108. package/src/capture-lane/settings.ts +119 -0
  109. package/src/capture-v1/compression.ts +50 -0
  110. package/src/capture-v1/errors.ts +50 -11
  111. package/src/capture-v1/sender.ts +405 -111
  112. package/src/capture-v1/serialize.ts +77 -0
  113. package/src/capture-v1/transform.ts +59 -92
  114. package/src/capture-v1/types.ts +19 -15
  115. package/src/capture-v1/uuid.ts +53 -0
  116. package/src/client.ts +847 -424
  117. package/src/compression.node.ts +30 -0
  118. package/src/entrypoints/index.node.ts +6 -0
  119. package/src/event-defaults.ts +177 -0
  120. package/src/exports.ts +3 -0
  121. package/src/extensions/context/context.ts +4 -4
  122. package/src/extensions/context/event-context.ts +3 -1
  123. package/src/extensions/context/types.ts +10 -1
  124. package/src/extensions/error-tracking/index.ts +51 -7
  125. package/src/extensions/express.ts +12 -3
  126. package/src/extensions/fetch-request.ts +7 -3
  127. package/src/extensions/nestjs.ts +9 -5
  128. package/src/extensions/tracing-headers.ts +26 -7
  129. package/src/flag-events.ts +5 -2
  130. package/src/types.ts +211 -44
  131. package/src/version.ts +1 -1
  132. package/dist/ai-capture/batching.d.ts +0 -11
  133. package/dist/ai-capture/batching.d.ts.map +0 -1
  134. package/dist/ai-capture/batching.js +0 -77
  135. package/dist/ai-capture/batching.mjs +0 -36
  136. package/dist/capture-v1/config.d.ts +0 -11
  137. package/dist/capture-v1/config.d.ts.map +0 -1
  138. package/dist/capture-v1/config.mjs +0 -8
  139. package/dist/capture-v1/routing.d.ts +0 -21
  140. package/dist/capture-v1/routing.d.ts.map +0 -1
  141. package/dist/capture-v1/routing.mjs +0 -7
  142. package/src/ai-capture/batching.ts +0 -47
  143. package/src/capture-v1/config.ts +0 -18
  144. 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,
@@ -92,13 +93,28 @@ import ErrorTracking from './extensions/error-tracking'
92
93
  import { getActiveTraceProperties } from './extensions/error-tracking/trace-context'
93
94
  import { PostHogMemoryStorage } from './storage-memory'
94
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'
95
116
  import { notifyContextListeners } from './extensions/context/listeners'
96
117
  import { getEventContext } from './extensions/context/event-context'
97
- import { type CaptureMode, resolveCaptureMode } from './capture-v1/config'
98
- import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from './capture-v1/routing'
99
- import { V1CaptureSender } from './capture-v1/sender'
100
- import { eventByteSize, partitionAiBatch } from './ai-capture/batching'
101
- import { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from './ai-capture/routing'
102
118
  import { DEFAULT_EMAIL_REQUEST_MAX_RETRIES, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS, EmailSender } from './emails/emails'
103
119
  import type { Emails } from './emails/types'
104
120
  import { resolveNodeLogsConfig } from './logs-config'
@@ -113,28 +129,16 @@ const WAITUNTIL_DEBOUNCE_MS = 50
113
129
  const WAITUNTIL_MAX_WAIT_MS = 500
114
130
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com'
115
131
 
116
- // Internal options of one event's trip through the capture pipeline.
117
- type PrepareEventOptions = {
118
- includeContextProperties?: boolean
119
- /** How a config version 2 flag event fixes its properties; see `flag-events.ts`. */
120
- flagEvent?: FlagEventCapture
121
- /**
122
- * Called when capture fails: `before_send` throws, or the event cannot be prepared or queued.
123
- * Not called when `before_send` discards the event.
124
- */
125
- onCaptureFailed?: () => void
126
- }
127
-
128
132
  // Process-wide dedup for deprecation warnings — without this, calling a deprecated
129
133
  // method in a loop would spam logs. Matches Python's `warnings.warn` default-dedup behavior.
130
134
  const _emittedDeprecations = new Set<string>()
131
135
 
132
- function emitDeprecationWarningOnce(id: string, message: string): void {
136
+ function emitDeprecationWarningOnce(id: string, message: string, log: (message: string) => void = console.warn): void {
133
137
  if (_emittedDeprecations.has(id)) {
134
138
  return
135
139
  }
136
140
  _emittedDeprecations.add(id)
137
- console.warn(`[PostHog] ${message}`)
141
+ log(`[PostHog] ${message}`)
138
142
  }
139
143
 
140
144
  /**
@@ -148,16 +152,210 @@ function normalizeApiKey(value?: unknown): string {
148
152
  return typeof value === 'string' ? value.trim() : ''
149
153
  }
150
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
+
151
181
  function normalizePersonalApiKey(value?: unknown): string | undefined {
152
182
  const normalizedValue = typeof value === 'string' ? value.trim() : ''
153
183
  return normalizedValue || undefined
154
184
  }
155
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
+
156
197
  function normalizeHost(value?: unknown): string {
157
198
  const normalizedValue = typeof value === 'string' ? value.trim() : ''
158
199
  return normalizedValue || DEFAULT_NODE_HOST
159
200
  }
160
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
+
161
359
  function positiveNumberOr(value: unknown, fallback: number): number {
162
360
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
163
361
  }
@@ -211,15 +409,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
211
409
  private _serviceName?: string | null
212
410
  private _spanContext?: SpanContextManager
213
411
 
214
- private readonly captureMode: CaptureMode
215
- 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
216
415
  private _emails?: EmailSender
217
416
  private _isShutdown = false
218
417
  /** Whether this client captures full AI content: see `enableFullAiCapture` in `PostHogOptions`. */
219
418
  public readonly enableFullAiCapture: boolean
220
419
  /** Whether PostHog AI integrations redact content: see `privacyMode` in `PostHogOptions`. */
221
420
  public readonly privacyMode: boolean
222
- 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> = {}
223
424
 
224
425
  // Feature flag overrides for local testing/development
225
426
  private _flagOverrides?: Record<string, FeatureFlagValue>
@@ -295,8 +496,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
295
496
  */
296
497
  constructor(apiKey: string, options: PostHogOptions = {}) {
297
498
  const normalizedApiKey = normalizeApiKey(apiKey)
499
+ const keyProblem = apiKeyProblem(normalizedApiKey)
298
500
  const normalizedOptions = {
299
501
  ...options,
502
+ disabled: options.disabled || keyProblem !== undefined,
300
503
  // Node's default is higher than the shared core default (1000) because backend
301
504
  // workloads are more likely to burst-enqueue synchronously ahead of a flush.
302
505
  // Applied after the spread with a nullish fallback so a wrapper forwarding
@@ -310,7 +513,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
310
513
  super(normalizedApiKey, normalizedOptions)
311
514
 
312
515
  this.options = normalizedOptions
313
- 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
+ )
314
525
  this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true
315
526
  this.privacyMode = normalizedOptions.privacyMode === true
316
527
  this.context = this.initializeContext()
@@ -369,23 +580,93 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
369
580
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE
370
581
  }
371
582
 
583
+ /** Queues the event on its capture lane instead of the core queue. */
372
584
  protected override enqueue(
373
585
  type: string,
374
586
  message: any,
375
587
  options?: PostHogCaptureOptions,
376
588
  explicitRoute?: string
377
589
  ): void {
378
- 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
+ })
379
602
  this.scheduleDebouncedFlush()
380
603
  }
381
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
+
382
662
  /**
383
663
  * Concurrent so a serverless handler waits for one round trip, not two. A
384
664
  * failed span export leaves the spans queued rather than rejecting, since
385
665
  * callers already treat `flush()` as safe to leave unwrapped.
386
666
  */
387
667
  private _flushEventsAndSpans(skipThrottledSpans = false): Promise<void> {
388
- 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())
389
670
  const others: Promise<unknown>[] = []
390
671
  if (this._traces && !(skipThrottledSpans && this._traces.throttled)) {
391
672
  others.push(this._traces.flush().catch(() => {}))
@@ -409,20 +690,53 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
409
690
  })
410
691
  }
411
692
 
412
- protected override flushAutomatic(): Promise<void> {
413
- // The events timer must not drag spans through a `Retry-After` window the
414
- // traces queue is honouring; its own timer picks them up when it closes.
415
- return this._flushKeepingRuntimeAlive(true)
416
- }
417
-
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
+ */
418
718
  override async flush(): Promise<void> {
419
719
  // An app's crash handler often flushes and exits before the end of the turn, when autocapture would capture.
420
720
  this.errorTracking.capturePendingExceptions()
421
- 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)
422
737
  }
423
738
 
424
- private _flushKeepingRuntimeAlive(skipThrottledSpans: boolean): Promise<void> {
425
- const flushPromise = this._flushEventsAndSpans(skipThrottledSpans)
739
+ private _keepRuntimeAlive(flushPromise: Promise<void>): Promise<void> {
426
740
  const waitUntil = this.options.waitUntil
427
741
  // Only register when no debounce promise is already keeping runtime alive
428
742
  if (waitUntil && !this._waitUntilCycle) {
@@ -593,127 +907,96 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
593
907
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options)
594
908
  }
595
909
 
596
- /**
597
- * Route an event to its queue. In v1 mode `$ai_*` events go to the isolated {@link AI_ROUTE}
598
- * (legacy transport) and everything else to {@link ANALYTICS_ROUTE} (Capture V1); in v0 mode
599
- * every event stays on {@link ANALYTICS_ROUTE}, which maps to the historical queue. Routing runs
600
- * on the post-`before_send`, normalized event name (core calls this after `processBeforeEnqueue`).
601
- */
602
- protected getQueueRouteKey(message: PostHogEventProperties): string {
603
- return this.captureMode === 'v1' && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE
604
- }
605
-
606
- protected persistedQueueKeyForRoute(route: string): PostHogPersistedProperty {
607
- if (route === AI_CAPTURE_ROUTE) {
608
- 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)
609
929
  }
610
- return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue
930
+ return lane
611
931
  }
612
932
 
613
- protected getActiveQueueRoutes(): string[] {
614
- const routes = this.captureMode === 'v1' ? [ANALYTICS_ROUTE, AI_ROUTE] : [ANALYTICS_ROUTE]
615
- if (this._aiCaptureRouteActive) {
616
- 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',
617
949
  }
618
- return routes
619
- }
620
-
621
- protected getBatchEndpointPath(route: string): string {
622
- return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route)
623
950
  }
624
951
 
625
- /**
626
- * Capture submission seam shared by the batched (`_flush`) and immediate (`sendImmediate`)
627
- * paths. Events are routed to homogeneous per-route queues at enqueue time, so a batch here is
628
- * never mixed: the {@link AI_ROUTE} (and all of v0 mode) uses the legacy `/batch/` transport,
629
- * which throws so `_flush` can shrink/persist/retry its own queue; the {@link ANALYTICS_ROUTE}
630
- * in v1 mode uses the Capture V1 endpoint. Because the routes flush independently, a v0/AI leg
631
- * failure can never re-send analytics events already accepted on the V1 leg.
632
- */
633
- protected async sendBatch(
634
- batchMessages: (PostHogEventProperties | undefined)[],
635
- retryOptions?: Partial<RetriableOptions>,
636
- route: string = ANALYTICS_ROUTE
637
- ): Promise<void> {
638
- if (route === AI_CAPTURE_ROUTE) {
639
- 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)
640
957
  }
641
-
642
- if (this.captureMode !== 'v1' || route === AI_ROUTE) {
643
- 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}`)
644
961
  }
645
-
646
- // Analytics route in v1 mode: homogeneous (no `$ai_*`, routed away at enqueue) and never
647
- // undefined for a freshly-enqueued event; drop any legacy undefined queue artifacts.
648
- const v1Events = batchMessages.filter((message): message is PostHogEventProperties => message !== undefined)
649
- await this.getV1Sender().sendV1Batch(v1Events)
650
962
  }
651
963
 
652
- private async sendAiCaptureBatch(
653
- batchMessages: (PostHogEventProperties | undefined)[],
654
- retryOptions?: Partial<RetriableOptions>
655
- ): Promise<void> {
656
- const { batches, dropped } = partitionAiBatch(batchMessages)
657
- for (const { event, bytes } of dropped) {
658
- const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / (1024 * 1024)}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`
659
- this._logger.error(message)
660
- this._events.emit('error', new Error(message))
661
- }
662
- for (const batch of batches) {
663
- await this.sendAiSubBatch(batch, retryOptions)
664
- }
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
665
972
  }
666
973
 
667
- // A single-event 413 means the server's cap is below that event's size, so no split can save it.
668
- private async sendAiSubBatch(
669
- batch: PostHogEventProperties[],
670
- retryOptions?: Partial<RetriableOptions>
671
- ): Promise<void> {
672
- try {
673
- await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE)
674
- } catch (err) {
675
- if (!isPostHogFetchContentTooLargeError(err)) {
676
- throw err
677
- }
678
- if (batch.length === 1) {
679
- const [event] = batch
680
- const eventName = typeof event.event === 'string' ? event.event : 'unknown'
681
- const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`
682
- this._logger.error(message)
683
- this._events.emit('error', new Error(message))
684
- return
685
- }
686
- const mid = Math.ceil(batch.length / 2)
687
- await this.sendAiSubBatch(batch.slice(0, mid), retryOptions)
688
- 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,
689
991
  }
690
992
  }
691
993
 
692
- private getV1Sender(): V1CaptureSender {
693
- if (!this._v1Sender) {
694
- this._v1Sender = new V1CaptureSender(
695
- {
696
- host: this.host,
697
- apiKey: this.apiKey,
698
- libraryId: this.getLibraryId(),
699
- libraryVersion: this.getLibraryVersion(),
700
- userAgent: this.getCustomUserAgent() || undefined,
701
- historicalMigration: this.historicalMigration,
702
- compressionEnabled: !this.disableCompression,
703
- requestTimeoutMs: this.requestTimeout,
704
- // Reuse the existing v0 retry knobs: 1 initial attempt + fetchRetryCount retries.
705
- maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
706
- initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
707
- isDebug: this.isDebug,
708
- },
709
- {
710
- fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
711
- onError: (error) => this._events.emit('error', error),
712
- compress: (payload) => this.compressPayload(payload),
713
- }
714
- )
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.')
715
999
  }
716
- return this._v1Sender
717
1000
  }
718
1001
 
719
1002
  /**
@@ -1127,32 +1410,85 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1127
1410
  }
1128
1411
 
1129
1412
  /**
1130
- * Returns the common properties attached to every captured event.
1131
- *
1132
- * @remarks
1133
- * Extends the shared core properties (`$lib`, `$lib_version`) with
1134
- * `$is_server: true` so that events emitted from the server-side SDKs
1135
- * (posthog-node and posthog-edge, which both extend this class) are
1136
- * distinguishable from browser and react-native events. Browser and
1137
- * react-native clients do not extend `PostHogBackendClient`, so they
1138
- * never receive this property.
1139
- *
1140
- * This is controlled by the `isServer` option, which defaults to `true`.
1141
- * When `isServer` is `false` (e.g. when using the SDK as a client/CLI), the
1142
- * `$is_server` property is omitted entirely so the device OS is attributed
1143
- * normally.
1144
- *
1145
- * @returns The common event properties, including `$is_server: true` when
1146
- * 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.
1147
1417
  */
1148
- protected override getCommonEventProperties(): PostHogEventProperties {
1149
- const commonProperties = super.getCommonEventProperties()
1150
-
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
+ }
1151
1428
  if (this.options.isServer ?? true) {
1152
- 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 {}
1153
1487
  }
1154
1488
 
1155
- 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 {}
1156
1492
  }
1157
1493
 
1158
1494
  /**
@@ -1215,6 +1551,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1215
1551
  this.featureFlagsPoller?.debug(enabled)
1216
1552
  }
1217
1553
 
1554
+ protected describeDebugPayload(payload: unknown): unknown {
1555
+ return summarizeForDebugLog(payload)
1556
+ }
1557
+
1218
1558
  private _warnIfInvalidCapture(
1219
1559
  props: EventMessage,
1220
1560
  stringArgumentWarning: string,
@@ -1235,34 +1575,44 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1235
1575
  prepareOptions?: PrepareEventOptions,
1236
1576
  explicitRoute?: string
1237
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
+ }
1238
1583
  return this.addPendingPromise(
1239
1584
  this._prepareEventMessage(props, prepareOptions)
1240
- .then(({ distinctId, event, properties, options }) => {
1585
+ .then(({ distinctId, event, properties, options, uuid, timestamp }) => {
1241
1586
  // The queue drops the event without an error when the client was disabled or opted out
1242
1587
  // while the event was prepared, so a flag event's dedupe key is released here.
1243
1588
  if (this.disabled || this.optedOut) {
1244
1589
  prepareOptions?.onCaptureFailed?.()
1245
1590
  }
1246
- const captureOptions: PostHogCaptureOptions = {
1247
- timestamp: options.timestamp,
1248
- disableGeoip: options.disableGeoip,
1249
- 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,
1250
1597
  }
1251
1598
  const message = {
1252
- distinctId,
1599
+ // Set directly, not as `distinctId`: core drops a falsy `distinctId`, which would hide what beforeSend left.
1600
+ distinct_id: distinctId,
1253
1601
  event,
1254
- properties: {
1255
- ...properties,
1256
- ...this.getCommonEventProperties(),
1257
- },
1602
+ properties,
1603
+ ...(options !== undefined ? { options } : {}),
1258
1604
  }
1259
1605
  return immediate
1260
1606
  ? this.sendImmediate(type, message, captureOptions, explicitRoute)
1261
1607
  : this.enqueue(type, message, captureOptions, explicitRoute)
1262
1608
  })
1263
1609
  .catch((err) => {
1264
- // A `before_send` discard rejects with null; it is not a failure.
1265
- 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) {
1266
1616
  console.error(err)
1267
1617
  prepareOptions?.onCaptureFailed?.()
1268
1618
  }
@@ -1270,6 +1620,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1270
1620
  )
1271
1621
  }
1272
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
+
1273
1634
  _capturePreparedEvent(props: EventMessage, immediate: boolean): Promise<void> {
1274
1635
  return this._sendPreparedEvent('capture', props, immediate)
1275
1636
  }
@@ -1333,7 +1694,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1333
1694
  * sendFeatureFlags: {
1334
1695
  * onlyEvaluateLocally: true,
1335
1696
  * personProperties: { plan: 'premium' },
1336
- * groupProperties: { org: { tier: 'enterprise' } }
1697
+ * groupProperties: { org: { tier: 'enterprise' } },
1337
1698
  * flagKeys: ['flag1', 'flag2']
1338
1699
  * }
1339
1700
  * })
@@ -1369,7 +1730,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1369
1730
  if (this.disabled) {
1370
1731
  return undefined
1371
1732
  }
1372
- const uuid = getEventUuid(props.uuid, uuidv7)
1733
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7()
1373
1734
  void this._sendPreparedAiEvent({ ...props, uuid }, false)
1374
1735
  return uuid
1375
1736
  }
@@ -1388,7 +1749,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1388
1749
  if (this.disabled) {
1389
1750
  return undefined
1390
1751
  }
1391
- const uuid = getEventUuid(props.uuid, uuidv7)
1752
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7()
1392
1753
  await this._sendPreparedAiEvent({ ...props, uuid }, true)
1393
1754
  return uuid
1394
1755
  }
@@ -1397,7 +1758,6 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1397
1758
  if (typeof props?.event === 'string' && !props.event.startsWith('$ai_')) {
1398
1759
  this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`)
1399
1760
  }
1400
- this._aiCaptureRouteActive = true
1401
1761
  return this._sendPreparedEvent('capture', props, immediate, undefined, AI_CAPTURE_ROUTE)
1402
1762
  }
1403
1763
 
@@ -1424,7 +1784,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1424
1784
  * distinctId: 'user_123',
1425
1785
  * properties: {
1426
1786
  * $set: { name: 'John Doe', email: 'john@example.com' },
1427
- * $set_once: { first_login: new Date().toISOString() }
1787
+ * $set_once: { first_login: new Date().toISOString() },
1428
1788
  * $anon_distinct_id: 'anonymous_user_456'
1429
1789
  * }
1430
1790
  * })
@@ -1434,22 +1794,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1434
1794
  *
1435
1795
  * @param data - The identify data containing distinctId and properties
1436
1796
  */
1437
- identify({ distinctId, properties = {}, disableGeoip }: IdentifyMessage): void {
1438
- // Catch properties passed as $set and move them to the top level
1439
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties
1440
- // if no $set is provided we assume all rest properties are $set
1441
- const setProps = $set || rest
1442
- const setOnceProps = $set_once || {}
1443
- const eventProperties = {
1444
- $set: setProps,
1445
- $set_once: setOnceProps,
1446
- $anon_distinct_id: $anon_distinct_id ?? undefined,
1447
- }
1797
+ identify({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): void {
1798
+ const eventProperties = identifyEventProperties(properties)
1448
1799
  this._sendPreparedEvent(
1449
1800
  'identify',
1450
- { distinctId, event: '$identify', properties: eventProperties, disableGeoip },
1451
- false,
1452
- { includeContextProperties: false }
1801
+ { distinctId, event: '$identify', properties: eventProperties, disableGeoip, options },
1802
+ false
1453
1803
  )
1454
1804
  }
1455
1805
 
@@ -1473,22 +1823,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1473
1823
  * @param data - The identify data containing distinctId and properties
1474
1824
  * @returns Promise that resolves when the identify is processed
1475
1825
  */
1476
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }: IdentifyMessage): Promise<void> {
1477
- // Catch properties passed as $set and move them to the top level
1478
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties
1479
- // if no $set is provided we assume all rest properties are $set
1480
- const setProps = $set || rest
1481
- const setOnceProps = $set_once || {}
1482
- const eventProperties = {
1483
- $set: setProps,
1484
- $set_once: setOnceProps,
1485
- $anon_distinct_id: $anon_distinct_id ?? undefined,
1486
- }
1826
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): Promise<void> {
1827
+ const eventProperties = identifyEventProperties(properties)
1487
1828
  await this._sendPreparedEvent(
1488
1829
  'identify',
1489
- { distinctId, event: '$identify', properties: eventProperties, disableGeoip },
1490
- true,
1491
- { includeContextProperties: false }
1830
+ { distinctId, event: '$identify', properties: eventProperties, disableGeoip, options },
1831
+ true
1492
1832
  )
1493
1833
  }
1494
1834
 
@@ -1508,7 +1848,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1508
1848
  *
1509
1849
  * @param data - The data containing distinctId and properties to set
1510
1850
  */
1511
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }: SetPersonPropertiesMessage): void {
1851
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }: SetPersonPropertiesMessage): void {
1512
1852
  if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0) {
1513
1853
  return
1514
1854
  }
@@ -1525,6 +1865,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1525
1865
  distinctId,
1526
1866
  event: '$set',
1527
1867
  properties: eventProperties,
1868
+ options,
1528
1869
  })
1529
1870
  }
1530
1871
 
@@ -1543,13 +1884,13 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1543
1884
  *
1544
1885
  * @param data - The data containing distinctId and property names to unset
1545
1886
  */
1546
- unsetPersonProperties({ distinctId, properties }: UnsetPersonPropertiesMessage): void {
1887
+ unsetPersonProperties({ distinctId, properties, options }: UnsetPersonPropertiesMessage): void {
1547
1888
  const propertyNames = normalizeUnsetPersonProperties(properties)
1548
1889
  if (propertyNames.length === 0) {
1549
1890
  return
1550
1891
  }
1551
1892
 
1552
- this.capture({ distinctId, event: '$set', properties: { $unset: propertyNames } })
1893
+ this.capture({ distinctId, event: '$set', properties: { $unset: propertyNames }, options })
1553
1894
  }
1554
1895
 
1555
1896
  /**
@@ -1568,17 +1909,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1568
1909
  *
1569
1910
  * @param data - The alias data containing distinctId and alias
1570
1911
  */
1571
- alias(data: { distinctId: string; alias: string; disableGeoip?: boolean }): void {
1912
+ alias(data: { distinctId: string; alias: string; disableGeoip?: boolean; options?: EventOptions }): void {
1572
1913
  this._sendPreparedEvent(
1573
1914
  'alias',
1574
1915
  {
1575
1916
  distinctId: data.distinctId,
1576
1917
  event: '$create_alias',
1577
- properties: { distinct_id: data.distinctId, alias: data.alias },
1918
+ properties: { alias: data.alias },
1578
1919
  disableGeoip: data.disableGeoip,
1920
+ options: data.options,
1579
1921
  },
1580
1922
  false,
1581
- { includeContextProperties: false }
1923
+ ALIAS_PREPARE_OPTIONS
1582
1924
  )
1583
1925
  }
1584
1926
 
@@ -1599,17 +1941,23 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1599
1941
  * @param data - The alias data containing distinctId and alias
1600
1942
  * @returns Promise that resolves when the alias is processed
1601
1943
  */
1602
- 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> {
1603
1950
  await this._sendPreparedEvent(
1604
1951
  'alias',
1605
1952
  {
1606
1953
  distinctId: data.distinctId,
1607
1954
  event: '$create_alias',
1608
- properties: { distinct_id: data.distinctId, alias: data.alias },
1955
+ properties: { alias: data.alias },
1609
1956
  disableGeoip: data.disableGeoip,
1957
+ options: data.options,
1610
1958
  },
1611
1959
  true,
1612
- { includeContextProperties: false }
1960
+ ALIAS_PREPARE_OPTIONS
1613
1961
  )
1614
1962
  }
1615
1963
 
@@ -2950,7 +3298,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2950
3298
  * The key is reserved before capture and stays reserved while capture runs, so a read during
2951
3299
  * capture does not send the event again. It is released when capture fails, so a later read
2952
3300
  * sends the event: the capture call throws, the client is disabled or opted out (also while the
2953
- * 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
2954
3302
  * its key: the application chose to drop it, and later reads would be dropped the same way.
2955
3303
  * A failure is logged and never reaches the read.
2956
3304
  */
@@ -3057,11 +3405,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3057
3405
  *
3058
3406
  * @param data - The group identify data
3059
3407
  */
3060
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void {
3408
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }: GroupIdentifyMessage): void {
3061
3409
  this._sendPreparedEvent(
3062
3410
  'capture',
3063
3411
  {
3064
- distinctId: distinctId || `$${groupType}_${groupKey}`,
3412
+ distinctId,
3065
3413
  event: '$groupidentify',
3066
3414
  properties: {
3067
3415
  $group_type: groupType,
@@ -3069,9 +3417,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3069
3417
  $group_set: properties || {},
3070
3418
  },
3071
3419
  disableGeoip,
3420
+ options,
3072
3421
  },
3073
3422
  false,
3074
- { includeContextProperties: false }
3423
+ { fallbackDistinctId: `$${groupType}_${groupKey}`, contextSession: false }
3075
3424
  )
3076
3425
  }
3077
3426
 
@@ -3103,11 +3452,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3103
3452
  properties,
3104
3453
  distinctId,
3105
3454
  disableGeoip,
3455
+ options,
3106
3456
  }: GroupIdentifyMessage): Promise<void> {
3107
3457
  await this._sendPreparedEvent(
3108
3458
  'capture',
3109
3459
  {
3110
- distinctId: distinctId || `$${groupType}_${groupKey}`,
3460
+ distinctId,
3111
3461
  event: '$groupidentify',
3112
3462
  properties: {
3113
3463
  $group_type: groupType,
@@ -3115,9 +3465,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3115
3465
  $group_set: properties || {},
3116
3466
  },
3117
3467
  disableGeoip,
3468
+ options,
3118
3469
  },
3119
3470
  true,
3120
- { includeContextProperties: false }
3471
+ { fallbackDistinctId: `$${groupType}_${groupKey}`, contextSession: false }
3121
3472
  )
3122
3473
  }
3123
3474
 
@@ -3256,6 +3607,86 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3256
3607
  return false
3257
3608
  }
3258
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
+
3259
3690
  protected abstract initializeContext(): IPostHogContext | undefined
3260
3691
 
3261
3692
  /**
@@ -3264,6 +3695,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3264
3695
  * Context properties like tags and sessionId will be automatically attached to all events.
3265
3696
  * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context.
3266
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
+ *
3267
3707
  * @example
3268
3708
  * ```ts
3269
3709
  * posthog.withContext({ distinctId: 'user_123' }, () => {
@@ -3273,7 +3713,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3273
3713
  *
3274
3714
  * {@label Context}
3275
3715
  *
3276
- * @param data - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture)
3716
+ * @param data - Context data to apply (sessionId, distinctId, properties, options)
3277
3717
  * @param fn - Function to run with the context
3278
3718
  * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3279
3719
  * @returns The return value of the function
@@ -3314,25 +3754,6 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3314
3754
  return this.context?.get()
3315
3755
  }
3316
3756
 
3317
- /**
3318
- * Set context without a callback wrapper.
3319
- *
3320
- * Uses `AsyncLocalStorage.enterWith()` to attach context to the current
3321
- * async execution context. The context lives until that async context ends.
3322
- *
3323
- * Must be called in the same async scope that makes PostHog calls.
3324
- * Calling this outside a request-scoped async context will leak context
3325
- * across unrelated work. Prefer `withContext()` when you can wrap code
3326
- * in a callback — it creates an isolated scope that cleans up automatically.
3327
- *
3328
- * @param data - Context data to apply (distinctId, sessionId, properties)
3329
- * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3330
- */
3331
- enterContext(data: Partial<ContextData>, options?: ContextOptions): void {
3332
- this.context?.enter(data as ContextData, options)
3333
- notifyContextListeners(this)
3334
- }
3335
-
3336
3757
  /**
3337
3758
  * Shutdown the PostHog client gracefully.
3338
3759
  *
@@ -3425,8 +3846,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3425
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.
3426
3847
  const emailsSettled = emailsDrained ? raceWithTimeout(emailsDrained, remainingMs) : undefined
3427
3848
  try {
3428
- 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)
3429
3853
  } finally {
3854
+ for (const lane of this._captureLanes.values()) {
3855
+ lane.finishShutdown()
3856
+ }
3430
3857
  await emailsSettled
3431
3858
  await logsDrained
3432
3859
  this._distinctIdHasSentFlagCalls.clear()
@@ -3435,6 +3862,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3435
3862
  }
3436
3863
  }
3437
3864
 
3865
+ private _drainCaptureLanes(deadlineMs: number): Promise<void> {
3866
+ return Promise.all([...this._captureLanes.values()].map((lane) => lane.drain(deadlineMs))).then(() => {})
3867
+ }
3868
+
3438
3869
  private async _requestRemoteConfigPayload(flagKey: string): Promise<PostHogFetchResponse | undefined> {
3439
3870
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) {
3440
3871
  return undefined
@@ -3617,6 +4048,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3617
4048
  /**
3618
4049
  * Capture an error exception as an event.
3619
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
+ *
3620
4056
  * @example
3621
4057
  * ```ts
3622
4058
  * // Capture an error with user ID
@@ -3624,20 +4060,20 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3624
4060
  * // Some risky operation
3625
4061
  * riskyOperation()
3626
4062
  * } catch (error) {
3627
- * client.captureException(error, 'user_123')
4063
+ * client.captureException(error, { distinctId: 'user_123' })
3628
4064
  * }
3629
4065
  * ```
3630
4066
  *
3631
4067
  * @example
3632
4068
  * ```ts
3633
- * // Capture with additional properties
4069
+ * // Capture with additional properties and a level
3634
4070
  * try {
3635
4071
  * apiCall()
3636
4072
  * } catch (error) {
3637
- * client.captureException(error, 'user_123', {
3638
- * endpoint: '/api/users',
3639
- * method: 'POST',
3640
- * status_code: 500
4073
+ * client.captureException(error, {
4074
+ * distinctId: 'user_123',
4075
+ * properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
4076
+ * level: 'warning',
3641
4077
  * })
3642
4078
  * }
3643
4079
  * ```
@@ -3645,29 +4081,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3645
4081
  * {@label Error tracking}
3646
4082
  *
3647
4083
  * @param error - The error to capture
3648
- * @param distinctId - Optional user distinct ID
3649
- * @param additionalProperties - Optional additional properties to include
3650
- * @param uuid - Optional event UUID
3651
- * @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
3652
4085
  */
3653
- captureException(
3654
- error: unknown,
3655
- distinctId?: string,
3656
- additionalProperties?: Record<string | number, any>,
3657
- uuid?: EventMessage['uuid'],
3658
- flags?: FeatureFlagEvaluations
3659
- ): 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)
3660
4089
  if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3661
4090
  const syntheticException = new Error('PostHog syntheticException')
3662
4091
  this.addPendingPromise(
3663
- ErrorTracking.buildEventMessage(
3664
- this.getErrorPropertiesBuilder(),
3665
- error,
3666
- { syntheticException },
3667
- distinctId,
3668
- additionalProperties,
3669
- this.getContext()
3670
- ).then((msg) => this._capturePreparedEvent({ ...msg, uuid, flags }, false))
4092
+ this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg) =>
4093
+ this._capturePreparedEvent(msg, false)
4094
+ )
3671
4095
  )
3672
4096
  }
3673
4097
  }
@@ -3675,6 +4099,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3675
4099
  /**
3676
4100
  * Capture an error exception as an event immediately (synchronously).
3677
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
+ *
3678
4107
  * @example
3679
4108
  * ```ts
3680
4109
  * // Capture an error immediately with user ID
@@ -3682,7 +4111,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3682
4111
  * // Some risky operation
3683
4112
  * riskyOperation()
3684
4113
  * } catch (error) {
3685
- * await client.captureExceptionImmediate(error, 'user_123')
4114
+ * await client.captureExceptionImmediate(error, { distinctId: 'user_123' })
3686
4115
  * }
3687
4116
  * ```
3688
4117
  *
@@ -3692,10 +4121,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3692
4121
  * try {
3693
4122
  * apiCall()
3694
4123
  * } catch (error) {
3695
- * await client.captureExceptionImmediate(error, 'user_123', {
3696
- * endpoint: '/api/users',
3697
- * method: 'POST',
3698
- * status_code: 500
4124
+ * await client.captureExceptionImmediate(error, {
4125
+ * distinctId: 'user_123',
4126
+ * properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
3699
4127
  * })
3700
4128
  * }
3701
4129
  * ```
@@ -3703,39 +4131,35 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3703
4131
  * {@label Error tracking}
3704
4132
  *
3705
4133
  * @param error - The error to capture
3706
- * @param distinctId - Optional user distinct ID
3707
- * @param additionalProperties - Optional additional properties to include
3708
- * @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
3709
4135
  * @returns Promise that resolves when the error is captured
3710
4136
  */
3711
- async captureExceptionImmediate(
3712
- error: unknown,
3713
- distinctId?: string,
3714
- additionalProperties?: Record<string | number, any>,
3715
- flags?: FeatureFlagEvaluations
3716
- ): 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)
3717
4140
  if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3718
4141
  const syntheticException = new Error('PostHog syntheticException')
3719
4142
  return this.addPendingPromise(
3720
- ErrorTracking.buildEventMessage(
3721
- this.getErrorPropertiesBuilder(),
3722
- error,
3723
- { syntheticException },
3724
- distinctId,
3725
- additionalProperties,
3726
- this.getContext()
3727
- ).then((msg) => this.captureImmediate({ ...msg, flags }))
4143
+ this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg) => this.captureImmediate(msg))
3728
4144
  )
3729
4145
  }
3730
4146
  }
3731
4147
 
3732
- public async prepareEventMessage(props: EventMessage): Promise<{
3733
- distinctId: string
3734
- event: string
3735
- properties: PostHogEventProperties
3736
- options: PostHogCaptureOptions
3737
- }> {
3738
- 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 }
3739
4163
  }
3740
4164
 
3741
4165
  /**
@@ -3765,15 +4189,43 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3765
4189
  return this._serviceName
3766
4190
  }
3767
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
+ */
3768
4225
  private async _prepareEventMessage(
3769
4226
  props: EventMessage,
3770
- options: PrepareEventOptions = {}
3771
- ): Promise<{
3772
- distinctId: string
3773
- event: string
3774
- properties: PostHogEventProperties
3775
- options: PostHogCaptureOptions
3776
- }> {
4227
+ prepareOptions: PrepareEventOptions = {}
4228
+ ): Promise<PreparedEventMessage> {
3777
4229
  const {
3778
4230
  distinctId,
3779
4231
  event,
@@ -3785,55 +4237,93 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3785
4237
  disableGeoip,
3786
4238
  uuid,
3787
4239
  }: EventMessage = props
4240
+ const callOptions = readEventOptions(props.options)
3788
4241
 
4242
+ // Read every layer now, before the first await, so later changes never reach this event.
3789
4243
  const contextData = getEventContext(props, this.context?.get())
3790
- const includeContextProperties = options.includeContextProperties ?? true
3791
-
3792
- let mergedDistinctId = distinctId || contextData?.distinctId
3793
-
3794
- const mergedProperties = includeContextProperties
3795
- ? {
3796
- ...this._serviceNameProperties(),
3797
- ...this.props,
3798
- ...(contextData?.properties || {}),
3799
- ...(properties || {}),
3800
- }
3801
- : { ...this._serviceNameProperties(), ...(properties || {}) }
3802
-
3803
- if (event === '$exception' && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) {
3804
- 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
3805
4262
  }
3806
-
3807
- if (!mergedDistinctId) {
3808
- mergedDistinctId = uuidv7()
3809
- 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
3810
4269
  }
3811
-
3812
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) {
3813
- 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 }])
3814
4276
  }
3815
4277
 
3816
- // A config version 2 flag event fixes its attribution after super and context properties are
3817
- // merged, so neither can change it or add a field the event never carries.
3818
- const flagEvent = options.flagEvent
3819
- const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties
3820
-
3821
- // Minimal $feature_flag_called events: rebuild from the strict allowlist before before_send
3822
- // runs, so a customer hook may deliberately re-add stripped properties. Everything the SDK
3823
- // itself adds after this point ($groups, $lib/$lib_version/$is_server, $geoip_disable) is
3824
- // allowlisted — no SDK enrichment may reintroduce stripped properties. A config version 2
3825
- // 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.
3826
4306
  const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties)
3827
4307
  ? flagEvent
3828
- ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties)
3829
- : minimizeFlagCalledEventProperties(enrichedProperties)
4308
+ ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES)
4309
+ : minimizeFlagCalledEventProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES)
3830
4310
  : enrichedProperties
3831
4311
 
3832
- // 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
+
3833
4323
  const eventMessage = this._runBeforeSend(
3834
4324
  {
3835
- distinctId: mergedDistinctId,
3836
- event,
4325
+ distinctId: eventDistinctId,
4326
+ event: finalEvent,
3837
4327
  properties: finalProperties,
3838
4328
  groups,
3839
4329
  flags,
@@ -3841,106 +4331,36 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3841
4331
  timestamp,
3842
4332
  disableGeoip,
3843
4333
  uuid,
4334
+ options: eventOptions,
3844
4335
  },
3845
- options.onCaptureFailed
4336
+ prepareOptions.onCaptureFailed
3846
4337
  )
3847
4338
 
3848
4339
  if (!eventMessage) {
3849
4340
  return Promise.reject(null)
3850
4341
  }
3851
4342
 
3852
- // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush
3853
- const eventProperties = await Promise.resolve()
3854
- .then(async () => {
3855
- // Precedence: an explicit `flags` snapshot always wins, regardless of
3856
- // `sendFeatureFlags`. The snapshot guarantees the event carries the same
3857
- // values the developer branched on with no additional network call. The
3858
- // `sendFeatureFlags` path only runs when no snapshot is provided.
3859
- if (flags) {
3860
- if (sendFeatureFlags) {
3861
- console.warn(
3862
- '[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.'
3863
- )
3864
- }
3865
- return flags._getEventProperties()
3866
- }
3867
-
3868
- if (sendFeatureFlags) {
3869
- emitDeprecationWarningOnce(
3870
- 'sendFeatureFlags',
3871
- '`sendFeatureFlags` is deprecated and will be removed in a future major version. ' +
3872
- 'Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a ' +
3873
- 'second `/flags` request per capture and guarantees the event carries the exact ' +
3874
- 'flag values your code branched on.'
3875
- )
3876
- // If we are sending feature flags, we evaluate them locally if the user prefers it, otherwise we fall back to remote evaluation
3877
- const sendFeatureFlagsOptions = typeof sendFeatureFlags === 'object' ? sendFeatureFlags : undefined
3878
- const flagValues = await this.getFeatureFlagsForEvent(
3879
- eventMessage.distinctId!,
3880
- groups,
3881
- disableGeoip,
3882
- sendFeatureFlagsOptions
3883
- )
3884
- return buildFlagEventProperties(flagValues)
3885
- }
3886
-
3887
- // $feature_flag_called events are not enriched with cached flags — the flags
3888
- // on that event should reflect the specific call, not a potentially stale snapshot.
3889
- return {}
3890
- })
3891
- .catch(() => {
3892
- // Something went wrong getting the flag info - we should capture the event anyways
3893
- return {}
3894
- })
3895
- .then((additionalProperties): PostHogEventProperties => {
3896
- // No matter what - capture the event
3897
- const resolvedGroups = eventMessage.groups || groups
3898
-
3899
- return {
3900
- ...additionalProperties,
3901
- ...(eventMessage.properties || {}),
3902
- // Only stamp $groups from the top-level `groups` when present — otherwise a
3903
- // caller-provided properties.$groups would be clobbered with undefined (#3888).
3904
- ...(resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0
3905
- ? { $groups: resolvedGroups }
3906
- : {}),
3907
- }
3908
- })
3909
-
3910
- // Handle bot pageview collection based on preview flag
3911
- if (
3912
- eventMessage.event === '$pageview' &&
3913
- this.options.__preview_capture_bot_pageviews &&
3914
- typeof eventProperties.$raw_user_agent === 'string'
3915
- ) {
3916
- if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
3917
- eventMessage.event = '$bot_pageview'
3918
- eventProperties.$browser_type = 'bot'
3919
- }
3920
- }
3921
-
3922
4343
  return {
3923
4344
  distinctId: eventMessage.distinctId!,
3924
4345
  event: eventMessage.event,
3925
- properties: eventProperties,
3926
- options: {
3927
- timestamp: eventMessage.timestamp,
3928
- disableGeoip: eventMessage.disableGeoip,
3929
- uuid: eventMessage.uuid,
3930
- },
4346
+ properties: eventMessage.properties || {},
4347
+ options: eventMessage.options,
4348
+ uuid: eventMessage.uuid,
4349
+ timestamp: eventMessage.timestamp,
4350
+ disableGeoip: eventMessage.disableGeoip,
3931
4351
  }
3932
4352
  }
3933
4353
 
3934
4354
  // `onError` is called when a hook throws. A hook that returns null discards the event, which
3935
4355
  // is not an error.
3936
4356
  private _runBeforeSend(eventMessage: EventMessage, onError?: () => void): EventMessage | null {
3937
- const beforeSend = this.options.before_send
4357
+ const beforeSend = this.options.beforeSend
3938
4358
  if (!beforeSend) {
3939
4359
  return eventMessage
3940
4360
  }
3941
4361
 
3942
4362
  const fns = Array.isArray(beforeSend) ? beforeSend : [beforeSend]
3943
- let result: EventMessage | null = eventMessage
4363
+ let result: EventMessage | null = readCallerValues(() => isolateForBeforeSend(eventMessage))
3944
4364
 
3945
4365
  for (const fn of fns) {
3946
4366
  try {
@@ -3954,7 +4374,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3954
4374
  this._logger.warn(message)
3955
4375
  }
3956
4376
  } catch (error) {
3957
- 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})`)
3958
4381
  onError?.()
3959
4382
  return null
3960
4383
  }