posthog-node 5.40.0 → 5.41.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 (41) hide show
  1. package/LICENSE +2 -2
  2. package/dist/capture-v1/config.d.ts +11 -0
  3. package/dist/capture-v1/config.d.ts.map +1 -0
  4. package/dist/capture-v1/config.js +42 -0
  5. package/dist/capture-v1/config.mjs +8 -0
  6. package/dist/capture-v1/errors.d.ts +32 -0
  7. package/dist/capture-v1/errors.d.ts.map +1 -0
  8. package/dist/capture-v1/errors.js +49 -0
  9. package/dist/capture-v1/errors.mjs +15 -0
  10. package/dist/capture-v1/routing.d.ts +21 -0
  11. package/dist/capture-v1/routing.d.ts.map +1 -0
  12. package/dist/capture-v1/routing.js +47 -0
  13. package/dist/capture-v1/routing.mjs +7 -0
  14. package/dist/capture-v1/sender.d.ts +70 -0
  15. package/dist/capture-v1/sender.d.ts.map +1 -0
  16. package/dist/capture-v1/sender.js +222 -0
  17. package/dist/capture-v1/sender.mjs +188 -0
  18. package/dist/capture-v1/transform.d.ts +34 -0
  19. package/dist/capture-v1/transform.d.ts.map +1 -0
  20. package/dist/capture-v1/transform.js +142 -0
  21. package/dist/capture-v1/transform.mjs +99 -0
  22. package/dist/capture-v1/types.d.ts +50 -0
  23. package/dist/capture-v1/types.d.ts.map +1 -0
  24. package/dist/capture-v1/types.js +18 -0
  25. package/dist/capture-v1/types.mjs +0 -0
  26. package/dist/client.d.ts +22 -1
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +42 -0
  29. package/dist/client.mjs +43 -1
  30. package/dist/version.d.ts +1 -1
  31. package/dist/version.js +1 -1
  32. package/dist/version.mjs +1 -1
  33. package/package.json +2 -2
  34. package/src/capture-v1/config.ts +18 -0
  35. package/src/capture-v1/errors.ts +52 -0
  36. package/src/capture-v1/routing.ts +28 -0
  37. package/src/capture-v1/sender.ts +298 -0
  38. package/src/capture-v1/transform.ts +159 -0
  39. package/src/capture-v1/types.ts +55 -0
  40. package/src/client.ts +77 -0
  41. package/src/version.ts +1 -1
@@ -0,0 +1,159 @@
1
+ import type { JsonType, PostHogEventProperties } from '@posthog/core'
2
+
3
+ import type { V1Batch, V1Event, V1EventOptions } from './types'
4
+
5
+ /**
6
+ * Coerce a value to a boolean the way the capture server does, or return
7
+ * `undefined` if it cannot be coerced (the option is then omitted so the server
8
+ * falls back to its default). Accepts native booleans, the strings
9
+ * `"true"`/`"1"`/`"false"`/`"0"` (trimmed, case-insensitive), and any number
10
+ * (nonzero -> true).
11
+ */
12
+ export function coerceBool(value: JsonType): boolean | undefined {
13
+ if (typeof value === 'boolean') {
14
+ return value
15
+ }
16
+ if (typeof value === 'number') {
17
+ return value !== 0
18
+ }
19
+ if (typeof value === 'string') {
20
+ const normalized = value.trim().toLowerCase()
21
+ if (normalized === 'true' || normalized === '1') {
22
+ return true
23
+ }
24
+ if (normalized === 'false' || normalized === '0') {
25
+ return false
26
+ }
27
+ }
28
+ return undefined
29
+ }
30
+
31
+ /**
32
+ * Accept only a native string, else return `undefined` (the option is then
33
+ * omitted). The backend's `product_tour_id` is `Option<String>`, so numbers,
34
+ * booleans, objects, and arrays are dropped rather than coerced — matching
35
+ * posthog-go, posthog-rs, and posthog-python exactly.
36
+ */
37
+ export function coerceString(value: JsonType): string | undefined {
38
+ return typeof value === 'string' ? value : undefined
39
+ }
40
+
41
+ /** Legacy sentinel property -> typed `options` field, with its coercion. */
42
+ const OPTION_SENTINELS: ReadonlyArray<{
43
+ property: string
44
+ optionKey: keyof V1EventOptions
45
+ coerce: (value: JsonType) => boolean | string | undefined
46
+ }> = [
47
+ { property: '$cookieless_mode', optionKey: 'cookieless_mode', coerce: coerceBool },
48
+ { property: '$ignore_sent_at', optionKey: 'disable_skew_correction', coerce: coerceBool },
49
+ { property: '$process_person_profile', optionKey: 'process_person_profile', coerce: coerceBool },
50
+ { property: '$product_tour_id', optionKey: 'product_tour_id', coerce: coerceString },
51
+ ]
52
+
53
+ /** Sentinel property -> top-level string field (string-only, non-string dropped). */
54
+ const TOPLEVEL_SENTINELS: ReadonlyArray<{ property: string; field: 'session_id' | 'window_id' }> = [
55
+ { property: '$session_id', field: 'session_id' },
56
+ { property: '$window_id', field: 'window_id' },
57
+ ]
58
+
59
+ function isRecord(value: JsonType | undefined): value is PostHogEventProperties {
60
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
61
+ }
62
+
63
+ /**
64
+ * Normalize an event timestamp to an RFC 3339 string. The queued message
65
+ * carries either an ISO string (from `currentISOTime()`) or a `Date` (when the
66
+ * caller passed one); numbers are treated as epoch milliseconds. Invalid values
67
+ * fall back to "now" so a bad timestamp never rejects the whole batch.
68
+ */
69
+ function toRfc3339(timestamp: unknown): string {
70
+ if (typeof timestamp === 'string') {
71
+ const asDate = new Date(timestamp)
72
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : timestamp
73
+ }
74
+ if (timestamp instanceof Date) {
75
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString()
76
+ }
77
+ const asDate = timestamp == null ? new Date() : new Date(timestamp as string | number)
78
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString()
79
+ }
80
+
81
+ /**
82
+ * Relocate a top-level `$set`/`$set_once` value into `properties`. v1 has no
83
+ * top-level form; the server reads them from inside `properties`. An existing
84
+ * `properties` value wins on collision.
85
+ */
86
+ function relocateInto(properties: PostHogEventProperties, key: string, value: JsonType | undefined): void {
87
+ if (value !== undefined && !(key in properties)) {
88
+ properties[key] = value
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Transform one already-normalized queued message into a Capture V1 wire event.
94
+ *
95
+ * The input message is never mutated (events may be retried or handed to
96
+ * callbacks): a fresh `properties` map is built. Sentinel properties are lifted
97
+ * out of `properties` (deleting the copy) into the typed `options` object and
98
+ * the top-level `session_id`/`window_id` fields; `$lib`/`$lib_version` are
99
+ * stripped (the server injects them from `PostHog-Sdk-Info`); top-level
100
+ * `$set`/`$set_once` are relocated into `properties`.
101
+ */
102
+ export function buildV1Event(message: PostHogEventProperties): V1Event {
103
+ const sourceProperties = isRecord(message.properties) ? message.properties : {}
104
+ const properties: PostHogEventProperties = { ...sourceProperties }
105
+
106
+ const options: V1EventOptions = {}
107
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS) {
108
+ if (property in properties) {
109
+ const coerced = coerce(properties[property])
110
+ if (coerced !== undefined) {
111
+ ;(options as Record<string, boolean | string>)[optionKey] = coerced
112
+ }
113
+ // Always strip the sentinel, even when coercion omits the option.
114
+ delete properties[property]
115
+ }
116
+ }
117
+
118
+ const topLevel: { session_id?: string; window_id?: string } = {}
119
+ for (const { property, field } of TOPLEVEL_SENTINELS) {
120
+ if (property in properties) {
121
+ const value = properties[property]
122
+ if (typeof value === 'string') {
123
+ topLevel[field] = value
124
+ }
125
+ delete properties[property]
126
+ }
127
+ }
128
+
129
+ delete properties.$lib
130
+ delete properties.$lib_version
131
+
132
+ relocateInto(properties, '$set', message.$set)
133
+ relocateInto(properties, '$set_once', message.$set_once)
134
+
135
+ return {
136
+ event: String(message.event ?? ''),
137
+ uuid: String(message.uuid ?? ''),
138
+ distinct_id: String(message.distinct_id ?? ''),
139
+ timestamp: toRfc3339(message.timestamp),
140
+ ...topLevel,
141
+ options,
142
+ properties,
143
+ }
144
+ }
145
+
146
+ /** Build a Capture V1 batch envelope from already-normalized queued messages. */
147
+ export function buildV1Batch(
148
+ messages: PostHogEventProperties[],
149
+ { createdAt, historicalMigration }: { createdAt: string; historicalMigration?: boolean }
150
+ ): V1Batch {
151
+ const batch: V1Batch = {
152
+ created_at: createdAt,
153
+ batch: messages.map(buildV1Event),
154
+ }
155
+ if (historicalMigration) {
156
+ batch.historical_migration = true
157
+ }
158
+ return batch
159
+ }
@@ -0,0 +1,55 @@
1
+ import type { PostHogEventProperties } from '@posthog/core'
2
+
3
+ /**
4
+ * Typed `options` object on a Capture V1 event. Legacy `$`-prefixed sentinel
5
+ * properties are lifted here (renamed + strictly typed) by the transform.
6
+ * Always serialized as an object (`{}` when empty), never `null`.
7
+ */
8
+ export interface V1EventOptions {
9
+ cookieless_mode?: boolean
10
+ disable_skew_correction?: boolean
11
+ process_person_profile?: boolean
12
+ product_tour_id?: string
13
+ }
14
+
15
+ /**
16
+ * A single event in a Capture V1 batch (`POST /i/v1/analytics/events`).
17
+ * `session_id`/`window_id` are promoted from the `$session_id`/`$window_id`
18
+ * sentinels; there is no top-level `api_key`.
19
+ */
20
+ export interface V1Event {
21
+ event: string
22
+ uuid: string
23
+ distinct_id: string
24
+ timestamp: string
25
+ session_id?: string
26
+ window_id?: string
27
+ options: V1EventOptions
28
+ properties: PostHogEventProperties
29
+ }
30
+
31
+ /**
32
+ * The Capture V1 batch envelope. Unlike v0 there is no `api_key` (Bearer auth)
33
+ * and no `sent_at`. `historical_migration` is omitted when false.
34
+ */
35
+ export interface V1Batch {
36
+ created_at: string
37
+ historical_migration?: boolean
38
+ batch: V1Event[]
39
+ }
40
+
41
+ /**
42
+ * Per-event result codes in a v1 2xx response body. Unknown strings are
43
+ * tolerated as terminal success for forward compatibility.
44
+ */
45
+ export type V1ResultCode = 'ok' | 'warning' | 'drop' | 'retry'
46
+
47
+ export interface V1EventResult {
48
+ result: V1ResultCode | string
49
+ details?: string | null
50
+ }
51
+
52
+ /** Shape of a v1 2xx response body: a per-uuid map of results. */
53
+ export interface V1BatchResponse {
54
+ results: Record<string, V1EventResult>
55
+ }
package/src/client.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  PostHogFlagsAndPayloadsResponse,
14
14
  PostHogFlagsResponse,
15
15
  PostHogPersistedProperty,
16
+ RetriableOptions,
16
17
  safeSetTimeout,
17
18
  uuidv7,
18
19
  } from '@posthog/core'
@@ -48,6 +49,9 @@ import {
48
49
  import ErrorTracking from './extensions/error-tracking'
49
50
  import { PostHogMemoryStorage } from './storage-memory'
50
51
  import { ContextData, ContextOptions, IPostHogContext } from './extensions/context/types'
52
+ import { type CaptureMode, resolveCaptureMode } from './capture-v1/config'
53
+ import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from './capture-v1/routing'
54
+ import { V1CaptureSender } from './capture-v1/sender'
51
55
 
52
56
  // Standard local evaluation rate limit is 600 per minute (10 per second),
53
57
  // so the fastest a poller should ever be set is 100ms.
@@ -131,6 +135,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
131
135
  public readonly options: PostHogOptions
132
136
  protected readonly context?: IPostHogContext
133
137
 
138
+ private readonly captureMode: CaptureMode
139
+ private _v1Sender?: V1CaptureSender
140
+
134
141
  // Feature flag overrides for local testing/development
135
142
  private _flagOverrides?: Record<string, FeatureFlagValue>
136
143
  private _payloadOverrides?: Record<string, JsonType>
@@ -184,6 +191,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
184
191
  super(normalizedApiKey, normalizedOptions)
185
192
 
186
193
  this.options = normalizedOptions
194
+ this.captureMode = resolveCaptureMode()
187
195
  this.context = this.initializeContext()
188
196
 
189
197
  this.options.featureFlagsPollingInterval =
@@ -394,6 +402,75 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
394
402
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options)
395
403
  }
396
404
 
405
+ /**
406
+ * Route an event to its queue. In v1 mode `$ai_*` events go to the isolated {@link AI_ROUTE}
407
+ * (legacy transport) and everything else to {@link ANALYTICS_ROUTE} (Capture V1); in v0 mode
408
+ * every event stays on {@link ANALYTICS_ROUTE}, which maps to the historical queue. Routing runs
409
+ * on the post-`before_send`, normalized event name (core calls this after `processBeforeEnqueue`).
410
+ */
411
+ protected getQueueRouteKey(message: PostHogEventProperties): string {
412
+ return this.captureMode === 'v1' && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE
413
+ }
414
+
415
+ protected persistedQueueKeyForRoute(route: string): PostHogPersistedProperty {
416
+ return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue
417
+ }
418
+
419
+ protected getActiveQueueRoutes(): string[] {
420
+ // Only surface the AI route in v1 mode — v0 mode never enqueues onto it, so keeping it out
421
+ // keeps v0's flush/shutdown identical to before (a single queue on ANALYTICS_ROUTE).
422
+ return this.captureMode === 'v1' ? [ANALYTICS_ROUTE, AI_ROUTE] : [ANALYTICS_ROUTE]
423
+ }
424
+
425
+ /**
426
+ * Capture submission seam shared by the batched (`_flush`) and immediate (`sendImmediate`)
427
+ * paths. Events are routed to homogeneous per-route queues at enqueue time, so a batch here is
428
+ * never mixed: the {@link AI_ROUTE} (and all of v0 mode) uses the legacy `/batch/` transport,
429
+ * which throws so `_flush` can shrink/persist/retry its own queue; the {@link ANALYTICS_ROUTE}
430
+ * in v1 mode uses the Capture V1 endpoint. Because the routes flush independently, a v0/AI leg
431
+ * failure can never re-send analytics events already accepted on the V1 leg.
432
+ */
433
+ protected async sendBatch(
434
+ batchMessages: (PostHogEventProperties | undefined)[],
435
+ retryOptions?: Partial<RetriableOptions>,
436
+ route: string = ANALYTICS_ROUTE
437
+ ): Promise<void> {
438
+ if (this.captureMode !== 'v1' || route === AI_ROUTE) {
439
+ return super.sendBatch(batchMessages, retryOptions, route)
440
+ }
441
+
442
+ // Analytics route in v1 mode: homogeneous (no `$ai_*`, routed away at enqueue) and never
443
+ // undefined for a freshly-enqueued event; drop any legacy undefined queue artifacts.
444
+ const v1Events = batchMessages.filter((message): message is PostHogEventProperties => message !== undefined)
445
+ await this.getV1Sender().sendV1Batch(v1Events)
446
+ }
447
+
448
+ private getV1Sender(): V1CaptureSender {
449
+ if (!this._v1Sender) {
450
+ this._v1Sender = new V1CaptureSender(
451
+ {
452
+ host: this.host,
453
+ apiKey: this.apiKey,
454
+ libraryId: this.getLibraryId(),
455
+ libraryVersion: this.getLibraryVersion(),
456
+ userAgent: this.getCustomUserAgent() || undefined,
457
+ historicalMigration: this.historicalMigration,
458
+ compressionEnabled: !this.disableCompression,
459
+ requestTimeoutMs: this.requestTimeout,
460
+ // Reuse the existing v0 retry knobs: 1 initial attempt + fetchRetryCount retries.
461
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
462
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
463
+ isDebug: this.isDebug,
464
+ },
465
+ {
466
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
467
+ onError: (error) => this._events.emit('error', error),
468
+ }
469
+ )
470
+ }
471
+ return this._v1Sender
472
+ }
473
+
397
474
  /**
398
475
  * Get the library version from package.json.
399
476
  *
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '5.40.0'
1
+ export const version = '5.41.0'