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.js CHANGED
@@ -51,13 +51,18 @@ const index_js_namespaceObject = require("./extensions/error-tracking/index.js")
51
51
  var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
52
52
  const trace_context_js_namespaceObject = require("./extensions/error-tracking/trace-context.js");
53
53
  const external_storage_memory_js_namespaceObject = require("./storage-memory.js");
54
+ const sender_js_namespaceObject = require("./capture-v1/sender.js");
55
+ const types_js_namespaceObject = require("./capture-v1/types.js");
56
+ const lane_js_namespaceObject = require("./capture-lane/lane.js");
57
+ const limits_js_namespaceObject = require("./capture-lane/limits.js");
58
+ const settings_js_namespaceObject = require("./capture-lane/settings.js");
59
+ const compression_js_namespaceObject = require("./capture-v1/compression.js");
60
+ const uuid_js_namespaceObject = require("./capture-v1/uuid.js");
61
+ const transform_js_namespaceObject = require("./capture-v1/transform.js");
62
+ const external_event_defaults_js_namespaceObject = require("./event-defaults.js");
63
+ const routing_js_namespaceObject = require("./ai-capture/routing.js");
54
64
  const listeners_js_namespaceObject = require("./extensions/context/listeners.js");
55
65
  const event_context_js_namespaceObject = require("./extensions/context/event-context.js");
56
- const config_js_namespaceObject = require("./capture-v1/config.js");
57
- const routing_js_namespaceObject = require("./capture-v1/routing.js");
58
- const sender_js_namespaceObject = require("./capture-v1/sender.js");
59
- const batching_js_namespaceObject = require("./ai-capture/batching.js");
60
- const external_ai_capture_routing_js_namespaceObject = require("./ai-capture/routing.js");
61
66
  const emails_js_namespaceObject = require("./emails/emails.js");
62
67
  const external_logs_config_js_namespaceObject = require("./logs-config.js");
63
68
  const MINIMUM_POLLING_INTERVAL = 100;
@@ -67,10 +72,10 @@ const WAITUNTIL_DEBOUNCE_MS = 50;
67
72
  const WAITUNTIL_MAX_WAIT_MS = 500;
68
73
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com';
69
74
  const _emittedDeprecations = new Set();
70
- function emitDeprecationWarningOnce(id, message) {
75
+ function emitDeprecationWarningOnce(id, message, log = console.warn) {
71
76
  if (_emittedDeprecations.has(id)) return;
72
77
  _emittedDeprecations.add(id);
73
- console.warn(`[PostHog] ${message}`);
78
+ log(`[PostHog] ${message}`);
74
79
  }
75
80
  function _resetDeprecationWarningsForTests() {
76
81
  _emittedDeprecations.clear();
@@ -78,14 +83,122 @@ function _resetDeprecationWarningsForTests() {
78
83
  function normalizeApiKey(value) {
79
84
  return 'string' == typeof value ? value.trim() : '';
80
85
  }
86
+ function apiKeyProblem(apiKey) {
87
+ if (!apiKey) return 'No project API key was passed';
88
+ if (apiKey.startsWith('phx_')) return 'A personal API key ("phx_...") was passed where the project API key ("phc_...") belongs';
89
+ }
90
+ function summarizeForDebugLog(payload) {
91
+ if (Array.isArray(payload)) return `${payload.length} item(s)`;
92
+ if (payload instanceof Error) return `${payload.name}: ${payload.message}`;
93
+ if (payload && 'object' == typeof payload && 'string' == typeof payload.event) {
94
+ const { event, uuid } = payload;
95
+ return void 0 === uuid ? {
96
+ event
97
+ } : {
98
+ event,
99
+ uuid
100
+ };
101
+ }
102
+ }
81
103
  function normalizePersonalApiKey(value) {
82
104
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
83
105
  return normalizedValue || void 0;
84
106
  }
107
+ function isUnsetUuid(uuid) {
108
+ return null == uuid || '' === uuid;
109
+ }
110
+ function isInvalidUuid(uuid) {
111
+ return !isUnsetUuid(uuid) && ('string' != typeof uuid || void 0 === (0, uuid_js_namespaceObject.canonicalizeUuid)(uuid));
112
+ }
85
113
  function normalizeHost(value) {
86
114
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
87
115
  return normalizedValue || DEFAULT_NODE_HOST;
88
116
  }
117
+ const FLAG_CALLED_OPTION_SOURCE_PROPERTIES = [
118
+ '$cookieless_mode',
119
+ '$ignore_sent_at',
120
+ '$product_tour_id',
121
+ '$process_person_profile',
122
+ '$session_id',
123
+ '$window_id'
124
+ ];
125
+ function readCaptureExceptionArgs(method, second, rest, legacyHasUuid) {
126
+ if ('string' != typeof second && (0 === rest.length || (0, core_namespaceObject.isPlainObject)(second))) {
127
+ if (rest.length > 0) emitDeprecationWarningOnce(`${method} extra arguments`, `${method}(error, options) ignores the arguments after the options object.`);
128
+ return (0, core_namespaceObject.isPlainObject)(second) ? second : {};
129
+ }
130
+ 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);
131
+ const [properties, ...tail] = rest;
132
+ const [uuid, flags] = legacyHasUuid ? tail : [
133
+ void 0,
134
+ tail[0]
135
+ ];
136
+ return {
137
+ distinctId: second ?? void 0,
138
+ properties: properties,
139
+ uuid: uuid,
140
+ flags: flags
141
+ };
142
+ }
143
+ class UnreadableEventError extends Error {
144
+ constructor(original){
145
+ super('A value in the event threw while it was read'), this.original = original;
146
+ }
147
+ }
148
+ function readCallerValues(read) {
149
+ try {
150
+ return read();
151
+ } catch (error) {
152
+ throw new UnreadableEventError(error);
153
+ }
154
+ }
155
+ function isolateForBeforeSend(eventMessage) {
156
+ const isolated = copyPlainValues(eventMessage, new WeakMap());
157
+ isolated.options ??= {};
158
+ return isolated;
159
+ }
160
+ function isPlainRecord(value) {
161
+ if (null === value || 'object' != typeof value) return false;
162
+ const prototype = Object.getPrototypeOf(value);
163
+ return prototype === Object.prototype || null === prototype;
164
+ }
165
+ function copyPlainValues(value, seen) {
166
+ if (!Array.isArray(value) && !isPlainRecord(value)) return value;
167
+ const known = seen.get(value);
168
+ if (void 0 !== known) return known;
169
+ if (Array.isArray(value)) {
170
+ const copy = new Array(value.length);
171
+ seen.set(value, copy);
172
+ value.forEach((item, index)=>{
173
+ copy[index] = copyPlainValues(item, seen);
174
+ });
175
+ return copy;
176
+ }
177
+ const copy = null === Object.getPrototypeOf(value) ? Object.create(null) : {};
178
+ seen.set(value, copy);
179
+ for (const key of Object.keys(value))copy[key] = copyPlainValues(value[key], seen);
180
+ return copy;
181
+ }
182
+ function identifyEventProperties(properties) {
183
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
184
+ return {
185
+ $set: $set || rest,
186
+ ...null != $set_once ? {
187
+ $set_once
188
+ } : {},
189
+ $anon_distinct_id: $anon_distinct_id ?? void 0
190
+ };
191
+ }
192
+ const ALIAS_PREPARE_OPTIONS = {
193
+ callOnlyProperties: [
194
+ 'alias'
195
+ ],
196
+ distinctIdProperty: true
197
+ };
198
+ function presentDistinctId(value) {
199
+ if (null == value || 'string' == typeof value && '' === value.trim()) return;
200
+ return 'string' == typeof value ? value : String(value);
201
+ }
89
202
  function positiveNumberOr(value, fallback) {
90
203
  return 'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
91
204
  }
@@ -115,16 +228,20 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
115
228
  }
116
229
  constructor(apiKey, options = {}){
117
230
  const normalizedApiKey = normalizeApiKey(apiKey);
231
+ const keyProblem = apiKeyProblem(normalizedApiKey);
118
232
  const normalizedOptions = {
119
233
  ...options,
234
+ disabled: options.disabled || void 0 !== keyProblem,
120
235
  maxQueueSize: options.maxQueueSize ?? 10000,
121
236
  flushInterval: options.flushInterval ?? 5000,
122
237
  host: normalizeHost(options.host),
123
238
  personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
124
239
  };
125
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new external_storage_memory_js_namespaceObject.PostHogMemoryStorage(), this._isShutdown = false, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
240
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new external_storage_memory_js_namespaceObject.PostHogMemoryStorage(), this._captureLanes = new Map(), this._isShutdown = false, this._globalOptions = {}, this._minimalFlagCalledEvents = false, this._loggedFlagsResponseWithoutTypedValues = false, this._experimentExposuresReported = new Map();
126
241
  this.options = normalizedOptions;
127
- this.captureMode = (0, config_js_namespaceObject.resolveCaptureMode)();
242
+ if (keyProblem) console.error(`[PostHog] ${keyProblem}, so the client is disabled.`);
243
+ this.warnIfCaptureModeSet();
244
+ this._captureSettings = (0, settings_js_namespaceObject.resolveCaptureSettings)(normalizedOptions, (message)=>console.error(`[PostHog] ${message}`));
128
245
  this.enableFullAiCapture = true === normalizedOptions.enableFullAiCapture;
129
246
  this.privacyMode = true === normalizedOptions.privacyMode;
130
247
  this.context = this.initializeContext();
@@ -161,11 +278,45 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
161
278
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
162
279
  }
163
280
  enqueue(type, message, options, explicitRoute) {
164
- super.enqueue(type, message, options, explicitRoute);
281
+ this.wrap(()=>{
282
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
283
+ const prepared = this._prepareLaneMessage(message, options);
284
+ if (null === prepared) return;
285
+ this._captureLane(explicitRoute).enqueue(prepared);
286
+ this._events.emit(type, prepared);
287
+ });
165
288
  this.scheduleDebouncedFlush();
166
289
  }
290
+ async sendImmediate(type, message, options, explicitRoute) {
291
+ if (this.disabled) return void this._logger.warn('The client is disabled');
292
+ if (!this._isInitialized) await this._initPromise;
293
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
294
+ const prepared = this._prepareLaneMessage(message, options);
295
+ if (null === prepared) return;
296
+ try {
297
+ await this._captureLane(explicitRoute).sendImmediate(prepared);
298
+ } catch (err) {
299
+ this._events.emit('error', err);
300
+ }
301
+ }
302
+ _prepareLaneMessage(message, options) {
303
+ const { _invalidUuidWarned, ...captureOptions } = options ?? {};
304
+ const uuid = this._canonicalEventUuid(captureOptions.uuid, !_invalidUuidWarned) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
305
+ const prepared = this.processBeforeEnqueue(this.prepareMessage(message, {
306
+ ...captureOptions,
307
+ uuid
308
+ }));
309
+ return null === prepared ? null : this.normalizeMessage(prepared);
310
+ }
311
+ _canonicalEventUuid(uuid, warnIfInvalid = true) {
312
+ if (isUnsetUuid(uuid)) return;
313
+ const canonical = 'string' == typeof uuid ? (0, uuid_js_namespaceObject.canonicalizeUuid)(uuid) : void 0;
314
+ if (void 0 !== canonical) return canonical;
315
+ if (warnIfInvalid) console.warn('[PostHog] Replaced an invalid event uuid with a generated one; uuids must be RFC 4122 strings');
316
+ return (0, uuid_js_namespaceObject.eventUuidv7)();
317
+ }
167
318
  _flushEventsAndSpans(skipThrottledSpans = false) {
168
- const events = this.flushWithPendingPromises();
319
+ const events = this.flushWithPendingPromises().then(()=>this._flushCaptureLanes());
169
320
  const others = [];
170
321
  if (this._traces && !(skipThrottledSpans && this._traces.throttled)) others.push(this._traces.flush().catch(()=>{}));
171
322
  if (this._logs && !(skipThrottledSpans && this._logs.throttled)) others.push(this._logs.flushInBackground());
@@ -177,15 +328,24 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
177
328
  if ('rejected' === eventsResult.status) throw eventsResult.reason;
178
329
  });
179
330
  }
180
- flushAutomatic() {
181
- return this._flushKeepingRuntimeAlive(true);
182
- }
183
331
  async flush() {
184
332
  this.errorTracking.capturePendingExceptions();
185
- return this._flushKeepingRuntimeAlive(false);
186
- }
187
- _flushKeepingRuntimeAlive(skipThrottledSpans) {
188
- const flushPromise = this._flushEventsAndSpans(skipThrottledSpans);
333
+ return this._keepRuntimeAlive(this._flushEventsAndSpans());
334
+ }
335
+ _flushCaptureLanes() {
336
+ return Promise.all([
337
+ ...this._captureLanes.values()
338
+ ].map((lane)=>lane.flush())).then(()=>{});
339
+ }
340
+ _onLaneBackgroundFlush(laneFlush) {
341
+ const traces = this._traces;
342
+ const flush = traces && !traces.throttled ? (0, core_namespaceObject.allSettled)([
343
+ laneFlush,
344
+ traces.flush().catch(()=>{})
345
+ ]).then(()=>{}) : laneFlush;
346
+ this._keepRuntimeAlive(flush);
347
+ }
348
+ _keepRuntimeAlive(flushPromise) {
189
349
  const waitUntil = this.options.waitUntil;
190
350
  if (waitUntil && !this._waitUntilCycle) try {
191
351
  waitUntil(flushPromise.catch(()=>{}));
@@ -254,78 +414,71 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
254
414
  fetch(url, options) {
255
415
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
256
416
  }
257
- getQueueRouteKey(message) {
258
- return 'v1' === this.captureMode && (0, routing_js_namespaceObject.isLegacyOnlyEvent)(message) ? routing_js_namespaceObject.AI_ROUTE : routing_js_namespaceObject.ANALYTICS_ROUTE;
417
+ _captureLane(route) {
418
+ const endpoint = route === routing_js_namespaceObject.AI_CAPTURE_ROUTE ? types_js_namespaceObject.AI_CAPTURE_ENDPOINT : types_js_namespaceObject.ANALYTICS_CAPTURE_ENDPOINT;
419
+ let lane = this._captureLanes.get(endpoint);
420
+ if (!lane) {
421
+ const compressor = this.captureCompressor();
422
+ lane = new lane_js_namespaceObject.CaptureLane(this._captureLaneConfig(endpoint), {
423
+ sender: new sender_js_namespaceObject.V1CaptureSender(this.captureSenderConfig(endpoint, compressor), {
424
+ fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
425
+ onError: (error, summary)=>this._reportCaptureLoss([
426
+ error
427
+ ], summary),
428
+ compress: (payload, codec)=>compressor.compress(payload, codec)
429
+ }),
430
+ onLocalDrops: (errors, summary)=>this._reportCaptureLoss(errors, summary),
431
+ onError: (error)=>this._events.emit('error', error),
432
+ onFlush: (messages)=>this._events.emit('flush', messages),
433
+ onBackgroundFlush: (flush)=>this._onLaneBackgroundFlush(flush),
434
+ logger: this._logger
435
+ });
436
+ this._captureLanes.set(endpoint, lane);
437
+ }
438
+ return lane;
259
439
  }
260
- persistedQueueKeyForRoute(route) {
261
- if (route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE) return core_namespaceObject.PostHogPersistedProperty.AiCaptureQueue;
262
- return route === routing_js_namespaceObject.AI_ROUTE ? core_namespaceObject.PostHogPersistedProperty.AiQueue : core_namespaceObject.PostHogPersistedProperty.Queue;
440
+ _captureLaneConfig(endpoint) {
441
+ const isAi = endpoint === types_js_namespaceObject.AI_CAPTURE_ENDPOINT;
442
+ const flushAt = isAi ? Math.min(this.flushAt, this._captureSettings.ai.maxQueueSize) : this.flushAt;
443
+ return {
444
+ endpoint,
445
+ flushAt,
446
+ flushIntervalMs: this.options.flushInterval ?? 5000,
447
+ maxBatchSize: Math.max(flushAt, this.options.maxBatchSize ?? 100),
448
+ maxQueueSize: isAi ? this._captureSettings.ai.maxQueueSize : Math.max(this.flushAt, this.options.maxQueueSize ?? 10000),
449
+ targetBatchBytes: limits_js_namespaceObject.CAPTURE_BATCH_TARGET_BYTES,
450
+ maxEventBytes: isAi ? limits_js_namespaceObject.AI_MAX_PROPERTIES_BYTES : limits_js_namespaceObject.ANALYTICS_MAX_EVENT_BYTES,
451
+ maxEventBytesOf: isAi ? 'properties' : 'event'
452
+ };
263
453
  }
264
- getActiveQueueRoutes() {
265
- const routes = 'v1' === this.captureMode ? [
266
- routing_js_namespaceObject.ANALYTICS_ROUTE,
267
- routing_js_namespaceObject.AI_ROUTE
268
- ] : [
269
- routing_js_namespaceObject.ANALYTICS_ROUTE
270
- ];
271
- if (this._aiCaptureRouteActive) routes.push(external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
272
- return routes;
273
- }
274
- getBatchEndpointPath(route) {
275
- return route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE ? external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
276
- }
277
- async sendBatch(batchMessages, retryOptions, route = routing_js_namespaceObject.ANALYTICS_ROUTE) {
278
- if (route === external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE) return this.sendAiCaptureBatch(batchMessages, retryOptions);
279
- if ('v1' !== this.captureMode || route === routing_js_namespaceObject.AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);
280
- const v1Events = batchMessages.filter((message)=>void 0 !== message);
281
- await this.getV1Sender().sendV1Batch(v1Events);
282
- }
283
- async sendAiCaptureBatch(batchMessages, retryOptions) {
284
- const { batches, dropped } = (0, batching_js_namespaceObject.partitionAiBatch)(batchMessages);
285
- for (const { event, bytes } of dropped){
286
- const message = `Event ${event} (${bytes} bytes) exceeds the ${external_ai_capture_routing_js_namespaceObject.AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
287
- this._logger.error(message);
288
- this._events.emit('error', new Error(message));
289
- }
290
- for (const batch of batches)await this.sendAiSubBatch(batch, retryOptions);
454
+ _reportCaptureLoss(errors, summary) {
455
+ const errorListeners = this._events.events['error']?.length ?? 0;
456
+ for (const error of errors)this._events.emit('error', error);
457
+ if (0 === errorListeners) console.warn(`[PostHog] ${summary}`);
291
458
  }
292
- async sendAiSubBatch(batch, retryOptions) {
293
- try {
294
- await super.sendBatch(batch, retryOptions, external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
295
- } catch (err) {
296
- if (!(0, core_namespaceObject.isPostHogFetchContentTooLargeError)(err)) throw err;
297
- if (1 === batch.length) {
298
- const [event] = batch;
299
- const eventName = 'string' == typeof event.event ? event.event : 'unknown';
300
- const message = `Event ${eventName} (${(0, batching_js_namespaceObject.eventByteSize)(event)} bytes) was rejected with 413 by ${external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
301
- this._logger.error(message);
302
- this._events.emit('error', new Error(message));
303
- return;
304
- }
305
- const mid = Math.ceil(batch.length / 2);
306
- await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
307
- await this.sendAiSubBatch(batch.slice(mid), retryOptions);
308
- }
459
+ captureCompressor() {
460
+ return compression_js_namespaceObject.webCompressor;
309
461
  }
310
- getV1Sender() {
311
- if (!this._v1Sender) this._v1Sender = new sender_js_namespaceObject.V1CaptureSender({
462
+ captureSenderConfig(path, compressor) {
463
+ const laneSettings = path === types_js_namespaceObject.AI_CAPTURE_ENDPOINT ? this._captureSettings.ai : this._captureSettings.analytics;
464
+ const compression = (0, compression_js_namespaceObject.resolveCaptureCodec)(laneSettings.compression, compressor, (fallback)=>this._logger.debug(`zstd compression is not available in this runtime; ${path} uses ${fallback} instead`));
465
+ return {
312
466
  host: this.host,
467
+ path,
313
468
  apiKey: this.apiKey,
314
469
  libraryId: this.getLibraryId(),
315
470
  libraryVersion: this.getLibraryVersion(),
316
471
  userAgent: this.getCustomUserAgent() || void 0,
317
472
  historicalMigration: this.historicalMigration,
318
- compressionEnabled: !this.disableCompression,
319
- requestTimeoutMs: this.requestTimeout,
320
- maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
321
- initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
473
+ compression,
474
+ requestTimeoutMs: laneSettings.requestTimeoutMs,
475
+ maxRetries: this._captureSettings.maxRetries,
322
476
  isDebug: this.isDebug
323
- }, {
324
- fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),
325
- onError: (error)=>this._events.emit('error', error),
326
- compress: (payload)=>this.compressPayload(payload)
327
- });
328
- return this._v1Sender;
477
+ };
478
+ }
479
+ warnIfCaptureModeSet() {
480
+ const captureMode = "u" > typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;
481
+ if (void 0 !== captureMode) console.warn('[PostHog] POSTHOG_CAPTURE_MODE is no longer read. Capture always uses capture v1.');
329
482
  }
330
483
  getLibraryVersion() {
331
484
  return external_version_js_namespaceObject.version;
@@ -458,14 +611,42 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
458
611
  this._loggedFlagsResponseWithoutTypedValues = true;
459
612
  this._logger.info(external_flags_response_js_namespaceObject.FLAGS_RESPONSE_WITHOUT_TYPED_VALUES_MESSAGE);
460
613
  }
461
- return shared.read(body);
614
+ const normalized = shared.read(body);
615
+ if ((0, core_namespaceObject.isPlainObject)(normalized.flags)) {
616
+ for (const [key, detail] of Object.entries(normalized.flags))if ((0, external_flags_response_js_namespaceObject.isUnreadableFlagRecord)(detail)) normalized.featureFlags[key] = false;
617
+ }
618
+ return normalized;
462
619
  }
463
620
  };
464
621
  }
465
- getCommonEventProperties() {
466
- const commonProperties = super.getCommonEventProperties();
467
- if (this.options.isServer ?? true) commonProperties.$is_server = true;
468
- return commonProperties;
622
+ async _sdkEventProperties(event, properties, distinctId, flagInputs) {
623
+ const sdkProperties = {
624
+ ...this._serviceNameProperties(),
625
+ ...await this._flagEventProperties(distinctId, flagInputs)
626
+ };
627
+ if (this.options.isServer ?? true) sdkProperties.$is_server = true;
628
+ if (this.options.disableGeoip ?? true) sdkProperties.$geoip_disable = true;
629
+ if ('$exception' === event) {
630
+ if ((0, external_event_defaults_js_namespaceObject.isUnsetProperty)(properties, '$trace_id') && (0, external_event_defaults_js_namespaceObject.isUnsetProperty)(properties, '$span_id')) Object.assign(sdkProperties, await (0, trace_context_js_namespaceObject.getActiveTraceProperties)());
631
+ const releaseId = core_namespaceObject.ErrorTracking.getInjectedReleaseId();
632
+ if (releaseId) sdkProperties.$release_id = releaseId;
633
+ }
634
+ return sdkProperties;
635
+ }
636
+ async _flagEventProperties(distinctId, { groups, flags, sendFeatureFlags, disableGeoip }) {
637
+ try {
638
+ if (flags) {
639
+ if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
640
+ return flags._getEventProperties();
641
+ }
642
+ if (sendFeatureFlags) {
643
+ 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.");
644
+ const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
645
+ const flagValues = await this.getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
646
+ return buildFlagEventProperties(flagValues);
647
+ }
648
+ } catch {}
649
+ return {};
469
650
  }
470
651
  enable() {
471
652
  return super.optIn();
@@ -477,34 +658,52 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
477
658
  super.debug(enabled);
478
659
  this.featureFlagsPoller?.debug(enabled);
479
660
  }
661
+ describeDebugPayload(payload) {
662
+ return summarizeForDebugLog(payload);
663
+ }
480
664
  _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
481
665
  if ('string' == typeof props) this._logger.warn(stringArgumentWarning);
482
666
  if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);
483
667
  }
484
668
  _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
485
- return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{
669
+ const invalidUuidWarned = isInvalidUuid(props.uuid);
670
+ const uuid = this._canonicalEventUuid(props.uuid);
671
+ if (uuid !== props.uuid) props = {
672
+ ...props,
673
+ uuid
674
+ };
675
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options, uuid, timestamp })=>{
486
676
  if (this.disabled || this.optedOut) prepareOptions?.onCaptureFailed?.();
487
677
  const captureOptions = {
488
- timestamp: options.timestamp,
489
- disableGeoip: options.disableGeoip,
490
- uuid: options.uuid
678
+ timestamp,
679
+ disableGeoip: false,
680
+ uuid,
681
+ _invalidUuidWarned: invalidUuidWarned
491
682
  };
492
683
  const message = {
493
- distinctId,
684
+ distinct_id: distinctId,
494
685
  event,
495
- properties: {
496
- ...properties,
497
- ...this.getCommonEventProperties()
498
- }
686
+ properties,
687
+ ...void 0 !== options ? {
688
+ options
689
+ } : {}
499
690
  };
500
691
  return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
501
692
  }).catch((err)=>{
502
- if (err) {
693
+ if (err instanceof UnreadableEventError) {
694
+ this._dropUnreadableEvent(uuid, immediate, explicitRoute);
695
+ prepareOptions?.onCaptureFailed?.();
696
+ } else if (err) {
503
697
  console.error(err);
504
698
  prepareOptions?.onCaptureFailed?.();
505
699
  }
506
700
  }));
507
701
  }
702
+ _dropUnreadableEvent(uuid, immediate, explicitRoute) {
703
+ if (this.disabled || this.optedOut) return;
704
+ this._captureLane(explicitRoute).dropUnserializable(uuid, immediate);
705
+ if (!immediate) this.scheduleDebouncedFlush();
706
+ }
508
707
  _capturePreparedEvent(props, immediate) {
509
708
  return this._sendPreparedEvent('capture', props, immediate);
510
709
  }
@@ -518,7 +717,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
518
717
  }
519
718
  captureAi(props) {
520
719
  if (this.disabled) return;
521
- const uuid = (0, core_namespaceObject.getEventUuid)(props.uuid, core_namespaceObject.uuidv7);
720
+ const uuid = this._canonicalEventUuid(props.uuid) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
522
721
  this._sendPreparedAiEvent({
523
722
  ...props,
524
723
  uuid
@@ -527,7 +726,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
527
726
  }
528
727
  async captureAiImmediate(props) {
529
728
  if (this.disabled) return;
530
- const uuid = (0, core_namespaceObject.getEventUuid)(props.uuid, core_namespaceObject.uuidv7);
729
+ const uuid = this._canonicalEventUuid(props.uuid) ?? (0, uuid_js_namespaceObject.eventUuidv7)();
531
730
  await this._sendPreparedAiEvent({
532
731
  ...props,
533
732
  uuid
@@ -536,46 +735,29 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
536
735
  }
537
736
  _sendPreparedAiEvent(props, immediate) {
538
737
  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.`);
539
- this._aiCaptureRouteActive = true;
540
- return this._sendPreparedEvent('capture', props, immediate, void 0, external_ai_capture_routing_js_namespaceObject.AI_CAPTURE_ROUTE);
541
- }
542
- identify({ distinctId, properties = {}, disableGeoip }) {
543
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
544
- const setProps = $set || rest;
545
- const setOnceProps = $set_once || {};
546
- const eventProperties = {
547
- $set: setProps,
548
- $set_once: setOnceProps,
549
- $anon_distinct_id: $anon_distinct_id ?? void 0
550
- };
738
+ return this._sendPreparedEvent('capture', props, immediate, void 0, routing_js_namespaceObject.AI_CAPTURE_ROUTE);
739
+ }
740
+ identify({ distinctId, properties = {}, disableGeoip, options }) {
741
+ const eventProperties = identifyEventProperties(properties);
551
742
  this._sendPreparedEvent('identify', {
552
743
  distinctId,
553
744
  event: '$identify',
554
745
  properties: eventProperties,
555
- disableGeoip
556
- }, false, {
557
- includeContextProperties: false
558
- });
746
+ disableGeoip,
747
+ options
748
+ }, false);
559
749
  }
560
- async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
561
- const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
562
- const setProps = $set || rest;
563
- const setOnceProps = $set_once || {};
564
- const eventProperties = {
565
- $set: setProps,
566
- $set_once: setOnceProps,
567
- $anon_distinct_id: $anon_distinct_id ?? void 0
568
- };
750
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }) {
751
+ const eventProperties = identifyEventProperties(properties);
569
752
  await this._sendPreparedEvent('identify', {
570
753
  distinctId,
571
754
  event: '$identify',
572
755
  properties: eventProperties,
573
- disableGeoip
574
- }, true, {
575
- includeContextProperties: false
576
- });
756
+ disableGeoip,
757
+ options
758
+ }, true);
577
759
  }
578
- setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
760
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }) {
579
761
  if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;
580
762
  const eventProperties = {};
581
763
  if (Object.keys(properties).length > 0) eventProperties.$set = properties;
@@ -583,10 +765,11 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
583
765
  this.capture({
584
766
  distinctId,
585
767
  event: '$set',
586
- properties: eventProperties
768
+ properties: eventProperties,
769
+ options
587
770
  });
588
771
  }
589
- unsetPersonProperties({ distinctId, properties }) {
772
+ unsetPersonProperties({ distinctId, properties, options }) {
590
773
  const propertyNames = normalizeUnsetPersonProperties(properties);
591
774
  if (0 === propertyNames.length) return;
592
775
  this.capture({
@@ -594,7 +777,8 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
594
777
  event: '$set',
595
778
  properties: {
596
779
  $unset: propertyNames
597
- }
780
+ },
781
+ options
598
782
  });
599
783
  }
600
784
  alias(data) {
@@ -602,26 +786,22 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
602
786
  distinctId: data.distinctId,
603
787
  event: '$create_alias',
604
788
  properties: {
605
- distinct_id: data.distinctId,
606
789
  alias: data.alias
607
790
  },
608
- disableGeoip: data.disableGeoip
609
- }, false, {
610
- includeContextProperties: false
611
- });
791
+ disableGeoip: data.disableGeoip,
792
+ options: data.options
793
+ }, false, ALIAS_PREPARE_OPTIONS);
612
794
  }
613
795
  async aliasImmediate(data) {
614
796
  await this._sendPreparedEvent('alias', {
615
797
  distinctId: data.distinctId,
616
798
  event: '$create_alias',
617
799
  properties: {
618
- distinct_id: data.distinctId,
619
800
  alias: data.alias
620
801
  },
621
- disableGeoip: data.disableGeoip
622
- }, true, {
623
- includeContextProperties: false
624
- });
802
+ disableGeoip: data.disableGeoip,
803
+ options: data.options
804
+ }, true, ALIAS_PREPARE_OPTIONS);
625
805
  }
626
806
  isLocalEvaluationReady() {
627
807
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
@@ -745,21 +925,24 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
745
925
  flagVersion = flagDetail.metadata?.version;
746
926
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
747
927
  flagHasExperiment = flagDetail.metadata?.has_experiment;
748
- let parsedPayload;
749
- if (flagDetail.metadata?.payload !== void 0) try {
750
- parsedPayload = JSON.parse(flagDetail.metadata.payload);
751
- } catch {
752
- parsedPayload = flagDetail.metadata.payload;
753
- }
754
- result = {
755
- key,
756
- enabled: flagDetail.enabled,
757
- variant: flagDetail.variant ?? void 0,
758
- payload: parsedPayload,
759
- reason: flagReason,
760
- reasonCode: flagDetail.reason?.code
761
- };
762
928
  flagRecord = (0, external_flags_response_js_namespaceObject.parsedFlagRecordOf)(flagDetail);
929
+ if ((0, external_flags_response_js_namespaceObject.isServerFailedFlagRecord)(flagRecord)) errors.push(external_types_js_namespaceObject.FeatureFlagError.EVALUATION_FAILED);
930
+ else {
931
+ let parsedPayload;
932
+ if (flagDetail.metadata?.payload !== void 0) try {
933
+ parsedPayload = JSON.parse(flagDetail.metadata.payload);
934
+ } catch {
935
+ parsedPayload = flagDetail.metadata.payload;
936
+ }
937
+ result = {
938
+ key,
939
+ enabled: flagDetail.enabled,
940
+ variant: flagDetail.variant ?? void 0,
941
+ payload: parsedPayload,
942
+ reason: flagReason,
943
+ reasonCode: flagDetail.reason?.code
944
+ };
945
+ }
763
946
  }
764
947
  if (void 0 !== flagDetail && (0, external_flags_response_js_namespaceObject.isUnreadableFlagRecord)(flagDetail)) {
765
948
  featureFlagError = external_types_js_namespaceObject.FeatureFlagError.UNKNOWN_ERROR;
@@ -986,8 +1169,9 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
986
1169
  quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');
987
1170
  for (const [key, detail] of Object.entries(details.flags)){
988
1171
  if (locallyEvaluatedKeys.has(key)) continue;
1172
+ const parsed = (0, external_flags_response_js_namespaceObject.parsedFlagRecordOf)(detail);
989
1173
  let parsedPayload;
990
- if (detail.metadata?.payload !== void 0) try {
1174
+ if (!(0, external_flags_response_js_namespaceObject.isServerFailedFlagRecord)(parsed) && detail.metadata?.payload !== void 0) try {
991
1175
  parsedPayload = JSON.parse(detail.metadata.payload);
992
1176
  } catch {
993
1177
  parsedPayload = detail.metadata.payload;
@@ -1002,7 +1186,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1002
1186
  reason: detail.reason?.description ?? detail.reason?.code,
1003
1187
  locallyEvaluated: false,
1004
1188
  hasExperiment: detail.metadata?.has_experiment,
1005
- parsed: (0, external_flags_response_js_namespaceObject.parsedFlagRecordOf)(detail)
1189
+ parsed
1006
1190
  };
1007
1191
  }
1008
1192
  }
@@ -1036,7 +1220,10 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1036
1220
  for (const key of Object.keys(records))if (!requestedFlagKeys.has(key)) delete records[key];
1037
1221
  }
1038
1222
  const unresolvedFlags = {};
1039
- for (const [key, reason] of Object.entries(localResult?.unresolved ?? {}))if (!Object.prototype.hasOwnProperty.call(records, key)) unresolvedFlags[key] = reason;
1223
+ for (const [key, reason] of Object.entries(localResult?.unresolved ?? {})){
1224
+ const parsed = records[key]?.parsed;
1225
+ if (!Object.prototype.hasOwnProperty.call(records, key) || parsed && (0, external_flags_response_js_namespaceObject.isServerFailedFlagRecord)(parsed)) unresolvedFlags[key] = reason;
1226
+ }
1040
1227
  return new external_feature_flag_evaluations_js_namespaceObject.FeatureFlagEvaluations({
1041
1228
  host: this._getFeatureFlagEvaluationsHost(),
1042
1229
  distinctId: resolvedDistinctId,
@@ -1132,32 +1319,36 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1132
1319
  };
1133
1320
  return this._featureFlagEvaluationsHost;
1134
1321
  }
1135
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1322
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1136
1323
  this._sendPreparedEvent('capture', {
1137
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1324
+ distinctId,
1138
1325
  event: '$groupidentify',
1139
1326
  properties: {
1140
1327
  $group_type: groupType,
1141
1328
  $group_key: groupKey,
1142
1329
  $group_set: properties || {}
1143
1330
  },
1144
- disableGeoip
1331
+ disableGeoip,
1332
+ options
1145
1333
  }, false, {
1146
- includeContextProperties: false
1334
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1335
+ contextSession: false
1147
1336
  });
1148
1337
  }
1149
- async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
1338
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip, options }) {
1150
1339
  await this._sendPreparedEvent('capture', {
1151
- distinctId: distinctId || `$${groupType}_${groupKey}`,
1340
+ distinctId,
1152
1341
  event: '$groupidentify',
1153
1342
  properties: {
1154
1343
  $group_type: groupType,
1155
1344
  $group_key: groupKey,
1156
1345
  $group_set: properties || {}
1157
1346
  },
1158
- disableGeoip
1347
+ disableGeoip,
1348
+ options
1159
1349
  }, true, {
1160
- includeContextProperties: false
1350
+ fallbackDistinctId: `$${groupType}_${groupKey}`,
1351
+ contextSession: false
1161
1352
  });
1162
1353
  }
1163
1354
  async reloadFeatureFlags() {
@@ -1210,6 +1401,26 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1210
1401
  }
1211
1402
  return false;
1212
1403
  }
1404
+ register(properties) {
1405
+ return super.register(properties);
1406
+ }
1407
+ unregister(property) {
1408
+ return super.unregister(property);
1409
+ }
1410
+ async registerOptions(options) {
1411
+ if (!(0, core_namespaceObject.isPlainObject)(options)) return void console.error('[PostHog] registerOptions takes an object; ignoring the value');
1412
+ this._globalOptions = {
1413
+ ...this._globalOptions,
1414
+ ...options
1415
+ };
1416
+ }
1417
+ async unregisterOptions(key) {
1418
+ const remaining = {
1419
+ ...this._globalOptions
1420
+ };
1421
+ delete remaining[key];
1422
+ this._globalOptions = remaining;
1423
+ }
1213
1424
  withContext(data, fn, options) {
1214
1425
  if (!this.context) return fn();
1215
1426
  return this.context.run(data, ()=>{
@@ -1220,10 +1431,6 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1220
1431
  getContext() {
1221
1432
  return this.context?.get();
1222
1433
  }
1223
- enterContext(data, options) {
1224
- this.context?.enter(data, options);
1225
- (0, listeners_js_namespaceObject.notifyContextListeners)(this);
1226
- }
1227
1434
  async _shutdown(shutdownTimeoutMs) {
1228
1435
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
1229
1436
  this._isShutdown = true;
@@ -1259,8 +1466,13 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1259
1466
  const remainingMs = Math.max(0, shutdownDeadlineMs - Date.now());
1260
1467
  const emailsSettled = emailsDrained ? (0, core_namespaceObject.raceWithTimeout)(emailsDrained, remainingMs) : void 0;
1261
1468
  try {
1262
- return await super._shutdown(remainingMs);
1469
+ await Promise.all([
1470
+ super._shutdown(remainingMs),
1471
+ this._drainCaptureLanes(shutdownDeadlineMs)
1472
+ ]);
1473
+ await this._drainCaptureLanes(shutdownDeadlineMs);
1263
1474
  } finally{
1475
+ for (const lane of this._captureLanes.values())lane.finishShutdown();
1264
1476
  await emailsSettled;
1265
1477
  await logsDrained;
1266
1478
  this._distinctIdHasSentFlagCalls.clear();
@@ -1268,6 +1480,11 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1268
1480
  resolve?.();
1269
1481
  }
1270
1482
  }
1483
+ _drainCaptureLanes(deadlineMs) {
1484
+ return Promise.all([
1485
+ ...this._captureLanes.values()
1486
+ ].map((lane)=>lane.drain(deadlineMs))).then(()=>{});
1487
+ }
1271
1488
  async _requestRemoteConfigPayload(flagKey) {
1272
1489
  if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;
1273
1490
  const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
@@ -1375,31 +1592,30 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1375
1592
  evaluationCache: {}
1376
1593
  };
1377
1594
  }
1378
- captureException(error, distinctId, additionalProperties, uuid, flags) {
1595
+ captureException(error, options, ...legacyArgs) {
1596
+ const exceptionOptions = readCaptureExceptionArgs('captureException', options, legacyArgs, true);
1379
1597
  if (!index_js_default().isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1380
1598
  const syntheticException = new Error('PostHog syntheticException');
1381
- this.addPendingPromise(index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1382
- syntheticException
1383
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this._capturePreparedEvent({
1384
- ...msg,
1385
- uuid,
1386
- flags
1387
- }, false)));
1599
+ this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this._capturePreparedEvent(msg, false)));
1388
1600
  }
1389
1601
  }
1390
- async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
1602
+ async captureExceptionImmediate(error, options, ...legacyArgs) {
1603
+ const exceptionOptions = readCaptureExceptionArgs('captureExceptionImmediate', options, legacyArgs, false);
1391
1604
  if (!index_js_default().isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
1392
1605
  const syntheticException = new Error('PostHog syntheticException');
1393
- return this.addPendingPromise(index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1394
- syntheticException
1395
- }, distinctId, additionalProperties, this.getContext()).then((msg)=>this.captureImmediate({
1396
- ...msg,
1397
- flags
1398
- })));
1606
+ return this.addPendingPromise(this._buildExceptionEvent(error, syntheticException, exceptionOptions).then((msg)=>this.captureImmediate(msg)));
1399
1607
  }
1400
1608
  }
1401
- async prepareEventMessage(props) {
1402
- return this._prepareEventMessage(props);
1609
+ async _buildExceptionEvent(error, syntheticException, { distinctId, properties, options, uuid, flags, level }) {
1610
+ const msg = await index_js_default().buildEventMessage(this.getErrorPropertiesBuilder(), error, {
1611
+ syntheticException
1612
+ }, distinctId, properties, level, this.getContext());
1613
+ return {
1614
+ ...msg,
1615
+ options,
1616
+ uuid,
1617
+ flags
1618
+ };
1403
1619
  }
1404
1620
  _serviceNameProperties() {
1405
1621
  const serviceName = this._resolveServiceName();
@@ -1411,87 +1627,109 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1411
1627
  if (void 0 === this._serviceName) this._serviceName = (this.options.traces ? (0, core_namespaceObject.resolveTracesConfig)(this.options.traces, this.hostResourceAttributes()).serviceName : void 0) || (0, core_namespaceObject.resolveMetricsConfig)(this.options.metrics).serviceName || null;
1412
1628
  return this._serviceName;
1413
1629
  }
1414
- async _prepareEventMessage(props, options = {}) {
1630
+ async prepareEventMessage(props) {
1631
+ try {
1632
+ return await this._prepareEventMessage(props);
1633
+ } catch (error) {
1634
+ throw error instanceof UnreadableEventError ? error.original : error;
1635
+ }
1636
+ }
1637
+ async _prepareEventMessage(props, prepareOptions = {}) {
1415
1638
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
1639
+ const callOptions = (0, transform_js_namespaceObject.readEventOptions)(props.options);
1416
1640
  const contextData = (0, event_context_js_namespaceObject.getEventContext)(props, this.context?.get());
1417
- const includeContextProperties = options.includeContextProperties ?? true;
1418
- let mergedDistinctId = distinctId || contextData?.distinctId;
1419
- const mergedProperties = includeContextProperties ? {
1420
- ...this._serviceNameProperties(),
1421
- ...this.props,
1422
- ...contextData?.properties || {},
1423
- ...properties || {}
1424
- } : {
1425
- ...this._serviceNameProperties(),
1426
- ...properties || {}
1641
+ const contextProperties = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(contextData?.properties);
1642
+ const contextOptions = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(contextData?.options);
1643
+ const globalProperties = (0, external_event_defaults_js_namespaceObject.snapshotLayer)(this.props);
1644
+ const globalOptions = this._globalOptions;
1645
+ const libraryId = this.getLibraryId();
1646
+ const libraryVersion = this.getLibraryVersion();
1647
+ const resolvedDistinctId = presentDistinctId(distinctId) ?? presentDistinctId(contextData?.distinctId) ?? prepareOptions.fallbackDistinctId;
1648
+ const eventDistinctId = resolvedDistinctId ?? (0, uuid_js_namespaceObject.eventUuidv7)();
1649
+ const eventProperties = readCallerValues(()=>({
1650
+ ...properties || {}
1651
+ }));
1652
+ const callerPersonProfile = eventProperties[core_namespaceObject.EVENT_OPTION_LEGACY_PROPERTIES.process_person_profile];
1653
+ if (prepareOptions.distinctIdProperty) eventProperties.distinct_id = eventDistinctId;
1654
+ if ((prepareOptions.contextSession ?? true) && contextData?.sessionId && (0, external_event_defaults_js_namespaceObject.isUnsetProperty)(eventProperties, '$session_id')) eventProperties.$session_id = contextData.sessionId;
1655
+ if ((0, core_namespaceObject.isPlainObject)(groups) && Object.keys(groups).length > 0) {
1656
+ const existingGroups = eventProperties.$groups;
1657
+ eventProperties.$groups = (0, external_event_defaults_js_namespaceObject.isMergeableObject)(existingGroups) ? {
1658
+ ...existingGroups,
1659
+ ...groups
1660
+ } : {
1661
+ ...groups
1662
+ };
1663
+ }
1664
+ if (null != disableGeoip) (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1665
+ {
1666
+ $geoip_disable: disableGeoip
1667
+ }
1668
+ ]);
1669
+ (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1670
+ contextProperties,
1671
+ globalProperties
1672
+ ], prepareOptions.callOnlyProperties);
1673
+ (0, external_event_defaults_js_namespaceObject.fillProperties)(eventProperties, [
1674
+ await this._sdkEventProperties(event, eventProperties, eventDistinctId, {
1675
+ groups,
1676
+ flags,
1677
+ sendFeatureFlags,
1678
+ disableGeoip
1679
+ })
1680
+ ]);
1681
+ (0, external_event_defaults_js_namespaceObject.fillLibraryProperties)(eventProperties, libraryId, libraryVersion);
1682
+ const filledOptions = {
1683
+ ...callOptions
1427
1684
  };
1428
- if ('$exception' === event && !('$trace_id' in mergedProperties || '$span_id' in mergedProperties)) Object.assign(mergedProperties, await (0, trace_context_js_namespaceObject.getActiveTraceProperties)());
1429
- if (!mergedDistinctId) {
1430
- mergedDistinctId = (0, core_namespaceObject.uuidv7)();
1431
- mergedProperties.$process_person_profile = false;
1685
+ (0, external_event_defaults_js_namespaceObject.fillIdentifyStylePersonProfile)(event, filledOptions, callerPersonProfile, void 0 !== resolvedDistinctId);
1686
+ (0, external_event_defaults_js_namespaceObject.fillOptions)(filledOptions, [
1687
+ contextOptions,
1688
+ globalOptions,
1689
+ void 0 !== resolvedDistinctId ? void 0 : {
1690
+ process_person_profile: false
1691
+ }
1692
+ ]);
1693
+ (0, external_event_defaults_js_namespaceObject.dropIdentifyStyleLegacyPersonProfile)(event, filledOptions, eventProperties);
1694
+ const eventOptions = void 0 !== callOptions || Object.keys(filledOptions).length > 0 ? filledOptions : void 0;
1695
+ const flagEvent = prepareOptions.flagEvent;
1696
+ const enrichedProperties = flagEvent ? (0, external_flag_events_js_namespaceObject.applyFlagEventCapture)(eventProperties, flagEvent) : eventProperties;
1697
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? (0, external_flag_events_js_namespaceObject.minimizeConfigVersion2FlagCalledProperties)(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : (0, core_namespaceObject.minimizeFlagCalledEventProperties)(enrichedProperties, FLAG_CALLED_OPTION_SOURCE_PROPERTIES) : enrichedProperties;
1698
+ let finalEvent = event;
1699
+ if ('$pageview' === event && this.options.__previewCaptureBotPageviews && 'string' == typeof finalProperties.$raw_user_agent && (0, core_namespaceObject.isBlockedUA)(finalProperties.$raw_user_agent, this.options.customBlockedUserAgents || [])) {
1700
+ finalEvent = '$bot_pageview';
1701
+ finalProperties.$browser_type = 'bot';
1432
1702
  }
1433
- if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;
1434
- const flagEvent = options.flagEvent;
1435
- const enrichedProperties = flagEvent ? (0, external_flag_events_js_namespaceObject.applyFlagEventCapture)(mergedProperties, flagEvent) : mergedProperties;
1436
- const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, enrichedProperties) ? flagEvent ? (0, external_flag_events_js_namespaceObject.minimizeConfigVersion2FlagCalledProperties)(enrichedProperties) : (0, core_namespaceObject.minimizeFlagCalledEventProperties)(enrichedProperties) : enrichedProperties;
1437
1703
  const eventMessage = this._runBeforeSend({
1438
- distinctId: mergedDistinctId,
1439
- event,
1704
+ distinctId: eventDistinctId,
1705
+ event: finalEvent,
1440
1706
  properties: finalProperties,
1441
1707
  groups,
1442
1708
  flags,
1443
1709
  sendFeatureFlags,
1444
1710
  timestamp,
1445
1711
  disableGeoip,
1446
- uuid
1447
- }, options.onCaptureFailed);
1712
+ uuid,
1713
+ options: eventOptions
1714
+ }, prepareOptions.onCaptureFailed);
1448
1715
  if (!eventMessage) return Promise.reject(null);
1449
- const eventProperties = await Promise.resolve().then(async ()=>{
1450
- if (flags) {
1451
- if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
1452
- return flags._getEventProperties();
1453
- }
1454
- if (sendFeatureFlags) {
1455
- 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.");
1456
- const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
1457
- const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
1458
- return buildFlagEventProperties(flagValues);
1459
- }
1460
- return {};
1461
- }).catch(()=>({})).then((additionalProperties)=>{
1462
- const resolvedGroups = eventMessage.groups || groups;
1463
- return {
1464
- ...additionalProperties,
1465
- ...eventMessage.properties || {},
1466
- ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {
1467
- $groups: resolvedGroups
1468
- } : {}
1469
- };
1470
- });
1471
- if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {
1472
- if ((0, core_namespaceObject.isBlockedUA)(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
1473
- eventMessage.event = '$bot_pageview';
1474
- eventProperties.$browser_type = 'bot';
1475
- }
1476
- }
1477
1716
  return {
1478
1717
  distinctId: eventMessage.distinctId,
1479
1718
  event: eventMessage.event,
1480
- properties: eventProperties,
1481
- options: {
1482
- timestamp: eventMessage.timestamp,
1483
- disableGeoip: eventMessage.disableGeoip,
1484
- uuid: eventMessage.uuid
1485
- }
1719
+ properties: eventMessage.properties || {},
1720
+ options: eventMessage.options,
1721
+ uuid: eventMessage.uuid,
1722
+ timestamp: eventMessage.timestamp,
1723
+ disableGeoip: eventMessage.disableGeoip
1486
1724
  };
1487
1725
  }
1488
1726
  _runBeforeSend(eventMessage, onError) {
1489
- const beforeSend = this.options.before_send;
1727
+ const beforeSend = this.options.beforeSend;
1490
1728
  if (!beforeSend) return eventMessage;
1491
1729
  const fns = Array.isArray(beforeSend) ? beforeSend : [
1492
1730
  beforeSend
1493
1731
  ];
1494
- let result = eventMessage;
1732
+ let result = readCallerValues(()=>isolateForBeforeSend(eventMessage));
1495
1733
  for (const fn of fns)try {
1496
1734
  result = fn(result);
1497
1735
  if (!result) {
@@ -1503,7 +1741,8 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
1503
1741
  this._logger.warn(message);
1504
1742
  }
1505
1743
  } catch (error) {
1506
- this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
1744
+ const errorType = error instanceof Error ? error.name : typeof error;
1745
+ console.error(`[PostHog] Error in beforeSend function for event '${eventMessage.event}' (${errorType})`);
1507
1746
  onError?.();
1508
1747
  return null;
1509
1748
  }