posthog-node 5.73.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/MIGRATION.md +556 -0
  2. package/README.md +3 -1
  3. package/dist/ai-capture/routing.d.ts +0 -3
  4. package/dist/ai-capture/routing.d.ts.map +1 -1
  5. package/dist/ai-capture/routing.js +2 -14
  6. package/dist/ai-capture/routing.mjs +1 -4
  7. package/dist/capture-lane/lane.d.ts +109 -0
  8. package/dist/capture-lane/lane.d.ts.map +1 -0
  9. package/dist/capture-lane/lane.js +308 -0
  10. package/dist/capture-lane/lane.mjs +270 -0
  11. package/dist/capture-lane/limits.d.ts +7 -0
  12. package/dist/capture-lane/limits.d.ts.map +1 -0
  13. package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
  14. package/dist/capture-lane/limits.mjs +4 -0
  15. package/dist/capture-lane/settings.d.ts +30 -0
  16. package/dist/capture-lane/settings.d.ts.map +1 -0
  17. package/dist/capture-lane/settings.js +100 -0
  18. package/dist/capture-lane/settings.mjs +47 -0
  19. package/dist/capture-v1/compression.d.ts +18 -0
  20. package/dist/capture-v1/compression.d.ts.map +1 -0
  21. package/dist/capture-v1/compression.js +70 -0
  22. package/dist/capture-v1/compression.mjs +26 -0
  23. package/dist/capture-v1/errors.d.ts +23 -7
  24. package/dist/capture-v1/errors.d.ts.map +1 -1
  25. package/dist/capture-v1/errors.js +37 -8
  26. package/dist/capture-v1/errors.mjs +29 -6
  27. package/dist/capture-v1/sender.d.ts +63 -23
  28. package/dist/capture-v1/sender.d.ts.map +1 -1
  29. package/dist/capture-v1/sender.js +281 -74
  30. package/dist/capture-v1/sender.mjs +275 -77
  31. package/dist/capture-v1/serialize.d.ts +28 -0
  32. package/dist/capture-v1/serialize.d.ts.map +1 -0
  33. package/dist/capture-v1/serialize.js +82 -0
  34. package/dist/capture-v1/serialize.mjs +38 -0
  35. package/dist/capture-v1/transform.d.ts +10 -25
  36. package/dist/capture-v1/transform.d.ts.map +1 -1
  37. package/dist/capture-v1/transform.js +33 -64
  38. package/dist/capture-v1/transform.mjs +28 -53
  39. package/dist/capture-v1/types.d.ts +16 -14
  40. package/dist/capture-v1/types.d.ts.map +1 -1
  41. package/dist/capture-v1/types.js +27 -1
  42. package/dist/capture-v1/types.mjs +3 -1
  43. package/dist/capture-v1/uuid.d.ts +9 -0
  44. package/dist/capture-v1/uuid.d.ts.map +1 -0
  45. package/dist/capture-v1/uuid.js +75 -0
  46. package/dist/capture-v1/uuid.mjs +34 -0
  47. package/dist/client.d.ts +201 -94
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +485 -246
  50. package/dist/client.mjs +485 -246
  51. package/dist/compression.node.d.ts +13 -0
  52. package/dist/compression.node.d.ts.map +1 -0
  53. package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
  54. package/dist/compression.node.mjs +18 -0
  55. package/dist/entrypoints/index.node.d.ts +2 -0
  56. package/dist/entrypoints/index.node.d.ts.map +1 -1
  57. package/dist/entrypoints/index.node.js +11 -4
  58. package/dist/entrypoints/index.node.mjs +4 -0
  59. package/dist/event-defaults.d.ts +46 -0
  60. package/dist/event-defaults.d.ts.map +1 -0
  61. package/dist/event-defaults.js +141 -0
  62. package/dist/event-defaults.mjs +79 -0
  63. package/dist/exports.d.ts +3 -0
  64. package/dist/exports.d.ts.map +1 -1
  65. package/dist/exports.js +22 -11
  66. package/dist/exports.mjs +1 -0
  67. package/dist/extensions/context/context.d.ts +0 -1
  68. package/dist/extensions/context/context.d.ts.map +1 -1
  69. package/dist/extensions/context/context.js +4 -3
  70. package/dist/extensions/context/context.mjs +4 -3
  71. package/dist/extensions/context/event-context.d.ts.map +1 -1
  72. package/dist/extensions/context/event-context.js +3 -0
  73. package/dist/extensions/context/event-context.mjs +3 -0
  74. package/dist/extensions/context/types.d.ts +9 -1
  75. package/dist/extensions/context/types.d.ts.map +1 -1
  76. package/dist/extensions/error-tracking/index.d.ts +1 -1
  77. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  78. package/dist/extensions/error-tracking/index.js +71 -7
  79. package/dist/extensions/error-tracking/index.mjs +75 -11
  80. package/dist/extensions/express.d.ts +8 -0
  81. package/dist/extensions/express.d.ts.map +1 -1
  82. package/dist/extensions/express.js +3 -3
  83. package/dist/extensions/express.mjs +4 -4
  84. package/dist/extensions/fetch-request.d.ts.map +1 -1
  85. package/dist/extensions/fetch-request.js +2 -2
  86. package/dist/extensions/fetch-request.mjs +3 -3
  87. package/dist/extensions/nestjs.d.ts.map +1 -1
  88. package/dist/extensions/nestjs.js +7 -4
  89. package/dist/extensions/nestjs.mjs +8 -5
  90. package/dist/extensions/tracing-headers.d.ts +7 -0
  91. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  92. package/dist/extensions/tracing-headers.js +11 -1
  93. package/dist/extensions/tracing-headers.mjs +9 -2
  94. package/dist/feature-flag-evaluations.d.ts +5 -5
  95. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  96. package/dist/feature-flag-evaluations.js +16 -9
  97. package/dist/feature-flag-evaluations.mjs +16 -9
  98. package/dist/flag-events.d.ts +1 -1
  99. package/dist/flag-events.d.ts.map +1 -1
  100. package/dist/flag-events.js +2 -2
  101. package/dist/flag-events.mjs +2 -2
  102. package/dist/flags-response.d.ts +2 -0
  103. package/dist/flags-response.d.ts.map +1 -1
  104. package/dist/flags-response.js +6 -0
  105. package/dist/flags-response.mjs +4 -1
  106. package/dist/types.d.ts +192 -27
  107. package/dist/types.d.ts.map +1 -1
  108. package/dist/types.js +1 -0
  109. package/dist/types.mjs +1 -0
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.d.ts.map +1 -1
  112. package/dist/version.js +1 -1
  113. package/dist/version.mjs +1 -1
  114. package/package.json +5 -4
  115. package/src/ai-capture/routing.ts +0 -6
  116. package/src/capture-lane/lane.ts +414 -0
  117. package/src/capture-lane/limits.ts +8 -0
  118. package/src/capture-lane/settings.ts +119 -0
  119. package/src/capture-v1/compression.ts +50 -0
  120. package/src/capture-v1/errors.ts +50 -11
  121. package/src/capture-v1/sender.ts +405 -111
  122. package/src/capture-v1/serialize.ts +77 -0
  123. package/src/capture-v1/transform.ts +59 -92
  124. package/src/capture-v1/types.ts +19 -15
  125. package/src/capture-v1/uuid.ts +53 -0
  126. package/src/client.ts +885 -446
  127. package/src/compression.node.ts +30 -0
  128. package/src/entrypoints/index.node.ts +6 -0
  129. package/src/event-defaults.ts +177 -0
  130. package/src/exports.ts +3 -0
  131. package/src/extensions/context/context.ts +4 -4
  132. package/src/extensions/context/event-context.ts +3 -1
  133. package/src/extensions/context/types.ts +10 -1
  134. package/src/extensions/error-tracking/index.ts +51 -7
  135. package/src/extensions/express.ts +12 -3
  136. package/src/extensions/fetch-request.ts +7 -3
  137. package/src/extensions/nestjs.ts +9 -5
  138. package/src/extensions/tracing-headers.ts +26 -7
  139. package/src/feature-flag-evaluations.ts +31 -23
  140. package/src/flag-events.ts +5 -2
  141. package/src/flags-response.ts +6 -1
  142. package/src/types.ts +212 -44
  143. package/src/version.ts +1 -1
  144. package/dist/ai-capture/batching.d.ts +0 -11
  145. package/dist/ai-capture/batching.d.ts.map +0 -1
  146. package/dist/ai-capture/batching.js +0 -77
  147. package/dist/ai-capture/batching.mjs +0 -36
  148. package/dist/capture-v1/config.d.ts +0 -11
  149. package/dist/capture-v1/config.d.ts.map +0 -1
  150. package/dist/capture-v1/config.mjs +0 -8
  151. package/dist/capture-v1/routing.d.ts +0 -21
  152. package/dist/capture-v1/routing.d.ts.map +0 -1
  153. package/dist/capture-v1/routing.mjs +0 -7
  154. package/src/ai-capture/batching.ts +0 -47
  155. package/src/capture-v1/config.ts +0 -18
  156. package/src/capture-v1/routing.ts +0 -28
package/dist/client.mjs CHANGED
@@ -1,20 +1,25 @@
1
1
  import { version } from "./version.mjs";
2
- import { PostHogCoreStateless, PostHogLogs, PostHogMetrics, PostHogPersistedProperty, PostHogTraces, SyncSpanContextManager, allSettled, getEventUuid, inertSpan, isBlockedUA, isPlainObject, isPostHogFetchContentTooLargeError, minimizeFlagCalledEventProperties, raceWithTimeout, resolveMetricsConfig, resolveTracesConfig, runWithActiveSpan, safeSetTimeout, uuidv7 } from "@posthog/core";
2
+ import { EVENT_OPTION_LEGACY_PROPERTIES, ErrorTracking, PostHogCoreStateless, PostHogLogs, PostHogMetrics, PostHogPersistedProperty, PostHogTraces, SyncSpanContextManager, allSettled, inertSpan, isBlockedUA, isPlainObject, minimizeFlagCalledEventProperties, raceWithTimeout, resolveMetricsConfig, resolveTracesConfig, runWithActiveSpan, safeSetTimeout } from "@posthog/core";
3
3
  import { FeatureFlagError } from "./types.mjs";
4
4
  import { FeatureFlagEvaluations } from "./feature-flag-evaluations.mjs";
5
- import { FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE, isUnreadableFlagRecord, parsedFlagRecordOf, readFlagRecords } from "./flags-response.mjs";
5
+ import { FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE, isServerFailedFlagRecord, isUnreadableFlagRecord, parsedFlagRecordOf, readFlagRecords } from "./flags-response.mjs";
6
6
  import { applyFlagEventCapture, buildConfigVersion2FlagEvents, minimizeConfigVersion2FlagCalledProperties } from "./flag-events.mjs";
7
7
  import { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from "./extensions/feature-flags/feature-flags.mjs";
8
8
  import error_tracking from "./extensions/error-tracking/index.mjs";
9
9
  import { getActiveTraceProperties } from "./extensions/error-tracking/trace-context.mjs";
10
10
  import { PostHogMemoryStorage } from "./storage-memory.mjs";
11
+ import { V1CaptureSender } from "./capture-v1/sender.mjs";
12
+ import { AI_CAPTURE_ENDPOINT, ANALYTICS_CAPTURE_ENDPOINT } from "./capture-v1/types.mjs";
13
+ import { CaptureLane } from "./capture-lane/lane.mjs";
14
+ import { AI_MAX_PROPERTIES_BYTES, ANALYTICS_MAX_EVENT_BYTES, CAPTURE_BATCH_TARGET_BYTES } from "./capture-lane/limits.mjs";
15
+ import { resolveCaptureSettings } from "./capture-lane/settings.mjs";
16
+ import { resolveCaptureCodec, webCompressor } from "./capture-v1/compression.mjs";
17
+ import { canonicalizeUuid, eventUuidv7 } from "./capture-v1/uuid.mjs";
18
+ import { readEventOptions } from "./capture-v1/transform.mjs";
19
+ import { dropIdentifyStyleLegacyPersonProfile, fillIdentifyStylePersonProfile, fillLibraryProperties, fillOptions, fillProperties, isMergeableObject, isUnsetProperty, snapshotLayer } from "./event-defaults.mjs";
20
+ import { AI_CAPTURE_ROUTE } from "./ai-capture/routing.mjs";
11
21
  import { notifyContextListeners } from "./extensions/context/listeners.mjs";
12
22
  import { getEventContext } from "./extensions/context/event-context.mjs";
13
- import { resolveCaptureMode } from "./capture-v1/config.mjs";
14
- import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from "./capture-v1/routing.mjs";
15
- import { V1CaptureSender } from "./capture-v1/sender.mjs";
16
- import { eventByteSize, partitionAiBatch } from "./ai-capture/batching.mjs";
17
- import { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from "./ai-capture/routing.mjs";
18
23
  import { DEFAULT_EMAIL_REQUEST_MAX_RETRIES, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS, EmailSender } from "./emails/emails.mjs";
19
24
  import { resolveNodeLogsConfig } from "./logs-config.mjs";
20
25
  const MINIMUM_POLLING_INTERVAL = 100;
@@ -24,10 +29,10 @@ const WAITUNTIL_DEBOUNCE_MS = 50;
24
29
  const WAITUNTIL_MAX_WAIT_MS = 500;
25
30
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com';
26
31
  const _emittedDeprecations = new Set();
27
- function emitDeprecationWarningOnce(id, message) {
32
+ function emitDeprecationWarningOnce(id, message, log = console.warn) {
28
33
  if (_emittedDeprecations.has(id)) return;
29
34
  _emittedDeprecations.add(id);
30
- console.warn(`[PostHog] ${message}`);
35
+ log(`[PostHog] ${message}`);
31
36
  }
32
37
  function _resetDeprecationWarningsForTests() {
33
38
  _emittedDeprecations.clear();
@@ -35,14 +40,122 @@ function _resetDeprecationWarningsForTests() {
35
40
  function normalizeApiKey(value) {
36
41
  return 'string' == typeof value ? value.trim() : '';
37
42
  }
43
+ function apiKeyProblem(apiKey) {
44
+ if (!apiKey) return 'No project API key was passed';
45
+ if (apiKey.startsWith('phx_')) return 'A personal API key ("phx_...") was passed where the project API key ("phc_...") belongs';
46
+ }
47
+ function summarizeForDebugLog(payload) {
48
+ if (Array.isArray(payload)) return `${payload.length} item(s)`;
49
+ if (payload instanceof Error) return `${payload.name}: ${payload.message}`;
50
+ if (payload && 'object' == typeof payload && 'string' == typeof payload.event) {
51
+ const { event, uuid } = payload;
52
+ return void 0 === uuid ? {
53
+ event
54
+ } : {
55
+ event,
56
+ uuid
57
+ };
58
+ }
59
+ }
38
60
  function normalizePersonalApiKey(value) {
39
61
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
40
62
  return normalizedValue || void 0;
41
63
  }
64
+ function isUnsetUuid(uuid) {
65
+ return null == uuid || '' === uuid;
66
+ }
67
+ function isInvalidUuid(uuid) {
68
+ return !isUnsetUuid(uuid) && ('string' != typeof uuid || void 0 === canonicalizeUuid(uuid));
69
+ }
42
70
  function normalizeHost(value) {
43
71
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
44
72
  return normalizedValue || DEFAULT_NODE_HOST;
45
73
  }
74
+ const FLAG_CALLED_OPTION_SOURCE_PROPERTIES = [
75
+ '$cookieless_mode',
76
+ '$ignore_sent_at',
77
+ '$product_tour_id',
78
+ '$process_person_profile',
79
+ '$session_id',
80
+ '$window_id'
81
+ ];
82
+ function readCaptureExceptionArgs(method, second, rest, legacyHasUuid) {
83
+ if ('string' != typeof second && (0 === rest.length || isPlainObject(second))) {
84
+ if (rest.length > 0) emitDeprecationWarningOnce(`${method} extra arguments`, `${method}(error, options) ignores the arguments after the options object.`);
85
+ return isPlainObject(second) ? second : {};
86
+ }
87
+ emitDeprecationWarningOnce(`${method} positional arguments`, `${method}(error, distinctId, properties) is deprecated: pass an object instead, e.g. ${method}(error, { distinctId, properties }). The old form will be removed in the next major version.`, console.error);
88
+ const [properties, ...tail] = rest;
89
+ const [uuid, flags] = legacyHasUuid ? tail : [
90
+ void 0,
91
+ tail[0]
92
+ ];
93
+ return {
94
+ distinctId: second ?? void 0,
95
+ properties: properties,
96
+ uuid: uuid,
97
+ flags: flags
98
+ };
99
+ }
100
+ class UnreadableEventError extends Error {
101
+ constructor(original){
102
+ super('A value in the event threw while it was read'), this.original = original;
103
+ }
104
+ }
105
+ function readCallerValues(read) {
106
+ try {
107
+ return read();
108
+ } catch (error) {
109
+ throw new UnreadableEventError(error);
110
+ }
111
+ }
112
+ function isolateForBeforeSend(eventMessage) {
113
+ const isolated = copyPlainValues(eventMessage, new WeakMap());
114
+ isolated.options ??= {};
115
+ return isolated;
116
+ }
117
+ function isPlainRecord(value) {
118
+ if (null === value || 'object' != typeof value) return false;
119
+ const prototype = Object.getPrototypeOf(value);
120
+ return prototype === Object.prototype || null === prototype;
121
+ }
122
+ function copyPlainValues(value, seen) {
123
+ if (!Array.isArray(value) && !isPlainRecord(value)) return value;
124
+ const known = seen.get(value);
125
+ if (void 0 !== known) return known;
126
+ if (Array.isArray(value)) {
127
+ const copy = new Array(value.length);
128
+ seen.set(value, copy);
129
+ value.forEach((item, index)=>{
130
+ copy[index] = copyPlainValues(item, seen);
131
+ });
132
+ return copy;
133
+ }
134
+ const copy = null === Object.getPrototypeOf(value) ? Object.create(null) : {};
135
+ seen.set(value, copy);
136
+ for (const key of Object.keys(value))copy[key] = copyPlainValues(value[key], seen);
137
+ return copy;
138
+ }
139
+ function identifyEventProperties(properties) {
140
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
141
+ return {
142
+ $set: $set || rest,
143
+ ...null != $set_once ? {
144
+ $set_once
145
+ } : {},
146
+ $anon_distinct_id: $anon_distinct_id ?? void 0
147
+ };
148
+ }
149
+ const ALIAS_PREPARE_OPTIONS = {
150
+ callOnlyProperties: [
151
+ 'alias'
152
+ ],
153
+ distinctIdProperty: true
154
+ };
155
+ function presentDistinctId(value) {
156
+ if (null == value || 'string' == typeof value && '' === value.trim()) return;
157
+ return 'string' == typeof value ? value : String(value);
158
+ }
46
159
  function positiveNumberOr(value, fallback) {
47
160
  return 'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
48
161
  }
@@ -72,16 +185,20 @@ class PostHogBackendClient extends PostHogCoreStateless {
72
185
  }
73
186
  constructor(apiKey, options = {}){
74
187
  const normalizedApiKey = normalizeApiKey(apiKey);
188
+ const keyProblem = apiKeyProblem(normalizedApiKey);
75
189
  const normalizedOptions = {
76
190
  ...options,
191
+ disabled: options.disabled || void 0 !== keyProblem,
77
192
  maxQueueSize: options.maxQueueSize ?? 10000,
78
193
  flushInterval: options.flushInterval ?? 5000,
79
194
  host: normalizeHost(options.host),
80
195
  personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
81
196
  };
82
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._isShutdown = false, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
197
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._captureLanes = new Map(), this._isShutdown = false, this._globalOptions = {}, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
83
198
  this.options = normalizedOptions;
84
- this.captureMode = resolveCaptureMode();
199
+ if (keyProblem) console.error(`[PostHog] ${keyProblem}, so the client is disabled.`);
200
+ this.warnIfCaptureModeSet();
201
+ this._captureSettings = resolveCaptureSettings(normalizedOptions, (message)=>console.error(`[PostHog] ${message}`));
85
202
  this.enableFullAiCapture = true === normalizedOptions.enableFullAiCapture;
86
203
  this.privacyMode = true === normalizedOptions.privacyMode;
87
204
  this.context = this.initializeContext();
@@ -118,11 +235,45 @@ class PostHogBackendClient extends PostHogCoreStateless {
118
235
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
119
236
  }
120
237
  enqueue(type, message, options, explicitRoute) {
121
- super.enqueue(type, message, options, explicitRoute);
238
+ this.wrap(()=>{
239
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
240
+ const prepared = this._prepareLaneMessage(message, options);
241
+ if (null === prepared) return;
242
+ this._captureLane(explicitRoute).enqueue(prepared);
243
+ this._events.emit(type, prepared);
244
+ });
122
245
  this.scheduleDebouncedFlush();
123
246
  }
247
+ async sendImmediate(type, message, options, explicitRoute) {
248
+ if (this.disabled) return void this._logger.warn('The client is disabled');
249
+ if (!this._isInitialized) await this._initPromise;
250
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
251
+ const prepared = this._prepareLaneMessage(message, options);
252
+ if (null === prepared) return;
253
+ try {
254
+ await this._captureLane(explicitRoute).sendImmediate(prepared);
255
+ } catch (err) {
256
+ this._events.emit('error', err);
257
+ }
258
+ }
259
+ _prepareLaneMessage(message, options) {
260
+ const { _invalidUuidWarned, ...captureOptions } = options ?? {};
261
+ const uuid = this._canonicalEventUuid(captureOptions.uuid, !_invalidUuidWarned) ?? eventUuidv7();
262
+ const prepared = this.processBeforeEnqueue(this.prepareMessage(message, {
263
+ ...captureOptions,
264
+ uuid
265
+ }));
266
+ return null === prepared ? null : this.normalizeMessage(prepared);
267
+ }
268
+ _canonicalEventUuid(uuid, warnIfInvalid = true) {
269
+ if (isUnsetUuid(uuid)) return;
270
+ const canonical = 'string' == typeof uuid ? canonicalizeUuid(uuid) : void 0;
271
+ if (void 0 !== canonical) return canonical;
272
+ if (warnIfInvalid) console.warn('[PostHog] Replaced an invalid event uuid with a generated one; uuids must be RFC 4122 strings');
273
+ return eventUuidv7();
274
+ }
124
275
  _flushEventsAndSpans(skipThrottledSpans = false) {
125
- const events = this.flushWithPendingPromises();
276
+ const events = this.flushWithPendingPromises().then(()=>this._flushCaptureLanes());
126
277
  const others = [];
127
278
  if (this._traces && !(skipThrottledSpans && this._traces.throttled)) others.push(this._traces.flush().catch(()=>{}));
128
279
  if (this._logs && !(skipThrottledSpans && this._logs.throttled)) others.push(this._logs.flushInBackground());
@@ -134,15 +285,24 @@ class PostHogBackendClient extends PostHogCoreStateless {
134
285
  if ('rejected' === eventsResult.status) throw eventsResult.reason;
135
286
  });
136
287
  }
137
- flushAutomatic() {
138
- return this._flushKeepingRuntimeAlive(true);
139
- }
140
288
  async flush() {
141
289
  this.errorTracking.capturePendingExceptions();
142
- return this._flushKeepingRuntimeAlive(false);
143
- }
144
- _flushKeepingRuntimeAlive(skipThrottledSpans) {
145
- const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
290
+ return this._keepRuntimeAlive(this._flushEventsAndSpans());
291
+ }
292
+ _flushCaptureLanes() {
293
+ return Promise.all([
294
+ ...this._captureLanes.values()
295
+ ].map((lane)=>lane.flush())).then(()=>{});
296
+ }
297
+ _onLaneBackgroundFlush(laneFlush) {
298
+ const traces = this._traces;
299
+ const flush = traces && !traces.throttled ? allSettled([
300
+ laneFlush,
301
+ traces.flush().catch(()=>{})
302
+ ]).then(()=>{}) : laneFlush;
303
+ this._keepRuntimeAlive(flush);
304
+ }
305
+ _keepRuntimeAlive(flushPromise) {
146
306
  const waitUntil = this.options.waitUntil;
147
307
  if (waitUntil && !this._waitUntilCycle) try {
148
308
  waitUntil(flushPromise.catch(()=>{}));
@@ -211,78 +371,71 @@ class PostHogBackendClient extends PostHogCoreStateless {
211
371
  fetch(url, options) {
212
372
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
213
373
  }
214
- getQueueRouteKey(message) {
215
- return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
374
+ _captureLane(route) {
375
+ const endpoint = route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT : ANALYTICS_CAPTURE_ENDPOINT;
376
+ let lane = this._captureLanes.get(endpoint);
377
+ if (!lane) {
378
+ const compressor = this.captureCompressor();
379
+ lane = new CaptureLane(this._captureLaneConfig(endpoint), {
380
+ sender: new V1CaptureSender(this.captureSenderConfig(endpoint, compressor), {
381
+ fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
382
+ onError: (error, summary)=>this._reportCaptureLoss([
383
+ error
384
+ ], summary),
385
+ compress: (payload, codec)=>compressor.compress(payload, codec)
386
+ }),
387
+ onLocalDrops: (errors, summary)=>this._reportCaptureLoss(errors, summary),
388
+ onError: (error)=>this._events.emit('error', error),
389
+ onFlush: (messages)=>this._events.emit('flush', messages),
390
+ onBackgroundFlush: (flush)=>this._onLaneBackgroundFlush(flush),
391
+ logger: this._logger
392
+ });
393
+ this._captureLanes.set(endpoint, lane);
394
+ }
395
+ return lane;
216
396
  }
217
- persistedQueueKeyForRoute(route) {
218
- if (route === AI_CAPTURE_ROUTE) return PostHogPersistedProperty.AiCaptureQueue;
219
- return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;
397
+ _captureLaneConfig(endpoint) {
398
+ const isAi = endpoint === AI_CAPTURE_ENDPOINT;
399
+ const flushAt = isAi ? Math.min(this.flushAt, this._captureSettings.ai.maxQueueSize) : this.flushAt;
400
+ return {
401
+ endpoint,
402
+ flushAt,
403
+ flushIntervalMs: this.options.flushInterval ?? 5000,
404
+ maxBatchSize: Math.max(flushAt, this.options.maxBatchSize ?? 100),
405
+ maxQueueSize: isAi ? this._captureSettings.ai.maxQueueSize : Math.max(this.flushAt, this.options.maxQueueSize ?? 10000),
406
+ targetBatchBytes: CAPTURE_BATCH_TARGET_BYTES,
407
+ maxEventBytes: isAi ? AI_MAX_PROPERTIES_BYTES : ANALYTICS_MAX_EVENT_BYTES,
408
+ maxEventBytesOf: isAi ? 'properties' : 'event'
409
+ };
220
410
  }
221
- getActiveQueueRoutes() {
222
- const routes = 'v1' === this.captureMode ? [
223
- ANALYTICS_ROUTE,
224
- AI_ROUTE
225
- ] : [
226
- ANALYTICS_ROUTE
227
- ];
228
- if (this._aiCaptureRouteActive) routes.push(AI_CAPTURE_ROUTE);
229
- return routes;
230
- }
231
- getBatchEndpointPath(route) {
232
- return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
233
- }
234
- async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
235
- if (route === AI_CAPTURE_ROUTE) return this.sendAiCaptureBatch(batchMessages, retryOptions);
236
- if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);
237
- const v1Events = batchMessages.filter((message)=>void 0 !== message);
238
- await this.getV1Sender().sendV1Batch(v1Events);
239
- }
240
- async sendAiCaptureBatch(batchMessages, retryOptions) {
241
- const { batches, dropped } = partitionAiBatch(batchMessages);
242
- for (const { event, bytes } of dropped){
243
- const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
244
- this._logger.error(message);
245
- this._events.emit('error', new Error(message));
246
- }
247
- for (const batch of batches)await this.sendAiSubBatch(batch, retryOptions);
411
+ _reportCaptureLoss(errors, summary) {
412
+ const errorListeners = this._events.events['error']?.length ?? 0;
413
+ for (const error of errors)this._events.emit('error', error);
414
+ if (0 === errorListeners) console.warn(`[PostHog] ${summary}`);
248
415
  }
249
- async sendAiSubBatch(batch, retryOptions) {
250
- try {
251
- await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);
252
- } catch (err) {
253
- if (!isPostHogFetchContentTooLargeError(err)) throw err;
254
- if (1 === batch.length) {
255
- const [event] = batch;
256
- const eventName = 'string' == typeof event.event ? event.event : 'unknown';
257
- const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
258
- this._logger.error(message);
259
- this._events.emit('error', new Error(message));
260
- return;
261
- }
262
- const mid = Math.ceil(batch.length / 2);
263
- await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
264
- await this.sendAiSubBatch(batch.slice(mid), retryOptions);
265
- }
416
+ captureCompressor() {
417
+ return webCompressor;
266
418
  }
267
- getV1Sender() {
268
- if (!this._v1Sender) this._v1Sender = new V1CaptureSender({
419
+ captureSenderConfig(path, compressor) {
420
+ const laneSettings = path === AI_CAPTURE_ENDPOINT ? this._captureSettings.ai : this._captureSettings.analytics;
421
+ const compression = resolveCaptureCodec(laneSettings.compression, compressor, (fallback)=>this._logger.debug(`zstd compression is not available in this runtime; ${path} uses ${fallback} instead`));
422
+ return {
269
423
  host: this.host,
424
+ path,
270
425
  apiKey: this.apiKey,
271
426
  libraryId: this.getLibraryId(),
272
427
  libraryVersion: this.getLibraryVersion(),
273
428
  userAgent: this.getCustomUserAgent() || void 0,
274
429
  historicalMigration: this.historicalMigration,
275
- compressionEnabled: !this.disableCompression,
276
- requestTimeoutMs: this.requestTimeout,
277
- maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
278
- initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
430
+ compression,
431
+ requestTimeoutMs: laneSettings.requestTimeoutMs,
432
+ maxRetries: this._captureSettings.maxRetries,
279
433
  isDebug: this.isDebug
280
- }, {
281
- fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
282
- onError: (error)=>this._events.emit('error', error),
283
- compress: (payload)=>this.compressPayload(payload)
284
- });
285
- return this._v1Sender;
434
+ };
435
+ }
436
+ warnIfCaptureModeSet() {
437
+ const captureMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;
438
+ if (void 0 !== captureMode) console.warn('[PostHog] POSTHOG_CAPTURE_MODE is no longer read. Capture always uses capture v1.');
286
439
  }
287
440
  getLibraryVersion() {
288
441
  return version;
@@ -415,14 +568,42 @@ class PostHogBackendClient extends PostHogCoreStateless {
415
568
  this._loggedFlagsResponseWithoutTypedValues = true;
416
569
  this._logger.info(FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE);
417
570
  }
418
- return shared.read(body);
571
+ const normalized = shared.read(body);
572
+ if (isPlainObject(normalized.flags)) {
573
+ for (const [key, detail] of Object.entries(normalized.flags))if (isUnreadableFlagRecord(detail)) normalized.featureFlags[key] = false;
574
+ }
575
+ return normalized;
419
576
  }
420
577
  };
421
578
  }
422
- getCommonEventProperties() {
423
- const commonProperties = super.getCommonEventProperties();
424
- if (this.options.isServer ?? true) commonProperties.$is_server = true;
425
- return commonProperties;
579
+ async _sdkEventProperties(event, properties, distinctId, flagInputs) {
580
+ const sdkProperties = {
581
+ ...this._serviceNameProperties(),
582
+ ...await this._flagEventProperties(distinctId, flagInputs)
583
+ };
584
+ if (this.options.isServer ?? true) sdkProperties.$is_server = true;
585
+ if (this.options.disableGeoip ?? true) sdkProperties.$geoip_disable = true;
586
+ if ('$exception' === event) {
587
+ if (isUnsetProperty(properties, '$trace_id') && isUnsetProperty(properties, '$span_id')) Object.assign(sdkProperties, await getActiveTraceProperties());
588
+ const releaseId = ErrorTracking.getInjectedReleaseId();
589
+ if (releaseId) sdkProperties.$release_id = releaseId;
590
+ }
591
+ return sdkProperties;
592
+ }
593
+ async _flagEventProperties(distinctId, { groups, flags, sendFeatureFlags, disableGeoip }) {
594
+ try {
595
+ if (flags) {
596
+ if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
597
+ return flags._getEventProperties();
598
+ }
599
+ if (sendFeatureFlags) {
600
+ emitDeprecationWarningOnce('sendFeatureFlags', "`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");
601
+ const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
602
+ const flagValues = await this.getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
603
+ return buildFlagEventProperties(flagValues);
604
+ }
605
+ } catch {}
606
+ return {};
426
607
  }
427
608
  enable() {
428
609
  return super.optIn();
@@ -434,34 +615,52 @@ class PostHogBackendClient extends PostHogCoreStateless {
434
615
  super.debug(enabled);
435
616
  this.featureFlagsPoller?.debug(enabled);
436
617
  }
618
+ describeDebugPayload(payload) {
619
+ return summarizeForDebugLog(payload);
620
+ }
437
621
  _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
438
622
  if ('string' == typeof props) this._logger.warn(stringArgumentWarning);
439
623
  if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);
440
624
  }
441
625
  _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
442
- return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{
626
+ const invalidUuidWarned = isInvalidUuid(props.uuid);
627
+ const uuid = this._canonicalEventUuid(props.uuid);
628
+ if (uuid !== props.uuid) props = {
629
+ ...props,
630
+ uuid
631
+ };
632
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options, uuid, timestamp })=>{
443
633
  if (this.disabled || this.optedOut) prepareOptions?.onCaptureFailed?.();
444
634
  const captureOptions = {
445
- timestamp: options.timestamp,
446
- disableGeoip: options.disableGeoip,
447
- uuid: options.uuid
635
+ timestamp,
636
+ disableGeoip: false,
637
+ uuid,
638
+ _invalidUuidWarned: invalidUuidWarned
448
639
  };
449
640
  const message = {
450
- distinctId,
641
+ distinct_id: distinctId,
451
642
  event,
452
- properties: {
453
- ...properties,
454
- ...this.getCommonEventProperties()
455
- }
643
+ properties,
644
+ ...void 0 !== options ? {
645
+ options
646
+ } : {}
456
647
  };
457
648
  return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
458
649
  }).catch((err)=>{
459
- if (err) {
650
+ if (err instanceof UnreadableEventError) {
651
+ this._dropUnreadableEvent(uuid, immediate, explicitRoute);
652
+ prepareOptions?.onCaptureFailed?.();
653
+ } else if (err) {
460
654
  console.error(err);
461
655
  prepareOptions?.onCaptureFailed?.();
462
656
  }
463
657
  }));
464
658
  }
659
+ _dropUnreadableEvent(uuid, immediate, explicitRoute) {
660
+ if (this.disabled || this.optedOut) return;
661
+ this._captureLane(explicitRoute).dropUnserializable(uuid, immediate);
662
+ if (!immediate) this.scheduleDebouncedFlush();
663
+ }
465
664
  _capturePreparedEvent(props, immediate) {
466
665
  return this._sendPreparedEvent('capture', props, immediate);
467
666
  }
@@ -475,7 +674,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
475
674
  }
476
675
  captureAi(props) {
477
676
  if (this.disabled) return;
478
- const uuid = getEventUuid(props.uuid, uuidv7);
677
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7();
479
678
  this._sendPreparedAiEvent({
480
679
  ...props,
481
680
  uuid
@@ -484,7 +683,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
484
683
  }
485
684
  async captureAiImmediate(props) {
486
685
  if (this.disabled) return;
487
- const uuid = getEventUuid(props.uuid, uuidv7);
686
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7();
488
687
  await this._sendPreparedAiEvent({
489
688
  ...props,
490
689
  uuid
@@ -493,46 +692,29 @@ class PostHogBackendClient extends PostHogCoreStateless {
493
692
  }
494
693
  _sendPreparedAiEvent(props, immediate) {
495
694
  if ('string' == typeof props?.event && !props.event.startsWith('$ai_')) this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
496
- this._aiCaptureRouteActive = true;
497
695
  return this._sendPreparedEvent('capture', props, immediate, void 0, AI_CAPTURE_ROUTE);
498
696
  }
499
- identify({ distinctId, properties = {}, disableGeoip }) {
500
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
501
- const setProps = $set || rest;
502
- const setOnceProps = $set_once || {};
503
- const eventProperties = {
504
- $set: setProps,
505
- $set_once: setOnceProps,
506
- $anon_distinct_id: $anon_distinct_id ?? void 0
507
- };
697
+ identify({ distinctId, properties = {}, disableGeoip, options }) {
698
+ const eventProperties = identifyEventProperties(properties);
508
699
  this._sendPreparedEvent('identify', {
509
700
  distinctId,
510
701
  event: '$identify',
511
702
  properties: eventProperties,
512
- disableGeoip
513
- }, false, {
514
- includeContextProperties: false
515
- });
703
+ disableGeoip,
704
+ options
705
+ }, false);
516
706
  }
517
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
518
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
519
- const setProps = $set || rest;
520
- const setOnceProps = $set_once || {};
521
- const eventProperties = {
522
- $set: setProps,
523
- $set_once: setOnceProps,
524
- $anon_distinct_id: $anon_distinct_id ?? void 0
525
- };
707
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }) {
708
+ const eventProperties = identifyEventProperties(properties);
526
709
  await this._sendPreparedEvent('identify', {
527
710
  distinctId,
528
711
  event: '$identify',
529
712
  properties: eventProperties,
530
- disableGeoip
531
- }, true, {
532
- includeContextProperties: false
533
- });
713
+ disableGeoip,
714
+ options
715
+ }, true);
534
716
  }
535
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
717
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }) {
536
718
  if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;
537
719
  const eventProperties = {};
538
720
  if (Object.keys(properties).length > 0) eventProperties.$set = properties;
@@ -540,10 +722,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
540
722
  this.capture({
541
723
  distinctId,
542
724
  event: '$set',
543
- properties: eventProperties
725
+ properties: eventProperties,
726
+ options
544
727
  });
545
728
  }
546
- unsetPersonProperties({ distinctId, properties }) {
729
+ unsetPersonProperties({ distinctId, properties, options }) {
547
730
  const propertyNames = normalizeUnsetPersonProperties(properties);
548
731
  if (0 === propertyNames.length) return;
549
732
  this.capture({
@@ -551,7 +734,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
551
734
  event: '$set',
552
735
  properties: {
553
736
  $unset: propertyNames
554
- }
737
+ },
738
+ options
555
739
  });
556
740
  }
557
741
  alias(data) {
@@ -559,26 +743,22 @@ class PostHogBackendClient extends PostHogCoreStateless {
559
743
  distinctId: data.distinctId,
560
744
  event: '$create_alias',
561
745
  properties: {
562
- distinct_id: data.distinctId,
563
746
  alias: data.alias
564
747
  },
565
- disableGeoip: data.disableGeoip
566
- }, false, {
567
- includeContextProperties: false
568
- });
748
+ disableGeoip: data.disableGeoip,
749
+ options: data.options
750
+ }, false, ALIAS_PREPARE_OPTIONS);
569
751
  }
570
752
  async aliasImmediate(data) {
571
753
  await this._sendPreparedEvent('alias', {
572
754
  distinctId: data.distinctId,
573
755
  event: '$create_alias',
574
756
  properties: {
575
- distinct_id: data.distinctId,
576
757
  alias: data.alias
577
758
  },
578
- disableGeoip: data.disableGeoip
579
- }, true, {
580
- includeContextProperties: false
581
- });
759
+ disableGeoip: data.disableGeoip,
760
+ options: data.options
761
+ }, true, ALIAS_PREPARE_OPTIONS);
582
762
  }
583
763
  isLocalEvaluationReady() {
584
764
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
@@ -702,21 +882,24 @@ class PostHogBackendClient extends PostHogCoreStateless {
702
882
  flagVersion = flagDetail.metadata?.version;
703
883
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
704
884
  flagHasExperiment = flagDetail.metadata?.has_experiment;
705
- let parsedPayload;
706
- if (flagDetail.metadata?.payload !== void 0) try {
707
- parsedPayload = JSON.parse(flagDetail.metadata.payload);
708
- } catch {
709
- parsedPayload = flagDetail.metadata.payload;
710
- }
711
- result = {
712
- key,
713
- enabled: flagDetail.enabled,
714
- variant: flagDetail.variant ?? void 0,
715
- payload: parsedPayload,
716
- reason: flagReason,
717
- reasonCode: flagDetail.reason?.code
718
- };
719
885
  flagRecord = parsedFlagRecordOf(flagDetail);
886
+ if (isServerFailedFlagRecord(flagRecord)) errors.push(FeatureFlagError.EVALUATION_FAILED);
887
+ else {
888
+ let parsedPayload;
889
+ if (flagDetail.metadata?.payload !== void 0) try {
890
+ parsedPayload = JSON.parse(flagDetail.metadata.payload);
891
+ } catch {
892
+ parsedPayload = flagDetail.metadata.payload;
893
+ }
894
+ result = {
895
+ key,
896
+ enabled: flagDetail.enabled,
897
+ variant: flagDetail.variant ?? void 0,
898
+ payload: parsedPayload,
899
+ reason: flagReason,
900
+ reasonCode: flagDetail.reason?.code
901
+ };
902
+ }
720
903
  }
721
904
  if (void 0 !== flagDetail && isUnreadableFlagRecord(flagDetail)) {
722
905
  featureFlagError = FeatureFlagError.UNKNOWN_ERROR;
@@ -943,8 +1126,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
943
1126
  quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');
944
1127
  for (const [key, detail] of Object.entries(details.flags)){
945
1128
  if (locallyEvaluatedKeys.has(key)) continue;
1129
+ const parsed = parsedFlagRecordOf(detail);
946
1130
  let parsedPayload;
947
- if (detail.metadata?.payload !== void 0) try {
1131
+ if (!isServerFailedFlagRecord(parsed) && detail.metadata?.payload !== void 0) try {
948
1132
  parsedPayload = JSON.parse(detail.metadata.payload);
949
1133
  } catch {
950
1134
  parsedPayload = detail.metadata.payload;
@@ -959,7 +1143,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
959
1143
  reason: detail.reason?.description ?? detail.reason?.code,
960
1144
  locallyEvaluated: false,
961
1145
  hasExperiment: detail.metadata?.has_experiment,
962
- parsed: parsedFlagRecordOf(detail)
1146
+ parsed
963
1147
  };
964
1148
  }
965
1149
  }
@@ -993,7 +1177,10 @@ class PostHogBackendClient extends PostHogCoreStateless {
993
1177
  for (const key of Object.keys(records))if (!requestedFlagKeys.has(key)) delete records[key];
994
1178
  }
995
1179
  const unresolvedFlags = {};
996
- for (const [key, reason] of Object.entries(localResult?.unresolved ?? {}))if (!Object.prototype.hasOwnProperty.call(records, key)) unresolvedFlags[key] = reason;
1180
+ for (const [key, reason] of Object.entries(localResult?.unresolved ?? {})){
1181
+ const parsed = records[key]?.parsed;
1182
+ if (!Object.prototype.hasOwnProperty.call(records, key) || parsed && isServerFailedFlagRecord(parsed)) unresolvedFlags[key] = reason;
1183
+ }
997
1184
  return new FeatureFlagEvaluations({
998
1185
  host: this._getFeatureFlagEvaluationsHost(),
999
1186
  distinctId: resolvedDistinctId,
@@ -1089,32 +1276,36 @@ class PostHogBackendClient extends PostHogCoreStateless {
1089
1276
  };
1090
1277
  return this._featureFlagEvaluationsHost;
1091
1278
  }
1092
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1279
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1093
1280
  this._sendPreparedEvent('capture', {
1094
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1281
+ distinctId,
1095
1282
  event: '$groupidentify',
1096
1283
  properties: {
1097
1284
  $group_type: groupType,
1098
1285
  $group_key: groupKey,
1099
1286
  $group_set: properties || {}
1100
1287
  },
1101
- disableGeoip
1288
+ disableGeoip,
1289
+ options
1102
1290
  }, false, {
1103
- includeContextProperties: false
1291
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1292
+ contextSession: false
1104
1293
  });
1105
1294
  }
1106
- async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1295
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1107
1296
  await this._sendPreparedEvent('capture', {
1108
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1297
+ distinctId,
1109
1298
  event: '$groupidentify',
1110
1299
  properties: {
1111
1300
  $group_type: groupType,
1112
1301
  $group_key: groupKey,
1113
1302
  $group_set: properties || {}
1114
1303
  },
1115
- disableGeoip
1304
+ disableGeoip,
1305
+ options
1116
1306
  }, true, {
1117
- includeContextProperties: false
1307
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1308
+ contextSession: false
1118
1309
  });
1119
1310
  }
1120
1311
  async reloadFeatureFlags() {
@@ -1167,6 +1358,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
1167
1358
  }
1168
1359
  return false;
1169
1360
  }
1361
+ register(properties) {
1362
+ return super.register(properties);
1363
+ }
1364
+ unregister(property) {
1365
+ return super.unregister(property);
1366
+ }
1367
+ async registerOptions(options) {
1368
+ if (!isPlainObject(options)) return void console.error('[PostHog] registerOptions takes an object; ignoring the value');
1369
+ this._globalOptions = {
1370
+ ...this._globalOptions,
1371
+ ...options
1372
+ };
1373
+ }
1374
+ async unregisterOptions(key) {
1375
+ const remaining = {
1376
+ ...this._globalOptions
1377
+ };
1378
+ delete remaining[key];
1379
+ this._globalOptions = remaining;
1380
+ }
1170
1381
  withContext(data, fn, options) {
1171
1382
  if (!this.context) return fn();
1172
1383
  return this.context.run(data, ()=>{
@@ -1177,10 +1388,6 @@ class PostHogBackendClient extends PostHogCoreStateless {
1177
1388
  getContext() {
1178
1389
  return this.context?.get();
1179
1390
  }
1180
- enterContext(data, options) {
1181
- this.context?.enter(data, options);
1182
- notifyContextListeners(this);
1183
- }
1184
1391
  async _shutdown(shutdownTimeoutMs) {
1185
1392
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
1186
1393
  this._isShutdown = true;
@@ -1216,8 +1423,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
1216
1423
  const remainingMs = Math.max(0, shutdownDeadlineMs - Date.now());
1217
1424
  const emailsSettled = emailsDrained ? raceWithTimeout(emailsDrained, remainingMs) : void 0;
1218
1425
  try {
1219
- return await super._shutdown(remainingMs);
1426
+ await Promise.all([
1427
+ super._shutdown(remainingMs),
1428
+ this._drainCaptureLanes(shutdownDeadlineMs)
1429
+ ]);
1430
+ await this._drainCaptureLanes(shutdownDeadlineMs);
1220
1431
  } finally{
1432
+ for (const lane of this._captureLanes.values())lane.finishShutdown();
1221
1433
  await emailsSettled;
1222
1434
  await logsDrained;
1223
1435
  this._distinctIdHasSentFlagCalls.clear();
@@ -1225,6 +1437,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
1225
1437
  resolve?.();
1226
1438
  }
1227
1439
  }
1440
+ _drainCaptureLanes(deadlineMs) {
1441
+ return Promise.all([
1442
+ ...this._captureLanes.values()
1443
+ ].map((lane)=>lane.drain(deadlineMs))).then(()=>{});
1444
+ }
1228
1445
  async _requestRemoteConfigPayload(flagKey) {
1229
1446
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;
1230
1447
  const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
@@ -1332,31 +1549,30 @@ class PostHogBackendClient extends PostHogCoreStateless {
1332
1549
  evaluationCache: {}
1333
1550
  };
1334
1551
  }
1335
- captureException(error, distinctId, additionalProperties, uuid, flags) {
1552
+ captureException(error, options, ...legacyArgs) {
1553
+ const exceptionOptions = readCaptureExceptionArgs('captureException', options, legacyArgs, true);
1336
1554
  if (!error_tracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1337
1555
  const syntheticException = new Error('PostHog syntheticException');
1338
- this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1339
- syntheticException
1340
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this._capturePreparedEvent({
1341
- ...msg,
1342
- uuid,
1343
- flags
1344
- }, false)));
1556
+ this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this._capturePreparedEvent(msg, false)));
1345
1557
  }
1346
1558
  }
1347
- async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
1559
+ async captureExceptionImmediate(error, options, ...legacyArgs) {
1560
+ const exceptionOptions = readCaptureExceptionArgs('captureExceptionImmediate', options, legacyArgs, false);
1348
1561
  if (!error_tracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1349
1562
  const syntheticException = new Error('PostHog syntheticException');
1350
- return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1351
- syntheticException
1352
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this.captureImmediate({
1353
- ...msg,
1354
- flags
1355
- })));
1563
+ return this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this.captureImmediate(msg)));
1356
1564
  }
1357
1565
  }
1358
- async prepareEventMessage(props) {
1359
- return this._prepareEventMessage(props);
1566
+ async _buildExceptionEvent(error, syntheticException, { distinctId, properties, options, uuid, flags, level }) {
1567
+ const msg = await error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1568
+ syntheticException
1569
+ }, distinctId, properties, level, this.getContext());
1570
+ return {
1571
+ ...msg,
1572
+ options,
1573
+ uuid,
1574
+ flags
1575
+ };
1360
1576
  }
1361
1577
  _serviceNameProperties() {
1362
1578
  const serviceName = this._resolveServiceName();
@@ -1368,87 +1584,109 @@ class PostHogBackendClient extends PostHogCoreStateless {
1368
1584
  if (void 0 === this._serviceName) this._serviceName = (this.options.traces ? resolveTracesConfig(this.options.traces, this.hostResourceAttributes()).serviceName : void 0) || resolveMetricsConfig(this.options.metrics).serviceName || null;
1369
1585
  return this._serviceName;
1370
1586
  }
1371
- async _prepareEventMessage(props, options = {}) {
1587
+ async prepareEventMessage(props) {
1588
+ try {
1589
+ return await this._prepareEventMessage(props);
1590
+ } catch (error) {
1591
+ throw error instanceof UnreadableEventError ? error.original : error;
1592
+ }
1593
+ }
1594
+ async _prepareEventMessage(props, prepareOptions = {}) {
1372
1595
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
1596
+ const callOptions = readEventOptions(props.options);
1373
1597
  const contextData = getEventContext(props, this.context?.get());
1374
- const includeContextProperties = options.includeContextProperties ?? true;
1375
- let mergedDistinctId = distinctId || contextData?.distinctId;
1376
- const mergedProperties = includeContextProperties ? {
1377
- ...this._serviceNameProperties(),
1378
- ...this.props,
1379
- ...contextData?.properties || {},
1380
- ...properties || {}
1381
- } : {
1382
- ...this._serviceNameProperties(),
1383
- ...properties || {}
1598
+ const contextProperties = snapshotLayer(contextData?.properties);
1599
+ const contextOptions = snapshotLayer(contextData?.options);
1600
+ const globalProperties = snapshotLayer(this.props);
1601
+ const globalOptions = this._globalOptions;
1602
+ const libraryId = this.getLibraryId();
1603
+ const libraryVersion = this.getLibraryVersion();
1604
+ const resolvedDistinctId = presentDistinctId(distinctId) ?? presentDistinctId(contextData?.distinctId) ?? prepareOptions.fallbackDistinctId;
1605
+ const eventDistinctId = resolvedDistinctId ?? eventUuidv7();
1606
+ const eventProperties = readCallerValues(()=>({
1607
+ ...properties || {}
1608
+ }));
1609
+ const callerPersonProfile = eventProperties[EVENT_OPTION_LEGACY_PROPERTIES.process_person_profile];
1610
+ if (prepareOptions.distinctIdProperty) eventProperties.distinct_id = eventDistinctId;
1611
+ if ((prepareOptions.contextSession ?? true) && contextData?.sessionId && isUnsetProperty(eventProperties, '$session_id')) eventProperties.$session_id = contextData.sessionId;
1612
+ if (isPlainObject(groups) && Object.keys(groups).length > 0) {
1613
+ const existingGroups = eventProperties.$groups;
1614
+ eventProperties.$groups = isMergeableObject(existingGroups) ? {
1615
+ ...existingGroups,
1616
+ ...groups
1617
+ } : {
1618
+ ...groups
1619
+ };
1620
+ }
1621
+ if (null != disableGeoip) fillProperties(eventProperties, [
1622
+ {
1623
+ $geoip_disable: disableGeoip
1624
+ }
1625
+ ]);
1626
+ fillProperties(eventProperties, [
1627
+ contextProperties,
1628
+ globalProperties
1629
+ ], prepareOptions.callOnlyProperties);
1630
+ fillProperties(eventProperties, [
1631
+ await this._sdkEventProperties(event, eventProperties, eventDistinctId, {
1632
+ groups,
1633
+ flags,
1634
+ sendFeatureFlags,
1635
+ disableGeoip
1636
+ })
1637
+ ]);
1638
+ fillLibraryProperties(eventProperties, libraryId, libraryVersion);
1639
+ const filledOptions = {
1640
+ ...callOptions
1384
1641
  };
1385
- if ('$exception' === event && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) Object.assign(mergedProperties, await getActiveTraceProperties());
1386
- if (!mergedDistinctId) {
1387
- mergedDistinctId = uuidv7();
1388
- mergedProperties.$process_person_profile = false;
1642
+ fillIdentifyStylePersonProfile(event, filledOptions, callerPersonProfile, void 0 !== resolvedDistinctId);
1643
+ fillOptions(filledOptions, [
1644
+ contextOptions,
1645
+ globalOptions,
1646
+ void 0 !== resolvedDistinctId ? void 0 : {
1647
+ process_person_profile: false
1648
+ }
1649
+ ]);
1650
+ dropIdentifyStyleLegacyPersonProfile(event, filledOptions, eventProperties);
1651
+ const eventOptions = void 0 !== callOptions || Object.keys(filledOptions).length > 0 ? filledOptions : void 0;
1652
+ const flagEvent = prepareOptions.flagEvent;
1653
+ const enrichedProperties = flagEvent ? applyFlagEventCapture(eventProperties, flagEvent) : eventProperties;
1654
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : minimizeFlagCalledEventProperties(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : enrichedProperties;
1655
+ let finalEvent = event;
1656
+ if ('$pageview' === event && this.options.__previewCaptureBotPageviews && 'string' == typeof finalProperties.$raw_user_agent && isBlockedUA(finalProperties.$raw_user_agent, this.options.customBlockedUserAgents || [])) {
1657
+ finalEvent = '$bot_pageview';
1658
+ finalProperties.$browser_type = 'bot';
1389
1659
  }
1390
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;
1391
- const flagEvent = options.flagEvent;
1392
- const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties;
1393
- const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties) : minimizeFlagCalledEventProperties(enrichedProperties) : enrichedProperties;
1394
1660
  const eventMessage = this._runBeforeSend({
1395
- distinctId: mergedDistinctId,
1396
- event,
1661
+ distinctId: eventDistinctId,
1662
+ event: finalEvent,
1397
1663
  properties: finalProperties,
1398
1664
  groups,
1399
1665
  flags,
1400
1666
  sendFeatureFlags,
1401
1667
  timestamp,
1402
1668
  disableGeoip,
1403
- uuid
1404
- }, options.onCaptureFailed);
1669
+ uuid,
1670
+ options: eventOptions
1671
+ }, prepareOptions.onCaptureFailed);
1405
1672
  if (!eventMessage) return Promise.reject(null);
1406
- const eventProperties = await Promise.resolve().then(async ()=>{
1407
- if (flags) {
1408
- if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
1409
- return flags._getEventProperties();
1410
- }
1411
- if (sendFeatureFlags) {
1412
- emitDeprecationWarningOnce('sendFeatureFlags', "`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");
1413
- const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
1414
- const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
1415
- return buildFlagEventProperties(flagValues);
1416
- }
1417
- return {};
1418
- }).catch(()=>({})).then((additionalProperties)=>{
1419
- const resolvedGroups = eventMessage.groups || groups;
1420
- return {
1421
- ...additionalProperties,
1422
- ...eventMessage.properties || {},
1423
- ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {
1424
- $groups: resolvedGroups
1425
- } : {}
1426
- };
1427
- });
1428
- if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {
1429
- if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
1430
- eventMessage.event = '$bot_pageview';
1431
- eventProperties.$browser_type = 'bot';
1432
- }
1433
- }
1434
1673
  return {
1435
1674
  distinctId: eventMessage.distinctId,
1436
1675
  event: eventMessage.event,
1437
- properties: eventProperties,
1438
- options: {
1439
- timestamp: eventMessage.timestamp,
1440
- disableGeoip: eventMessage.disableGeoip,
1441
- uuid: eventMessage.uuid
1442
- }
1676
+ properties: eventMessage.properties || {},
1677
+ options: eventMessage.options,
1678
+ uuid: eventMessage.uuid,
1679
+ timestamp: eventMessage.timestamp,
1680
+ disableGeoip: eventMessage.disableGeoip
1443
1681
  };
1444
1682
  }
1445
1683
  _runBeforeSend(eventMessage, onError) {
1446
- const beforeSend = this.options.before_send;
1684
+ const beforeSend = this.options.beforeSend;
1447
1685
  if (!beforeSend) return eventMessage;
1448
1686
  const fns = Array.isArray(beforeSend) ? beforeSend : [
1449
1687
  beforeSend
1450
1688
  ];
1451
- let result = eventMessage;
1689
+ let result = readCallerValues(()=>isolateForBeforeSend(eventMessage));
1452
1690
  for (const fn of fns)try {
1453
1691
  result = fn(result);
1454
1692
  if (!result) {
@@ -1460,7 +1698,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
1460
1698
  this._logger.warn(message);
1461
1699
  }
1462
1700
  } catch (error) {
1463
- this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
1701
+ const errorType = error instanceof Error ? error.name : typeof error;
1702
+ console.error(`[PostHog] Error in beforeSend function for event '${eventMessage.event}' (${errorType})`);
1464
1703
  onError?.();
1465
1704
  return null;
1466
1705
  }