posthog-node 5.74.0 → 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 (144) hide show
  1. package/MIGRATION.md +556 -0
  2. package/README.md +3 -1
  3. package/dist/ai-capture/routing.d.ts +0 -3
  4. package/dist/ai-capture/routing.d.ts.map +1 -1
  5. package/dist/ai-capture/routing.js +2 -14
  6. package/dist/ai-capture/routing.mjs +1 -4
  7. package/dist/capture-lane/lane.d.ts +109 -0
  8. package/dist/capture-lane/lane.d.ts.map +1 -0
  9. package/dist/capture-lane/lane.js +308 -0
  10. package/dist/capture-lane/lane.mjs +270 -0
  11. package/dist/capture-lane/limits.d.ts +7 -0
  12. package/dist/capture-lane/limits.d.ts.map +1 -0
  13. package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
  14. package/dist/capture-lane/limits.mjs +4 -0
  15. package/dist/capture-lane/settings.d.ts +30 -0
  16. package/dist/capture-lane/settings.d.ts.map +1 -0
  17. package/dist/capture-lane/settings.js +100 -0
  18. package/dist/capture-lane/settings.mjs +47 -0
  19. package/dist/capture-v1/compression.d.ts +18 -0
  20. package/dist/capture-v1/compression.d.ts.map +1 -0
  21. package/dist/capture-v1/compression.js +70 -0
  22. package/dist/capture-v1/compression.mjs +26 -0
  23. package/dist/capture-v1/errors.d.ts +23 -7
  24. package/dist/capture-v1/errors.d.ts.map +1 -1
  25. package/dist/capture-v1/errors.js +37 -8
  26. package/dist/capture-v1/errors.mjs +29 -6
  27. package/dist/capture-v1/sender.d.ts +63 -23
  28. package/dist/capture-v1/sender.d.ts.map +1 -1
  29. package/dist/capture-v1/sender.js +281 -74
  30. package/dist/capture-v1/sender.mjs +275 -77
  31. package/dist/capture-v1/serialize.d.ts +28 -0
  32. package/dist/capture-v1/serialize.d.ts.map +1 -0
  33. package/dist/capture-v1/serialize.js +82 -0
  34. package/dist/capture-v1/serialize.mjs +38 -0
  35. package/dist/capture-v1/transform.d.ts +10 -25
  36. package/dist/capture-v1/transform.d.ts.map +1 -1
  37. package/dist/capture-v1/transform.js +33 -64
  38. package/dist/capture-v1/transform.mjs +28 -53
  39. package/dist/capture-v1/types.d.ts +16 -14
  40. package/dist/capture-v1/types.d.ts.map +1 -1
  41. package/dist/capture-v1/types.js +27 -1
  42. package/dist/capture-v1/types.mjs +3 -1
  43. package/dist/capture-v1/uuid.d.ts +9 -0
  44. package/dist/capture-v1/uuid.d.ts.map +1 -0
  45. package/dist/capture-v1/uuid.js +75 -0
  46. package/dist/capture-v1/uuid.mjs +34 -0
  47. package/dist/client.d.ts +201 -94
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +456 -228
  50. package/dist/client.mjs +455 -227
  51. package/dist/compression.node.d.ts +13 -0
  52. package/dist/compression.node.d.ts.map +1 -0
  53. package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
  54. package/dist/compression.node.mjs +18 -0
  55. package/dist/entrypoints/index.node.d.ts +2 -0
  56. package/dist/entrypoints/index.node.d.ts.map +1 -1
  57. package/dist/entrypoints/index.node.js +11 -4
  58. package/dist/entrypoints/index.node.mjs +4 -0
  59. package/dist/event-defaults.d.ts +46 -0
  60. package/dist/event-defaults.d.ts.map +1 -0
  61. package/dist/event-defaults.js +141 -0
  62. package/dist/event-defaults.mjs +79 -0
  63. package/dist/exports.d.ts +3 -0
  64. package/dist/exports.d.ts.map +1 -1
  65. package/dist/exports.js +22 -11
  66. package/dist/exports.mjs +1 -0
  67. package/dist/extensions/context/context.d.ts +0 -1
  68. package/dist/extensions/context/context.d.ts.map +1 -1
  69. package/dist/extensions/context/context.js +4 -3
  70. package/dist/extensions/context/context.mjs +4 -3
  71. package/dist/extensions/context/event-context.d.ts.map +1 -1
  72. package/dist/extensions/context/event-context.js +3 -0
  73. package/dist/extensions/context/event-context.mjs +3 -0
  74. package/dist/extensions/context/types.d.ts +9 -1
  75. package/dist/extensions/context/types.d.ts.map +1 -1
  76. package/dist/extensions/error-tracking/index.d.ts +1 -1
  77. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  78. package/dist/extensions/error-tracking/index.js +71 -7
  79. package/dist/extensions/error-tracking/index.mjs +75 -11
  80. package/dist/extensions/express.d.ts +8 -0
  81. package/dist/extensions/express.d.ts.map +1 -1
  82. package/dist/extensions/express.js +3 -3
  83. package/dist/extensions/express.mjs +4 -4
  84. package/dist/extensions/fetch-request.d.ts.map +1 -1
  85. package/dist/extensions/fetch-request.js +2 -2
  86. package/dist/extensions/fetch-request.mjs +3 -3
  87. package/dist/extensions/nestjs.d.ts.map +1 -1
  88. package/dist/extensions/nestjs.js +7 -4
  89. package/dist/extensions/nestjs.mjs +8 -5
  90. package/dist/extensions/tracing-headers.d.ts +7 -0
  91. package/dist/extensions/tracing-headers.d.ts.map +1 -1
  92. package/dist/extensions/tracing-headers.js +11 -1
  93. package/dist/extensions/tracing-headers.mjs +9 -2
  94. package/dist/flag-events.d.ts +1 -1
  95. package/dist/flag-events.d.ts.map +1 -1
  96. package/dist/flag-events.js +2 -2
  97. package/dist/flag-events.mjs +2 -2
  98. package/dist/types.d.ts +191 -27
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/version.d.ts +1 -1
  101. package/dist/version.d.ts.map +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/version.mjs +1 -1
  104. package/package.json +5 -4
  105. package/src/ai-capture/routing.ts +0 -6
  106. package/src/capture-lane/lane.ts +414 -0
  107. package/src/capture-lane/limits.ts +8 -0
  108. package/src/capture-lane/settings.ts +119 -0
  109. package/src/capture-v1/compression.ts +50 -0
  110. package/src/capture-v1/errors.ts +50 -11
  111. package/src/capture-v1/sender.ts +405 -111
  112. package/src/capture-v1/serialize.ts +77 -0
  113. package/src/capture-v1/transform.ts +59 -92
  114. package/src/capture-v1/types.ts +19 -15
  115. package/src/capture-v1/uuid.ts +53 -0
  116. package/src/client.ts +845 -422
  117. package/src/compression.node.ts +30 -0
  118. package/src/entrypoints/index.node.ts +6 -0
  119. package/src/event-defaults.ts +177 -0
  120. package/src/exports.ts +3 -0
  121. package/src/extensions/context/context.ts +4 -4
  122. package/src/extensions/context/event-context.ts +3 -1
  123. package/src/extensions/context/types.ts +10 -1
  124. package/src/extensions/error-tracking/index.ts +51 -7
  125. package/src/extensions/express.ts +12 -3
  126. package/src/extensions/fetch-request.ts +7 -3
  127. package/src/extensions/nestjs.ts +9 -5
  128. package/src/extensions/tracing-headers.ts +26 -7
  129. package/src/flag-events.ts +5 -2
  130. package/src/types.ts +211 -44
  131. package/src/version.ts +1 -1
  132. package/dist/ai-capture/batching.d.ts +0 -11
  133. package/dist/ai-capture/batching.d.ts.map +0 -1
  134. package/dist/ai-capture/batching.js +0 -77
  135. package/dist/ai-capture/batching.mjs +0 -36
  136. package/dist/capture-v1/config.d.ts +0 -11
  137. package/dist/capture-v1/config.d.ts.map +0 -1
  138. package/dist/capture-v1/config.mjs +0 -8
  139. package/dist/capture-v1/routing.d.ts +0 -21
  140. package/dist/capture-v1/routing.d.ts.map +0 -1
  141. package/dist/capture-v1/routing.mjs +0 -7
  142. package/src/ai-capture/batching.ts +0 -47
  143. package/src/capture-v1/config.ts +0 -18
  144. package/src/capture-v1/routing.ts +0 -28
package/dist/client.mjs CHANGED
@@ -1,5 +1,5 @@
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
5
  import { FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE, isServerFailedFlagRecord, isUnreadableFlagRecord, parsedFlagRecordOf, readFlagRecords } from "./flags-response.mjs";
@@ -8,13 +8,18 @@ import { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation }
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;
@@ -423,10 +576,34 @@ class PostHogBackendClient extends PostHogCoreStateless {
423
576
  }
424
577
  };
425
578
  }
426
- getCommonEventProperties() {
427
- const commonProperties = super.getCommonEventProperties();
428
- if (this.options.isServer ?? true) commonProperties.$is_server = true;
429
- 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 {};
430
607
  }
431
608
  enable() {
432
609
  return super.optIn();
@@ -438,34 +615,52 @@ class PostHogBackendClient extends PostHogCoreStateless {
438
615
  super.debug(enabled);
439
616
  this.featureFlagsPoller?.debug(enabled);
440
617
  }
618
+ describeDebugPayload(payload) {
619
+ return summarizeForDebugLog(payload);
620
+ }
441
621
  _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
442
622
  if ('string' == typeof props) this._logger.warn(stringArgumentWarning);
443
623
  if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);
444
624
  }
445
625
  _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
446
- 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 })=>{
447
633
  if (this.disabled || this.optedOut) prepareOptions?.onCaptureFailed?.();
448
634
  const captureOptions = {
449
- timestamp: options.timestamp,
450
- disableGeoip: options.disableGeoip,
451
- uuid: options.uuid
635
+ timestamp,
636
+ disableGeoip: false,
637
+ uuid,
638
+ _invalidUuidWarned: invalidUuidWarned
452
639
  };
453
640
  const message = {
454
- distinctId,
641
+ distinct_id: distinctId,
455
642
  event,
456
- properties: {
457
- ...properties,
458
- ...this.getCommonEventProperties()
459
- }
643
+ properties,
644
+ ...void 0 !== options ? {
645
+ options
646
+ } : {}
460
647
  };
461
648
  return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
462
649
  }).catch((err)=>{
463
- if (err) {
650
+ if (err instanceof UnreadableEventError) {
651
+ this._dropUnreadableEvent(uuid, immediate, explicitRoute);
652
+ prepareOptions?.onCaptureFailed?.();
653
+ } else if (err) {
464
654
  console.error(err);
465
655
  prepareOptions?.onCaptureFailed?.();
466
656
  }
467
657
  }));
468
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
+ }
469
664
  _capturePreparedEvent(props, immediate) {
470
665
  return this._sendPreparedEvent('capture', props, immediate);
471
666
  }
@@ -479,7 +674,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
479
674
  }
480
675
  captureAi(props) {
481
676
  if (this.disabled) return;
482
- const uuid = getEventUuid(props.uuid, uuidv7);
677
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7();
483
678
  this._sendPreparedAiEvent({
484
679
  ...props,
485
680
  uuid
@@ -488,7 +683,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
488
683
  }
489
684
  async captureAiImmediate(props) {
490
685
  if (this.disabled) return;
491
- const uuid = getEventUuid(props.uuid, uuidv7);
686
+ const uuid = this._canonicalEventUuid(props.uuid) ?? eventUuidv7();
492
687
  await this._sendPreparedAiEvent({
493
688
  ...props,
494
689
  uuid
@@ -497,46 +692,29 @@ class PostHogBackendClient extends PostHogCoreStateless {
497
692
  }
498
693
  _sendPreparedAiEvent(props, immediate) {
499
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.`);
500
- this._aiCaptureRouteActive = true;
501
695
  return this._sendPreparedEvent('capture', props, immediate, void 0, AI_CAPTURE_ROUTE);
502
696
  }
503
- identify({ distinctId, properties = {}, disableGeoip }) {
504
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
505
- const setProps = $set || rest;
506
- const setOnceProps = $set_once || {};
507
- const eventProperties = {
508
- $set: setProps,
509
- $set_once: setOnceProps,
510
- $anon_distinct_id: $anon_distinct_id ?? void 0
511
- };
697
+ identify({ distinctId, properties = {}, disableGeoip, options }) {
698
+ const eventProperties = identifyEventProperties(properties);
512
699
  this._sendPreparedEvent('identify', {
513
700
  distinctId,
514
701
  event: '$identify',
515
702
  properties: eventProperties,
516
- disableGeoip
517
- }, false, {
518
- includeContextProperties: false
519
- });
703
+ disableGeoip,
704
+ options
705
+ }, false);
520
706
  }
521
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
522
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
523
- const setProps = $set || rest;
524
- const setOnceProps = $set_once || {};
525
- const eventProperties = {
526
- $set: setProps,
527
- $set_once: setOnceProps,
528
- $anon_distinct_id: $anon_distinct_id ?? void 0
529
- };
707
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }) {
708
+ const eventProperties = identifyEventProperties(properties);
530
709
  await this._sendPreparedEvent('identify', {
531
710
  distinctId,
532
711
  event: '$identify',
533
712
  properties: eventProperties,
534
- disableGeoip
535
- }, true, {
536
- includeContextProperties: false
537
- });
713
+ disableGeoip,
714
+ options
715
+ }, true);
538
716
  }
539
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
717
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }) {
540
718
  if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;
541
719
  const eventProperties = {};
542
720
  if (Object.keys(properties).length > 0) eventProperties.$set = properties;
@@ -544,10 +722,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
544
722
  this.capture({
545
723
  distinctId,
546
724
  event: '$set',
547
- properties: eventProperties
725
+ properties: eventProperties,
726
+ options
548
727
  });
549
728
  }
550
- unsetPersonProperties({ distinctId, properties }) {
729
+ unsetPersonProperties({ distinctId, properties, options }) {
551
730
  const propertyNames = normalizeUnsetPersonProperties(properties);
552
731
  if (0 === propertyNames.length) return;
553
732
  this.capture({
@@ -555,7 +734,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
555
734
  event: '$set',
556
735
  properties: {
557
736
  $unset: propertyNames
558
- }
737
+ },
738
+ options
559
739
  });
560
740
  }
561
741
  alias(data) {
@@ -563,26 +743,22 @@ class PostHogBackendClient extends PostHogCoreStateless {
563
743
  distinctId: data.distinctId,
564
744
  event: '$create_alias',
565
745
  properties: {
566
- distinct_id: data.distinctId,
567
746
  alias: data.alias
568
747
  },
569
- disableGeoip: data.disableGeoip
570
- }, false, {
571
- includeContextProperties: false
572
- });
748
+ disableGeoip: data.disableGeoip,
749
+ options: data.options
750
+ }, false, ALIAS_PREPARE_OPTIONS);
573
751
  }
574
752
  async aliasImmediate(data) {
575
753
  await this._sendPreparedEvent('alias', {
576
754
  distinctId: data.distinctId,
577
755
  event: '$create_alias',
578
756
  properties: {
579
- distinct_id: data.distinctId,
580
757
  alias: data.alias
581
758
  },
582
- disableGeoip: data.disableGeoip
583
- }, true, {
584
- includeContextProperties: false
585
- });
759
+ disableGeoip: data.disableGeoip,
760
+ options: data.options
761
+ }, true, ALIAS_PREPARE_OPTIONS);
586
762
  }
587
763
  isLocalEvaluationReady() {
588
764
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
@@ -1100,32 +1276,36 @@ class PostHogBackendClient extends PostHogCoreStateless {
1100
1276
  };
1101
1277
  return this._featureFlagEvaluationsHost;
1102
1278
  }
1103
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1279
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1104
1280
  this._sendPreparedEvent('capture', {
1105
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1281
+ distinctId,
1106
1282
  event: '$groupidentify',
1107
1283
  properties: {
1108
1284
  $group_type: groupType,
1109
1285
  $group_key: groupKey,
1110
1286
  $group_set: properties || {}
1111
1287
  },
1112
- disableGeoip
1288
+ disableGeoip,
1289
+ options
1113
1290
  }, false, {
1114
- includeContextProperties: false
1291
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1292
+ contextSession: false
1115
1293
  });
1116
1294
  }
1117
- async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1295
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1118
1296
  await this._sendPreparedEvent('capture', {
1119
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1297
+ distinctId,
1120
1298
  event: '$groupidentify',
1121
1299
  properties: {
1122
1300
  $group_type: groupType,
1123
1301
  $group_key: groupKey,
1124
1302
  $group_set: properties || {}
1125
1303
  },
1126
- disableGeoip
1304
+ disableGeoip,
1305
+ options
1127
1306
  }, true, {
1128
- includeContextProperties: false
1307
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1308
+ contextSession: false
1129
1309
  });
1130
1310
  }
1131
1311
  async reloadFeatureFlags() {
@@ -1178,6 +1358,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
1178
1358
  }
1179
1359
  return false;
1180
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
+ }
1181
1381
  withContext(data, fn, options) {
1182
1382
  if (!this.context) return fn();
1183
1383
  return this.context.run(data, ()=>{
@@ -1188,10 +1388,6 @@ class PostHogBackendClient extends PostHogCoreStateless {
1188
1388
  getContext() {
1189
1389
  return this.context?.get();
1190
1390
  }
1191
- enterContext(data, options) {
1192
- this.context?.enter(data, options);
1193
- notifyContextListeners(this);
1194
- }
1195
1391
  async _shutdown(shutdownTimeoutMs) {
1196
1392
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
1197
1393
  this._isShutdown = true;
@@ -1227,8 +1423,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
1227
1423
  const remainingMs = Math.max(0, shutdownDeadlineMs - Date.now());
1228
1424
  const emailsSettled = emailsDrained ? raceWithTimeout(emailsDrained, remainingMs) : void 0;
1229
1425
  try {
1230
- return await super._shutdown(remainingMs);
1426
+ await Promise.all([
1427
+ super._shutdown(remainingMs),
1428
+ this._drainCaptureLanes(shutdownDeadlineMs)
1429
+ ]);
1430
+ await this._drainCaptureLanes(shutdownDeadlineMs);
1231
1431
  } finally{
1432
+ for (const lane of this._captureLanes.values())lane.finishShutdown();
1232
1433
  await emailsSettled;
1233
1434
  await logsDrained;
1234
1435
  this._distinctIdHasSentFlagCalls.clear();
@@ -1236,6 +1437,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
1236
1437
  resolve?.();
1237
1438
  }
1238
1439
  }
1440
+ _drainCaptureLanes(deadlineMs) {
1441
+ return Promise.all([
1442
+ ...this._captureLanes.values()
1443
+ ].map((lane)=>lane.drain(deadlineMs))).then(()=>{});
1444
+ }
1239
1445
  async _requestRemoteConfigPayload(flagKey) {
1240
1446
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;
1241
1447
  const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
@@ -1343,31 +1549,30 @@ class PostHogBackendClient extends PostHogCoreStateless {
1343
1549
  evaluationCache: {}
1344
1550
  };
1345
1551
  }
1346
- captureException(error, distinctId, additionalProperties, uuid, flags) {
1552
+ captureException(error, options, ...legacyArgs) {
1553
+ const exceptionOptions = readCaptureExceptionArgs('captureException', options, legacyArgs, true);
1347
1554
  if (!error_tracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1348
1555
  const syntheticException = new Error('PostHog syntheticException');
1349
- this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1350
- syntheticException
1351
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this._capturePreparedEvent({
1352
- ...msg,
1353
- uuid,
1354
- flags
1355
- }, false)));
1556
+ this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this._capturePreparedEvent(msg, false)));
1356
1557
  }
1357
1558
  }
1358
- async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
1559
+ async captureExceptionImmediate(error, options, ...legacyArgs) {
1560
+ const exceptionOptions = readCaptureExceptionArgs('captureExceptionImmediate', options, legacyArgs, false);
1359
1561
  if (!error_tracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1360
1562
  const syntheticException = new Error('PostHog syntheticException');
1361
- return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1362
- syntheticException
1363
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this.captureImmediate({
1364
- ...msg,
1365
- flags
1366
- })));
1563
+ return this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this.captureImmediate(msg)));
1367
1564
  }
1368
1565
  }
1369
- async prepareEventMessage(props) {
1370
- 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
+ };
1371
1576
  }
1372
1577
  _serviceNameProperties() {
1373
1578
  const serviceName = this._resolveServiceName();
@@ -1379,87 +1584,109 @@ class PostHogBackendClient extends PostHogCoreStateless {
1379
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;
1380
1585
  return this._serviceName;
1381
1586
  }
1382
- 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 = {}) {
1383
1595
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
1596
+ const callOptions = readEventOptions(props.options);
1384
1597
  const contextData = getEventContext(props, this.context?.get());
1385
- const includeContextProperties = options.includeContextProperties ?? true;
1386
- let mergedDistinctId = distinctId || contextData?.distinctId;
1387
- const mergedProperties = includeContextProperties ? {
1388
- ...this._serviceNameProperties(),
1389
- ...this.props,
1390
- ...contextData?.properties || {},
1391
- ...properties || {}
1392
- } : {
1393
- ...this._serviceNameProperties(),
1394
- ...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
1395
1641
  };
1396
- if ('$exception' === event && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) Object.assign(mergedProperties, await getActiveTraceProperties());
1397
- if (!mergedDistinctId) {
1398
- mergedDistinctId = uuidv7();
1399
- 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';
1400
1659
  }
1401
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;
1402
- const flagEvent = options.flagEvent;
1403
- const enrichedProperties = flagEvent ? applyFlagEventCapture(mergedProperties, flagEvent) : mergedProperties;
1404
- const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? minimizeConfigVersion2FlagCalledProperties(enrichedProperties) : minimizeFlagCalledEventProperties(enrichedProperties) : enrichedProperties;
1405
1660
  const eventMessage = this._runBeforeSend({
1406
- distinctId: mergedDistinctId,
1407
- event,
1661
+ distinctId: eventDistinctId,
1662
+ event: finalEvent,
1408
1663
  properties: finalProperties,
1409
1664
  groups,
1410
1665
  flags,
1411
1666
  sendFeatureFlags,
1412
1667
  timestamp,
1413
1668
  disableGeoip,
1414
- uuid
1415
- }, options.onCaptureFailed);
1669
+ uuid,
1670
+ options: eventOptions
1671
+ }, prepareOptions.onCaptureFailed);
1416
1672
  if (!eventMessage) return Promise.reject(null);
1417
- const eventProperties = await Promise.resolve().then(async ()=>{
1418
- if (flags) {
1419
- if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
1420
- return flags._getEventProperties();
1421
- }
1422
- if (sendFeatureFlags) {
1423
- 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.");
1424
- const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
1425
- const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
1426
- return buildFlagEventProperties(flagValues);
1427
- }
1428
- return {};
1429
- }).catch(()=>({})).then((additionalProperties)=>{
1430
- const resolvedGroups = eventMessage.groups || groups;
1431
- return {
1432
- ...additionalProperties,
1433
- ...eventMessage.properties || {},
1434
- ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {
1435
- $groups: resolvedGroups
1436
- } : {}
1437
- };
1438
- });
1439
- if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {
1440
- if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
1441
- eventMessage.event = '$bot_pageview';
1442
- eventProperties.$browser_type = 'bot';
1443
- }
1444
- }
1445
1673
  return {
1446
1674
  distinctId: eventMessage.distinctId,
1447
1675
  event: eventMessage.event,
1448
- properties: eventProperties,
1449
- options: {
1450
- timestamp: eventMessage.timestamp,
1451
- disableGeoip: eventMessage.disableGeoip,
1452
- uuid: eventMessage.uuid
1453
- }
1676
+ properties: eventMessage.properties || {},
1677
+ options: eventMessage.options,
1678
+ uuid: eventMessage.uuid,
1679
+ timestamp: eventMessage.timestamp,
1680
+ disableGeoip: eventMessage.disableGeoip
1454
1681
  };
1455
1682
  }
1456
1683
  _runBeforeSend(eventMessage, onError) {
1457
- const beforeSend = this.options.before_send;
1684
+ const beforeSend = this.options.beforeSend;
1458
1685
  if (!beforeSend) return eventMessage;
1459
1686
  const fns = Array.isArray(beforeSend) ? beforeSend : [
1460
1687
  beforeSend
1461
1688
  ];
1462
- let result = eventMessage;
1689
+ let result = readCallerValues(()=>isolateForBeforeSend(eventMessage));
1463
1690
  for (const fn of fns)try {
1464
1691
  result = fn(result);
1465
1692
  if (!result) {
@@ -1471,7 +1698,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
1471
1698
  this._logger.warn(message);
1472
1699
  }
1473
1700
  } catch (error) {
1474
- 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})`);
1475
1703
  onError?.();
1476
1704
  return null;
1477
1705
  }