posthog-node 5.72.0 → 5.73.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.
package/src/client.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  PostHogEventProperties,
15
15
  PostHogFetchOptions,
16
16
  PostHogFetchResponse,
17
+ PostHogFeatureFlagsResponse,
17
18
  PostHogFlagsAndPayloadsResponse,
18
19
  PostHogFlagsResponse,
19
20
  PostHogMetrics,
@@ -66,6 +67,20 @@ import {
66
67
  FeatureFlagEvaluationsHost,
67
68
  FlagCalledEventParams,
68
69
  } from './feature-flag-evaluations'
70
+ import {
71
+ FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE,
72
+ isUnreadableFlagRecord,
73
+ ParsedFlagRecord,
74
+ parsedFlagRecordOf,
75
+ readFlagRecords,
76
+ } from './flags-response'
77
+ import {
78
+ applyFlagEventCapture,
79
+ buildConfigVersion2FlagEvents,
80
+ FlagEvent,
81
+ FlagEventCapture,
82
+ minimizeConfigVersion2FlagCalledProperties,
83
+ } from './flag-events'
69
84
  import {
70
85
  type FeatureFlagEvaluationContext,
71
86
  FeatureFlagsPoller,
@@ -97,6 +112,18 @@ const WAITUNTIL_DEBOUNCE_MS = 50
97
112
  const WAITUNTIL_MAX_WAIT_MS = 500
98
113
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com'
99
114
 
115
+ // Internal options of one event's trip through the capture pipeline.
116
+ type PrepareEventOptions = {
117
+ includeContextProperties?: boolean
118
+ /** How a config version 2 flag event fixes its properties; see `flag-events.ts`. */
119
+ flagEvent?: FlagEventCapture
120
+ /**
121
+ * Called when capture fails: `before_send` throws, or the event cannot be prepared or queued.
122
+ * Not called when `before_send` discards the event.
123
+ */
124
+ onCaptureFailed?: () => void
125
+ }
126
+
100
127
  // Process-wide dedup for deprecation warnings — without this, calling a deprecated
101
128
  // method in a loop would spam logs. Matches Python's `warnings.warn` default-dedup behavior.
102
129
  const _emittedDeprecations = new Set<string>()
@@ -202,10 +229,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
202
229
  // flag-definition loads) — both derive from the same per-team server config and converge.
203
230
  private _minimalFlagCalledEvents: boolean = false
204
231
 
232
+ // Whether this client has logged that /flags sent records without typed values.
233
+ private _loggedFlagsResponseWithoutTypedValues = false
234
+
205
235
  // Insertion-ordered LRU of the `$feature_flag_called` keys already reported per distinct id.
206
236
  // Map iteration order is insertion order, so the first entry is always the least recently used.
207
237
  private _distinctIdHasSentFlagCalls: Map<string, Set<string>>
208
238
 
239
+ // The `$experiment_exposure` keys already reported per distinct id, kept apart from the
240
+ // `$feature_flag_called` keys so that a reported call never suppresses its exposure. Same bound
241
+ // and eviction. Shutdown clears it.
242
+ private _experimentExposuresReported: Map<string, Set<string>> = new Map()
243
+
209
244
  /**
210
245
  * Snapshot of the `$feature_flag_called` dedupe state, keyed by distinct id.
211
246
  * Adding or deleting keys on the returned object does not affect deduplication;
@@ -1055,6 +1090,32 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1055
1090
  return 'server'
1056
1091
  }
1057
1092
 
1093
+ /**
1094
+ * posthog-node and posthog-edge request the v4 `/flags` response, which carries one typed
1095
+ * value per flag plus its reason and rule metadata. A server that does not serve v4 answers
1096
+ * with the older record, which is read as before. Other SDKs on the shared core keep `v=2`.
1097
+ *
1098
+ * The reader reads each flag record into its legacy rendering and keeps the parsed record,
1099
+ * then reads the rest of the response with the shared reader.
1100
+ */
1101
+ protected override getFlagsResponseFormat(): {
1102
+ version: 4
1103
+ read: (body: unknown) => PostHogFeatureFlagsResponse
1104
+ } {
1105
+ const shared = super.getFlagsResponseFormat()
1106
+ return {
1107
+ version: 4,
1108
+ read: (response) => {
1109
+ const { body, withoutTypedValues } = readFlagRecords(response)
1110
+ if (withoutTypedValues && !this._loggedFlagsResponseWithoutTypedValues) {
1111
+ this._loggedFlagsResponseWithoutTypedValues = true
1112
+ this._logger.info(FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE)
1113
+ }
1114
+ return shared.read(body)
1115
+ },
1116
+ }
1117
+ }
1118
+
1058
1119
  /**
1059
1120
  * Returns the common properties attached to every captured event.
1060
1121
  *
@@ -1161,12 +1222,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1161
1222
  type: string,
1162
1223
  props: EventMessage,
1163
1224
  immediate: boolean,
1164
- prepareOptions?: { includeContextProperties?: boolean },
1225
+ prepareOptions?: PrepareEventOptions,
1165
1226
  explicitRoute?: string
1166
1227
  ): Promise<void> {
1167
1228
  return this.addPendingPromise(
1168
1229
  this._prepareEventMessage(props, prepareOptions)
1169
1230
  .then(({ distinctId, event, properties, options }) => {
1231
+ // The queue drops the event without an error when the client was disabled or opted out
1232
+ // while the event was prepared, so a flag event's dedupe key is released here.
1233
+ if (this.disabled || this.optedOut) {
1234
+ prepareOptions?.onCaptureFailed?.()
1235
+ }
1170
1236
  const captureOptions: PostHogCaptureOptions = {
1171
1237
  timestamp: options.timestamp,
1172
1238
  disableGeoip: options.disableGeoip,
@@ -1185,8 +1251,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1185
1251
  : this.enqueue(type, message, captureOptions, explicitRoute)
1186
1252
  })
1187
1253
  .catch((err) => {
1254
+ // A `before_send` discard rejects with null; it is not a failure.
1188
1255
  if (err) {
1189
1256
  console.error(err)
1257
+ prepareOptions?.onCaptureFailed?.()
1190
1258
  }
1191
1259
  })
1192
1260
  )
@@ -1772,6 +1840,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1772
1840
  let flagVersion: number | undefined = undefined
1773
1841
  let flagReason: string | undefined = undefined
1774
1842
  let flagHasExperiment: boolean | undefined = undefined
1843
+ // The parsed /flags record when it supplied the result. Only such a read can carry config
1844
+ // version 2 attribution and send $experiment_exposure.
1845
+ let flagRecord: ParsedFlagRecord | undefined = undefined
1775
1846
 
1776
1847
  // Try local evaluation first
1777
1848
  const localEvaluationEnabled = this.featureFlagsPoller !== undefined
@@ -1869,9 +1940,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1869
1940
  reason: flagReason,
1870
1941
  reasonCode: flagDetail.reason?.code,
1871
1942
  }
1943
+ flagRecord = parsedFlagRecordOf(flagDetail)
1872
1944
  }
1873
1945
 
1874
- if (errors.length > 0) {
1946
+ if (flagDetail !== undefined && isUnreadableFlagRecord(flagDetail)) {
1947
+ // The record had a known field with the wrong JSON type, so the flag reads as disabled.
1948
+ // A single-flag read reports what a failed /flags request reports: an unknown error
1949
+ // and no request details.
1950
+ featureFlagError = FeatureFlagError.UNKNOWN_ERROR
1951
+ requestId = undefined
1952
+ evaluatedAt = undefined
1953
+ } else if (errors.length > 0) {
1875
1954
  featureFlagError = errors.join(',')
1876
1955
  }
1877
1956
  }
@@ -1914,6 +1993,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1914
1993
  groups,
1915
1994
  disableGeoip,
1916
1995
  properties,
1996
+ record: flagRecord,
1917
1997
  })
1918
1998
  }
1919
1999
 
@@ -2475,10 +2555,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2475
2555
  *
2476
2556
  * **Exposure events.** `isEnabled()` and `getFlag()` send a `$feature_flag_called` event the
2477
2557
  * first time each flag value is read for a user. Experiments use these events as exposures.
2558
+ * When a remotely evaluated config version 2 flag assigns an experiment variant, the read also
2559
+ * sends `$experiment_exposure`, once per user, groups, flag, rule and variant.
2478
2560
  * The client's `sendFeatureFlagEvent` option sets the default for these reads. Pass
2479
2561
  * `{ sendFeatureFlagEvents: true }` or `{ sendFeatureFlagEvents: false }` to a read to override
2480
2562
  * it, so one snapshot can serve both experiment flags and flags that should send no events.
2481
- * `getFlagPayload()` never sends events.
2563
+ * The option governs both events. `getFlagPayload()` never sends events.
2482
2564
  *
2483
2565
  * **Trim the request.** Pass `flagKeys` to scope local evaluation, the underlying
2484
2566
  * `/flags` request, and the returned snapshot to a subset of flags. Remote evaluation
@@ -2673,6 +2755,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2673
2755
  reason: detail.reason?.description ?? detail.reason?.code,
2674
2756
  locallyEvaluated: false,
2675
2757
  hasExperiment: detail.metadata?.has_experiment,
2758
+ parsed: parsedFlagRecordOf(detail),
2676
2759
  }
2677
2760
  }
2678
2761
  }
@@ -2703,6 +2786,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2703
2786
  for (const [key, payload] of Object.entries(this._payloadOverrides)) {
2704
2787
  const existing = records[key]
2705
2788
  if (existing) {
2789
+ // A payload override keeps the parsed record, because the record still supplied the
2790
+ // flag's value. A value override, above, drops it.
2706
2791
  records[key] = { ...existing, payload }
2707
2792
  }
2708
2793
  }
@@ -2755,50 +2840,142 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2755
2840
  }
2756
2841
 
2757
2842
  /**
2758
- * Fires a `$feature_flag_called` event for the given flag if the (distinctId, flag, response)
2759
- * triple hasn't already been reported for this client. Shared by the single-flag evaluation
2760
- * path and `FeatureFlagEvaluations.isEnabled() / getFlag()` so both paths dedupe identically.
2843
+ * Sends the flag events of a flag read: `$feature_flag_called` and, for a config version 2
2844
+ * experiment split, `$experiment_exposure`. Shared by the single-flag evaluation path and
2845
+ * `FeatureFlagEvaluations.isEnabled() / getFlag()` so both paths report and dedupe identically.
2846
+ *
2847
+ * `$feature_flag_called` is sent if the (distinctId, flag, response, groups) tuple hasn't already
2848
+ * been reported for this client. When `params.record` is a config version 2 record, both events
2849
+ * are built from it in one step (see `flag-events.ts`): the call gains the record's attribution
2850
+ * and its tuple gains the attribution too, and a complete experiment split also sends
2851
+ * `$experiment_exposure`, deduped in its own namespace. Config version 1 events are sent and
2852
+ * deduped as before.
2761
2853
  *
2762
2854
  * @internal
2763
2855
  */
2764
2856
  protected _captureFlagCalledEventIfNeeded(params: FlagCalledEventParams): void {
2765
- const { distinctId, key, response, groups, disableGeoip, properties } = params
2857
+ const { distinctId, key, response, groups, disableGeoip, properties, record } = params
2858
+
2859
+ const configVersion2Events = buildConfigVersion2FlagEvents({ key, response, groups, properties, record })
2860
+ if (configVersion2Events !== undefined) {
2861
+ // Each event is attempted on its own, so a failed capture of one does not stop the other.
2862
+ this._captureFlagEventOnce(this._distinctIdHasSentFlagCalls, distinctId, configVersion2Events.flagCalled, params)
2863
+ if (configVersion2Events.exposure !== undefined) {
2864
+ // Keyed by the distinct id as the event carries it, a string.
2865
+ this._captureFlagEventOnce(
2866
+ this._experimentExposuresReported,
2867
+ String(distinctId),
2868
+ configVersion2Events.exposure,
2869
+ params
2870
+ )
2871
+ }
2872
+ return
2873
+ }
2874
+
2766
2875
  const groupSuffix =
2767
2876
  groups && Object.keys(groups).length > 0
2768
2877
  ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))}`
2769
2878
  : ''
2770
2879
  const featureFlagReportedKey = `${key}_${response}${groupSuffix}`
2771
2880
 
2772
- const reported = this._distinctIdHasSentFlagCalls.get(distinctId) ?? new Set<string>()
2881
+ if (this._reserveFlagEventKey(this._distinctIdHasSentFlagCalls, distinctId, featureFlagReportedKey) === undefined) {
2882
+ return
2883
+ }
2884
+
2885
+ this.capture({
2886
+ distinctId,
2887
+ event: '$feature_flag_called',
2888
+ properties,
2889
+ groups,
2890
+ disableGeoip,
2891
+ })
2892
+ }
2893
+
2894
+ /**
2895
+ * Adds `key` to the keys reported for `distinctId` unless it is there already, and returns the
2896
+ * set that now holds it, or `undefined` when the event was already reported or is being
2897
+ * captured. Node runs one read at a time, so the check and the add are one step.
2898
+ *
2899
+ * The cache is an LRU of distinct ids: each call moves `distinctId` to the most recently used
2900
+ * end, and adding a key evicts only the least recently used distinct ids. Clearing the whole
2901
+ * cache under capacity pressure would re-send events for every active user at once. The current
2902
+ * id is always kept, even when maxCacheSize is below 1.
2903
+ */
2904
+ private _reserveFlagEventKey(
2905
+ cache: Map<string, Set<string>>,
2906
+ distinctId: string,
2907
+ key: string
2908
+ ): Set<string> | undefined {
2909
+ const reported = cache.get(distinctId) ?? new Set<string>()
2773
2910
 
2774
2911
  // Re-insert so the distinct id moves to the most-recently-used end of the map.
2775
- this._distinctIdHasSentFlagCalls.delete(distinctId)
2776
- this._distinctIdHasSentFlagCalls.set(distinctId, reported)
2912
+ cache.delete(distinctId)
2913
+ cache.set(distinctId, reported)
2777
2914
 
2778
- if (reported.has(featureFlagReportedKey)) {
2779
- return
2915
+ if (reported.has(key)) {
2916
+ return undefined
2780
2917
  }
2781
2918
 
2782
- reported.add(featureFlagReportedKey)
2919
+ reported.add(key)
2783
2920
 
2784
- // Evict only the least recently used distinct ids. Clearing the whole tracker under capacity
2785
- // pressure would re-send `$feature_flag_called` for every active user at once. The current id
2786
- // is always kept, even when maxCacheSize is below 1.
2787
- while (this._distinctIdHasSentFlagCalls.size > Math.max(this.maxCacheSize, 1)) {
2788
- const lruDistinctId = this._distinctIdHasSentFlagCalls.keys().next().value
2921
+ while (cache.size > Math.max(this.maxCacheSize, 1)) {
2922
+ const lruDistinctId = cache.keys().next().value
2789
2923
  if (lruDistinctId === undefined) {
2790
2924
  break
2791
2925
  }
2792
- this._distinctIdHasSentFlagCalls.delete(lruDistinctId)
2926
+ cache.delete(lruDistinctId)
2793
2927
  }
2928
+ return reported
2929
+ }
2794
2930
 
2795
- this.capture({
2796
- distinctId,
2797
- event: '$feature_flag_called',
2798
- properties,
2799
- groups,
2800
- disableGeoip,
2801
- })
2931
+ /**
2932
+ * Captures one config version 2 flag event, once per key in `cache`.
2933
+ *
2934
+ * The key is reserved before capture and stays reserved while capture runs, so a read during
2935
+ * capture does not send the event again. It is released when capture fails, so a later read
2936
+ * sends the event: the capture call throws, the client is disabled or opted out (also while the
2937
+ * event is prepared), `before_send` throws, or the event cannot be prepared or queued. An event that `before_send` discards keeps
2938
+ * its key: the application chose to drop it, and later reads would be dropped the same way.
2939
+ * A failure is logged and never reaches the read.
2940
+ */
2941
+ private _captureFlagEventOnce(
2942
+ cache: Map<string, Set<string>>,
2943
+ distinctId: string,
2944
+ flagEvent: FlagEvent,
2945
+ params: FlagCalledEventParams
2946
+ ): void {
2947
+ const reported = this._reserveFlagEventKey(cache, distinctId, flagEvent.dedupeKey)
2948
+ if (reported === undefined) {
2949
+ return
2950
+ }
2951
+ let released = false
2952
+ const release = (): void => {
2953
+ if (!released) {
2954
+ released = true
2955
+ reported.delete(flagEvent.dedupeKey)
2956
+ }
2957
+ }
2958
+ try {
2959
+ if (this.disabled || this.optedOut) {
2960
+ release()
2961
+ return
2962
+ }
2963
+ void this._sendPreparedEvent(
2964
+ 'capture',
2965
+ {
2966
+ distinctId: params.distinctId,
2967
+ event: flagEvent.event,
2968
+ properties: flagEvent.properties,
2969
+ groups: params.groups,
2970
+ disableGeoip: params.disableGeoip,
2971
+ },
2972
+ false,
2973
+ { flagEvent: flagEvent.capture, onCaptureFailed: release }
2974
+ )
2975
+ } catch (error) {
2976
+ this._logger.error(`[FEATURE FLAGS] Failed to capture ${flagEvent.event}:`, error)
2977
+ release()
2978
+ }
2802
2979
  }
2803
2980
 
2804
2981
  /**
@@ -3171,11 +3348,28 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3171
3348
  // Logs drain alongside the other pipelines rather than ahead of them, so a stalled
3172
3349
  // logs endpoint can't spend the budget traces and events need.
3173
3350
  const logs = this._logs
3351
+ let logsDrainStopped = false
3352
+ const oldestQueuedLog = (): unknown =>
3353
+ (this.getPersistedProperty(PostHogPersistedProperty.LogsQueue) as unknown[] | undefined)?.[0]
3354
+ // One flush only sends what was queued when it started, so records logged while it was in
3355
+ // flight (a SIGTERM handler logging after calling shutdown) need another pass. Stops once a
3356
+ // pass leaves the oldest record in place (the endpoint is down), the race below has ended, or
3357
+ // the deadline has passed. The deadline check matters when every pass resolves without yielding
3358
+ // to timers (a fetch that logs each request), since the race's timeout could then never fire.
3359
+ const drainLogs = async (pipeline: PostHogLogs): Promise<void> => {
3360
+ let oldest = oldestQueuedLog()
3361
+ while (oldest !== undefined && !logsDrainStopped && Date.now() < shutdownDeadlineMs) {
3362
+ await pipeline.flush().catch(() => {})
3363
+ const next = oldestQueuedLog()
3364
+ if (next === oldest) {
3365
+ return
3366
+ }
3367
+ oldest = next
3368
+ }
3369
+ }
3174
3370
  const logsDrained = logs
3175
- ? raceWithTimeout(
3176
- logs.flush().catch(() => {}),
3177
- Math.max(0, shutdownDeadlineMs - Date.now())
3178
- ).then(() => {
3371
+ ? raceWithTimeout(drainLogs(logs), Math.max(0, shutdownDeadlineMs - Date.now())).then(() => {
3372
+ logsDrainStopped = true
3179
3373
  logs.reset()
3180
3374
  // Retire a flush that lost the race: otherwise, when it settles with records
3181
3375
  // left, its background retry re-arms the timer and keeps sending after shutdown.
@@ -3220,6 +3414,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3220
3414
  await emailsSettled
3221
3415
  await logsDrained
3222
3416
  this._distinctIdHasSentFlagCalls.clear()
3417
+ this._experimentExposuresReported.clear()
3223
3418
  resolve?.()
3224
3419
  }
3225
3420
  }
@@ -3556,7 +3751,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3556
3751
 
3557
3752
  private async _prepareEventMessage(
3558
3753
  props: EventMessage,
3559
- options: { includeContextProperties?: boolean } = {}
3754
+ options: PrepareEventOptions = {}
3560
3755
  ): Promise<{
3561
3756
  distinctId: string
3562
3757
  event: string
@@ -3602,26 +3797,37 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3602
3797
  mergedProperties.$session_id = contextData.sessionId
3603
3798
  }
3604
3799
 
3800
+ // A config version 2 flag event fixes its attribution after super and context properties are
3801
+ // merged, so neither can change it or add a field the event never carries.
3802
+ const flagEvent = options.flagEvent
3803
+ const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties
3804
+
3605
3805
  // Minimal $feature_flag_called events: rebuild from the strict allowlist before before_send
3606
3806
  // runs, so a customer hook may deliberately re-add stripped properties. Everything the SDK
3607
3807
  // itself adds after this point ($groups, $lib/$lib_version/$is_server, $geoip_disable) is
3608
- // allowlisted — no SDK enrichment may reintroduce stripped properties.
3609
- const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties)
3610
- ? minimizeFlagCalledEventProperties(mergedProperties)
3611
- : mergedProperties
3808
+ // allowlisted — no SDK enrichment may reintroduce stripped properties. A config version 2
3809
+ // event also keeps its attribution.
3810
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties)
3811
+ ? flagEvent
3812
+ ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties)
3813
+ : minimizeFlagCalledEventProperties(enrichedProperties)
3814
+ : enrichedProperties
3612
3815
 
3613
3816
  // Run before_send if configured
3614
- const eventMessage = this._runBeforeSend({
3615
- distinctId: mergedDistinctId,
3616
- event,
3617
- properties: finalProperties,
3618
- groups,
3619
- flags,
3620
- sendFeatureFlags,
3621
- timestamp,
3622
- disableGeoip,
3623
- uuid,
3624
- })
3817
+ const eventMessage = this._runBeforeSend(
3818
+ {
3819
+ distinctId: mergedDistinctId,
3820
+ event,
3821
+ properties: finalProperties,
3822
+ groups,
3823
+ flags,
3824
+ sendFeatureFlags,
3825
+ timestamp,
3826
+ disableGeoip,
3827
+ uuid,
3828
+ },
3829
+ options.onCaptureFailed
3830
+ )
3625
3831
 
3626
3832
  if (!eventMessage) {
3627
3833
  return Promise.reject(null)
@@ -3709,7 +3915,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3709
3915
  }
3710
3916
  }
3711
3917
 
3712
- private _runBeforeSend(eventMessage: EventMessage): EventMessage | null {
3918
+ // `onError` is called when a hook throws. A hook that returns null discards the event, which
3919
+ // is not an error.
3920
+ private _runBeforeSend(eventMessage: EventMessage, onError?: () => void): EventMessage | null {
3713
3921
  const beforeSend = this.options.before_send
3714
3922
  if (!beforeSend) {
3715
3923
  return eventMessage
@@ -3731,6 +3939,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3731
3939
  }
3732
3940
  } catch (error) {
3733
3941
  this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error)
3942
+ onError?.()
3734
3943
  return null
3735
3944
  }
3736
3945
  }
@@ -1,5 +1,6 @@
1
1
  import { FeatureFlagValue, JsonType, UnresolvedFlagReason } from '@posthog/core'
2
2
 
3
+ import type { ParsedFlagRecord } from './flags-response'
3
4
  import { FeatureFlagError } from './types'
4
5
 
5
6
  /**
@@ -19,6 +20,12 @@ export type EvaluatedFlagRecord = {
19
20
  locallyEvaluated: boolean
20
21
  /** Whether the flag is linked to an experiment; undefined when the server did not report it. */
21
22
  hasExperiment: boolean | undefined
23
+ /**
24
+ * The parsed `/flags` record of a remotely evaluated flag, with its typed value, failure
25
+ * state, reason and rule metadata, for the typed flag API and flag events. Absent for locally
26
+ * evaluated flags and flags with a value override.
27
+ */
28
+ parsed?: ParsedFlagRecord
22
29
  }
23
30
 
24
31
  /**
@@ -33,6 +40,13 @@ export type FlagCalledEventParams = {
33
40
  groups: Record<string, string | number> | undefined
34
41
  disableGeoip: boolean | undefined
35
42
  properties: Record<string, any>
43
+ /**
44
+ * The parsed `/flags` record that supplied the read's value. Absent when the value came from
45
+ * local evaluation or an override, or the flag is missing. A config version 2 record adds its
46
+ * attribution to `$feature_flag_called`, and a complete experiment split also sends
47
+ * `$experiment_exposure`.
48
+ */
49
+ record?: ParsedFlagRecord
36
50
  }
37
51
 
38
52
  /**
@@ -375,6 +389,9 @@ export class FeatureFlagEvaluations {
375
389
  groups: this._groups,
376
390
  disableGeoip: this._disableGeoip,
377
391
  properties,
392
+ // The record that supplied the value. A remotely evaluated experiment split also sends
393
+ // $experiment_exposure.
394
+ record: flag?.parsed,
378
395
  })
379
396
  }
380
397
  }