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
@@ -0,0 +1,119 @@
1
+ import { CAPTURE_COMPRESSIONS, type CaptureCompression } from '../capture-v1/compression'
2
+ import type { PostHogOptions } from '../types'
3
+
4
+ export const DEFAULT_CAPTURE_MAX_RETRIES = 3
5
+ export const MAX_CAPTURE_MAX_RETRIES = 9
6
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000
7
+ export const DEFAULT_AI_REQUEST_TIMEOUT_MS = 30_000
8
+ export const DEFAULT_AI_MAX_QUEUE_SIZE = 1000
9
+
10
+ /** Capture settings resolved once per client from `PostHogOptions`. */
11
+ export interface CaptureSettings {
12
+ /** Retries after the first attempt, for both lanes. */
13
+ maxRetries: number
14
+ analytics: CaptureLaneSettings
15
+ ai: CaptureLaneSettings & {
16
+ /** Queued AI events; the analytics queue size stays a client setting. */
17
+ maxQueueSize: number
18
+ }
19
+ }
20
+
21
+ export interface CaptureLaneSettings {
22
+ /** The requested body encoding; the runtime may not support it. */
23
+ compression: CaptureCompression
24
+ requestTimeoutMs: number
25
+ }
26
+
27
+ type LogInvalid = (message: string) => void
28
+
29
+ const isIntegerInRange = (value: unknown, min: number, max: number): value is number =>
30
+ typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max
31
+
32
+ /**
33
+ * Validates the capture options. An invalid value is reported once through `logInvalid` and
34
+ * behaves as if it were not set, so a bad option never throws.
35
+ */
36
+ export function resolveCaptureSettings(options: PostHogOptions, logInvalid: LogInvalid): CaptureSettings {
37
+ return {
38
+ maxRetries: resolveMaxRetries(options, logInvalid),
39
+ analytics: {
40
+ compression:
41
+ resolveCompression('captureCompression', options.captureCompression, logInvalid) ??
42
+ (options.disableCompression ? 'none' : 'gzip'),
43
+ requestTimeoutMs: options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS,
44
+ },
45
+ ai: {
46
+ // The AI lane does not read captureCompression or disableCompression.
47
+ compression: resolveCompression('captureAiCompression', options.captureAiCompression, logInvalid) ?? 'gzip',
48
+ requestTimeoutMs: resolvePositive(
49
+ 'captureAiRequestTimeoutMs',
50
+ options.captureAiRequestTimeoutMs,
51
+ DEFAULT_AI_REQUEST_TIMEOUT_MS,
52
+ logInvalid,
53
+ { integer: false }
54
+ ),
55
+ maxQueueSize: resolvePositive(
56
+ 'captureAiMaxQueueSize',
57
+ options.captureAiMaxQueueSize,
58
+ DEFAULT_AI_MAX_QUEUE_SIZE,
59
+ logInvalid,
60
+ { integer: true }
61
+ ),
62
+ },
63
+ }
64
+ }
65
+
66
+ function resolveCompression(name: string, value: unknown, logInvalid: LogInvalid): CaptureCompression | undefined {
67
+ if (value == null) {
68
+ return undefined
69
+ }
70
+ if ((CAPTURE_COMPRESSIONS as readonly unknown[]).includes(value)) {
71
+ return value as CaptureCompression
72
+ }
73
+ logInvalid(
74
+ `${name} must be one of ${CAPTURE_COMPRESSIONS.map((codec) => `'${codec}'`).join(', ')}; using the default.`
75
+ )
76
+ return undefined
77
+ }
78
+
79
+ // Node clamps a timer delay above this to 1 ms, which would time out every request.
80
+ const MAX_SETTING_VALUE = 2_147_483_647
81
+
82
+ function resolvePositive(
83
+ name: string,
84
+ value: unknown,
85
+ fallback: number,
86
+ logInvalid: LogInvalid,
87
+ { integer }: { integer: boolean }
88
+ ): number {
89
+ if (value == null) {
90
+ return fallback
91
+ }
92
+ if (
93
+ typeof value === 'number' &&
94
+ value > 0 &&
95
+ value <= MAX_SETTING_VALUE &&
96
+ (integer ? Number.isSafeInteger(value) : Number.isFinite(value))
97
+ ) {
98
+ return value
99
+ }
100
+ logInvalid(
101
+ `${name} must be a positive ${integer ? 'integer' : 'number'} up to ${MAX_SETTING_VALUE}; using the default.`
102
+ )
103
+ return fallback
104
+ }
105
+
106
+ function resolveMaxRetries(options: PostHogOptions, logInvalid: LogInvalid): number {
107
+ const { captureMaxRetries, fetchRetryCount } = options
108
+ if (captureMaxRetries != null) {
109
+ if (isIntegerInRange(captureMaxRetries, 0, MAX_CAPTURE_MAX_RETRIES)) {
110
+ return captureMaxRetries
111
+ }
112
+ logInvalid(`captureMaxRetries must be an integer from 0 to ${MAX_CAPTURE_MAX_RETRIES}; using the default.`)
113
+ }
114
+ // fetchRetryCount also configures other requests, so an out-of-range value is clamped for capture, not reported.
115
+ if (typeof fetchRetryCount === 'number' && Number.isFinite(fetchRetryCount)) {
116
+ return Math.min(Math.max(Math.trunc(fetchRetryCount), 0), MAX_CAPTURE_MAX_RETRIES)
117
+ }
118
+ return DEFAULT_CAPTURE_MAX_RETRIES
119
+ }
@@ -0,0 +1,50 @@
1
+ import { gzipCompress, isGzipSupported } from '@posthog/core'
2
+
3
+ export const CAPTURE_COMPRESSIONS = ['none', 'gzip', 'deflate', 'zstd'] as const
4
+
5
+ /** A capture request body encoding; `deflate` is zlib-wrapped, as HTTP `Content-Encoding: deflate` requires. */
6
+ export type CaptureCompression = (typeof CAPTURE_COMPRESSIONS)[number]
7
+
8
+ export type CaptureCodec = Exclude<CaptureCompression, 'none'>
9
+
10
+ /** Compresses capture request bodies with the codecs one runtime provides. */
11
+ export interface CaptureCompressor {
12
+ supports(codec: CaptureCodec): boolean
13
+ /** Resolves to null, or rejects, when compression fails; the sender then sends the body uncompressed. */
14
+ compress(payload: string, codec: CaptureCodec): Promise<Uint8Array | null>
15
+ }
16
+
17
+ /** Uses CompressionStream, so it works wherever the runtime has one. It has no zstd. */
18
+ export const webCompressor: CaptureCompressor = {
19
+ supports: (codec) => codec !== 'zstd' && isGzipSupported(),
20
+ async compress(payload, codec) {
21
+ if (codec === 'gzip') {
22
+ const compressed = await gzipCompress(payload, false)
23
+ return compressed && new Uint8Array(await compressed.arrayBuffer())
24
+ }
25
+ if (codec !== 'deflate') {
26
+ return null
27
+ }
28
+ const stream = new Response(payload).body!.pipeThrough(new globalThis.CompressionStream('deflate'))
29
+ return new Uint8Array(await new Response(stream).arrayBuffer())
30
+ },
31
+ }
32
+
33
+ /**
34
+ * The codec a lane sends with: `requested` when the runtime has it, gzip in place of an unavailable
35
+ * zstd, or no compression when the runtime cannot compress at all.
36
+ */
37
+ export function resolveCaptureCodec(
38
+ requested: CaptureCompression,
39
+ compressor: CaptureCompressor,
40
+ onZstdUnavailable: (fallback: CaptureCompression) => void
41
+ ): CaptureCompression {
42
+ if (requested === 'none' || compressor.supports(requested)) {
43
+ return requested
44
+ }
45
+ const fallback = compressor.supports('gzip') ? 'gzip' : 'none'
46
+ if (requested === 'zstd') {
47
+ onZstdUnavailable(fallback)
48
+ }
49
+ return fallback
50
+ }
@@ -1,13 +1,17 @@
1
+ import type { CaptureEndpoint } from './types'
2
+
1
3
  /** A single event the server explicitly rejected (`drop`). */
2
- export interface V1DroppedEvent {
4
+ export interface CaptureDroppedEvent {
3
5
  uuid: string
4
6
  details?: string
5
7
  }
6
8
 
7
- export interface CaptureV1ErrorParams {
9
+ export interface CaptureErrorParams {
10
+ /** The capture lane the batch was sent to. */
11
+ endpoint: CaptureEndpoint
8
12
  requestId: string
9
13
  /** Events the server rejected outright (billing/validation). */
10
- drops: V1DroppedEvent[]
14
+ drops: CaptureDroppedEvent[]
11
15
  /** UUIDs of events still pending `retry` after the attempt budget was exhausted, or lost to a batch-level failure. */
12
16
  retryExhausted: string[]
13
17
  /** The underlying transport/HTTP/parse failure, when the whole batch failed. */
@@ -15,22 +19,24 @@ export interface CaptureV1ErrorParams {
15
19
  }
16
20
 
17
21
  /**
18
- * Surfaced on the client error channel whenever a Capture V1 batch did not
22
+ * Surfaced on the client error channel whenever a capture batch did not
19
23
  * fully deliver: some events were `drop`ped, some `retry` events outlived the
20
24
  * attempt budget, or the batch hit a terminal transport/HTTP/parse failure.
21
25
  *
22
26
  * A 2xx with drops is still a partial failure and is reported here — a
23
27
  * successful HTTP status does not mean every event was accepted.
24
28
  */
25
- export class CaptureV1Error extends Error {
26
- name = 'CaptureV1Error'
29
+ export class CaptureError extends Error {
30
+ name = 'CaptureError'
31
+ readonly endpoint: CaptureEndpoint
27
32
  readonly requestId: string
28
- readonly drops: V1DroppedEvent[]
33
+ readonly drops: CaptureDroppedEvent[]
29
34
  readonly retryExhausted: string[]
30
35
  cause?: unknown
31
36
 
32
- constructor({ requestId, drops, retryExhausted, cause }: CaptureV1ErrorParams) {
33
- super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause))
37
+ constructor({ endpoint, requestId, drops, retryExhausted, cause }: CaptureErrorParams) {
38
+ super(CaptureError.buildMessage(endpoint, requestId, drops, retryExhausted, cause))
39
+ this.endpoint = endpoint
34
40
  this.requestId = requestId
35
41
  this.drops = drops
36
42
  this.retryExhausted = retryExhausted
@@ -38,15 +44,48 @@ export class CaptureV1Error extends Error {
38
44
  }
39
45
 
40
46
  private static buildMessage(
47
+ endpoint: CaptureEndpoint,
41
48
  requestId: string,
42
- drops: V1DroppedEvent[],
49
+ drops: CaptureDroppedEvent[],
43
50
  retryExhausted: string[],
44
51
  cause: unknown
45
52
  ): string {
46
- let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`
53
+ let message = `Capture batch ${requestId} to ${endpoint} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`
47
54
  if (cause instanceof Error) {
48
55
  message += ` (${cause.message})`
49
56
  }
50
57
  return message
51
58
  }
52
59
  }
60
+
61
+ /** Counts of undelivered events by cause, in the order the causes first occurred. */
62
+ export class CaptureLossTally {
63
+ private readonly counts = new Map<string, number>()
64
+
65
+ add(cause: string, count: number): void {
66
+ if (count > 0) {
67
+ this.counts.set(cause, (this.counts.get(cause) ?? 0) + count)
68
+ }
69
+ }
70
+
71
+ get total(): number {
72
+ let total = 0
73
+ for (const count of this.counts.values()) {
74
+ total += count
75
+ }
76
+ return total
77
+ }
78
+
79
+ entries(): [cause: string, count: number][] {
80
+ return [...this.counts]
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The one line logged for a capture loss when nothing listens for `'error'`. It holds the lane,
86
+ * counts and causes only: never server response text, event content or uuids.
87
+ */
88
+ export function describeCaptureLoss(endpoint: CaptureEndpoint, loss: CaptureLossTally): string {
89
+ const causes = loss.entries().map(([cause, count]) => `${count} ${cause}`)
90
+ return `${loss.total} event(s) were not delivered to ${endpoint}: ${causes.join(', ')}`
91
+ }