posthog-node 5.60.1 → 5.61.1

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 (43) hide show
  1. package/dist/client.d.ts +34 -0
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +33 -4
  4. package/dist/client.mjs +33 -4
  5. package/dist/emails/emails.d.ts +45 -0
  6. package/dist/emails/emails.d.ts.map +1 -0
  7. package/dist/emails/emails.js +360 -0
  8. package/dist/emails/emails.mjs +316 -0
  9. package/dist/emails/errors.d.ts +37 -0
  10. package/dist/emails/errors.d.ts.map +1 -0
  11. package/dist/emails/errors.js +79 -0
  12. package/dist/emails/errors.mjs +41 -0
  13. package/dist/emails/types.d.ts +112 -0
  14. package/dist/emails/types.d.ts.map +1 -0
  15. package/dist/emails/types.js +18 -0
  16. package/dist/emails/types.mjs +1 -0
  17. package/dist/exports.d.ts +3 -0
  18. package/dist/exports.d.ts.map +1 -1
  19. package/dist/exports.js +19 -9
  20. package/dist/exports.mjs +1 -0
  21. package/dist/extensions/error-tracking/autocapture.d.ts +32 -2
  22. package/dist/extensions/error-tracking/autocapture.d.ts.map +1 -1
  23. package/dist/extensions/error-tracking/autocapture.js +337 -35
  24. package/dist/extensions/error-tracking/autocapture.mjs +324 -28
  25. package/dist/extensions/error-tracking/index.d.ts +16 -1
  26. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  27. package/dist/extensions/error-tracking/index.js +23 -8
  28. package/dist/extensions/error-tracking/index.mjs +24 -9
  29. package/dist/types.d.ts +33 -2
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/dist/version.mjs +1 -1
  34. package/package.json +2 -2
  35. package/src/client.ts +76 -3
  36. package/src/emails/emails.ts +459 -0
  37. package/src/emails/errors.ts +90 -0
  38. package/src/emails/types.ts +108 -0
  39. package/src/exports.ts +12 -0
  40. package/src/extensions/error-tracking/autocapture.ts +579 -57
  41. package/src/extensions/error-tracking/index.ts +48 -10
  42. package/src/types.ts +34 -2
  43. package/src/version.ts +1 -1
package/dist/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
- const version = "5.60.1";
1
+ const version = "5.61.1";
2
2
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-node",
3
- "version": "5.60.1",
3
+ "version": "5.61.1",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -29,7 +29,7 @@
29
29
  "module": "dist/entrypoints/index.node.mjs",
30
30
  "types": "dist/entrypoints/index.node.d.ts",
31
31
  "dependencies": {
32
- "@posthog/core": "^1.61.2"
32
+ "@posthog/core": "^1.62.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@edge-runtime/vm": "^5.0.0",
package/src/client.ts CHANGED
@@ -79,6 +79,8 @@ import { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from './capture-v1/routi
79
79
  import { V1CaptureSender } from './capture-v1/sender'
80
80
  import { eventByteSize, partitionAiBatch } from './ai-capture/batching'
81
81
  import { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from './ai-capture/routing'
82
+ import { DEFAULT_EMAIL_REQUEST_MAX_RETRIES, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS, EmailSender } from './emails/emails'
83
+ import type { Emails } from './emails/types'
82
84
 
83
85
  // Standard local evaluation rate limit is 600 per minute (10 per second),
84
86
  // so the fastest a poller should ever be set is 100ms.
@@ -123,6 +125,14 @@ function normalizeHost(value?: unknown): string {
123
125
  return normalizedValue || DEFAULT_NODE_HOST
124
126
  }
125
127
 
128
+ function positiveNumberOr(value: unknown, fallback: number): number {
129
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
130
+ }
131
+
132
+ function nonNegativeIntegerOr(value: unknown, fallback: number): number {
133
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback
134
+ }
135
+
126
136
  function normalizeUnsetPersonProperties(value: string | string[]): string[] {
127
137
  const propertyNames = Array.isArray(value) ? value : [value]
128
138
  return propertyNames.filter(
@@ -166,6 +176,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
166
176
 
167
177
  private readonly captureMode: CaptureMode
168
178
  private _v1Sender?: V1CaptureSender
179
+ private _emails?: EmailSender
180
+ private _isShutdown = false
169
181
  /** Whether this client captures full AI content: see `enableFullAiCapture` in `PostHogOptions`. */
170
182
  public readonly enableFullAiCapture: boolean
171
183
  /** Whether PostHog AI integrations redact content: see `privacyMode` in `PostHogOptions`. */
@@ -350,6 +362,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
350
362
  }
351
363
 
352
364
  override async flush(): Promise<void> {
365
+ // An app's crash handler often flushes and exits before the end of the turn, when autocapture would capture.
366
+ this.errorTracking.capturePendingExceptions()
353
367
  return this._flushKeepingRuntimeAlive(false)
354
368
  }
355
369
 
@@ -673,6 +687,58 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
673
687
  return this._metrics
674
688
  }
675
689
 
690
+ /**
691
+ * The `posthog.emails` API: sends transactional email from PostHog email templates, and reads
692
+ * the status of each email it sent.
693
+ *
694
+ * Needs `secretKey`, a project secret API key with the `hog_flow:write` scope. A key with only
695
+ * `hog_flow:read` can read statuses but not send. Requests go to `appHost`, or to the PostHog
696
+ * Cloud app host of `host`. `send` and `get` resolve to `{ data, error }` and do not reject.
697
+ * `data.id` is the queued email's message ID, which `get` takes. A disabled client sends nothing
698
+ * and returns the error `client_disabled`. After `shutdown()`, the client sends nothing and
699
+ * returns the error `client_closed`.
700
+ *
701
+ * @example
702
+ * ```ts
703
+ * const client = new PostHog('phc_...', { secretKey: 'phs_...', host: 'https://eu.i.posthog.com' })
704
+ * const { data, error } = await client.emails.send({
705
+ * to: 'user@example.com',
706
+ * templateId: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b',
707
+ * templateData: { name: 'Ada' },
708
+ * distinctId: 'user_123',
709
+ * idempotencyKey: 'welcome:user_123',
710
+ * })
711
+ * if (error) {
712
+ * console.error(error.code, error.message)
713
+ * }
714
+ *
715
+ * const status = await client.emails.get(data.id) // later, for example from a job
716
+ * ```
717
+ *
718
+ * {@label Emails}
719
+ */
720
+ public get emails(): Emails {
721
+ if (!this._emails) {
722
+ this._emails = new EmailSender(
723
+ {
724
+ secretKey: this.options.personalApiKey,
725
+ host: this.host,
726
+ appHost: this.options.appHost,
727
+ requestTimeoutMs: positiveNumberOr(this.options.emailRequestTimeoutMs, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS),
728
+ maxRetries: nonNegativeIntegerOr(this.options.emailRequestMaxRetries, DEFAULT_EMAIL_REQUEST_MAX_RETRIES),
729
+ },
730
+ {
731
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
732
+ isDisabled: () => this.disabled,
733
+ isClosed: () => this._isShutdown,
734
+ logger: this._logger,
735
+ userAgent: this.getCustomUserAgent() || undefined,
736
+ }
737
+ )
738
+ }
739
+ return this._emails
740
+ }
741
+
676
742
  /**
677
743
  * Active-span tracking. Overridden by the Node entrypoint with an
678
744
  * `AsyncLocalStorage`-backed manager; the edge build keeps this synchronous
@@ -2936,6 +3002,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2936
3002
  // super._shutdown spend from the same budget, so shutdown(500) can't take
2937
3003
  // ~1000ms by giving each phase a fresh full timeout.
2938
3004
  const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000)
3005
+ this._isShutdown = true
3006
+ // Sends that started before shutdown keep running alongside the flushes below, within the same budget.
3007
+ const emailsDrained = this._emails?.drain()
2939
3008
  // Cancel any pending debounced flush — shutdown will flush directly.
2940
3009
  const resolve = this._consumeWaitUntilCycle()
2941
3010
 
@@ -2965,9 +3034,13 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2965
3034
  )
2966
3035
  this._traces.reset()
2967
3036
  }
3037
+ const remainingMs = Math.max(0, shutdownDeadlineMs - Date.now())
3038
+ // Wait for the email sends next to the core flush, not before it, so a slow send can't use up the budget for events.
3039
+ const emailsSettled = emailsDrained ? raceWithTimeout(emailsDrained, remainingMs) : undefined
2968
3040
  try {
2969
- return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()))
3041
+ return await super._shutdown(remainingMs)
2970
3042
  } finally {
3043
+ await emailsSettled
2971
3044
  this._distinctIdHasSentFlagCalls.clear()
2972
3045
  resolve?.()
2973
3046
  }
@@ -3195,7 +3268,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3195
3268
  uuid?: EventMessage['uuid'],
3196
3269
  flags?: FeatureFlagEvaluations
3197
3270
  ): void {
3198
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3271
+ if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3199
3272
  const syntheticException = new Error('PostHog syntheticException')
3200
3273
  this.addPendingPromise(
3201
3274
  ErrorTracking.buildEventMessage(
@@ -3252,7 +3325,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3252
3325
  additionalProperties?: Record<string | number, any>,
3253
3326
  flags?: FeatureFlagEvaluations
3254
3327
  ): Promise<void> {
3255
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3328
+ if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3256
3329
  const syntheticException = new Error('PostHog syntheticException')
3257
3330
  return this.addPendingPromise(
3258
3331
  ErrorTracking.buildEventMessage(
@@ -0,0 +1,459 @@
1
+ import {
2
+ type FetchLike,
3
+ type Logger,
4
+ type PostHogFetchResponse,
5
+ parseRetryAfterMs,
6
+ removeTrailingSlash,
7
+ safeJsonStringify,
8
+ } from '@posthog/core'
9
+
10
+ import { EmailError } from './errors'
11
+ import type {
12
+ EmailStatus,
13
+ EmailWarning,
14
+ Emails,
15
+ GetEmailResponse,
16
+ SendEmailOptions,
17
+ SendEmailResponse,
18
+ SendEmailResult,
19
+ } from './types'
20
+
21
+ const SEND_PATH = '/api/projects/@current/messaging/send/email/'
22
+ const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/'
23
+ const US_APP_HOST = 'https://us.posthog.com'
24
+ const EU_APP_HOST = 'https://eu.posthog.com'
25
+ const CLOUD_APP_HOSTS: Record<string, string> = {
26
+ 'https://us.i.posthog.com': US_APP_HOST,
27
+ 'https://us.posthog.com': US_APP_HOST,
28
+ 'https://app.posthog.com': US_APP_HOST,
29
+ 'https://eu.i.posthog.com': EU_APP_HOST,
30
+ 'https://eu.posthog.com': EU_APP_HOST,
31
+ }
32
+ const MAX_RETRY_DELAY_MS = 30_000
33
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
34
+ const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/
35
+
36
+ export const DEFAULT_EMAIL_REQUEST_TIMEOUT_MS = 15_000
37
+ export const DEFAULT_EMAIL_REQUEST_MAX_RETRIES = 2
38
+
39
+ export interface EmailSenderConfig {
40
+ secretKey?: string
41
+ /** The client's `host`. Used only when it is PostHog Cloud. */
42
+ host: string
43
+ appHost?: string
44
+ requestTimeoutMs: number
45
+ maxRetries: number
46
+ }
47
+
48
+ export interface EmailSenderHooks {
49
+ fetch: FetchLike
50
+ isDisabled: () => boolean
51
+ isClosed: () => boolean
52
+ logger: Logger
53
+ userAgent?: string
54
+ }
55
+
56
+ interface PreparedSend {
57
+ path: string
58
+ body: string
59
+ idempotencyKey: string
60
+ maxRetries: number
61
+ }
62
+
63
+ interface Reply {
64
+ status: number
65
+ payload: unknown
66
+ retryAfterMs?: number
67
+ }
68
+
69
+ /**
70
+ * Sends one transactional email per call to the messaging send API on the app host, and reads
71
+ * the status of a sent email. Owns the attempt loop, so every attempt of a send carries the same
72
+ * idempotency key.
73
+ */
74
+ export class EmailSender implements Emails {
75
+ private readonly config: EmailSenderConfig
76
+ private readonly hooks: EmailSenderHooks
77
+ private readonly inFlight = new Set<Promise<unknown>>()
78
+
79
+ constructor(config: EmailSenderConfig, hooks: EmailSenderHooks) {
80
+ this.config = config
81
+ this.hooks = hooks
82
+ }
83
+
84
+ send(options: SendEmailOptions): Promise<SendEmailResponse> {
85
+ return this.track(this.sendUntracked(options))
86
+ }
87
+
88
+ get(id: string): Promise<GetEmailResponse> {
89
+ return this.track(this.getUntracked(id))
90
+ }
91
+
92
+ private track<T>(pending: Promise<T>): Promise<T> {
93
+ this.inFlight.add(pending)
94
+ void pending.finally(() => this.inFlight.delete(pending))
95
+ return pending
96
+ }
97
+
98
+ /**
99
+ * Resolves when every send and status read in flight, retries included, has settled.
100
+ * Kept apart from the client's pending-promise queue, so a send in its retry backoff does not hold back `flush()`.
101
+ */
102
+ async drain(): Promise<void> {
103
+ while (this.inFlight.size > 0) {
104
+ await Promise.all(this.inFlight)
105
+ }
106
+ }
107
+
108
+ private async sendUntracked(options: SendEmailOptions): Promise<SendEmailResponse> {
109
+ try {
110
+ const prepared = prepareSend(options, this.config.maxRetries)
111
+ const { appHost, secretKey } = this.connect(
112
+ 'no email was sent',
113
+ 'Sending email needs secretKey, a project secret API key with the hog_flow:write scope.'
114
+ )
115
+ const headers = this.headers(secretKey, {
116
+ 'Content-Type': 'application/json',
117
+ 'Idempotency-Key': prepared.idempotencyKey,
118
+ })
119
+ const result = await this.withRetries(prepared.maxRetries, async () =>
120
+ parseSendReply(await this.request(appHost + prepared.path, 'POST', headers, prepared.body))
121
+ )
122
+ for (const warning of result.warnings) {
123
+ this.hooks.logger.warn(`PostHog email warning ${warning.code}: ${warning.message}`)
124
+ }
125
+ return { data: result, error: null }
126
+ } catch (error) {
127
+ return { data: null, error: asEmailError(error, 'Sending the email failed unexpectedly.') }
128
+ }
129
+ }
130
+
131
+ private async getUntracked(id: string): Promise<GetEmailResponse> {
132
+ try {
133
+ if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {
134
+ throw invalid('invalid_message_id', 'id must be the message ID that send() returned.', 'id')
135
+ }
136
+ const { appHost, secretKey } = this.connect(
137
+ 'no email status was read',
138
+ 'Reading an email status needs secretKey, a project secret API key with the hog_flow:read or hog_flow:write scope.'
139
+ )
140
+ const url = appHost + STATUS_PATH.replace('{messageId}', id.toLowerCase())
141
+ const headers = this.headers(secretKey, {})
142
+ const status = await this.withRetries(this.config.maxRetries, async () =>
143
+ parseStatusReply(await this.request(url, 'GET', headers))
144
+ )
145
+ return { data: status, error: null }
146
+ } catch (error) {
147
+ return { data: null, error: asEmailError(error, 'Reading the email status failed unexpectedly.') }
148
+ }
149
+ }
150
+
151
+ private connect(nothingDone: string, missingSecretKey: string): { appHost: string; secretKey: string } {
152
+ if (this.hooks.isDisabled()) {
153
+ throw new EmailError({
154
+ code: 'client_disabled',
155
+ message: `The PostHog client is disabled, so ${nothingDone}.`,
156
+ })
157
+ }
158
+ if (this.hooks.isClosed()) {
159
+ throw new EmailError({
160
+ code: 'client_closed',
161
+ message: `The PostHog client is shut down, so ${nothingDone}.`,
162
+ })
163
+ }
164
+ const appHost = resolveAppHost(this.config.host, this.config.appHost)
165
+ if (!appHost) {
166
+ // A custom host is often an ingestion proxy, which must not receive the secret key.
167
+ throw new EmailError({
168
+ code: 'missing_app_host',
169
+ message:
170
+ "The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client.",
171
+ })
172
+ }
173
+ const secretKey = this.config.secretKey?.trim()
174
+ if (!secretKey) {
175
+ throw new EmailError({ code: 'missing_secret_key', message: missingSecretKey })
176
+ }
177
+ return { appHost, secretKey }
178
+ }
179
+
180
+ private headers(secretKey: string, extra: Record<string, string>): Record<string, string> {
181
+ const headers: Record<string, string> = {
182
+ Authorization: `Bearer ${secretKey}`,
183
+ Accept: 'application/json',
184
+ ...extra,
185
+ }
186
+ if (this.hooks.userAgent) {
187
+ headers['User-Agent'] = this.hooks.userAgent
188
+ }
189
+ return headers
190
+ }
191
+
192
+ private async withRetries<T>(maxRetries: number, attemptOnce: () => Promise<T>): Promise<T> {
193
+ for (let attempt = 0; ; attempt++) {
194
+ let error: EmailError
195
+ try {
196
+ return await attemptOnce()
197
+ } catch (caught) {
198
+ error =
199
+ caught instanceof EmailError
200
+ ? caught
201
+ : new EmailError({
202
+ code: 'network_error',
203
+ message: 'The request to PostHog failed.',
204
+ cause: caught,
205
+ })
206
+ }
207
+ const delayMs = retryDelayMs(error, attempt, maxRetries)
208
+ if (delayMs === undefined) {
209
+ throw error
210
+ }
211
+ // A plain timer, not an unref'd one: the caller awaits the request, so the process must stay up for the retry.
212
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
213
+ }
214
+ }
215
+
216
+ private async request(
217
+ url: string,
218
+ method: 'GET' | 'POST',
219
+ headers: Record<string, string>,
220
+ body?: string
221
+ ): Promise<Reply> {
222
+ const controller = new AbortController()
223
+ const timeoutMs = this.config.requestTimeoutMs
224
+ let timer: ReturnType<typeof setTimeout>
225
+ // `fetch` is injectable and may ignore the abort signal, so both phases race the deadline.
226
+ // A plain timer, not an unref'd one: an injected fetch may hold no handle, and the process must stay up until
227
+ // the deadline settles the send.
228
+ const deadline = new Promise<never>((_resolve, reject) => {
229
+ timer = setTimeout(() => {
230
+ const timeoutError = new Error(`Email request timed out after ${timeoutMs}ms`)
231
+ timeoutError.name = 'AbortError'
232
+ reject(timeoutError)
233
+ controller.abort(timeoutError)
234
+ }, timeoutMs)
235
+ })
236
+ const fetchPromise = Promise.resolve().then(() =>
237
+ this.hooks.fetch(url, {
238
+ method,
239
+ headers,
240
+ ...(body === undefined ? {} : { body }),
241
+ signal: controller.signal,
242
+ })
243
+ )
244
+ void fetchPromise
245
+ .then((lateResponse) => {
246
+ if (controller.signal.aborted) {
247
+ // Release a late response from an injected fetch that ignored the deadline, so it frees its connection.
248
+ void Promise.resolve(lateResponse.body?.cancel()).catch(() => {})
249
+ }
250
+ })
251
+ .catch(() => {})
252
+ let response: PostHogFetchResponse | undefined
253
+ try {
254
+ response = await Promise.race([fetchPromise, deadline])
255
+ let text: string
256
+ try {
257
+ text = await Promise.race([response.text(), deadline])
258
+ } catch (error) {
259
+ // An accepted send may already be queued, so a failed read stays a retryable network error.
260
+ if (response.status >= 200 && response.status < 300) {
261
+ throw error
262
+ }
263
+ // The status and Retry-After still decide the retry when an error body can't be read.
264
+ return { status: response.status, payload: null, retryAfterMs: readRetryAfter(response) }
265
+ }
266
+ return { status: response.status, payload: parseJson(text), retryAfterMs: readRetryAfter(response) }
267
+ } finally {
268
+ clearTimeout(timer!)
269
+ if (controller.signal.aborted && response) {
270
+ // Release a body whose read passed the deadline. Do not await: an injected cancel may never settle.
271
+ void Promise.resolve(response.body?.cancel()).catch(() => {})
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): PreparedSend {
278
+ const fallback: Partial<SendEmailOptions> = {}
279
+ const { to, templateId, templateData, distinctId, idempotencyKey, maxRetries } = options ?? fallback
280
+ if (typeof to !== 'string' || !to.trim()) {
281
+ throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to')
282
+ }
283
+ if (typeof templateId !== 'string' || !UUID_PATTERN.test(templateId)) {
284
+ throw invalid('invalid_template_id', "templateId must be the template's UUID.", 'templateId')
285
+ }
286
+ if (
287
+ templateData !== undefined &&
288
+ (typeof templateData !== 'object' || templateData === null || Array.isArray(templateData))
289
+ ) {
290
+ throw invalid('invalid_template_data', 'templateData must be an object.', 'templateData')
291
+ }
292
+ if (distinctId !== undefined && (typeof distinctId !== 'string' || !distinctId)) {
293
+ throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId')
294
+ }
295
+ if (
296
+ idempotencyKey !== undefined &&
297
+ (typeof idempotencyKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))
298
+ ) {
299
+ throw invalid(
300
+ 'invalid_idempotency_key',
301
+ 'idempotencyKey must be 1 to 255 visible ASCII characters without spaces.',
302
+ 'idempotencyKey'
303
+ )
304
+ }
305
+ if (maxRetries !== undefined && !(Number.isInteger(maxRetries) && maxRetries >= 0)) {
306
+ throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries')
307
+ }
308
+
309
+ const payload: Record<string, unknown> = {
310
+ template: { id: templateId.toLowerCase() },
311
+ to,
312
+ message_data: templateData ?? {},
313
+ }
314
+ if (distinctId !== undefined) {
315
+ payload.identifiers = { distinct_id: distinctId }
316
+ }
317
+ return {
318
+ path: SEND_PATH,
319
+ body: safeJsonStringify(payload),
320
+ idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
321
+ maxRetries: maxRetries ?? defaultMaxRetries,
322
+ }
323
+ }
324
+
325
+ function invalid(code: string, message: string, field: string): EmailError {
326
+ return new EmailError({ code, message, field })
327
+ }
328
+
329
+ /**
330
+ * The app host for a send, or undefined when the client can't tell it.
331
+ * PostHog Cloud ingestion hosts don't serve the app API, so they map to their region's app host.
332
+ */
333
+ function resolveAppHost(host: string, appHost: string | undefined): string | undefined {
334
+ const explicit = typeof appHost === 'string' ? removeTrailingSlash(appHost.trim()) : ''
335
+ if (explicit) {
336
+ return CLOUD_APP_HOSTS[explicit] ?? explicit
337
+ }
338
+ return CLOUD_APP_HOSTS[removeTrailingSlash(host)]
339
+ }
340
+
341
+ function parseJson(text: string): unknown {
342
+ try {
343
+ return JSON.parse(text)
344
+ } catch {
345
+ return null
346
+ }
347
+ }
348
+
349
+ function readRetryAfter(response: PostHogFetchResponse): number | undefined {
350
+ try {
351
+ // The full wait, not the shared five minute cap: callers schedule their own retry from it, and the retry ceiling
352
+ // here applies separately in retryDelayMs.
353
+ return parseRetryAfterMs(response.headers?.get('retry-after'), Date.now(), Number.MAX_SAFE_INTEGER)
354
+ } catch {
355
+ return undefined
356
+ }
357
+ }
358
+
359
+ function text(value: unknown): string | undefined {
360
+ return typeof value === 'string' && value ? value : undefined
361
+ }
362
+
363
+ function replyFields(payload: unknown): Record<string, unknown> {
364
+ return (payload !== null && typeof payload === 'object' && !Array.isArray(payload) ? payload : {}) as Record<
365
+ string,
366
+ unknown
367
+ >
368
+ }
369
+
370
+ function parseSendReply({ status, payload, retryAfterMs }: Reply): SendEmailResult {
371
+ const fields = replyFields(payload)
372
+ if (status >= 200 && status < 300) {
373
+ const id = text(fields.message_id)
374
+ if (!id) {
375
+ throw new EmailError({
376
+ code: 'api_error',
377
+ message: 'PostHog answered without a message ID.',
378
+ statusCode: status,
379
+ })
380
+ }
381
+ const warnings: EmailWarning[] = []
382
+ if (Array.isArray(fields.warnings)) {
383
+ for (const warning of fields.warnings) {
384
+ if (warning !== null && typeof warning === 'object') {
385
+ warnings.push({
386
+ code: text(warning.code) ?? 'warning',
387
+ message: text(warning.detail) ?? text(warning.message) ?? '',
388
+ fix: text(warning.fix),
389
+ })
390
+ }
391
+ }
392
+ }
393
+ return { id, replayed: fields.replayed === true, warnings }
394
+ }
395
+ throw replyError(fields, status, retryAfterMs)
396
+ }
397
+
398
+ function parseStatusReply({ status, payload, retryAfterMs }: Reply): EmailStatus {
399
+ const fields = replyFields(payload)
400
+ if (status < 200 || status >= 300) {
401
+ throw replyError(fields, status, retryAfterMs)
402
+ }
403
+ const id = text(fields.id)
404
+ const deliveryStatus = text(fields.status)
405
+ const createdAt = text(fields.created_at)
406
+ const statusAt = text(fields.status_at)
407
+ if (!id || !deliveryStatus || !createdAt || !statusAt) {
408
+ throw new EmailError({
409
+ code: 'api_error',
410
+ message: 'PostHog answered without an email status.',
411
+ statusCode: status,
412
+ })
413
+ }
414
+ return { id, status: deliveryStatus, createdAt, statusAt, reason: text(fields.reason) ?? null }
415
+ }
416
+
417
+ function replyError(fields: Record<string, unknown>, status: number, retryAfterMs: number | undefined): EmailError {
418
+ return new EmailError({
419
+ code: text(fields.code) ?? 'api_error',
420
+ message: text(fields.detail) ?? `PostHog answered HTTP ${status}.`,
421
+ statusCode: status,
422
+ why: text(fields.why),
423
+ fix: text(fields.fix),
424
+ docsUrl: text(fields.docs_url),
425
+ field: text(fields.attr),
426
+ retryAfterMs,
427
+ })
428
+ }
429
+
430
+ function asEmailError(error: unknown, message: string): EmailError {
431
+ return error instanceof EmailError ? error : new EmailError({ code: 'unexpected_error', message, cause: error })
432
+ }
433
+
434
+ function isRetryable(error: EmailError): boolean {
435
+ // A send carries an idempotency key, so a retry can't queue a second email. A status read changes nothing.
436
+ if (error.statusCode === undefined) {
437
+ return error.code === 'network_error'
438
+ }
439
+ if (error.statusCode === 409) {
440
+ return error.code === 'idempotency_key_in_flight'
441
+ }
442
+ if (error.statusCode === 429) {
443
+ // Waiting doesn't fix a monthly quota.
444
+ return error.code !== 'quota_limited'
445
+ }
446
+ return error.statusCode === 503
447
+ }
448
+
449
+ function retryDelayMs(error: EmailError, attempt: number, maxRetries: number): number | undefined {
450
+ if (attempt >= maxRetries || !isRetryable(error)) {
451
+ return undefined
452
+ }
453
+ // Retrying before a longer Retry-After would break the server's rate limit.
454
+ if (error.retryAfterMs !== undefined && error.retryAfterMs > MAX_RETRY_DELAY_MS) {
455
+ return undefined
456
+ }
457
+ const backoffMs = Math.min(MAX_RETRY_DELAY_MS, 1000 * 2 ** attempt * (0.8 + Math.random() * 0.4))
458
+ return Math.max(backoffMs, error.retryAfterMs ?? 0)
459
+ }