posthog-node 5.39.4 → 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.
- package/LICENSE +2 -2
- package/dist/capture-v1/config.d.ts +11 -0
- package/dist/capture-v1/config.d.ts.map +1 -0
- package/dist/capture-v1/config.js +42 -0
- package/dist/capture-v1/config.mjs +8 -0
- package/dist/capture-v1/errors.d.ts +32 -0
- package/dist/capture-v1/errors.d.ts.map +1 -0
- package/dist/capture-v1/errors.js +49 -0
- package/dist/capture-v1/errors.mjs +15 -0
- package/dist/capture-v1/routing.d.ts +21 -0
- package/dist/capture-v1/routing.d.ts.map +1 -0
- package/dist/capture-v1/routing.js +47 -0
- package/dist/capture-v1/routing.mjs +7 -0
- package/dist/capture-v1/sender.d.ts +70 -0
- package/dist/capture-v1/sender.d.ts.map +1 -0
- package/dist/capture-v1/sender.js +222 -0
- package/dist/capture-v1/sender.mjs +188 -0
- package/dist/capture-v1/transform.d.ts +34 -0
- package/dist/capture-v1/transform.d.ts.map +1 -0
- package/dist/capture-v1/transform.js +142 -0
- package/dist/capture-v1/transform.mjs +99 -0
- package/dist/capture-v1/types.d.ts +50 -0
- package/dist/capture-v1/types.d.ts.map +1 -0
- package/dist/capture-v1/types.js +18 -0
- package/dist/capture-v1/types.mjs +0 -0
- package/dist/client.d.ts +24 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +43 -1
- package/dist/client.mjs +44 -2
- package/dist/extensions/feature-flags/feature-flags.js +2 -2
- package/dist/extensions/feature-flags/feature-flags.mjs +2 -2
- package/dist/types.d.ts +17 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +3 -3
- package/src/capture-v1/config.ts +18 -0
- package/src/capture-v1/errors.ts +52 -0
- package/src/capture-v1/routing.ts +28 -0
- package/src/capture-v1/sender.ts +298 -0
- package/src/capture-v1/transform.ts +159 -0
- package/src/capture-v1/types.ts +55 -0
- package/src/client.ts +80 -3
- package/src/extensions/feature-flags/feature-flags.ts +2 -2
- package/src/types.ts +19 -2
- package/src/version.ts +1 -1
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type FetchLike,
|
|
3
|
+
type PostHogEventProperties,
|
|
4
|
+
type PostHogFetchOptions,
|
|
5
|
+
type PostHogFetchResponse,
|
|
6
|
+
gzipCompress,
|
|
7
|
+
safeJsonStringify,
|
|
8
|
+
safeSetTimeout,
|
|
9
|
+
uuidv7,
|
|
10
|
+
} from '@posthog/core'
|
|
11
|
+
|
|
12
|
+
import { CaptureV1Error, type V1DroppedEvent } from './errors'
|
|
13
|
+
import { buildV1Batch } from './transform'
|
|
14
|
+
import type { V1BatchResponse, V1Event } from './types'
|
|
15
|
+
|
|
16
|
+
const V1_ANALYTICS_PATH = '/i/v1/analytics/events'
|
|
17
|
+
const DEFAULT_MAX_BACKOFF_MS = 30_000
|
|
18
|
+
|
|
19
|
+
/** HTTP statuses the v1 backend wants retried. 429 is intentionally terminal in v1. */
|
|
20
|
+
const RETRYABLE_STATUSES = new Set([408, 500, 502, 503, 504])
|
|
21
|
+
|
|
22
|
+
export interface V1CaptureSenderConfig {
|
|
23
|
+
host: string
|
|
24
|
+
apiKey: string
|
|
25
|
+
/** Canonical `$lib` identity, materialized by the server from `PostHog-Sdk-Info`. */
|
|
26
|
+
libraryId: string
|
|
27
|
+
libraryVersion: string
|
|
28
|
+
/** Value for the `User-Agent` header, if the runtime allows setting it. */
|
|
29
|
+
userAgent?: string
|
|
30
|
+
historicalMigration: boolean
|
|
31
|
+
/** When true, the body is gzip-compressed (falling back to uncompressed on failure). */
|
|
32
|
+
compressionEnabled: boolean
|
|
33
|
+
requestTimeoutMs: number
|
|
34
|
+
/** Total attempts, including the first (1 initial + N retries). */
|
|
35
|
+
maxAttempts: number
|
|
36
|
+
/** Base exponential backoff, doubled each retry and capped at `maxBackoffMs`. */
|
|
37
|
+
initialRetryDelayMs: number
|
|
38
|
+
/** Single ceiling for both the backoff schedule and the `Retry-After` clamp. */
|
|
39
|
+
maxBackoffMs?: number
|
|
40
|
+
isDebug?: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface V1CaptureSenderHooks {
|
|
44
|
+
fetch: FetchLike
|
|
45
|
+
/** Surfaces partial/terminal delivery failures on the client error channel. */
|
|
46
|
+
onError: (error: Error) => void
|
|
47
|
+
now?: () => number
|
|
48
|
+
sleep?: (ms: number) => Promise<void>
|
|
49
|
+
generateRequestId?: () => string
|
|
50
|
+
compress?: (payload: string, isDebug?: boolean) => Promise<Blob | null>
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Sends already-normalized events to the Capture V1 endpoint
|
|
55
|
+
* (`POST /i/v1/analytics/events`), owning the full attempt loop: per-event
|
|
56
|
+
* partial retry, exponential backoff clamped against `Retry-After`, v1 status
|
|
57
|
+
* classification, and surfacing drops / undelivered events on the error
|
|
58
|
+
* channel. Used by both the batched and immediate send paths.
|
|
59
|
+
*
|
|
60
|
+
* Never throws for a handled outcome: after exhausting its own attempt budget it
|
|
61
|
+
* reports the failure via `onError` and resolves, so the caller's queue treats
|
|
62
|
+
* the batch as consumed (the internal budget replaces v0's queue-level retry).
|
|
63
|
+
*/
|
|
64
|
+
export class V1CaptureSender {
|
|
65
|
+
private readonly config: V1CaptureSenderConfig
|
|
66
|
+
private readonly maxBackoffMs: number
|
|
67
|
+
private readonly fetchFn: FetchLike
|
|
68
|
+
private readonly onError: (error: Error) => void
|
|
69
|
+
private readonly now: () => number
|
|
70
|
+
private readonly sleep: (ms: number) => Promise<void>
|
|
71
|
+
private readonly generateRequestId: () => string
|
|
72
|
+
private readonly compress: (payload: string, isDebug?: boolean) => Promise<Blob | null>
|
|
73
|
+
|
|
74
|
+
constructor(config: V1CaptureSenderConfig, hooks: V1CaptureSenderHooks) {
|
|
75
|
+
this.config = config
|
|
76
|
+
this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS
|
|
77
|
+
this.fetchFn = hooks.fetch
|
|
78
|
+
this.onError = hooks.onError
|
|
79
|
+
this.now = hooks.now ?? Date.now
|
|
80
|
+
this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)))
|
|
81
|
+
this.generateRequestId = hooks.generateRequestId ?? uuidv7
|
|
82
|
+
this.compress = hooks.compress ?? gzipCompress
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async sendV1Batch(messages: PostHogEventProperties[]): Promise<void> {
|
|
86
|
+
if (messages.length === 0) {
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const requestId = this.generateRequestId()
|
|
91
|
+
// created_at is generated once and stays stable across every retry.
|
|
92
|
+
const createdAt = new Date(this.now()).toISOString()
|
|
93
|
+
const { batch } = buildV1Batch(messages, {
|
|
94
|
+
createdAt,
|
|
95
|
+
historicalMigration: this.config.historicalMigration,
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
const url = `${this.config.host}${V1_ANALYTICS_PATH}`
|
|
99
|
+
const drops: V1DroppedEvent[] = []
|
|
100
|
+
let pending = batch
|
|
101
|
+
|
|
102
|
+
// Guard against a misconfigured budget (e.g. fetchRetryCount: -1): always make
|
|
103
|
+
// at least one attempt so a bad config surfaces a delivery error instead of
|
|
104
|
+
// silently dropping the batch without ever sending or calling onError.
|
|
105
|
+
const maxAttempts = Math.max(1, this.config.maxAttempts)
|
|
106
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
107
|
+
const isLastAttempt = attempt === maxAttempts
|
|
108
|
+
const payload = safeJsonStringify({
|
|
109
|
+
created_at: createdAt,
|
|
110
|
+
...(this.config.historicalMigration ? { historical_migration: true } : {}),
|
|
111
|
+
batch: pending,
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
let response: PostHogFetchResponse
|
|
115
|
+
try {
|
|
116
|
+
response = await this.sendOnce(url, payload, attempt, requestId)
|
|
117
|
+
} catch (transportError) {
|
|
118
|
+
// Connection/timeout with no HTTP response: retry until the budget runs out.
|
|
119
|
+
if (isLastAttempt) {
|
|
120
|
+
return this.surfaceBatchFailure(requestId, drops, pending, transportError)
|
|
121
|
+
}
|
|
122
|
+
await this.sleep(this.backoffDelay(attempt))
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const { status } = response
|
|
127
|
+
if (status < 200 || status >= 300) {
|
|
128
|
+
if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
|
|
129
|
+
const retryAfterMs = this.parseRetryAfter(response)
|
|
130
|
+
await this.cancelBody(response)
|
|
131
|
+
await this.sleep(this.backoffDelay(attempt, retryAfterMs))
|
|
132
|
+
continue
|
|
133
|
+
}
|
|
134
|
+
const httpError = await this.buildHttpError(response, status)
|
|
135
|
+
return this.surfaceBatchFailure(requestId, drops, pending, httpError)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let parsed: V1BatchResponse
|
|
139
|
+
try {
|
|
140
|
+
parsed = await this.parseResponse(response)
|
|
141
|
+
} catch {
|
|
142
|
+
// A 2xx we cannot parse is terminal — re-sending against a broken success would loop forever.
|
|
143
|
+
return this.surfaceBatchFailure(
|
|
144
|
+
requestId,
|
|
145
|
+
drops,
|
|
146
|
+
pending,
|
|
147
|
+
new Error(`Capture V1 returned an unparseable ${status} response body`)
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const retryable = this.classify(pending, parsed, drops)
|
|
152
|
+
if (retryable.length === 0) {
|
|
153
|
+
return this.surfacePartialDrops(requestId, drops)
|
|
154
|
+
}
|
|
155
|
+
if (isLastAttempt) {
|
|
156
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: retryable.map((event) => event.uuid) }))
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
pending = retryable
|
|
160
|
+
// A 200 partial-retry body can also carry Retry-After (e.g. rate-limited
|
|
161
|
+
// retry events); honor it as a minimum the same way as on a retryable status.
|
|
162
|
+
const retryAfterMs = this.parseRetryAfter(response)
|
|
163
|
+
await this.sleep(this.backoffDelay(attempt, retryAfterMs))
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private async sendOnce(
|
|
168
|
+
url: string,
|
|
169
|
+
payload: string,
|
|
170
|
+
attempt: number,
|
|
171
|
+
requestId: string
|
|
172
|
+
): Promise<PostHogFetchResponse> {
|
|
173
|
+
const headers = this.buildHeaders(attempt, requestId)
|
|
174
|
+
let body: string | Blob = payload
|
|
175
|
+
if (this.config.compressionEnabled) {
|
|
176
|
+
const compressed = await this.compress(payload, this.config.isDebug)
|
|
177
|
+
if (compressed !== null) {
|
|
178
|
+
body = compressed
|
|
179
|
+
headers['Content-Encoding'] = 'gzip'
|
|
180
|
+
}
|
|
181
|
+
// A codec that fails to compress falls back to sending uncompressed.
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const controller = new AbortController()
|
|
185
|
+
const timer = safeSetTimeout(() => controller.abort(), this.config.requestTimeoutMs)
|
|
186
|
+
try {
|
|
187
|
+
return await this.fetchFn(url, { method: 'POST', headers, body, signal: controller.signal })
|
|
188
|
+
} finally {
|
|
189
|
+
clearTimeout(timer)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private buildHeaders(attempt: number, requestId: string): PostHogFetchOptions['headers'] {
|
|
194
|
+
const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`
|
|
195
|
+
const headers: { [key: string]: string } = {
|
|
196
|
+
'Content-Type': 'application/json',
|
|
197
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
198
|
+
'PostHog-Sdk-Info': sdkInfo,
|
|
199
|
+
'PostHog-Attempt': String(attempt),
|
|
200
|
+
'PostHog-Request-Id': requestId,
|
|
201
|
+
// Regenerated per attempt — a per-attempt wall-clock stamp, unlike Request-Id / created_at.
|
|
202
|
+
'PostHog-Request-Timestamp': new Date(this.now()).toISOString(),
|
|
203
|
+
}
|
|
204
|
+
if (this.config.userAgent) {
|
|
205
|
+
headers['User-Agent'] = this.config.userAgent
|
|
206
|
+
}
|
|
207
|
+
return headers
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Partition the pending events against a 2xx result map: `drop` accumulates as
|
|
212
|
+
* a terminal failure, `retry` is returned for the next attempt, and
|
|
213
|
+
* `ok`/`warning`/unknown/absent are terminal successes.
|
|
214
|
+
*/
|
|
215
|
+
private classify(pending: V1Event[], parsed: V1BatchResponse, drops: V1DroppedEvent[]): V1Event[] {
|
|
216
|
+
const results = parsed.results ?? {}
|
|
217
|
+
const retryable: V1Event[] = []
|
|
218
|
+
for (const event of pending) {
|
|
219
|
+
const result = results[event.uuid]
|
|
220
|
+
if (!result) {
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
if (result.result === 'drop') {
|
|
224
|
+
drops.push({ uuid: event.uuid, details: result.details ?? undefined })
|
|
225
|
+
} else if (result.result === 'retry') {
|
|
226
|
+
retryable.push(event)
|
|
227
|
+
}
|
|
228
|
+
// ok / warning / unknown codes are terminal successes.
|
|
229
|
+
}
|
|
230
|
+
return retryable
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private backoffDelay(attempt: number, retryAfterMs?: number): number {
|
|
234
|
+
const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs)
|
|
235
|
+
if (retryAfterMs === undefined) {
|
|
236
|
+
return exponential
|
|
237
|
+
}
|
|
238
|
+
// Retry-After is a minimum (never lets us retry earlier than our own backoff) and is clamped to the ceiling.
|
|
239
|
+
return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Parse `Retry-After` (delta-seconds or HTTP-date). Non-positive/past values are ignored. */
|
|
243
|
+
private parseRetryAfter(response: PostHogFetchResponse): number | undefined {
|
|
244
|
+
const raw = response.headers?.get('Retry-After')
|
|
245
|
+
if (!raw) {
|
|
246
|
+
return undefined
|
|
247
|
+
}
|
|
248
|
+
const trimmed = raw.trim()
|
|
249
|
+
if (/^\d+$/.test(trimmed)) {
|
|
250
|
+
const seconds = parseInt(trimmed, 10)
|
|
251
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined
|
|
252
|
+
}
|
|
253
|
+
const dateMs = Date.parse(trimmed)
|
|
254
|
+
if (Number.isNaN(dateMs)) {
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
const delta = dateMs - this.now()
|
|
258
|
+
return delta > 0 ? delta : undefined
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private async parseResponse(response: PostHogFetchResponse): Promise<V1BatchResponse> {
|
|
262
|
+
const text = await response.text()
|
|
263
|
+
const parsed = JSON.parse(text)
|
|
264
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
265
|
+
throw new Error('unexpected response shape')
|
|
266
|
+
}
|
|
267
|
+
const results = (parsed as { results?: unknown }).results
|
|
268
|
+
if (results !== undefined && (typeof results !== 'object' || results === null || Array.isArray(results))) {
|
|
269
|
+
throw new Error('unexpected results shape')
|
|
270
|
+
}
|
|
271
|
+
return { results: (results as V1BatchResponse['results']) ?? {} }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async buildHttpError(response: PostHogFetchResponse, status: number): Promise<Error> {
|
|
275
|
+
let bodyText = ''
|
|
276
|
+
try {
|
|
277
|
+
bodyText = (await response.text()).slice(0, 512)
|
|
278
|
+
} catch {
|
|
279
|
+
// best-effort; a missing body should not mask the status
|
|
280
|
+
}
|
|
281
|
+
const suffix = bodyText ? `: ${bodyText}` : ''
|
|
282
|
+
return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private surfaceBatchFailure(requestId: string, drops: V1DroppedEvent[], pending: V1Event[], cause: unknown): void {
|
|
286
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: pending.map((event) => event.uuid), cause }))
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private surfacePartialDrops(requestId: string, drops: V1DroppedEvent[]): void {
|
|
290
|
+
if (drops.length > 0) {
|
|
291
|
+
this.onError(new CaptureV1Error({ requestId, drops, retryExhausted: [] }))
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private async cancelBody(response: PostHogFetchResponse): Promise<void> {
|
|
296
|
+
await response.body?.cancel()?.catch(() => {})
|
|
297
|
+
}
|
|
298
|
+
}
|
|
@@ -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>
|
|
@@ -158,12 +165,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
158
165
|
*
|
|
159
166
|
* @example
|
|
160
167
|
* ```ts
|
|
161
|
-
* // With
|
|
168
|
+
* // With a secret key (Personal API Key or Project Secret API Key) for local evaluation
|
|
162
169
|
* const client = new PostHogBackendClient(
|
|
163
170
|
* 'your-api-key',
|
|
164
171
|
* {
|
|
165
172
|
* host: 'https://app.posthog.com',
|
|
166
|
-
*
|
|
173
|
+
* secretKey: 'your-secret-key'
|
|
167
174
|
* }
|
|
168
175
|
* )
|
|
169
176
|
* ```
|
|
@@ -178,12 +185,13 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
|
|
|
178
185
|
const normalizedOptions = {
|
|
179
186
|
...options,
|
|
180
187
|
host: normalizeHost(options.host),
|
|
181
|
-
personalApiKey: normalizePersonalApiKey(options.personalApiKey),
|
|
188
|
+
personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey),
|
|
182
189
|
}
|
|
183
190
|
|
|
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
|
*
|
|
@@ -884,7 +884,7 @@ class FeatureFlagsPoller {
|
|
|
884
884
|
// Invalid API key
|
|
885
885
|
this.beginBackoff()
|
|
886
886
|
throw new ClientError(
|
|
887
|
-
`Your project key or
|
|
887
|
+
`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`
|
|
888
888
|
)
|
|
889
889
|
|
|
890
890
|
case 402:
|
|
@@ -902,7 +902,7 @@ class FeatureFlagsPoller {
|
|
|
902
902
|
// Permissions issue
|
|
903
903
|
this.beginBackoff()
|
|
904
904
|
throw new ClientError(
|
|
905
|
-
`Your
|
|
905
|
+
`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`
|
|
906
906
|
)
|
|
907
907
|
|
|
908
908
|
case 429:
|