diff --git a/.changeset/node-emails-get.md b/.changeset/node-emails-get.md new file mode 100644 index 0000000000..191f58348b --- /dev/null +++ b/.changeset/node-emails-get.md @@ -0,0 +1,5 @@ +--- +'posthog-node': minor +--- + +Add `posthog.emails.get(id)` to read the latest status of an email that `posthog.emails.send()` queued. diff --git a/packages/node/references/posthog-node-references-latest.json b/packages/node/references/posthog-node-references-latest.json index 825c1e0e0d..fb2e2123f3 100644 --- a/packages/node/references/posthog-node-references-latest.json +++ b/packages/node/references/posthog-node-references-latest.json @@ -2206,7 +2206,7 @@ "name": "EmailError", "properties": [ { - "description": "PostHog's error code, such as `invalid_recipient`, or one of the SDK's own: `missing_secret_key`, `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error` for an answer without a code, `unexpected_error`, and `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` and `invalid_idempotency_key` for a send the SDK refused before any request.", + "description": "PostHog's error code, such as `invalid_recipient`, or one of the SDK's own: `missing_secret_key`, `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error` for an answer without a code, `unexpected_error`, `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` and `invalid_idempotency_key` for a send the SDK refused before any request, and `invalid_message_id` for a read.", "type": "string", "name": "code" }, @@ -2260,6 +2260,44 @@ "properties": [], "path": "src/emails.ts" }, + { + "id": "EmailStatus", + "name": "EmailStatus", + "properties": [], + "path": "src/emails.ts", + "example": "\"queued\" | \"waiting\" | \"unknown\" | \"skipped\" | \"failed\" | \"sent\" | \"delivered\" | \"bounced\" | \"complained\"" + }, + { + "id": "EmailStatusRecord", + "name": "EmailStatusRecord", + "properties": [ + { + "description": "When PostHog queued the email, as an ISO 8601 timestamp.", + "type": "string", + "name": "createdAt" + }, + { + "description": "The `id` that `posthog.emails.send()` returned.", + "type": "string", + "name": "id" + }, + { + "description": "Why the email was skipped, failed or bounced, when PostHog knows.", + "type": "string", + "name": "reason" + }, + { + "type": "EmailStatus", + "name": "status" + }, + { + "description": "When the email reached its status, as an ISO 8601 timestamp.", + "type": "string", + "name": "statusAt" + } + ], + "path": "src/emails.ts" + }, { "id": "EmailTag", "name": "EmailTag", @@ -2789,6 +2827,13 @@ "path": "src/types.ts", "example": "string | number | (string | number)[] | boolean" }, + { + "id": "GetEmailResult", + "name": "GetEmailResult", + "properties": [], + "path": "src/emails.ts", + "example": "{\n data: EmailStatusRecord;\n error: null;\n} | {\n data: null;\n error: EmailError;\n}" + }, { "id": "GetFlagsResult", "name": "GetFlagsResult", diff --git a/packages/node/src/__tests__/emails.spec.ts b/packages/node/src/__tests__/emails.spec.ts index 96f1790506..8d08b26711 100644 --- a/packages/node/src/__tests__/emails.spec.ts +++ b/packages/node/src/__tests__/emails.spec.ts @@ -380,6 +380,114 @@ describe('emails', () => { }) }) + describe('get', () => { + const MESSAGE_ID = '0192a7c4-5e2f-7d1a-8b3c-4d5e6f708192' + const STATUS = `GET /api/projects/@current/messaging/emails/${MESSAGE_ID}/` + + it('reads the status of an email from the app host with the secret key', async () => { + api.recordStatus({ + id: MESSAGE_ID, + status: 'bounced', + created_at: '2026-10-22T08:00:00Z', + status_at: '2026-10-22T08:00:05Z', + reason: 'mailbox_full', + }) + + const result = await createClient({ migratedFrom: 'resend' }).emails.get(MESSAGE_ID) + + expect(result).toEqual({ + data: { + id: MESSAGE_ID, + status: 'bounced', + createdAt: '2026-10-22T08:00:00Z', + statusAt: '2026-10-22T08:00:05Z', + reason: 'mailbox_full', + }, + error: null, + }) + expect(requestLog()).toEqual([STATUS]) + expect(api.received[0]).toEqual( + expect.objectContaining({ + origin: APP_HOST, + headers: expect.objectContaining({ + authorization: `Bearer ${SECRET_KEY}`, + 'user-agent': 'posthog-node/1.2.3', + 'x-posthog-migrated-from': 'resend', + }), + }) + ) + }) + + it('leaves out a reason PostHog did not give', async () => { + api.recordStatus({ id: MESSAGE_ID, status: 'sent', created_at: 'a', status_at: 'b' }) + + const result = await createClient().emails.get(MESSAGE_ID) + + expect(result.data).toEqual({ id: MESSAGE_ID, status: 'sent', createdAt: 'a', statusAt: 'b' }) + }) + + it.each([ + ['an unknown or new email', undefined, 'not_found'], + [ + 'an unavailable pipeline', + { status: 503, body: refusalBody('delivery_unavailable', null) }, + 'delivery_unavailable', + ], + ['a throttled read', { status: 429, body: refusalBody('throttled', null) }, 'throttled'], + ['a network failure', { networkError: new Error('ECONNRESET') }, 'network_error'], + ['an answer without a status', { status: 200, body: { id: MESSAGE_ID } }, 'api_error'], + ] satisfies [string, Fault | undefined, string][])( + 'returns %s as the error, without a retry', + async (_, fault, code) => { + if (fault) { + api.failNext(fault, Infinity) + } + + const result = await createClient().emails.get(MESSAGE_ID) + + expect(result).toEqual({ data: null, error: expect.objectContaining({ code }) }) + expect(api.received).toHaveLength(1) + } + ) + + it.each([ + ['missing_secret_key', 'missing_api_key', { secretKey: undefined }, MESSAGE_ID, 'hog_flow:read'], + ['missing_app_host', 'application_error', { appHost: undefined }, MESSAGE_ID, 'appHost'], + ['client_disabled', 'application_error', { disabled: true }, MESSAGE_ID, 'disabled'], + ['invalid_message_id', 'validation_error', {}, '', 'id'], + ['invalid_message_id', 'validation_error', {}, 'message-\uD800', 'id'], + ['invalid_message_id', 'validation_error', {}, '.', 'id'], + ['invalid_message_id', 'validation_error', {}, '..', 'id'], + ])('returns %s as %s without a request', async (code, name, clientOptions: PostHogOptions, id, says) => { + const result = await createClient(clientOptions).emails.get(id) + + expect(result).toEqual({ + data: null, + error: expect.objectContaining({ name, code, message: expect.stringContaining(says) }), + }) + expect(api.received).toEqual([]) + }) + + it('returns client_closed as application_error after shutdown without a request', async () => { + const client = createClient() + await client.shutdown() + + const result = await client.emails.get(MESSAGE_ID) + + expect(result).toEqual({ + data: null, + error: expect.objectContaining({ name: 'application_error', code: 'client_closed' }), + }) + expect(api.received).toEqual([]) + }) + + it('reads an id with reserved characters as one path segment', async () => { + await createClient().emails.get('a/b?c') + + expect(requestLog()).toEqual(['GET /api/projects/@current/messaging/emails/a%2Fb%3Fc/']) + }) + }) + describe('errors', () => { it.each([ [400, 'invalid_recipient', 'validation_error'], diff --git a/packages/node/src/__tests__/utils/fake-emails-api.ts b/packages/node/src/__tests__/utils/fake-emails-api.ts index 14283c34f4..7b5509d5d3 100644 --- a/packages/node/src/__tests__/utils/fake-emails-api.ts +++ b/packages/node/src/__tests__/utils/fake-emails-api.ts @@ -3,6 +3,7 @@ import { emailContentHash } from '@/email-content-hash' const SEND_PATH = '/api/projects/@current/messaging/send/email/' const UPLOAD_PATH = /^\/api\/projects\/@current\/messaging_templates\/by_key\/([^/]+)\/$/ +const STATUS_PATH = /^\/api\/projects\/@current\/messaging\/emails\/([^/]+)\/$/ const DOCS_URL = 'https://posthog.com/docs/workflows/transactional-email-api' export interface ReceivedRequest { @@ -25,6 +26,14 @@ export interface DeliveredEmail { distinctId?: string } +export interface StatusRecord { + id: string + status: string + created_at: string + status_at: string + reason?: string +} + interface LocalTemplate { subject: string html: string @@ -47,7 +56,7 @@ interface ScheduledFault { /** * An in-memory PostHog app host that speaks the send and upload routes of the transactional email API: a template by * id, rendered content by `template_key`, and a local template by key and content hash, which answers - * `template_outdated` until an upload publishes that content. An idempotency key PostHog already accepted for the + * `template_outdated` until an upload publishes that content. It answers the status of an email it was told about. An idempotency key PostHog already accepted for the * same request answers the first `202` again. */ export class FakeEmailsApi { @@ -55,6 +64,7 @@ export class FakeEmailsApi { readonly delivered: DeliveredEmail[] = [] private readonly templateIds = new Set() private readonly localTemplates = new Map() + private readonly statuses = new Map() private readonly accepted = new Map() private readonly faults: ScheduledFault[] = [] private nextId = 1 @@ -85,6 +95,10 @@ export class FakeEmailsApi { this.localTemplates.set(key, { ...content, contentHash: 'v1:edited', editedInPostHog: true }) } + recordStatus(record: StatusRecord): void { + this.statuses.set(record.id, record) + } + localTemplate(key: string): LocalTemplate | undefined { return this.localTemplates.get(key) } @@ -119,6 +133,11 @@ export class FakeEmailsApi { if (request.method === 'POST' && request.path === SEND_PATH) { return this.handleSend(request) } + const messageId = STATUS_PATH.exec(request.path)?.[1] + if (request.method === 'GET' && messageId) { + const record = this.statuses.get(decodeURIComponent(messageId)) + return record ? respond(200, record) : refusal(404, 'not_found', null) + } return refusal(404, 'not_found', null) } diff --git a/packages/node/src/client.ts b/packages/node/src/client.ts index f2427235e2..b95894992b 100644 --- a/packages/node/src/client.ts +++ b/packages/node/src/client.ts @@ -3067,10 +3067,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen /** One attempt: `posthog.emails` retries on its own, with the same idempotency key. */ private async _requestEmailsApi( - method: 'POST' | 'PUT', + method: 'GET' | 'POST' | 'PUT', url: string, headers: Record, - body: string + body: string | undefined ): Promise { try { return await this.requestJson(url, { method, headers, body }) diff --git a/packages/node/src/emails.ts b/packages/node/src/emails.ts index 46c5096f6b..ffac63ca22 100644 --- a/packages/node/src/emails.ts +++ b/packages/node/src/emails.ts @@ -3,6 +3,8 @@ import { emailContentHash } from './email-content-hash' const SEND_PATH = '/api/projects/@current/messaging/send/email/' const UPLOAD_PATH = (key: string): string => `/api/projects/@current/messaging_templates/by_key/${key}/` +const STATUS_PATH = (messageId: string): string => + `/api/projects/@current/messaging/emails/${encodeURIComponent(messageId)}/` interface SendForm { name: 'templateId' | 'templateKey' @@ -53,6 +55,7 @@ const DEFAULT_MAX_RETRIES = 2 const FIRST_RETRY_DELAY_MS = 1_000 const MAX_RETRY_DELAY_MS = 30_000 const BASE64_CHUNK_BYTES = 0x8000 +const DOT_SEGMENTS = new Set(['.', '..']) /** What every send takes, whatever its form. */ export interface SendEmailBase { @@ -172,8 +175,8 @@ export interface EmailError { /** * PostHog's error code, such as `invalid_recipient`, or one of the SDK's own: `missing_secret_key`, * `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error` for an answer without a - * code, `unexpected_error`, and `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` - * and `invalid_idempotency_key` for a send the SDK refused before any request. + * code, `unexpected_error`, `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` and + * `invalid_idempotency_key` for a send the SDK refused before any request, and `invalid_message_id` for a read. */ code: string message: string @@ -206,6 +209,34 @@ export type SendEmailResult = | { data: { id: string; warnings: EmailWarning[] }; error: null } | { data: null; error: EmailError } +/** Where an email is. `sent` and later come from the email provider. */ +export type EmailStatus = + | 'queued' + | 'waiting' + | 'unknown' + | 'skipped' + | 'failed' + | 'sent' + | 'delivered' + | 'bounced' + | 'complained' + +/** The latest status PostHog knows of one email. */ +export interface EmailStatusRecord { + /** The `id` that `posthog.emails.send()` returned. */ + id: string + status: EmailStatus + /** When PostHog queued the email, as an ISO 8601 timestamp. */ + createdAt: string + /** When the email reached its status, as an ISO 8601 timestamp. */ + statusAt: string + /** Why the email was skipped, failed or bounced, when PostHog knows. */ + reason?: string +} + +/** The result of `posthog.emails.get()`: the email's status, or the `error`. */ +export type GetEmailResult = { data: EmailStatusRecord; error: null } | { data: null; error: EmailError } + /** The `posthog.emails` API: send transactional email from your server. */ export interface Emails { /** @@ -268,6 +299,25 @@ export interface Emails { * ``` */ send(options: SendEmailOptions): Promise + + /** + * Read the latest status of an email that `send` queued. + * + * `status` is not Resend's `last_event`: it is where the email is now, from `queued` to `delivered`, `bounced` + * or `complained`. A new email can take a few seconds to show up, and until then the read answers `not_found`. + * Never throws, and never retries: call it again later to see a newer status. + * + * Needs the `secretKey` client option, a project secret API key with the `hog_flow:read` scope. + * + * @example + * ```ts + * const { data, error } = await posthog.emails.get(sent.id) + * if (data?.status === 'bounced') { + * console.log(`Bounced: ${data.reason}`) + * } + * ``` + */ + get(id: string): Promise } /** @internal */ @@ -283,10 +333,10 @@ export interface EmailsApi { track(work: Promise): Promise /** Rejects only when PostHog never answered. */ request( - method: 'POST' | 'PUT', + method: 'GET' | 'POST' | 'PUT', url: string, headers: Record, - body: string + body: string | undefined ): Promise } @@ -294,14 +344,24 @@ type Outcome = { data: T; error: null } | Failure type Failure = { data: null; error: EmailError } interface Delivery { - idempotencyKey: string + idempotencyKey?: string maxRetries: number } +const READ_ONCE: Delivery = { maxRetries: 0 } + +interface EmailCall { + action: string + scope: string +} + +const SENDING: EmailCall = { action: 'Sending email', scope: 'hog_flow:write' } +const READING: EmailCall = { action: 'Reading an email', scope: 'hog_flow:read' } + interface ApiRequest { - method: 'POST' | 'PUT' + method: 'GET' | 'POST' | 'PUT' path: string - body: JsonType + body?: JsonType } interface Attempt { @@ -342,27 +402,47 @@ export class PostHogEmails implements Emails { ) } + get(id: string): Promise { + const refusal = this.clientRefusal(READING) + if (refusal) { + return Promise.resolve(refusal) + } + const path = statusPath(id) + if (path === undefined) { + return Promise.resolve(failure('invalid_message_id', 'id must be the id that send returned.', { field: 'id' })) + } + return this.api.track( + this.exchange({ method: 'GET', path }, READ_ONCE) + .then((outcome) => (outcome.error ? outcome : statusRecord(outcome.data))) + .catch(unexpectedFailure) + ) + } + private refusalBeforeRequest(options: SendEmailOptions): Failure | undefined { + return this.clientRefusal(SENDING) ?? formRefusal(options) ?? idempotencyKeyRefusal(options.idempotencyKey) + } + + private clientRefusal({ action, scope }: EmailCall): Failure | undefined { if (this.api.isDisabled()) { - return failure('client_disabled', 'The PostHog client is disabled, so nothing was sent.') + return failure('client_disabled', 'The PostHog client is disabled, so the SDK made no request.') } if (this.api.isClosed()) { - return failure('client_closed', 'The PostHog client was shut down, so nothing was sent.') + return failure('client_closed', 'The PostHog client was shut down, so the SDK made no request.') } if (!this.api.secretKey()) { return failure( 'missing_secret_key', - 'Sending email needs the secretKey client option, a project secret API key with the hog_flow:write scope.' + `${action} needs the secretKey client option, a project secret API key with the ${scope} scope.` ) } if (!this.api.appHost()) { return failure( 'missing_app_host', - 'Sending email needs the appHost client option when host is not PostHog Cloud, so the secret key never ' + - 'goes to a proxy.' + `${action} needs the appHost client option when host is not PostHog Cloud, so the secret key never goes ` + + 'to a proxy.' ) } - return formRefusal(options) ?? idempotencyKeyRefusal(options.idempotencyKey) + return undefined } private async sendForm(options: SendEmailOptions, delivery: Delivery): Promise { @@ -398,7 +478,7 @@ export class PostHogEmails implements Emails { } private async exchange(request: ApiRequest, delivery: Delivery): Promise> { - const body = JSON.stringify(request.body) + const body = request.body === undefined ? undefined : JSON.stringify(request.body) for (let retry = 0; ; retry++) { const { outcome, retryAfterMs } = await this.attempt(request, body, delivery) if (retry >= delivery.maxRetries || !isRetryable(outcome)) { @@ -408,12 +488,12 @@ export class PostHogEmails implements Emails { } } - private async attempt(request: ApiRequest, body: string, delivery: Delivery): Promise { + private async attempt(request: ApiRequest, body: string | undefined, delivery: Delivery): Promise { const headers = { ...this.api.headers(), - 'Content-Type': 'application/json', + ...(body !== undefined && { 'Content-Type': 'application/json' }), Authorization: `Bearer ${this.api.secretKey()}`, - 'Idempotency-Key': delivery.idempotencyKey, + ...(delivery.idempotencyKey !== undefined && { 'Idempotency-Key': delivery.idempotencyKey }), } let response: PostHogApiResponse try { @@ -661,6 +741,7 @@ function errorName(code: string, statusCode?: number): EmailErrorName { case 'invalid_template_id': case 'invalid_template_key': case 'invalid_attachment': + case 'invalid_message_id': case 'invalid_idempotency_key': return 'validation_error' } @@ -709,6 +790,31 @@ function apiError({ status, body }: PostHogApiResponse): EmailError { } } +function statusPath(id: unknown): string | undefined { + if (typeof id !== 'string' || !id || DOT_SEGMENTS.has(id)) { + return undefined + } + try { + return STATUS_PATH(id) + } catch { + return undefined + } +} + +function statusRecord({ status, body }: PostHogApiResponse): GetEmailResult { + const fields = isRecord(body) ? body : {} + const [id, emailStatus, createdAt, statusAt] = [fields.id, fields.status, fields.created_at, fields.status_at].map( + textOf + ) + if (!id || !emailStatus || !createdAt || !statusAt) { + return failure('api_error', `PostHog answered HTTP ${status} with an unexpected body.`, { statusCode: status }) + } + return { + data: { id, status: emailStatus as EmailStatus, createdAt, statusAt, ...optional('reason', textOf(fields.reason)) }, + error: null, + } +} + function warningsOf(warnings: unknown): EmailWarning[] { return (Array.isArray(warnings) ? warnings : []).flatMap((warning) => { if (!isRecord(warning) || !textOf(warning.code) || !textOf(warning.detail)) { diff --git a/packages/node/src/exports.ts b/packages/node/src/exports.ts index e156d3dd84..ab03cd3f15 100644 --- a/packages/node/src/exports.ts +++ b/packages/node/src/exports.ts @@ -8,9 +8,12 @@ export type { EmailAttachment, EmailError, EmailErrorName, + EmailStatus, + EmailStatusRecord, Emails, EmailTag, EmailWarning, + GetEmailResult, SendCodeEmailOptions, SendEmailBase, SendEmailOptions,