@posthog/core 1.69.9 → 1.71.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 (122) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagLocalEvaluation.d.ts +2 -0
  35. package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  36. package/dist/featureFlagLocalEvaluation.js +38 -0
  37. package/dist/featureFlagLocalEvaluation.mjs +38 -0
  38. package/dist/featureFlagUtils.d.ts +7 -5
  39. package/dist/featureFlagUtils.d.ts.map +1 -1
  40. package/dist/featureFlagUtils.js +17 -11
  41. package/dist/featureFlagUtils.mjs +14 -11
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +27 -16
  45. package/dist/index.mjs +1 -1
  46. package/dist/posthog-core-stateless.d.ts +44 -7
  47. package/dist/posthog-core-stateless.d.ts.map +1 -1
  48. package/dist/posthog-core-stateless.js +103 -24
  49. package/dist/posthog-core-stateless.mjs +103 -24
  50. package/dist/posthog-core.d.ts +138 -53
  51. package/dist/posthog-core.d.ts.map +1 -1
  52. package/dist/posthog-core.js +341 -115
  53. package/dist/posthog-core.mjs +338 -115
  54. package/dist/types.d.ts +33 -1
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/index.js +25 -12
  59. package/dist/utils/index.mjs +1 -1
  60. package/dist/utils/json-utils.d.ts +11 -1
  61. package/dist/utils/json-utils.d.ts.map +1 -1
  62. package/dist/utils/json-utils.js +50 -2
  63. package/dist/utils/json-utils.mjs +46 -1
  64. package/package.json +13 -3
  65. package/src/capture-v1/compression.ts +50 -0
  66. package/src/capture-v1/errors.ts +91 -0
  67. package/src/capture-v1/index.ts +34 -0
  68. package/src/capture-v1/sender.ts +779 -0
  69. package/src/capture-v1/serialize.ts +113 -0
  70. package/src/capture-v1/transform.ts +135 -0
  71. package/src/capture-v1/types.ts +59 -0
  72. package/src/capture-v1/uuid.ts +53 -0
  73. package/src/featureFlagLocalEvaluation.ts +51 -0
  74. package/src/featureFlagUtils.ts +22 -10
  75. package/src/index.ts +1 -0
  76. package/src/posthog-core-stateless.ts +190 -35
  77. package/src/posthog-core.ts +615 -178
  78. package/src/types.ts +31 -1
  79. package/src/utils/index.ts +1 -1
  80. package/src/utils/json-utils.ts +64 -1
  81. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  82. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  83. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  84. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  85. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  86. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  87. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  88. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  89. package/src/error-tracking/exception-steps.spec.ts +0 -115
  90. package/src/error-tracking/parsers/base.spec.ts +0 -156
  91. package/src/error-tracking/parsers/index.spec.ts +0 -270
  92. package/src/error-tracking/parsers/node.spec.ts +0 -34
  93. package/src/error-tracking/release.spec.ts +0 -34
  94. package/src/logs/index.spec.ts +0 -2421
  95. package/src/logs/logs-utils.spec.ts +0 -266
  96. package/src/metrics/index.spec.ts +0 -1249
  97. package/src/surveys/activation.spec.ts +0 -61
  98. package/src/surveys/events.spec.ts +0 -183
  99. package/src/surveys/keys.spec.ts +0 -29
  100. package/src/surveys/property-matching.spec.ts +0 -539
  101. package/src/surveys/shuffling.spec.ts +0 -51
  102. package/src/surveys/translations.spec.ts +0 -274
  103. package/src/surveys/validation.spec.ts +0 -168
  104. package/src/traces/config.spec.ts +0 -271
  105. package/src/traces/ids.spec.ts +0 -115
  106. package/src/traces/index.spec.ts +0 -3287
  107. package/src/traces/live-spans.spec.ts +0 -69
  108. package/src/traces/otlp.spec.ts +0 -368
  109. package/src/traces/span.spec.ts +0 -1137
  110. package/src/traces/traceparent.spec.ts +0 -184
  111. package/src/utils/bot-detection.spec.ts +0 -107
  112. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  113. package/src/utils/json-utils.spec.ts +0 -115
  114. package/src/utils/named-error.spec.ts +0 -36
  115. package/src/utils/number-utils.spec.ts +0 -212
  116. package/src/utils/otlp-any-value.spec.ts +0 -376
  117. package/src/utils/otlp-resource.spec.ts +0 -171
  118. package/src/utils/promise-queue.spec.ts +0 -55
  119. package/src/utils/string-utils.spec.ts +0 -158
  120. package/src/utils/type-utils.spec.ts +0 -38
  121. package/src/utils/webview-app-utils.spec.ts +0 -118
  122. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -5,6 +5,7 @@ import type {
5
5
  PostHogCoreOptions,
6
6
  PostHogEventProperties,
7
7
  PostHogCaptureOptions,
8
+ PostHogCaptureOptionsWithEventOptions,
8
9
  JsonType,
9
10
  PostHogRemoteConfig,
10
11
  FeatureFlagValue,
@@ -27,6 +28,7 @@ import {
27
28
  createFlagsResponseFromFlagsAndPayloads,
28
29
  flagDetailsToResults,
29
30
  getEnabledFromValue,
31
+ isEnabledFlagValue,
30
32
  getFeatureFlagValue,
31
33
  getFlagValuesFromFlags,
32
34
  getPayloadsFromFlags,
@@ -56,10 +58,87 @@ interface PendingFlagsRequest extends FlagsAsyncOptions {
56
58
  }[]
57
59
  }
58
60
 
61
+ const resolveSendFeatureFlagEvent = (options?: FeatureFlagResultOptions): boolean | undefined =>
62
+ options?.sendFeatureFlagEvent ?? options?.sendEvent
63
+
64
+ // Whether stored flag details hold no flags from a successful load or bootstrap. Details stored before
65
+ // the `noFlagsCached` marker existed count as holding none when a failed or quota-limited load left them empty,
66
+ // unless they carry `minimalFlagCalledEvents`, which every successful load has written since RN 4.58.0.
67
+ const holdsNoCachedFlags = (storedDetails: PostHogFlagsStorageFormat): boolean => {
68
+ if (storedDetails.noFlagsCached !== undefined) {
69
+ return storedDetails.noFlagsCached
70
+ }
71
+ const failedOrQuotaLimited =
72
+ storedDetails.requestError !== undefined ||
73
+ storedDetails.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags) === true
74
+ return (
75
+ failedOrQuotaLimited &&
76
+ storedDetails.minimalFlagCalledEvents === undefined &&
77
+ Object.keys(storedDetails.flags ?? {}).length === 0
78
+ )
79
+ }
80
+
81
+ // The per-event `options` a caller or the SDK passed with the capture options, which capture v1 sends apart from the properties.
82
+ const eventOptionsOf = (options?: PostHogCaptureOptions): { [key: string]: JsonType } | undefined => {
83
+ const eventOptions = (options as { options?: unknown } | undefined)?.options
84
+ return isObject(eventOptions) ? (eventOptions as { [key: string]: JsonType }) : undefined
85
+ }
86
+
87
+ // Events that identify, alias, merge or update a person or group.
88
+ const IDENTITY_EVENTS = ['$identify', '$create_alias', '$merge_dangerously', '$groupidentify', '$set', '$set_once']
89
+
90
+ const isFilledString = (value: unknown): value is string => typeof value === 'string' && value.length > 0
91
+
92
+ // Fills the SDK's own `$lib` and `$lib_version` as a pair, as posthog-ios and posthog-android 4.0 do: an event without
93
+ // a `$lib` gets both, an event naming this SDK's `$lib` without a version gets the version, and another library's
94
+ // `$lib` is left as it is.
95
+ function fillLibraryIdentity(properties: PostHogEventProperties, lib: JsonType, libVersion: JsonType): void {
96
+ if (!isFilledString(properties.$lib)) {
97
+ properties.$lib = lib
98
+ properties.$lib_version = libVersion
99
+ } else if (properties.$lib === lib && !isFilledString(properties.$lib_version)) {
100
+ properties.$lib_version = libVersion
101
+ }
102
+ }
103
+
104
+ // The person-properties hash of a queued message's distinct id, `$set` and `$set_once`, or null when either isn't an
105
+ // object or can't be hashed, such as one holding a cycle or a BigInt.
106
+ // Null when the properties can't be serialized, such as a cycle or a BigInt, which skips the duplicate check, as on
107
+ // posthog-android.
108
+ function personPropertiesHashOrNull(
109
+ distinctId: string,
110
+ userPropertiesToSet?: { [key: string]: JsonType },
111
+ userPropertiesToSetOnce?: { [key: string]: JsonType }
112
+ ): string | null {
113
+ try {
114
+ return getPersonPropertiesHash(distinctId, userPropertiesToSet, userPropertiesToSetOnce)
115
+ } catch {
116
+ return null
117
+ }
118
+ }
119
+
120
+ function sentPersonPropertiesHash(message: PostHogEventProperties): string | null {
121
+ const properties = (isObject(message.properties) ? message.properties : {}) as PostHogEventProperties
122
+ const set = properties.$set
123
+ const setOnce = properties.$set_once
124
+ if ((!isNullish(set) && !isObject(set)) || (!isNullish(setOnce) && !isObject(setOnce))) {
125
+ return null
126
+ }
127
+ return personPropertiesHashOrNull(
128
+ String(message.distinct_id),
129
+ set as { [key: string]: JsonType } | undefined,
130
+ setOnce as { [key: string]: JsonType } | undefined
131
+ )
132
+ }
133
+
59
134
  // How far session activity moves before its timestamp is stored again. The browser SDK uses the same value.
60
135
  const SESSION_ACTIVITY_PERSIST_GRANULARITY_MS = 5_000
61
136
 
62
- export abstract class PostHogCore extends PostHogCoreStateless {
137
+ /**
138
+ * The PostHog client core without the feature flag getters that `getFeatureFlagResult()`,
139
+ * `getAllFeatureFlags()` and `updateFlags()` replace.
140
+ */
141
+ export abstract class PostHogCoreBase extends PostHogCoreStateless {
63
142
  // options
64
143
  private sendFeatureFlagEvent: boolean
65
144
  private disableRemoteFeatureFlags: boolean
@@ -79,6 +158,8 @@ export abstract class PostHogCore extends PostHogCoreStateless {
79
158
  // Track if an additional reload was requested while a request was in flight
80
159
  // This prevents dropping reload requests (e.g., from identify()) when preload is in progress
81
160
  private _pendingFlagsRequest?: PendingFlagsRequest
161
+ // Counts reset() calls, so a /flags response requested for the previous identity isn't stored for the next.
162
+ private _flagsResetCount = 0
82
163
 
83
164
  // The cached /config sessionRecording that a /flags `false` replaced, so a later /flags object can restore it.
84
165
  private _sessionRecordingReplacedByFlags?: { value: PostHogRemoteConfig['sessionRecording'] }
@@ -88,6 +169,8 @@ export abstract class PostHogCore extends PostHogCoreStateless {
88
169
 
89
170
  // cache for person properties to avoid duplicate $set events
90
171
  protected _cachedPersonProperties: string | null = null
172
+ // The hash a person-properties update being captured records once queued, or null to clear the stored one
173
+ private _pendingPersonPropertiesHash: string | null | undefined = undefined
91
174
 
92
175
  constructor(projectToken: string, options?: PostHogCoreOptions) {
93
176
  // Default for stateful mode is to not disable geoip. Only override if explicitly set
@@ -134,9 +217,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
134
217
  const bootstrapFeatureFlags = bootstrap.featureFlags
135
218
  const bootstrapFeatureFlagPayloads = bootstrap.featureFlagPayloads ?? {}
136
219
  if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {
220
+ // Bootstrapped payloads are already decoded values, so a string payload stays a string.
137
221
  const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(
138
222
  bootstrapFeatureFlags,
139
- bootstrapFeatureFlagPayloads
223
+ bootstrapFeatureFlagPayloads,
224
+ this.usesLegacyFlagValues() ? parsePayload : (payload) => payload
140
225
  )
141
226
 
142
227
  if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {
@@ -146,6 +231,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
146
231
  const newFeatureFlagDetails = {
147
232
  ...this.getStoredFlagDetails(),
148
233
  requestError: undefined,
234
+ noFlagsCached: undefined,
149
235
  flags: {
150
236
  ...normalizedBootstrapFeatureFlagDetails.flags,
151
237
  ...Object.fromEntries(
@@ -203,6 +289,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
203
289
  */
204
290
  reset(propertiesToKeep?: PostHogPersistedProperty[]): void {
205
291
  this.wrap(() => {
292
+ this._flagsResetCount++
206
293
  const allPropertiesToKeep = [
207
294
  PostHogPersistedProperty.Queue,
208
295
  PostHogPersistedProperty.AiQueue,
@@ -245,8 +332,21 @@ export abstract class PostHogCore extends PostHogCoreStateless {
245
332
  }
246
333
  }
247
334
 
335
+ /**
336
+ * Whether flag values keep the legacy semantics: a flag whose variant is an empty string reads as enabled,
337
+ * `$active_feature_flags` lists every loaded flag, bootstrapped string payloads are parsed as JSON, and every
338
+ * `$feature_flag_called` event carries `$used_bootstrap_value`. {@link PostHogCore} keeps them for posthog-js-lite.
339
+ */
340
+ protected usesLegacyFlagValues(): boolean {
341
+ return false
342
+ }
343
+
344
+ private isFlagValueEnabled(value: FeatureFlagValue): boolean {
345
+ return this.usesLegacyFlagValues() ? getEnabledFromValue(value) : isEnabledFlagValue(value)
346
+ }
347
+
248
348
  protected getCommonEventProperties(): PostHogEventProperties {
249
- const featureFlags = this.getFeatureFlags()
349
+ const featureFlags = this.getFeatureFlagValues()
250
350
 
251
351
  const featureVariantProperties: Record<string, FeatureFlagValue> = {}
252
352
  if (featureFlags) {
@@ -255,30 +355,165 @@ export abstract class PostHogCore extends PostHogCoreStateless {
255
355
  }
256
356
  }
257
357
  return {
258
- ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : undefined),
358
+ ...maybeAdd(
359
+ '$active_feature_flags',
360
+ featureFlags
361
+ ? Object.keys(featureFlags).filter(
362
+ (key) => this.usesLegacyFlagValues() || isEnabledFlagValue(featureFlags[key])
363
+ )
364
+ : undefined
365
+ ),
259
366
  ...featureVariantProperties,
260
367
  ...super.getCommonEventProperties(),
261
368
  }
262
369
  }
263
370
 
264
- private enrichProperties(properties?: PostHogEventProperties): PostHogEventProperties {
371
+ private enrichProperties(
372
+ properties?: PostHogEventProperties,
373
+ options?: PostHogCaptureOptions
374
+ ): PostHogEventProperties {
265
375
  const userProperties = properties || {}
266
- return {
267
- ...this.props, // Persisted properties first
268
- ...this.sessionProps, // Followed by session properties
269
- ...this.getCommonEventProperties(), // Followed by SDK context and FF props
270
- ...userProperties, // User specified properties win over all of the above
271
- $session_id: this.getSessionId(),
376
+ if (this.usesLegacyEventPropertyOrder()) {
377
+ return {
378
+ ...this.props, // Persisted properties first
379
+ ...this.sessionProps, // Followed by session properties
380
+ ...this.getCommonEventProperties(), // Followed by SDK context and FF props
381
+ ...userProperties, // User specified properties win over all of the above
382
+ $session_id: this.getSessionId(),
383
+ }
384
+ }
385
+ // As in native 4.0: the SDK's own properties, then registered and session properties, then the caller's. A
386
+ // per-call `disableGeoip` sits under the caller's `$geoip_disable`. A `null`, `undefined` or blank `$session_id`
387
+ // counts as unset, and `$lib` and `$lib_version` fill last, as a pair. The SDK session is read, which records
388
+ // session activity and can rotate the session, unless the caller's properties carry a `$session_id`; a
389
+ // registered `$session_id` still wins for the event. A caller `$groups` map adds to the registered groups, its
390
+ // key winning per group type, instead of replacing them.
391
+ const { $lib, $lib_version, ...sdkProperties } = this.getCommonEventProperties()
392
+ const callerSessionId = userProperties.$session_id
393
+ const sessionId = isFilledString(callerSessionId) && callerSessionId.trim() ? undefined : this.getSessionId()
394
+ const registered: PostHogEventProperties = {
395
+ ...sdkProperties,
396
+ ...this.props,
397
+ ...this.sessionProps,
398
+ ...(options?.disableGeoip != null && { $geoip_disable: options.disableGeoip }),
399
+ }
400
+ const enriched: PostHogEventProperties = { ...registered, ...userProperties }
401
+ if (isObject(registered.$groups) && isObject(userProperties.$groups)) {
402
+ enriched.$groups = { ...registered.$groups, ...userProperties.$groups }
403
+ }
404
+ if (!isFilledString(enriched.$session_id) || !enriched.$session_id.trim()) {
405
+ enriched.$session_id = sessionId ?? this.getSessionId()
272
406
  }
407
+ fillLibraryIdentity(enriched, $lib, $lib_version)
408
+ return enriched
409
+ }
410
+
411
+ /**
412
+ * Whether events use the posthog-js-lite / React Native 4.x property order: the SDK's own properties, such as
413
+ * `$lib`, `$os` and `$feature/<key>`, replace registered ones, the SDK's `$session_id` replaces a registered or
414
+ * caller one, the client-level `disableGeoip` setting replaces a registered or caller `$geoip_disable`, and
415
+ * `capture()` and `identify()` register a caller `$groups`, which on `capture()` then replaces the registered
416
+ * groups for that event.
417
+ * {@link PostHogCore} keeps it for posthog-js-lite and `@posthog/electron`.
418
+ */
419
+ protected usesLegacyEventPropertyOrder(): boolean {
420
+ return false
421
+ }
422
+
423
+ /**
424
+ * Whether events use the posthog-js-lite / React Native 4.x person state: the SDK's `$process_person_profile` and
425
+ * `$is_identified` replace a registered or caller value, identity events carry a registered
426
+ * `$process_person_profile`, and `$autocapture` events get neither. {@link PostHogCore} keeps it for
427
+ * posthog-js-lite and `@posthog/electron`.
428
+ */
429
+ protected usesLegacyEventPersonState(): boolean {
430
+ return false
431
+ }
432
+
433
+ // A registered or caller `$process_person_profile` or `$is_identified` wins over the SDK's value, as in native
434
+ // 4.0. On a personless event the SDK sets the `process_person_profile: false` capture option, unless the caller
435
+ // set that option, and returns the options to send the event with; PostHog processes the person when both are
436
+ // missing. The option is set before `before_send`, which can't undo it by editing properties. A `null`
437
+ // `$process_person_profile` counts as unset; a `null` or `undefined` `$is_identified` still wins, so the event is
438
+ // sent without it. The legacy person state always sets the SDK's values as properties.
439
+ private stampPersonState(
440
+ properties: PostHogEventProperties,
441
+ options?: PostHogCaptureOptions
442
+ ): PostHogCaptureOptions | undefined {
443
+ const hasPersonProcessing = this._hasPersonProcessing()
444
+ let stampedOptions = options
445
+ if (this.usesLegacyEventPersonState()) {
446
+ properties['$process_person_profile'] = hasPersonProcessing
447
+ } else if (properties['$process_person_profile'] == null) {
448
+ delete properties['$process_person_profile']
449
+ const eventOptions = eventOptionsOf(options)
450
+ if (!hasPersonProcessing && eventOptions?.process_person_profile == null) {
451
+ const personless: PostHogCaptureOptions & { options: { [key: string]: JsonType } } = {
452
+ ...options,
453
+ options: { ...eventOptions, process_person_profile: false },
454
+ }
455
+ stampedOptions = personless
456
+ }
457
+ }
458
+ if (this.usesLegacyEventPersonState() || !Object.prototype.hasOwnProperty.call(properties, '$is_identified')) {
459
+ properties['$is_identified'] = this._isIdentified()
460
+ }
461
+ // If the event has person processing, ensure that all future events will too
462
+ if (hasPersonProcessing) {
463
+ this._requirePersonProcessing('capture')
464
+ }
465
+ return stampedOptions
466
+ }
467
+
468
+ // The capture options' `options` go on the message, which capture v1 sends as the event's options. Outside the
469
+ // legacy property order, an event's `$geoip_disable`, then a per-call `disableGeoip`, win over the client-level
470
+ // setting. enrichProperties already layered the per-call value under the caller's and over the registered one.
471
+ protected prepareMessage(message: any, options?: PostHogCaptureOptions): PostHogEventProperties {
472
+ const eventGeoipDisable = message?.properties?.['$geoip_disable']
473
+ const geoipDisable = this.usesLegacyEventPropertyOrder()
474
+ ? undefined
475
+ : eventGeoipDisable != null
476
+ ? eventGeoipDisable
477
+ : options?.disableGeoip
478
+ const prepared = super.prepareMessage(message, options)
479
+ if (geoipDisable != null) {
480
+ ;(prepared.properties as PostHogEventProperties)['$geoip_disable'] = geoipDisable
481
+ }
482
+ const eventOptions = eventOptionsOf(options)
483
+ if (eventOptions) {
484
+ prepared.options = { ...eventOptions }
485
+ }
486
+ return prepared
487
+ }
488
+
489
+ // A registered `$process_person_profile` is left off identity events: PostHog drops `$identify`, `$create_alias`
490
+ // and `$groupidentify` when person processing is off, so a registered `false` would break identify, alias and
491
+ // group. `before_send` can still set it.
492
+ private enrichIdentityProperties(
493
+ properties: PostHogEventProperties,
494
+ options?: PostHogCaptureOptions
495
+ ): PostHogEventProperties {
496
+ const enriched = this.enrichProperties(properties, options)
497
+ if (!this.usesLegacyEventPersonState()) {
498
+ delete enriched['$process_person_profile']
499
+ }
500
+ return enriched
273
501
  }
274
502
 
275
503
  // enrichProperties already merged the common properties under the caller's, so only fill in
276
- // the ones that are missing instead of overriding the caller.
504
+ // the ones that are missing instead of overriding the caller. Outside the legacy property order,
505
+ // `$lib` and `$lib_version` fill as a pair.
277
506
  protected mergeCommonEventProperties(properties: PostHogEventProperties): PostHogEventProperties {
278
- return {
279
- ...this.getCommonEventProperties(),
280
- ...properties,
507
+ if (this.usesLegacyEventPropertyOrder()) {
508
+ return {
509
+ ...this.getCommonEventProperties(),
510
+ ...properties,
511
+ }
281
512
  }
513
+ const { $lib, $lib_version, ...sdkProperties } = this.getCommonEventProperties()
514
+ const merged: PostHogEventProperties = { ...sdkProperties, ...properties }
515
+ fillLibraryIdentity(merged, $lib, $lib_version)
516
+ return merged
282
517
  }
283
518
 
284
519
  /**
@@ -399,8 +634,24 @@ export abstract class PostHogCore extends PostHogCoreStateless {
399
634
  *** TRACKING
400
635
  ***/
401
636
 
637
+ /**
638
+ * Whether `identify()` drops this distinct id: a whitespace-only one, and an empty one unless the legacy
639
+ * person state keeps `identify('')` sending `$set` for the current user.
640
+ */
641
+ protected isIgnoredIdentifyId(distinctId: string | undefined): boolean {
642
+ if (typeof distinctId !== 'string' || distinctId.trim() !== '') {
643
+ return false
644
+ }
645
+ return distinctId !== '' || !this.usesLegacyEventPersonState()
646
+ }
647
+
402
648
  identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void {
403
649
  this.wrap(() => {
650
+ if (this.isIgnoredIdentifyId(distinctId)) {
651
+ this._logger.warn('identify() was called with an empty or whitespace-only distinct id, so it is ignored.')
652
+ return
653
+ }
654
+
404
655
  if (!this._requirePersonProcessing('posthog.identify')) {
405
656
  return
406
657
  }
@@ -412,7 +663,8 @@ export abstract class PostHogCore extends PostHogCoreStateless {
412
663
  const idWasSupplied = !!distinctId
413
664
  distinctId = distinctId || previousDistinctId
414
665
 
415
- if (properties?.$groups) {
666
+ // The legacy property order registers a caller `$groups`, as `capture()` does there.
667
+ if (this.usesLegacyEventPropertyOrder() && properties?.$groups) {
416
668
  this.groups(properties.$groups as PostHogGroupProperties)
417
669
  }
418
670
 
@@ -423,11 +675,14 @@ export abstract class PostHogCore extends PostHogCoreStateless {
423
675
  // if no $set is provided we assume all properties are $set
424
676
  const userProps = properties?.$set || properties
425
677
 
426
- const allProperties = this.enrichProperties({
427
- $anon_distinct_id: this.getAnonymousId(),
428
- ...maybeAdd('$set', userProps),
429
- ...maybeAdd('$set_once', userPropsOnce),
430
- })
678
+ const allProperties = this.enrichIdentityProperties(
679
+ {
680
+ $anon_distinct_id: this.getAnonymousId(),
681
+ ...maybeAdd('$set', userProps),
682
+ ...maybeAdd('$set_once', userPropsOnce),
683
+ },
684
+ options
685
+ )
431
686
 
432
687
  // Safely cast userProps and userPropsOnce to object types for hash and setPersonProperties
433
688
  const userPropsObj = isObject(userProps) ? (userProps as { [key: string]: JsonType }) : undefined
@@ -446,10 +701,13 @@ export abstract class PostHogCore extends PostHogCoreStateless {
446
701
  this.setPersistedProperty(PostHogPersistedProperty.PersonMode, 'identified')
447
702
  this.reloadFeatureFlags()
448
703
 
449
- super.identifyStateless(distinctId, allProperties, options)
450
-
451
- // Update the cached person properties hash
452
- this._cachedPersonProperties = getPersonPropertiesHash(distinctId, userPropsObj, userPropsOnceObj)
704
+ const newDistinctId = distinctId
705
+ this._captureWithPersonPropertiesHash(
706
+ this._surelyProcessesPerson(options)
707
+ ? personPropertiesHashOrNull(newDistinctId, userPropsObj, userPropsOnceObj)
708
+ : null,
709
+ () => super.identifyStateless(newDistinctId, allProperties, options)
710
+ )
453
711
  } else if (shouldTransitionToIdentified) {
454
712
  // Matching id while still anonymous (e.g. a non-identified bootstrap seeded the same id):
455
713
  // upgrade to identified and emit one person-processed $set. There is no anonymous id to
@@ -459,11 +717,14 @@ export abstract class PostHogCore extends PostHogCoreStateless {
459
717
  const setProps = userPropsObj || {}
460
718
  const setOnceProps = userPropsOnceObj || {}
461
719
  this.setPersonPropertiesForFlags({ $set: setProps, $set_once: setOnceProps }, false)
462
- this.capture('$set', { $set: setProps, $set_once: setOnceProps })
463
-
464
- // The transition event must fire even when an identical property call was cached earlier;
465
- // cache only after capture so deduplication cannot suppress it.
466
- this._cachedPersonProperties = getPersonPropertiesHash(distinctId, userPropsObj, userPropsOnceObj)
720
+ // The transition event must fire even when an identical property call was cached earlier,
721
+ // so it skips the duplicate check and only records the hash once queued.
722
+ this._captureWithPersonPropertiesHash(
723
+ this._surelyProcessesPerson(options)
724
+ ? personPropertiesHashOrNull(distinctId, userPropsObj, userPropsOnceObj)
725
+ : null,
726
+ () => this.capture('$set', { $set: setProps, $set_once: setOnceProps }, options)
727
+ )
467
728
 
468
729
  // The identified state itself is not part of the flags request; reload only when the
469
730
  // caller supplied properties that can affect flag evaluation.
@@ -473,7 +734,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
473
734
  } else if (userPropsObj || userPropsOnceObj) {
474
735
  // If the distinct_id is not changing, but we have user properties to set, we can check if they have changed
475
736
  // and if so, send a $set event
476
- this.setPersonProperties(userPropsObj, userPropsOnceObj)
737
+ this.setPersonProperties(userPropsObj, userPropsOnceObj, true, options)
477
738
  }
478
739
  })
479
740
  }
@@ -488,36 +749,37 @@ export abstract class PostHogCore extends PostHogCoreStateless {
488
749
  this.wrap(() => {
489
750
  const distinctId = this.getDistinctId()
490
751
 
491
- if (properties?.$groups) {
752
+ // The legacy property order registers a caller `$groups`, which can reload feature flags and turn on person
753
+ // processing. Otherwise the caller's groups apply to this event only.
754
+ if (this.usesLegacyEventPropertyOrder() && properties?.$groups) {
492
755
  this.groups(properties.$groups as PostHogGroupProperties)
493
756
  }
494
757
 
495
- const allProperties = this.enrichProperties(properties)
496
-
497
- // Add $process_person_profile flag to event properties
498
- const hasPersonProcessing = this._hasPersonProcessing()
499
- allProperties['$process_person_profile'] = hasPersonProcessing
500
- allProperties['$is_identified'] = this._isIdentified()
501
-
502
- // If the event has person processing, ensure that all future events will too
503
- if (hasPersonProcessing) {
504
- this._requirePersonProcessing('capture')
758
+ const allProperties = this.enrichProperties(properties, options)
759
+ // A registered `$process_person_profile` doesn't apply to identity events or person updates.
760
+ if (
761
+ !this.usesLegacyEventPersonState() &&
762
+ IDENTITY_EVENTS.includes(event) &&
763
+ properties?.['$process_person_profile'] == null
764
+ ) {
765
+ delete allProperties['$process_person_profile']
505
766
  }
767
+ const stampedOptions = this.stampPersonState(allProperties, options)
506
768
 
507
- super.captureStateless(distinctId, event, allProperties, options)
769
+ super.captureStateless(distinctId, event, allProperties, stampedOptions)
508
770
  })
509
771
  }
510
772
 
511
- alias(alias: string): void {
773
+ alias(alias: string, options?: PostHogCaptureOptions): void {
512
774
  this.wrap(() => {
513
775
  if (!this._requirePersonProcessing('posthog.alias')) {
514
776
  return
515
777
  }
516
778
 
517
779
  const distinctId = this.getDistinctId()
518
- const allProperties = this.enrichProperties({})
780
+ const allProperties = this.enrichIdentityProperties({}, options)
519
781
 
520
- super.aliasStateless(alias, distinctId, allProperties)
782
+ super.aliasStateless(alias, distinctId, allProperties, options)
521
783
  })
522
784
  }
523
785
 
@@ -529,17 +791,21 @@ export abstract class PostHogCore extends PostHogCoreStateless {
529
791
  ): void {
530
792
  this.wrap(() => {
531
793
  const distinctId = this.getDistinctId()
794
+ const autocaptureProperties: PostHogEventProperties = {
795
+ ...this.enrichProperties(properties, options),
796
+ $event_type: eventType,
797
+ $elements: elements,
798
+ }
799
+ const stampedOptions = this.usesLegacyEventPersonState()
800
+ ? options
801
+ : this.stampPersonState(autocaptureProperties, options)
532
802
  const payload = {
533
803
  distinct_id: distinctId,
534
804
  event: '$autocapture',
535
- properties: {
536
- ...this.enrichProperties(properties),
537
- $event_type: eventType,
538
- $elements: elements,
539
- },
805
+ properties: autocaptureProperties,
540
806
  }
541
807
 
542
- this.enqueue('autocapture', payload, options)
808
+ this.enqueue('autocapture', payload, stampedOptions)
543
809
  })
544
810
  }
545
811
 
@@ -604,7 +870,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
604
870
  }
605
871
 
606
872
  const distinctId = this.getDistinctId()
607
- const eventProperties = this.enrichProperties({})
873
+ const eventProperties = this.enrichIdentityProperties({}, options)
608
874
  super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties)
609
875
  })
610
876
  }
@@ -887,6 +1153,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
887
1153
  return this._remoteConfigResponsePromise
888
1154
  }
889
1155
 
1156
+ /** The device's IANA time zone, such as `Europe/Berlin`, sent as `timezone` on `/flags` requests. */
1157
+ protected getFlagsRequestTimezone(): string | undefined {
1158
+ return undefined
1159
+ }
1160
+
890
1161
  // An SDK can discard an obsolete result without recording it as a request failure.
891
1162
  protected getFlagsForContext(
892
1163
  ...args: Parameters<PostHogCoreStateless['getFlags']>
@@ -900,6 +1171,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
900
1171
  const triggerOnRemoteConfig = options?.triggerOnRemoteConfig ?? false
901
1172
  this._flagsResponsePromise = this._initPromise
902
1173
  .then(async () => {
1174
+ const resetCount = this._flagsResetCount
903
1175
  const distinctId = this.getDistinctId()
904
1176
  const groups = this.props.$groups || {}
905
1177
  const personProperties =
@@ -914,6 +1186,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
914
1186
  $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
915
1187
  // Only set by the React Native SDK; omitted from JSON when DeviceId is not persisted
916
1188
  $device_id: deviceId ?? undefined,
1189
+ ...maybeAdd('timezone', this.getFlagsRequestTimezone()),
917
1190
  ...(this.disableRemoteFeatureFlags ? { disable_flags: true } : {}),
918
1191
  }
919
1192
 
@@ -927,14 +1200,19 @@ export abstract class PostHogCore extends PostHogCoreStateless {
927
1200
  )
928
1201
 
929
1202
  if (result === undefined) return undefined
1203
+ // reset() ran while this request was in flight. Its flags belong to the previous identity, and
1204
+ // reset() queued a reload for the new one, so only the remote config is still used.
1205
+ const isForPreviousIdentity = resetCount !== this._flagsResetCount
930
1206
  if (!result.success) {
931
- if (!this.disableRemoteFeatureFlags) {
1207
+ if (!this.disableRemoteFeatureFlags && !isForPreviousIdentity) {
932
1208
  // Keep the persisted gate alongside the kept flags — a failed request is not a
933
1209
  // signal that the server turned minimal flag-called events off.
1210
+ const storedDetails = this.getStoredFlagDetails()
934
1211
  this.setKnownFeatureFlagDetails({
935
1212
  flags: this.getKnownFeatureFlagDetails()?.flags ?? {},
936
1213
  requestError: result.error,
937
- minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents,
1214
+ minimalFlagCalledEvents: storedDetails?.minimalFlagCalledEvents,
1215
+ noFlagsCached: !storedDetails || holdsNoCachedFlags(storedDetails),
938
1216
  })
939
1217
  }
940
1218
  return undefined
@@ -943,11 +1221,13 @@ export abstract class PostHogCore extends PostHogCoreStateless {
943
1221
  const res = result.response
944
1222
 
945
1223
  if (res?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {
946
- if (!this.disableRemoteFeatureFlags) {
1224
+ if (!this.disableRemoteFeatureFlags && !isForPreviousIdentity) {
1225
+ const storedDetails = this.getStoredFlagDetails()
947
1226
  this.setKnownFeatureFlagDetails({
948
1227
  flags: this.getKnownFeatureFlagDetails()?.flags ?? {},
949
1228
  quotaLimited: res.quotaLimited,
950
- minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents,
1229
+ minimalFlagCalledEvents: storedDetails?.minimalFlagCalledEvents,
1230
+ noFlagsCached: !storedDetails || holdsNoCachedFlags(storedDetails),
951
1231
  })
952
1232
  }
953
1233
  this._logger.warn(
@@ -957,11 +1237,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
957
1237
  return res
958
1238
  }
959
1239
  if (res?.featureFlags) {
960
- if (this.disableRemoteFeatureFlags) {
1240
+ if (this.disableRemoteFeatureFlags || isForPreviousIdentity) {
961
1241
  this.cacheSessionReplay('flags', res)
962
1242
  this.syncRemoteConfigSessionRecording(res)
963
1243
  this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res)
964
- return res
1244
+ return isForPreviousIdentity ? undefined : res
965
1245
  }
966
1246
 
967
1247
  let newFeatureFlagDetails = res
@@ -1053,8 +1333,8 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1053
1333
  return createFlagsResponseFromFlagsAndPayloads(featureFlags ?? {}, featureFlagPayloads ?? {})
1054
1334
  }
1055
1335
 
1056
- return normalizeFlagsResponse(
1057
- storedDetails as PostHogV1FlagsResponse | PostHogV2FlagsResponse
1336
+ return normalizeFlagsResponse(storedDetails as PostHogV1FlagsResponse | PostHogV2FlagsResponse, (payload) =>
1337
+ this.decodeFeatureFlagPayload(payload)
1058
1338
  ) as PostHogFeatureFlagDetails
1059
1339
  }
1060
1340
 
@@ -1062,6 +1342,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1062
1342
  return this.getPersistedProperty<PostHogFlagsStorageFormat>(PostHogPersistedProperty.FeatureFlagDetails)
1063
1343
  }
1064
1344
 
1345
+ /** Whether the latest feature flag load failed. A quota-limited response is not a failure. */
1346
+ protected didLatestFeatureFlagsLoadFail(): boolean {
1347
+ return this.getStoredFlagDetails()?.requestError !== undefined
1348
+ }
1349
+
1065
1350
  protected isMinimalFlagCalledEventsEnabled(): boolean {
1066
1351
  return this.getStoredFlagDetails()?.minimalFlagCalledEvents === true
1067
1352
  }
@@ -1101,7 +1386,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1101
1386
  if (!details) {
1102
1387
  return undefined
1103
1388
  }
1104
- return getPayloadsFromFlags(details.flags)
1389
+ return getPayloadsFromFlags(details.flags, (payload) => this.decodeFeatureFlagPayload(payload))
1105
1390
  }
1106
1391
 
1107
1392
  /**
@@ -1109,15 +1394,46 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1109
1394
  * off result; `undefined` means no evaluation is available for the key.
1110
1395
  */
1111
1396
  getFeatureFlagResult(key: string, options?: FeatureFlagResultOptions): FeatureFlagResult | undefined {
1112
- return this._getFeatureFlagResult(key, options)
1397
+ return this._getFeatureFlagResult(key, { sendEvent: resolveSendFeatureFlagEvent(options) })
1398
+ }
1399
+
1400
+ /** Decodes a flag's stored serialized payload. */
1401
+ protected decodeFeatureFlagPayload(payload: any): JsonType {
1402
+ return parsePayload(payload)
1403
+ }
1404
+
1405
+ // A v1 response carries raw payloads, so they're decoded with this client's decoder as they're read.
1406
+ protected getFlagsResponseFormat(): {
1407
+ version: 2 | 4
1408
+ read: (body: unknown) => PostHogFeatureFlagsResponse
1409
+ } {
1410
+ return {
1411
+ version: super.getFlagsResponseFormat().version,
1412
+ read: (body) =>
1413
+ normalizeFlagsResponse(body as PostHogV1FlagsResponse | PostHogV2FlagsResponse, (payload) =>
1414
+ this.decodeFeatureFlagPayload(payload)
1415
+ ),
1416
+ }
1113
1417
  }
1114
1418
 
1115
1419
  /**
1116
1420
  * Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of
1117
1421
  * the flags from the last load (no network request) and does not send a `$feature_flag_called` event.
1422
+ *
1423
+ * Returns `undefined` while no flags are cached, such as before the first successful load or when no
1424
+ * flags were bootstrapped, and a list, empty when no flags apply, once they are.
1118
1425
  */
1119
- getAllFeatureFlags(): FeatureFlagResult[] {
1120
- return flagDetailsToResults(this.getFeatureFlagDetails()?.flags ?? {})
1426
+ getAllFeatureFlags(): FeatureFlagResult[] | undefined {
1427
+ const flags = this.getFeatureFlagDetails()?.flags
1428
+ const storedDetails = this.getStoredFlagDetails()
1429
+ if (!flags || (storedDetails && holdsNoCachedFlags(storedDetails))) {
1430
+ return undefined
1431
+ }
1432
+ return flagDetailsToResults(
1433
+ flags,
1434
+ (payload) => this.decodeFeatureFlagPayload(payload),
1435
+ (value) => this.isFlagValueEnabled(value)
1436
+ )
1121
1437
  }
1122
1438
 
1123
1439
  protected _getFeatureFlagResult(
@@ -1195,8 +1511,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1195
1511
  ...maybeAdd('$feature_flag_reason', featureFlag?.reason?.description ?? featureFlag?.reason?.code),
1196
1512
  ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),
1197
1513
  ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),
1198
- // If we haven't yet received a response from the /flags endpoint, we must have used the bootstrapped value
1199
- $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),
1514
+ // If we haven't yet received a response from the /flags endpoint, we must have used the bootstrapped value.
1515
+ // Only a bootstrapped flag gets it, as in posthog-ios and posthog-android, unless legacy flag values are kept.
1516
+ ...(this.usesLegacyFlagValues() || bootstrappedResponse !== undefined
1517
+ ? { $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit) }
1518
+ : {}),
1200
1519
  ...maybeAdd('$feature_flag_request_id', details?.requestId),
1201
1520
  ...maybeAdd('$feature_flag_evaluated_at', details?.evaluatedAt),
1202
1521
  ...maybeAdd('$feature_flag_error', featureFlagError),
@@ -1223,53 +1542,23 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1223
1542
  }
1224
1543
 
1225
1544
  const rawPayload = featureFlag?.metadata?.payload
1226
- const payload = rawPayload !== undefined ? parsePayload(rawPayload) : null
1545
+ const payload = rawPayload !== undefined ? this.decodeFeatureFlagPayload(rawPayload) : null
1227
1546
  return {
1228
1547
  key,
1229
- enabled: getEnabledFromValue(flagValue),
1548
+ enabled: this.isFlagValueEnabled(flagValue),
1230
1549
  variant: getVariantFromValue(flagValue),
1231
1550
  payload,
1232
1551
  }
1233
1552
  }
1234
1553
 
1235
- /**
1236
- * Returns the current feature flag value. For backwards compatibility, a missing key can resolve
1237
- * to `false` once a non-empty flag response has been stored. Use `getFeatureFlagResult()` when
1238
- * code must distinguish a conclusive off result from an unavailable key.
1239
- */
1554
+ /** Returns the current feature flag value, or `undefined` when no evaluation is available for the key. */
1240
1555
  getFeatureFlag(key: string, options?: FeatureFlagResultOptions): FeatureFlagValue | undefined {
1241
- const result = this._getFeatureFlagResult(key, {
1242
- missingFlagBehavior: 'getFeatureFlag',
1243
- sendEvent: options?.sendEvent,
1244
- })
1556
+ const result = this._getFeatureFlagResult(key, { sendEvent: resolveSendFeatureFlagEvent(options) })
1245
1557
  return result?.variant ?? result?.enabled
1246
1558
  }
1247
1559
 
1248
- /**
1249
- * @deprecated Use `getFeatureFlagResult()` instead, which returns the flag value and payload from a single evaluation.
1250
- */
1251
- getFeatureFlagPayload(key: string): JsonType | undefined {
1252
- const result = this._getFeatureFlagResult(key, { missingFlagBehavior: 'getFeatureFlagPayload', sendEvent: false })
1253
- return result?.payload
1254
- }
1255
-
1256
- /**
1257
- * Returns the payload of every loaded flag, keyed by flag key.
1258
- *
1259
- * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
1260
- */
1261
- getFeatureFlagPayloads(): PostHogFlagsResponse['featureFlagPayloads'] | undefined {
1262
- return this.getFeatureFlagDetails()?.featureFlagPayloads
1263
- }
1264
-
1265
- /**
1266
- * Returns the value of every loaded flag, keyed by flag key.
1267
- *
1268
- * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
1269
- */
1270
- getFeatureFlags(): PostHogFlagsResponse['featureFlags'] | undefined {
1271
- // NOTE: We don't check for _initPromise here as the function is designed to be
1272
- // callable before the state being loaded anyways
1560
+ /** The value of every loaded flag, keyed by flag key, with local overrides applied. */
1561
+ protected getFeatureFlagValues(): PostHogFlagsResponse['featureFlags'] | undefined {
1273
1562
  return this.getFeatureFlagDetails()?.featureFlags
1274
1563
  }
1275
1564
 
@@ -1294,7 +1583,8 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1294
1583
  if (!overriddenFlags[key]) {
1295
1584
  delete flags[key]
1296
1585
  } else {
1297
- flags[key] = updateFlagValue(flags[key], overriddenFlags[key])
1586
+ // An override can name a flag that never loaded, which has no stored detail to take the key from.
1587
+ flags[key] = { ...updateFlagValue(flags[key], overriddenFlags[key]), key }
1298
1588
  }
1299
1589
  }
1300
1590
 
@@ -1303,31 +1593,14 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1303
1593
  flags,
1304
1594
  }
1305
1595
 
1306
- return normalizeFlagsResponse(result) as PostHogFeatureFlagDetails
1307
- }
1308
-
1309
- /**
1310
- * Returns the values and payloads of every loaded flag, as two maps keyed by flag key.
1311
- *
1312
- * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
1313
- */
1314
- getFeatureFlagsAndPayloads(): {
1315
- flags: PostHogFlagsResponse['featureFlags'] | undefined
1316
- payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined
1317
- } {
1318
- const flags = this.getFeatureFlags()
1319
- const payloads = this.getFeatureFlagPayloads()
1320
-
1321
- return {
1322
- flags,
1323
- payloads,
1324
- }
1596
+ return normalizeFlagsResponse(result, (payload) =>
1597
+ this.decodeFeatureFlagPayload(payload)
1598
+ ) as PostHogFeatureFlagDetails
1325
1599
  }
1326
1600
 
1327
1601
  /**
1328
1602
  * Returns whether the current feature flag value is enabled. When no evaluation is available,
1329
- * `defaultValue` is returned if provided; without one, the legacy missing-key behavior of
1330
- * `getFeatureFlag()` applies.
1603
+ * `defaultValue` is returned if provided; without one, `getFeatureFlag()` decides the result.
1331
1604
  */
1332
1605
  isFeatureEnabled(key: string, options: IsFeatureEnabledOptions & { defaultValue: boolean }): boolean
1333
1606
  isFeatureEnabled(key: string, options?: IsFeatureEnabledOptions): boolean | undefined
@@ -1336,7 +1609,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1336
1609
  const response = this.getFeatureFlag(key, options)
1337
1610
  return response === undefined ? undefined : !!response
1338
1611
  }
1339
- const result = this._getFeatureFlagResult(key, { sendEvent: options.sendEvent })
1612
+ const result = this._getFeatureFlagResult(key, { sendEvent: resolveSendFeatureFlagEvent(options) })
1340
1613
  const value = result?.variant ?? result?.enabled
1341
1614
  return value === undefined ? options.defaultValue : !!value
1342
1615
  }
@@ -1351,7 +1624,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1351
1624
  cb?: (err?: Error, flags?: PostHogFlagsResponse['featureFlags']) => void
1352
1625
  }): void {
1353
1626
  if (this.disableRemoteFeatureFlags && !this.disabled) {
1354
- this._initPromise.then(() => options?.cb?.(undefined, this.getFeatureFlags()))
1627
+ this._initPromise.then(() => options?.cb?.(undefined, this.getFeatureFlagValues()))
1355
1628
  return
1356
1629
  }
1357
1630
  this.flagsAsync({ sendAnonDistinctId: true })
@@ -1370,57 +1643,21 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1370
1643
  return await this.remoteConfigAsync()
1371
1644
  }
1372
1645
 
1373
- async reloadFeatureFlagsAsync(
1646
+ /** Reloads feature flags and resolves with every loaded flag's value. */
1647
+ protected async loadFeatureFlagsAsync(
1374
1648
  sendAnonDistinctId?: boolean
1375
1649
  ): Promise<PostHogFlagsResponse['featureFlags'] | undefined> {
1376
1650
  if (this.disableRemoteFeatureFlags && !this.disabled) {
1377
1651
  await this._initPromise
1378
- return this.getFeatureFlags()
1652
+ return this.getFeatureFlagValues()
1379
1653
  }
1380
1654
  return (await this.flagsAsync({ sendAnonDistinctId: sendAnonDistinctId }))?.featureFlags
1381
1655
  }
1382
1656
 
1383
- onFeatureFlags(cb: (flags: PostHogFlagsResponse['featureFlags']) => void): () => void {
1384
- return this.on('featureflags', async () => {
1385
- const flags = this.getFeatureFlags()
1386
- if (flags) {
1387
- cb(flags)
1388
- }
1389
- })
1390
- }
1391
-
1392
- /**
1393
- * Calls `cb` with the flag's value whenever flags load.
1394
- *
1395
- * @deprecated Use `onFeatureFlags()` and read the flag with `getFeatureFlagResult()` in the callback.
1396
- */
1397
- onFeatureFlag(key: string, cb: (value: FeatureFlagValue) => void): () => void {
1398
- return this.on('featureflags', async () => {
1399
- const flagResponse = this.getFeatureFlag(key)
1400
- if (flagResponse !== undefined) {
1401
- cb(flagResponse)
1402
- }
1403
- })
1404
- }
1405
-
1406
- /**
1407
- * Overrides the values of the given flags locally until cleared with `null`.
1408
- *
1409
- * @deprecated Use `updateFlags()` instead. To keep the values from being replaced by the next flags load, also set `disableRemoteFeatureFlags`.
1410
- */
1411
- async overrideFeatureFlag(flags: PostHogFlagsResponse['featureFlags'] | null): Promise<void> {
1412
- this.wrap(() => {
1413
- if (flags === null) {
1414
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null)
1415
- }
1416
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags)
1417
- })
1418
- }
1419
-
1420
1657
  /**
1421
1658
  * Replaces (or merges into) the stored feature flags and payloads with locally supplied
1422
1659
  * values, exactly as if they had been returned by the flags endpoint: the values are
1423
- * persisted, `getFeatureFlag()`/`getFeatureFlagPayload()` read them back, and
1660
+ * persisted, `getFeatureFlag()`/`getFeatureFlagResult()` read them back, and
1424
1661
  * `onFeatureFlags` listeners fire. Makes no network request.
1425
1662
  *
1426
1663
  * Intended for apps that evaluate flags outside the SDK (e.g. server-side local
@@ -1446,7 +1683,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1446
1683
  for (const key in existingDetails) {
1447
1684
  const storedPayload = existingDetails[key].metadata?.payload
1448
1685
  if (!existingDetails[key].failed && storedPayload !== undefined) {
1449
- existingPayloads[key] = parsePayload(storedPayload)
1686
+ existingPayloads[key] = this.decodeFeatureFlagPayload(storedPayload)
1450
1687
  }
1451
1688
  }
1452
1689
  const finalFlags = { ...existingFlags, ...flags }
@@ -1717,11 +1954,13 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1717
1954
  * @param userPropertiesToSetOnce - Optional: An object of properties to store about the user.
1718
1955
  * If a property is previously set, this does not override that value.
1719
1956
  * @param reloadFeatureFlags - Whether to reload feature flags after setting the properties. Defaults to true.
1957
+ * @param options - Optional capture options for the `$set` event
1720
1958
  */
1721
1959
  setPersonProperties(
1722
1960
  userPropertiesToSet?: { [key: string]: JsonType },
1723
1961
  userPropertiesToSetOnce?: { [key: string]: JsonType },
1724
- reloadFeatureFlags = true
1962
+ reloadFeatureFlags = true,
1963
+ options?: PostHogCaptureOptions
1725
1964
  ): void {
1726
1965
  this.wrap(() => {
1727
1966
  const isSetEmpty = isNullish(userPropertiesToSet) || isEmptyObject(userPropertiesToSet)
@@ -1734,10 +1973,11 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1734
1973
  return
1735
1974
  }
1736
1975
 
1737
- const hash = getPersonPropertiesHash(this.getDistinctId(), userPropertiesToSet, userPropertiesToSetOnce)
1976
+ const hash = personPropertiesHashOrNull(this.getDistinctId(), userPropertiesToSet, userPropertiesToSetOnce)
1977
+ const tracksHash = this._surelyProcessesPerson(options)
1738
1978
 
1739
1979
  // If exactly this $set call has been sent before, don't send it again - determine based on hash of properties
1740
- if (this._cachedPersonProperties === hash) {
1980
+ if (tracksHash && hash !== null && this._cachedPersonProperties === hash) {
1741
1981
  this._logger.info(
1742
1982
  'A duplicate setPersonProperties call was made with the same properties. It has been ignored.'
1743
1983
  )
@@ -1750,12 +1990,58 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1750
1990
  reloadFeatureFlags
1751
1991
  )
1752
1992
 
1753
- this.capture('$set', { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} })
1754
-
1755
- this._cachedPersonProperties = hash
1993
+ // An update that may be personless leaves the person unchanged, so it must not suppress the next one.
1994
+ this._captureWithPersonPropertiesHash(tracksHash ? hash : null, () =>
1995
+ this.capture('$set', { $set: userPropertiesToSet || {}, $set_once: userPropertiesToSetOnce || {} }, options)
1996
+ )
1756
1997
  })
1757
1998
  }
1758
1999
 
2000
+ /**
2001
+ * Whether an update with these capture options surely processes the person: its
2002
+ * `process_person_profile` option is missing, `null` or the Boolean `true`. Other values are not
2003
+ * parsed, because PostHog decides how to read them. Used to skip a duplicate before capture; the
2004
+ * event as sent decides whether the hash is recorded (see {@link _recordPersonPropertiesHash}).
2005
+ */
2006
+ private _surelyProcessesPerson(options?: PostHogCaptureOptionsWithEventOptions): boolean {
2007
+ const eventOptions: unknown = options?.options
2008
+ const setting: unknown = isObject(eventOptions) ? eventOptions.process_person_profile : undefined
2009
+ return isNullish(setting) || setting === true
2010
+ }
2011
+
2012
+ // Runs `capture`, which captures one person-properties update synchronously, so the update's hash is recorded
2013
+ // or cleared once it is queued. An update that `before_send` drops, or that isn't queued, leaves the hash alone.
2014
+ private _captureWithPersonPropertiesHash(hash: string | null, capture: () => void): void {
2015
+ this._pendingPersonPropertiesHash = hash
2016
+ try {
2017
+ capture()
2018
+ } finally {
2019
+ this._pendingPersonPropertiesHash = undefined
2020
+ }
2021
+ }
2022
+
2023
+ /**
2024
+ * Records the pending hash from the update as sent, after `before_send`, or clears the stored one. The update
2025
+ * surely processes the person when it keeps its name and its distinct id, `$set` and `$set_once`, and its
2026
+ * `process_person_profile` option (or, when that is missing or null, its `$process_person_profile` property)
2027
+ * is missing, null or the Boolean `true`.
2028
+ */
2029
+ private _recordPersonPropertiesHash(
2030
+ captured: { hash: string | null; event: unknown; payloadHash: string | null },
2031
+ sent: PostHogEventProperties
2032
+ ): void {
2033
+ const option = isObject(sent.options) ? (sent.options as PostHogEventProperties).process_person_profile : undefined
2034
+ const properties = (isObject(sent.properties) ? sent.properties : {}) as PostHogEventProperties
2035
+ const setting = isNullish(option) ? properties.$process_person_profile : option
2036
+ const surelyProcessesPerson =
2037
+ captured.hash !== null &&
2038
+ sent.event === captured.event &&
2039
+ (isNullish(setting) || setting === true) &&
2040
+ captured.payloadHash !== null &&
2041
+ sentPersonPropertiesHash(sent) === captured.payloadHash
2042
+ this._cachedPersonProperties = surelyProcessesPerson ? captured.hash : null
2043
+ }
2044
+
1759
2045
  /**
1760
2046
  * Removes properties from the person profile associated with the current `distinct_id`.
1761
2047
  * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)
@@ -1784,8 +2070,13 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1784
2070
  *
1785
2071
  * @param propertyNames - The name (or names) of the person properties to remove.
1786
2072
  * @param reloadFeatureFlags - Whether to reload feature flags after removing the properties. Defaults to true.
2073
+ * @param options - Optional capture options for the `$set` event
1787
2074
  */
1788
- unsetPersonProperties(propertyNames: string | string[], reloadFeatureFlags = true): void {
2075
+ unsetPersonProperties(
2076
+ propertyNames: string | string[],
2077
+ reloadFeatureFlags = true,
2078
+ options?: PostHogCaptureOptions
2079
+ ): void {
1789
2080
  this.wrap(() => {
1790
2081
  const names = (isArray(propertyNames) ? propertyNames : [propertyNames]).filter(
1791
2082
  (name) => isString(name) && name.length > 0
@@ -1812,7 +2103,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1812
2103
  this.reloadFeatureFlags()
1813
2104
  }
1814
2105
 
1815
- this.capture('$set', { $unset: names })
2106
+ this.capture('$set', { $unset: names }, options)
1816
2107
 
1817
2108
  // Invalidate the setPersonProperties dedupe cache so a subsequent set of an unset
1818
2109
  // property is not skipped as a duplicate.
@@ -1829,10 +2120,24 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1829
2120
  * queued messages; type is a no-op, while library and library_version are only used as fallbacks
1830
2121
  * for the official properties.$lib and properties.$lib_version fields.
1831
2122
  * CaptureEvent exposes a subset matching the web SDK's
1832
- * CaptureResult: uuid, event, properties, $set, $set_once, timestamp.
2123
+ * CaptureResult: uuid, event, properties, $set, $set_once, timestamp, plus options when the event has them.
1833
2124
  * Note: $set/$set_once are extracted from properties.$set and properties.$set_once.
1834
2125
  */
1835
2126
  protected processBeforeEnqueue(message: PostHogEventProperties): PostHogEventProperties | null {
2127
+ // Taken first, so a capture nested in `before_send` never records it.
2128
+ const hash = this._pendingPersonPropertiesHash
2129
+ this._pendingPersonPropertiesHash = undefined
2130
+ // Read before `before_send`, which can change the message in place.
2131
+ const captured =
2132
+ hash === undefined ? undefined : { hash, event: message.event, payloadHash: sentPersonPropertiesHash(message) }
2133
+ const result = this._runBeforeSendOnMessage(message)
2134
+ if (result && captured) {
2135
+ this._recordPersonPropertiesHash(captured, result)
2136
+ }
2137
+ return result
2138
+ }
2139
+
2140
+ private _runBeforeSendOnMessage(message: PostHogEventProperties): PostHogEventProperties | null {
1836
2141
  if (!this._beforeSend) {
1837
2142
  return message
1838
2143
  }
@@ -1849,6 +2154,9 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1849
2154
  // Convert timestamp to Date if it's a string (from currentISOTime())
1850
2155
  timestamp: typeof timestamp === 'string' ? new Date(timestamp) : (timestamp as unknown as Date | undefined),
1851
2156
  }
2157
+ if (message.options !== undefined) {
2158
+ captureEvent.options = message.options as CaptureEvent['options']
2159
+ }
1852
2160
 
1853
2161
  const result = this._runBeforeSend(captureEvent)
1854
2162
 
@@ -1876,6 +2184,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1876
2184
  event: result.event,
1877
2185
  properties: resultProps,
1878
2186
  timestamp: result.timestamp as unknown as JsonType,
2187
+ ...(result.options !== undefined ? { options: result.options as JsonType } : {}),
1879
2188
  }
1880
2189
  }
1881
2190
 
@@ -1902,7 +2211,9 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1902
2211
  return null
1903
2212
  }
1904
2213
  } catch (e) {
1905
- this._logger.error(`Error in before_send function for event '${captureEvent.event}':`, e)
2214
+ // The error's message can carry the data the hook was redacting, so only its type is logged.
2215
+ const errorType = e instanceof Error ? e.name : typeof e
2216
+ this._logger.error(`Error in before_send function for event '${captureEvent.event}' (${errorType})`)
1906
2217
  return null
1907
2218
  }
1908
2219
  }
@@ -1910,3 +2221,129 @@ export abstract class PostHogCore extends PostHogCoreStateless {
1910
2221
  return result
1911
2222
  }
1912
2223
  }
2224
+
2225
+ /** The PostHog client core, including the deprecated feature flag getters. */
2226
+ export abstract class PostHogCore extends PostHogCoreBase {
2227
+ protected usesLegacyEventPersonState(): boolean {
2228
+ return true
2229
+ }
2230
+
2231
+ protected usesLegacyEventPropertyOrder(): boolean {
2232
+ return true
2233
+ }
2234
+
2235
+ protected usesLegacyFlagValues(): boolean {
2236
+ return true
2237
+ }
2238
+
2239
+ async reloadFeatureFlagsAsync(
2240
+ sendAnonDistinctId?: boolean
2241
+ ): Promise<PostHogFlagsResponse['featureFlags'] | undefined> {
2242
+ return this.loadFeatureFlagsAsync(sendAnonDistinctId)
2243
+ }
2244
+
2245
+ /**
2246
+ * Returns all currently cached feature flags as `FeatureFlagResult`s, with local overrides applied, or an
2247
+ * empty list while none are cached. This is a synchronous read of the flags from the last load (no network
2248
+ * request) and does not send a `$feature_flag_called` event.
2249
+ */
2250
+ getAllFeatureFlags(): FeatureFlagResult[] {
2251
+ return flagDetailsToResults(this.getFeatureFlagDetails()?.flags ?? {})
2252
+ }
2253
+
2254
+ onFeatureFlags(cb: (flags: PostHogFlagsResponse['featureFlags']) => void): () => void {
2255
+ return this.on('featureflags', async () => {
2256
+ const flags = this.getFeatureFlagValues()
2257
+ if (flags) {
2258
+ cb(flags)
2259
+ }
2260
+ })
2261
+ }
2262
+
2263
+ /**
2264
+ * Returns the current feature flag value. For backwards compatibility, a missing key can resolve
2265
+ * to `false` once a non-empty flag response has been stored. Use `getFeatureFlagResult()` when
2266
+ * code must distinguish a conclusive off result from an unavailable key.
2267
+ */
2268
+ getFeatureFlag(key: string, options?: FeatureFlagResultOptions): FeatureFlagValue | undefined {
2269
+ const result = this._getFeatureFlagResult(key, {
2270
+ missingFlagBehavior: 'getFeatureFlag',
2271
+ sendEvent: resolveSendFeatureFlagEvent(options),
2272
+ })
2273
+ return result?.variant ?? result?.enabled
2274
+ }
2275
+
2276
+ /**
2277
+ * @deprecated Use `getFeatureFlagResult()` instead, which returns the flag value and payload from a single evaluation.
2278
+ */
2279
+ getFeatureFlagPayload(key: string): JsonType | undefined {
2280
+ const result = this._getFeatureFlagResult(key, { missingFlagBehavior: 'getFeatureFlagPayload', sendEvent: false })
2281
+ return result?.payload
2282
+ }
2283
+
2284
+ /**
2285
+ * Returns the payload of every loaded flag, keyed by flag key.
2286
+ *
2287
+ * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
2288
+ */
2289
+ getFeatureFlagPayloads(): PostHogFlagsResponse['featureFlagPayloads'] | undefined {
2290
+ return this.getFeatureFlagDetails()?.featureFlagPayloads
2291
+ }
2292
+
2293
+ /**
2294
+ * Returns the value of every loaded flag, keyed by flag key.
2295
+ *
2296
+ * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
2297
+ */
2298
+ getFeatureFlags(): PostHogFlagsResponse['featureFlags'] | undefined {
2299
+ // NOTE: We don't check for _initPromise here as the function is designed to be
2300
+ // callable before the state being loaded anyways
2301
+ return this.getFeatureFlagDetails()?.featureFlags
2302
+ }
2303
+
2304
+ /**
2305
+ * Returns the values and payloads of every loaded flag, as two maps keyed by flag key.
2306
+ *
2307
+ * @deprecated Use `getAllFeatureFlags()` instead, which returns each flag's value and payload together.
2308
+ */
2309
+ getFeatureFlagsAndPayloads(): {
2310
+ flags: PostHogFlagsResponse['featureFlags'] | undefined
2311
+ payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined
2312
+ } {
2313
+ const flags = this.getFeatureFlags()
2314
+ const payloads = this.getFeatureFlagPayloads()
2315
+
2316
+ return {
2317
+ flags,
2318
+ payloads,
2319
+ }
2320
+ }
2321
+
2322
+ /**
2323
+ * Calls `cb` with the flag's value whenever flags load.
2324
+ *
2325
+ * @deprecated Use `onFeatureFlags()` and read the flag with `getFeatureFlagResult()` in the callback.
2326
+ */
2327
+ onFeatureFlag(key: string, cb: (value: FeatureFlagValue) => void): () => void {
2328
+ return this.on('featureflags', async () => {
2329
+ const flagResponse = this.getFeatureFlag(key)
2330
+ if (flagResponse !== undefined) {
2331
+ cb(flagResponse)
2332
+ }
2333
+ })
2334
+ }
2335
+
2336
+ /**
2337
+ * Overrides the values of the given flags locally until cleared with `null`.
2338
+ *
2339
+ * @deprecated Use `updateFlags()` instead. To keep the values from being replaced by the next flags load, also set `disableRemoteFeatureFlags`.
2340
+ */
2341
+ async overrideFeatureFlag(flags: PostHogFlagsResponse['featureFlags'] | null): Promise<void> {
2342
+ this.wrap(() => {
2343
+ if (flags === null) {
2344
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null)
2345
+ }
2346
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags)
2347
+ })
2348
+ }
2349
+ }