@posthog/core 1.69.9 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/capture-v1/package.json +6 -0
  2. package/dist/capture-v1/compression.d.ts +18 -0
  3. package/dist/capture-v1/compression.d.ts.map +1 -0
  4. package/dist/capture-v1/compression.js +70 -0
  5. package/dist/capture-v1/compression.mjs +26 -0
  6. package/dist/capture-v1/errors.d.ts +48 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +82 -0
  9. package/dist/capture-v1/errors.mjs +38 -0
  10. package/dist/capture-v1/index.d.ts +15 -0
  11. package/dist/capture-v1/index.d.ts.map +1 -0
  12. package/dist/capture-v1/index.js +88 -0
  13. package/dist/capture-v1/index.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +150 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +554 -0
  17. package/dist/capture-v1/sender.mjs +507 -0
  18. package/dist/capture-v1/serialize.d.ts +30 -0
  19. package/dist/capture-v1/serialize.d.ts.map +1 -0
  20. package/dist/capture-v1/serialize.js +106 -0
  21. package/dist/capture-v1/serialize.mjs +59 -0
  22. package/dist/capture-v1/transform.d.ts +19 -0
  23. package/dist/capture-v1/transform.d.ts.map +1 -0
  24. package/dist/capture-v1/transform.js +118 -0
  25. package/dist/capture-v1/transform.mjs +77 -0
  26. package/dist/capture-v1/types.d.ts +52 -0
  27. package/dist/capture-v1/types.d.ts.map +1 -0
  28. package/dist/capture-v1/types.js +44 -0
  29. package/dist/capture-v1/types.mjs +3 -0
  30. package/dist/capture-v1/uuid.d.ts +9 -0
  31. package/dist/capture-v1/uuid.d.ts.map +1 -0
  32. package/dist/capture-v1/uuid.js +75 -0
  33. package/dist/capture-v1/uuid.mjs +34 -0
  34. package/dist/featureFlagLocalEvaluation.d.ts +2 -0
  35. package/dist/featureFlagLocalEvaluation.d.ts.map +1 -1
  36. package/dist/featureFlagLocalEvaluation.js +38 -0
  37. package/dist/featureFlagLocalEvaluation.mjs +38 -0
  38. package/dist/featureFlagUtils.d.ts +7 -5
  39. package/dist/featureFlagUtils.d.ts.map +1 -1
  40. package/dist/featureFlagUtils.js +17 -11
  41. package/dist/featureFlagUtils.mjs +14 -11
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +27 -16
  45. package/dist/index.mjs +1 -1
  46. package/dist/posthog-core-stateless.d.ts +44 -7
  47. package/dist/posthog-core-stateless.d.ts.map +1 -1
  48. package/dist/posthog-core-stateless.js +103 -24
  49. package/dist/posthog-core-stateless.mjs +103 -24
  50. package/dist/posthog-core.d.ts +138 -53
  51. package/dist/posthog-core.d.ts.map +1 -1
  52. package/dist/posthog-core.js +341 -115
  53. package/dist/posthog-core.mjs +338 -115
  54. package/dist/types.d.ts +33 -1
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/index.js +25 -12
  59. package/dist/utils/index.mjs +1 -1
  60. package/dist/utils/json-utils.d.ts +11 -1
  61. package/dist/utils/json-utils.d.ts.map +1 -1
  62. package/dist/utils/json-utils.js +50 -2
  63. package/dist/utils/json-utils.mjs +46 -1
  64. package/package.json +13 -3
  65. package/src/capture-v1/compression.ts +50 -0
  66. package/src/capture-v1/errors.ts +91 -0
  67. package/src/capture-v1/index.ts +34 -0
  68. package/src/capture-v1/sender.ts +779 -0
  69. package/src/capture-v1/serialize.ts +113 -0
  70. package/src/capture-v1/transform.ts +135 -0
  71. package/src/capture-v1/types.ts +59 -0
  72. package/src/capture-v1/uuid.ts +53 -0
  73. package/src/featureFlagLocalEvaluation.ts +51 -0
  74. package/src/featureFlagUtils.ts +22 -10
  75. package/src/index.ts +1 -0
  76. package/src/posthog-core-stateless.ts +190 -35
  77. package/src/posthog-core.ts +615 -178
  78. package/src/types.ts +31 -1
  79. package/src/utils/index.ts +1 -1
  80. package/src/utils/json-utils.ts +64 -1
  81. package/src/error-tracking/chunk-ids.spec.ts +0 -77
  82. package/src/error-tracking/coercers/error-event-coercer.spec.ts +0 -142
  83. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +0 -77
  84. package/src/error-tracking/coercers/string-coercer.spec.ts +0 -26
  85. package/src/error-tracking/error-properties-builder.aggregate-errors.spec.ts +0 -412
  86. package/src/error-tracking/error-properties-builder.coerce.spec.ts +0 -337
  87. package/src/error-tracking/error-properties-builder.metadata.spec.ts +0 -318
  88. package/src/error-tracking/error-properties-builder.parse.spec.ts +0 -37
  89. package/src/error-tracking/exception-steps.spec.ts +0 -115
  90. package/src/error-tracking/parsers/base.spec.ts +0 -156
  91. package/src/error-tracking/parsers/index.spec.ts +0 -270
  92. package/src/error-tracking/parsers/node.spec.ts +0 -34
  93. package/src/error-tracking/release.spec.ts +0 -34
  94. package/src/logs/index.spec.ts +0 -2421
  95. package/src/logs/logs-utils.spec.ts +0 -266
  96. package/src/metrics/index.spec.ts +0 -1249
  97. package/src/surveys/activation.spec.ts +0 -61
  98. package/src/surveys/events.spec.ts +0 -183
  99. package/src/surveys/keys.spec.ts +0 -29
  100. package/src/surveys/property-matching.spec.ts +0 -539
  101. package/src/surveys/shuffling.spec.ts +0 -51
  102. package/src/surveys/translations.spec.ts +0 -274
  103. package/src/surveys/validation.spec.ts +0 -168
  104. package/src/traces/config.spec.ts +0 -271
  105. package/src/traces/ids.spec.ts +0 -115
  106. package/src/traces/index.spec.ts +0 -3287
  107. package/src/traces/live-spans.spec.ts +0 -69
  108. package/src/traces/otlp.spec.ts +0 -368
  109. package/src/traces/span.spec.ts +0 -1137
  110. package/src/traces/traceparent.spec.ts +0 -184
  111. package/src/utils/bot-detection.spec.ts +0 -107
  112. package/src/utils/bucketed-rate-limiter.spec.ts +0 -327
  113. package/src/utils/json-utils.spec.ts +0 -115
  114. package/src/utils/named-error.spec.ts +0 -36
  115. package/src/utils/number-utils.spec.ts +0 -212
  116. package/src/utils/otlp-any-value.spec.ts +0 -376
  117. package/src/utils/otlp-resource.spec.ts +0 -171
  118. package/src/utils/promise-queue.spec.ts +0 -55
  119. package/src/utils/string-utils.spec.ts +0 -158
  120. package/src/utils/type-utils.spec.ts +0 -38
  121. package/src/utils/webview-app-utils.spec.ts +0 -118
  122. package/src/vendor/uuidv7.spec.ts +0 -26
@@ -0,0 +1,779 @@
1
+ import type { FetchLike, PostHogFetchOptions, PostHogFetchResponse } from '../types'
2
+ import { uuidv7 } from '../vendor/uuidv7'
3
+
4
+ import { type CaptureCodec, type CaptureCompression, webCompressor } from './compression'
5
+ import {
6
+ CaptureError,
7
+ CaptureLossTally,
8
+ type CaptureDroppedEvent,
9
+ type CaptureErrorParams,
10
+ describeCaptureLoss,
11
+ } from './errors'
12
+ import { type SerializedV1Event, buildV1Body } from './serialize'
13
+ import type { CaptureEndpoint, V1BatchResponse, V1EventResult } from './types'
14
+ import { canonicalizeUuid } from './uuid'
15
+
16
+ /** Wait before the first retry; each later retry doubles it. */
17
+ export const RETRY_BASE_DELAY_MS = 100
18
+ /** Ceiling for every retry wait, including one raised by `Retry-After`. */
19
+ export const MAX_RETRY_DELAY_MS = 30_000
20
+
21
+ // Retry waits and request deadlines use ref'd timers, unlike safeSetTimeout, so an
22
+ // awaited flush or shutdown keeps the process alive until the send finishes.
23
+ /** Settles with `work`, or rejects with an `AbortError` as soon as `signal` aborts. */
24
+ async function raceAbort<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
25
+ if (!signal) {
26
+ return work
27
+ }
28
+ let onAbort!: () => void
29
+ const aborted = new Promise<never>((_resolve, reject) => {
30
+ onAbort = () => {
31
+ const abortError = new Error('Capture V1 request aborted while compressing the body')
32
+ abortError.name = 'AbortError'
33
+ abortError.cause = signal.reason
34
+ reject(abortError)
35
+ }
36
+ if (signal.aborted) {
37
+ onAbort()
38
+ } else {
39
+ signal.addEventListener('abort', onAbort, { once: true })
40
+ }
41
+ })
42
+ try {
43
+ return await Promise.race([work, aborted])
44
+ } finally {
45
+ signal.removeEventListener('abort', onAbort)
46
+ }
47
+ }
48
+
49
+ // What a compression that outlasts the request timeout resolves to in encodeBody.
50
+ const COMPRESSION_TIMED_OUT = Symbol('compression timed out')
51
+
52
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
53
+ return new Promise((resolve) => {
54
+ const onAbort = (): void => {
55
+ clearTimeout(timer)
56
+ resolve()
57
+ }
58
+ // A lane reuses one signal for every send, so a finished wait must not leave its listener behind.
59
+ const timer = setTimeout(() => {
60
+ signal?.removeEventListener('abort', onAbort)
61
+ resolve()
62
+ }, ms)
63
+ signal?.addEventListener('abort', onAbort, { once: true })
64
+ })
65
+ }
66
+
67
+ /** HTTP statuses a capture request is retried on. 404 and 429 can come from a proxy in front of capture. */
68
+ const RETRYABLE_STATUSES = new Set([404, 408, 429, 500, 502, 503, 504])
69
+
70
+ /** Only these redirects keep the method and body, so they are the only ones a capture request follows. */
71
+ const FOLLOWED_REDIRECT_STATUSES = new Set([307, 308])
72
+ const MAX_REDIRECTS = 5
73
+
74
+ /** Errors the sender raised for its own request deadline, so a loss summary can call them timeouts. */
75
+ const timeoutErrors = new WeakSet<Error>()
76
+
77
+ /** Drop details for a copy of an event the server dropped as a duplicate of an earlier one in the request. */
78
+ export const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid'
79
+
80
+ export interface V1CaptureSenderConfig {
81
+ host: string
82
+ /** The capture lane this sender posts to. */
83
+ path: CaptureEndpoint
84
+ /** The project token, sent as `Authorization: Bearer <projectToken>`. */
85
+ projectToken: string
86
+ /**
87
+ * @deprecated Pass `projectToken`. Read only when `projectToken` is missing, for SDK builds
88
+ * published before the rename.
89
+ */
90
+ apiKey?: string
91
+ /** The `PostHog-Sdk-Info` library name. PostHog fills `$lib` from it only for an event that has no `$lib`. */
92
+ libraryId: string
93
+ libraryVersion: string
94
+ /** Value for the `User-Agent` header, if the runtime allows setting it. */
95
+ userAgent?: string
96
+ /** Extra headers sent on every request. A header the sender sets itself always wins, whatever its case. */
97
+ extraHeaders?: Record<string, string>
98
+ historicalMigration: boolean
99
+ /** The body encoding; a body that fails to compress is sent uncompressed. */
100
+ compression: CaptureCompression
101
+ requestTimeoutMs: number
102
+ /** Retries after the first attempt. */
103
+ maxRetries: number
104
+ isDebug?: boolean
105
+ }
106
+
107
+ export interface V1CaptureSenderHooks {
108
+ fetch: FetchLike
109
+ /**
110
+ * Surfaces partial/terminal delivery failures on the client error channel, at most once per
111
+ * batch. `summary` is one line with counts and causes only, for when nothing listens.
112
+ */
113
+ onError: (error: CaptureError, summary: string) => void
114
+ now?: () => number
115
+ /** Waits between attempts. The sender stops waiting when `signal` aborts, even if this does not. */
116
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
117
+ generateRequestId?: () => string
118
+ /** Uniform in [0, 1); sets the jitter of each retry wait. */
119
+ random?: () => number
120
+ compress?: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
121
+ }
122
+
123
+ export interface V1SendOptions {
124
+ /** Aborting stops the current attempt and every later one; the pending events come back as unsent. */
125
+ signal?: AbortSignal
126
+ /**
127
+ * When true, events whose last attempt got no HTTP response (or were cut off by `signal`) are
128
+ * returned to the caller unreported, so it can queue them again. When false they are reported
129
+ * as undelivered.
130
+ */
131
+ keepUnsent?: boolean
132
+ /**
133
+ * For an SDK with a durable queue. When set, events the server asked to resend (a retryable
134
+ * status or `retry` results on the last attempt) and a batch of more than one event that got a
135
+ * `413` are returned to the caller unreported, and this is called once with why, so the caller can
136
+ * wait or halve the batch before sending them again. Unsent events (`keepUnsent`) also call it.
137
+ */
138
+ onDeferred?: (deferral: V1SendDeferral) => void
139
+ /**
140
+ * The request these events were kept from, when they are exactly the events it left to send again.
141
+ * The send reuses its request ID and `created_at` and continues its attempt numbers.
142
+ */
143
+ retryOf?: V1RequestIdentity
144
+ }
145
+
146
+ /** A capture request's identity, which a resend of the same events keeps. */
147
+ export interface V1RequestIdentity {
148
+ requestId: string
149
+ /** The batch's `created_at`. */
150
+ createdAt: string
151
+ /** The `PostHog-Attempt` of the request's last attempt. */
152
+ attempt: number
153
+ }
154
+
155
+ export interface V1SendDeferral {
156
+ /** Why the events were kept, such as `HTTP 404`, for logs. */
157
+ reason: string
158
+ /** The server's `Retry-After`, when the last response carried one. */
159
+ retryAfterMs?: number
160
+ /** The batch got a `413` and should be resent in smaller batches. */
161
+ tooLarge: boolean
162
+ /** The last attempt hit `requestTimeoutMs` before a response was read. */
163
+ timedOut?: boolean
164
+ /** The request the events were kept from, for a resend of exactly those events to pass as `retryOf`. */
165
+ request: V1RequestIdentity
166
+ }
167
+
168
+ interface RedirectOutcome {
169
+ response: PostHogFetchResponse
170
+ /** Set when `response` is a redirect the sender does not follow. */
171
+ redirectFailure?: string
172
+ }
173
+
174
+ interface V1CaptureAttempt extends RedirectOutcome {
175
+ signal: AbortSignal
176
+ waitFor<T>(operation: Promise<T>): Promise<T>
177
+ cancelBody: () => Promise<void>
178
+ cleanup: () => void
179
+ }
180
+
181
+ /**
182
+ * Sends already-serialized events to one Capture V1 lane (`config.path`),
183
+ * owning the full attempt loop: per-event partial retry, exponential backoff
184
+ * clamped against `Retry-After`, v1 status classification, and surfacing drops
185
+ * / undelivered events on the error channel. Used by both the batched and
186
+ * immediate send paths.
187
+ *
188
+ * Never throws for a handled outcome: after exhausting its own attempt budget it
189
+ * reports the failure via `onError` and resolves. Only events that never got an
190
+ * HTTP response can come back to the caller, and only with `keepUnsent`.
191
+ */
192
+ export class V1CaptureSender {
193
+ private readonly config: V1CaptureSenderConfig
194
+ private readonly hostOrigin: string | undefined
195
+ private readonly fetchFn: FetchLike
196
+ private readonly onError: (error: CaptureError, summary: string) => void
197
+ private readonly now: () => number
198
+ private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>
199
+ private readonly generateRequestId: () => string
200
+ private readonly random: () => number
201
+ private readonly compress: (payload: string, codec: CaptureCodec) => Promise<Uint8Array | null>
202
+
203
+ constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
204
+ this.config = config
205
+ this.hostOrigin = originOf(config.host)
206
+ this.fetchFn = hooks.fetch
207
+ this.onError = hooks.onError
208
+ this.now = hooks.now ?? Date.now
209
+ this.sleep = hooks.sleep ?? abortableSleep
210
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7
211
+ this.random = hooks.random ?? Math.random
212
+ this.compress = hooks.compress ?? webCompressor.compress
213
+ }
214
+
215
+ /** Sends `events` and resolves with the ones to queue again (always empty unless `keepUnsent`). */
216
+ async send<T extends SerializedV1Event>(events: T[], options: V1SendOptions = {}): Promise<T[]> {
217
+ if (events.length === 0) {
218
+ return []
219
+ }
220
+
221
+ const { signal, keepUnsent = false, onDeferred, retryOf } = options
222
+ const requestId = retryOf?.requestId ?? this.generateRequestId()
223
+ // created_at is generated once and stays stable across every retry.
224
+ const createdAt = retryOf?.createdAt ?? new Date(this.now()).toISOString()
225
+ const attemptsBefore = retryOf?.attempt ?? 0
226
+ let lastAttempt = attemptsBefore
227
+ const url = `${this.config.host}${this.config.path}`
228
+ const drops: CaptureDroppedEvent[] = []
229
+ const loss = new CaptureLossTally()
230
+ let pending = events
231
+
232
+ const unsent = (cause: unknown, failure: string): T[] => {
233
+ if (keepUnsent) {
234
+ this.surfacePartialDrops(requestId, drops, loss)
235
+ const timedOut = cause instanceof Error && timeoutErrors.has(cause)
236
+ onDeferred?.({
237
+ reason: failure,
238
+ tooLarge: false,
239
+ ...(timedOut ? { timedOut } : {}),
240
+ request: { requestId, createdAt, attempt: lastAttempt },
241
+ })
242
+ return pending
243
+ }
244
+ this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure)
245
+ return []
246
+ }
247
+ const deferred = (kept: T[], deferral: Omit<V1SendDeferral, 'request'>): T[] => {
248
+ this.surfacePartialDrops(requestId, drops, loss)
249
+ onDeferred?.({ ...deferral, request: { requestId, createdAt, attempt: lastAttempt } })
250
+ return kept
251
+ }
252
+
253
+ // Always make one attempt, so a bad budget reports a delivery error instead of dropping the batch silently.
254
+ const { maxRetries } = this.config
255
+ const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1
256
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
257
+ if (signal?.aborted) {
258
+ return unsent(signal.reason, 'not sent: aborted')
259
+ }
260
+ const isLastAttempt = attempt === maxAttempts
261
+ const payload = buildV1Body(pending, { createdAt, historicalMigration: this.config.historicalMigration })
262
+
263
+ let captureAttempt: V1CaptureAttempt | undefined
264
+ let retryDelayMs: number | undefined
265
+ try {
266
+ lastAttempt = attemptsBefore + attempt
267
+ captureAttempt = await this.sendOnce(url, payload, lastAttempt, requestId, signal)
268
+ const { response, signal: attemptSignal, redirectFailure } = captureAttempt
269
+ const { status } = response
270
+ if (redirectFailure !== undefined) {
271
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
272
+ const failure = `failed on a redirect it does not follow (HTTP ${status})`
273
+ this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure)
274
+ return []
275
+ }
276
+ if (status < 200 || status >= 300) {
277
+ const tooLarge = status === 413 && pending.length > 1
278
+ if (onDeferred && (tooLarge || (isLastAttempt && RETRYABLE_STATUSES.has(status)))) {
279
+ const retryAfterMs = this.parseRetryAfter(response)
280
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
281
+ return deferred(pending, { reason: `HTTP ${status}`, retryAfterMs, tooLarge })
282
+ }
283
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
284
+ const retryAfterMs = this.parseRetryAfter(response)
285
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {})
286
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs)
287
+ } else {
288
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor)
289
+ this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`)
290
+ return []
291
+ }
292
+ } else {
293
+ let parsed: V1BatchResponse
294
+ try {
295
+ parsed = await captureAttempt.waitFor(this.parseResponse(response))
296
+ } catch (error) {
297
+ if (attemptSignal.aborted) {
298
+ throw error
299
+ }
300
+ // A 2xx without a readable results map is terminal — re-sending against a broken success would loop forever.
301
+ this.surfaceBatchFailure(
302
+ requestId,
303
+ drops,
304
+ pending,
305
+ new Error(`Capture V1 returned an unparseable ${status} response body`),
306
+ loss,
307
+ `failed with an unreadable response (HTTP ${status})`
308
+ )
309
+ return []
310
+ }
311
+
312
+ const dropsBefore = drops.length
313
+ const retryable = this.classify(pending, parsed, drops)
314
+ for (const drop of drops.slice(dropsBefore)) {
315
+ const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server'
316
+ loss.add(`${cause} (HTTP ${status})`, 1)
317
+ }
318
+ if (retryable.length === 0) {
319
+ this.surfacePartialDrops(requestId, drops, loss)
320
+ return []
321
+ }
322
+ if (isLastAttempt && onDeferred) {
323
+ return deferred(retryable, {
324
+ reason: 'the server asked to retry them',
325
+ retryAfterMs: this.parseRetryAfter(response),
326
+ tooLarge: false,
327
+ })
328
+ }
329
+ if (isLastAttempt) {
330
+ loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length)
331
+ this.report(
332
+ this.captureError({
333
+ requestId,
334
+ drops,
335
+ retryExhausted: retryable.map((event) => event.uuid),
336
+ }),
337
+ loss
338
+ )
339
+ return []
340
+ }
341
+ pending = retryable
342
+ // A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
343
+ // retry events); honor it as a minimum the same way as on a retryable status.
344
+ const retryAfterMs = this.parseRetryAfter(response)
345
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs)
346
+ }
347
+ } catch (transportError) {
348
+ if (captureAttempt && !captureAttempt.signal.aborted) {
349
+ throw transportError
350
+ }
351
+ // Connection/timeouts, including a timeout while consuming the response body,
352
+ // are retried until the budget runs out.
353
+ if (isLastAttempt || signal?.aborted) {
354
+ return unsent(transportError, this.describeTransportFailure(transportError, signal))
355
+ }
356
+ retryDelayMs = this.backoffDelay(attempt)
357
+ } finally {
358
+ captureAttempt?.cleanup()
359
+ }
360
+
361
+ if (retryDelayMs !== undefined) {
362
+ await this.sleepUnlessAborted(retryDelayMs, signal)
363
+ }
364
+ }
365
+ return []
366
+ }
367
+
368
+ private async sleepUnlessAborted(ms: number, signal: AbortSignal | undefined): Promise<void> {
369
+ if (!signal) {
370
+ return this.sleep(ms)
371
+ }
372
+ if (signal.aborted) {
373
+ return
374
+ }
375
+ let onAbort!: () => void
376
+ const aborted = new Promise<void>((resolve) => {
377
+ onAbort = resolve
378
+ signal.addEventListener('abort', onAbort, { once: true })
379
+ })
380
+ try {
381
+ await Promise.race([this.sleep(ms, signal), aborted])
382
+ } finally {
383
+ signal.removeEventListener('abort', onAbort)
384
+ }
385
+ }
386
+
387
+ private async sendOnce(
388
+ url: string,
389
+ payload: string,
390
+ attempt: number,
391
+ requestId: string,
392
+ externalSignal: AbortSignal | undefined
393
+ ): Promise<V1CaptureAttempt> {
394
+ // Compression runs on the libuv pool, so a busy pool must not hold the request past an external deadline.
395
+ const { body, contentEncoding } = await this.encodeBody(payload, externalSignal)
396
+ // Built after compression, so the request timestamp is when the request starts.
397
+ const headers = this.buildHeaders(attempt, requestId)
398
+ if (contentEncoding) {
399
+ headers['Content-Encoding'] = contentEncoding
400
+ }
401
+
402
+ const controller = new AbortController()
403
+ let timeoutPhase = 'waiting for response headers'
404
+ let timer: ReturnType<typeof setTimeout> | undefined
405
+ let onExternalAbort: (() => void) | undefined
406
+ const stopListening = (): void => {
407
+ if (onExternalAbort) {
408
+ externalSignal?.removeEventListener('abort', onExternalAbort)
409
+ }
410
+ }
411
+ // hooks.fetch is user-injectable, so it may ignore an abort signal while
412
+ // resolving headers or reading the body. Race both phases against the same
413
+ // deadline rather than relying only on standards-compliant fetch behavior.
414
+ const deadline = new Promise<never>((_resolve, reject) => {
415
+ const abortWith = (error: Error): void => {
416
+ // Reject first so this phase-specific error wins even when an abort-aware
417
+ // custom fetch rejects synchronously from the abort event.
418
+ reject(error)
419
+ controller.abort(error)
420
+ }
421
+ timer = setTimeout(() => {
422
+ const timeoutError = new Error(
423
+ `Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`
424
+ )
425
+ timeoutError.name = 'AbortError'
426
+ timeoutErrors.add(timeoutError)
427
+ abortWith(timeoutError)
428
+ }, this.config.requestTimeoutMs)
429
+ if (externalSignal) {
430
+ onExternalAbort = () => {
431
+ const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`)
432
+ abortError.name = 'AbortError'
433
+ abortError.cause = externalSignal.reason
434
+ abortWith(abortError)
435
+ }
436
+ if (externalSignal.aborted) {
437
+ onExternalAbort()
438
+ } else {
439
+ externalSignal.addEventListener('abort', onExternalAbort, { once: true })
440
+ }
441
+ }
442
+ })
443
+ // Keeps an early abort from surfacing as an unhandled rejection before the race below observes it.
444
+ deadline.catch(() => {})
445
+ try {
446
+ const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal)
447
+ let responseAccepted = false
448
+ void fetchPromise
449
+ .then((late) => {
450
+ if (controller.signal.aborted && !responseAccepted) {
451
+ // An injected fetch may ignore abort and resolve after the deadline.
452
+ // Cancel its otherwise unreachable body to release any held resources.
453
+ void this.cancelBody(late.response)
454
+ }
455
+ })
456
+ .catch(() => {})
457
+ const { response, redirectFailure } = await Promise.race([fetchPromise, deadline])
458
+ responseAccepted = true
459
+ timeoutPhase = 'while reading the response body'
460
+ let cleanedUp = false
461
+ let cancellation: Promise<void> | undefined
462
+ const cancelBody = (): Promise<void> => (cancellation ??= this.cancelBody(response))
463
+ return {
464
+ response,
465
+ redirectFailure,
466
+ signal: controller.signal,
467
+ waitFor: <T>(operation: Promise<T>) => Promise.race([operation, deadline]),
468
+ cancelBody,
469
+ cleanup: () => {
470
+ if (cleanedUp) {
471
+ return
472
+ }
473
+ cleanedUp = true
474
+ clearTimeout(timer)
475
+ stopListening()
476
+ if (controller.signal.aborted) {
477
+ // The attempt deadline has already elapsed, so cleanup cannot wait
478
+ // for a custom response body's cancellation promise to settle.
479
+ void cancelBody()
480
+ }
481
+ },
482
+ }
483
+ } catch (error) {
484
+ clearTimeout(timer)
485
+ stopListening()
486
+ throw error
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Sends with `redirect: 'manual'` and follows 307 and 308 to the configured host's origin, at most
492
+ * `MAX_REDIRECTS` times, with the same method, headers and body. A fetch that follows redirects
493
+ * itself still works: its final response is not a redirect.
494
+ */
495
+ private async fetchFollowingRedirects(
496
+ url: string,
497
+ headers: PostHogFetchOptions['headers'],
498
+ body: string | Uint8Array,
499
+ signal: AbortSignal
500
+ ): Promise<RedirectOutcome> {
501
+ let target = url
502
+ for (let redirects = 0; ; redirects++) {
503
+ const response = await this.fetchFn(target, {
504
+ method: 'POST',
505
+ headers,
506
+ // A fresh copy per request: fetch may detach a byte body it has sent.
507
+ body: typeof body === 'string' ? body : body.slice(),
508
+ signal,
509
+ redirect: 'manual',
510
+ })
511
+ const { status } = response
512
+ if (status < 300 || status >= 400) {
513
+ return { response }
514
+ }
515
+ if (!FOLLOWED_REDIRECT_STATUSES.has(status)) {
516
+ return {
517
+ response,
518
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`,
519
+ }
520
+ }
521
+ if (redirects === MAX_REDIRECTS) {
522
+ return { response, redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times` }
523
+ }
524
+ const next = resolveLocation(response.headers?.get('Location'), target)
525
+ if (next === undefined || originOf(next) !== this.hostOrigin) {
526
+ return {
527
+ response,
528
+ redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`,
529
+ }
530
+ }
531
+ void this.cancelBody(response)
532
+ // An injected fetch may ignore abort, so stop the chain here.
533
+ if (signal.aborted) {
534
+ throw signal.reason
535
+ }
536
+ target = next
537
+ }
538
+ }
539
+
540
+ /** Compresses `payload` with the configured codec; `contentEncoding` names the codec when it compressed. */
541
+ private async encodeBody(
542
+ payload: string,
543
+ signal: AbortSignal | undefined
544
+ ): Promise<{ body: string | Uint8Array; contentEncoding?: string }> {
545
+ const codec = this.config.compression
546
+ if (codec === 'none') {
547
+ return { body: payload }
548
+ }
549
+ let timer: ReturnType<typeof setTimeout> | undefined
550
+ try {
551
+ const compression = this.compress(payload, codec)
552
+ // A compressor that settles after the deadline is ignored, so it can't start a request late.
553
+ compression.catch(() => {})
554
+ const timedOut = new Promise<typeof COMPRESSION_TIMED_OUT>((resolve) => {
555
+ timer = setTimeout(() => resolve(COMPRESSION_TIMED_OUT), this.config.requestTimeoutMs)
556
+ })
557
+ const compressed = await raceAbort(Promise.race([compression, timedOut]), signal)
558
+ if (compressed === COMPRESSION_TIMED_OUT) {
559
+ if (this.config.isDebug) {
560
+ console.error(
561
+ `Capture request body ${codec} compression took over ${this.config.requestTimeoutMs}ms, sending it uncompressed`
562
+ )
563
+ }
564
+ } else if (compressed !== null) {
565
+ return { body: compressed, contentEncoding: codec }
566
+ }
567
+ } catch (error) {
568
+ if (signal?.aborted) {
569
+ throw error
570
+ }
571
+ if (this.config.isDebug) {
572
+ console.error(`Failed to ${codec} compress the capture request body`, error)
573
+ }
574
+ } finally {
575
+ clearTimeout(timer)
576
+ }
577
+ return { body: payload }
578
+ }
579
+
580
+ private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
581
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
582
+ const headers: { [key: string]: string } = {
583
+ 'Content-Type': 'application/json',
584
+ Authorization: `Bearer ${this.config.projectToken ?? this.config.apiKey}`,
585
+ 'PostHog-Sdk-Info': sdkInfo,
586
+ 'PostHog-Attempt': String(attempt),
587
+ 'PostHog-Request-Id': requestId,
588
+ // Regenerated per attempt — a per-attempt wall-clock stamp, unlike Request-Id / created_at.
589
+ 'PostHog-Request-Timestamp': new Date(this.now()).toISOString(),
590
+ }
591
+ if (this.config.userAgent) {
592
+ headers['User-Agent'] = this.config.userAgent
593
+ }
594
+ const extraHeaders = this.config.extraHeaders
595
+ if (extraHeaders) {
596
+ const reserved = new Set([
597
+ 'user-agent',
598
+ 'content-encoding',
599
+ ...Object.keys(headers).map((name) => name.toLowerCase()),
600
+ ])
601
+ for (const [name, value] of Object.entries(extraHeaders)) {
602
+ if (!reserved.has(name.toLowerCase())) {
603
+ headers[name] = value
604
+ }
605
+ }
606
+ }
607
+ return headers
608
+ }
609
+
610
+ /**
611
+ * Partition the pending events against a 2xx result map: `drop` accumulates as
612
+ * a terminal failure, `retry` is returned for the next attempt, and
613
+ * `ok`/`warning`/unknown/absent are terminal successes.
614
+ */
615
+ private classify<T extends SerializedV1Event>(
616
+ pending: T[],
617
+ parsed: V1BatchResponse,
618
+ drops: CaptureDroppedEvent[]
619
+ ): T[] {
620
+ // Events carry canonical uuids, so results match by the canonical form of the server's keys.
621
+ const results = new Map<string, V1EventResult>()
622
+ for (const [uuid, result] of Object.entries(parsed.results)) {
623
+ results.set(canonicalizeUuid(uuid) ?? uuid, result)
624
+ }
625
+ const retryable: T[] = []
626
+ // Only built when a result reports duplicates, so the usual response costs nothing extra.
627
+ let copiesSeen: Map<string, number> | undefined
628
+ for (const event of pending) {
629
+ const result = results.get(event.uuid)
630
+ if (!result) {
631
+ continue
632
+ }
633
+ const duplicates = result.duplicates_dropped
634
+ if (typeof duplicates === 'number' && Number.isSafeInteger(duplicates) && duplicates > 0) {
635
+ copiesSeen ??= new Map()
636
+ const copy = copiesSeen.get(event.uuid) ?? 0
637
+ copiesSeen.set(event.uuid, copy + 1)
638
+ // The first copy takes the result; the next `duplicates` copies are the ones the server dropped.
639
+ if (copy >= 1 && copy <= duplicates) {
640
+ drops.push({ uuid: event.uuid, details: DUPLICATE_EVENT_UUID })
641
+ continue
642
+ }
643
+ }
644
+ if (result.result === 'drop') {
645
+ drops.push({ uuid: event.uuid, details: result.details ?? undefined })
646
+ } else if (result.result === 'retry') {
647
+ retryable.push(event)
648
+ }
649
+ // ok / warning / unknown codes are terminal successes.
650
+ }
651
+ return retryable
652
+ }
653
+
654
+ /** The wait after failed attempt `attempt` (1-based): jittered exponential backoff, raised to `Retry-After`. */
655
+ private backoffDelay(attempt: number, retryAfterMs?: number): number {
656
+ const jitter = 0.75 + 0.5 * this.random()
657
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS)
658
+ if (retryAfterMs === undefined) {
659
+ return backoff
660
+ }
661
+ // Compared after jitter, so jitter can never make the wait shorter than Retry-After.
662
+ return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS))
663
+ }
664
+
665
+ /** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
666
+ private parseRetryAfter(response: PostHogFetchResponse): number | undefined {
667
+ const raw = response.headers?.get('Retry-After')
668
+ if (!raw) {
669
+ return undefined
670
+ }
671
+ const trimmed = raw.trim()
672
+ if (/^\d+$/.test(trimmed)) {
673
+ const seconds = parseInt(trimmed, 10)
674
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined
675
+ }
676
+ const dateMs = Date.parse(trimmed)
677
+ if (Number.isNaN(dateMs)) {
678
+ return undefined
679
+ }
680
+ const delta = dateMs - this.now()
681
+ return delta > 0 ? delta : undefined
682
+ }
683
+
684
+ private async parseResponse(response: PostHogFetchResponse): Promise<V1BatchResponse> {
685
+ const text = await response.text()
686
+ const parsed = JSON.parse(text)
687
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
688
+ throw new Error('unexpected response shape')
689
+ }
690
+ const results = (parsed as { results?: unknown }).results
691
+ if (typeof results !== 'object' || results === null || Array.isArray(results)) {
692
+ throw new Error('unexpected results shape')
693
+ }
694
+ return { results: results as V1BatchResponse['results'] }
695
+ }
696
+
697
+ private async buildHttpError(
698
+ response: PostHogFetchResponse,
699
+ status: number,
700
+ waitFor: V1CaptureAttempt['waitFor']
701
+ ): Promise<Error> {
702
+ let bodyText = ''
703
+ try {
704
+ bodyText = (await waitFor(response.text())).slice(0, 512)
705
+ } catch {
706
+ // best-effort; a missing or timed-out body should not mask the status
707
+ }
708
+ const suffix = bodyText ? `: ${bodyText}` : ''
709
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
710
+ }
711
+
712
+ private surfaceBatchFailure(
713
+ requestId: string,
714
+ drops: CaptureDroppedEvent[],
715
+ pending: SerializedV1Event[],
716
+ cause: unknown,
717
+ loss: CaptureLossTally,
718
+ failure: string
719
+ ): void {
720
+ loss.add(failure, pending.length)
721
+ this.report(
722
+ this.captureError({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }),
723
+ loss
724
+ )
725
+ }
726
+
727
+ private surfacePartialDrops(requestId: string, drops: CaptureDroppedEvent[], loss: CaptureLossTally): void {
728
+ if (drops.length > 0) {
729
+ this.report(this.captureError({ requestId, drops, retryExhausted: [] }), loss)
730
+ }
731
+ }
732
+
733
+ private report(error: CaptureError, loss: CaptureLossTally): void {
734
+ this.onError(error, describeCaptureLoss(this.config.path, loss))
735
+ }
736
+
737
+ /** A failure without an HTTP response, named by type only: its message can carry server or proxy text. */
738
+ private describeTransportFailure(error: unknown, signal: AbortSignal | undefined): string {
739
+ if (error instanceof Error && timeoutErrors.has(error)) {
740
+ return 'failed: request timed out'
741
+ }
742
+ if (signal?.aborted) {
743
+ return 'failed: request aborted'
744
+ }
745
+ const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown'
746
+ return `failed with a network error (${name})`
747
+ }
748
+
749
+ private captureError(params: Omit<CaptureErrorParams, 'endpoint'>): CaptureError {
750
+ return new CaptureError({ endpoint: this.config.path, ...params })
751
+ }
752
+
753
+ private async cancelBody(response: PostHogFetchResponse): Promise<void> {
754
+ try {
755
+ await response.body?.cancel()
756
+ } catch {
757
+ // Cancellation is best-effort and must never mask delivery handling.
758
+ }
759
+ }
760
+ }
761
+
762
+ function originOf(url: string): string | undefined {
763
+ try {
764
+ return new URL(url).origin
765
+ } catch {
766
+ return undefined
767
+ }
768
+ }
769
+
770
+ function resolveLocation(location: string | null | undefined, base: string): string | undefined {
771
+ if (!location) {
772
+ return undefined
773
+ }
774
+ try {
775
+ return new URL(location, base).href
776
+ } catch {
777
+ return undefined
778
+ }
779
+ }