diff --git a/README.md b/README.md index 60b6013..730ea43 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,88 @@ for (const [i, result] of data.entries()) { } ``` +## Attachments + +Attach up to 10 files (10 MB together) as bytes or base64: + +```ts +import { readFile } from "node:fs/promises"; + +await zalify.emails.send({ + from: "Emma ", + to: "creator@example.com", + subject: "Spring collab brief", + html: "

Brief attached.

", + attachments: [{ filename: "brief.pdf", content: await readFile("brief.pdf") }], +}); +``` + +`headers` takes up to 10 extra headers. Ones Zalify or the mail provider set (From, To, Cc, Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe…) are refused. + +## Conversations + +For back-and-forth with a person: start a conversation, reply in it, and replies that come back land in it. Zalify fills in the sender, recipient, `Re:` subject and thread headers, so follow-ups and answers stay in one thread in their mail client. Email today; every conversation and message carries `channel`, so SMS and WhatsApp won't change the API. The key needs the **Conversations** permission. + +```ts +// Start one: the first email +const { conversation } = await zalify.conversations.create( + { + inbox: "emma@acme.com", // an inbox id or address: see zalify.inboxes.list() + contact: { email: "creator@example.com" }, + subject: "Spring collab", + html: "

Hi…

", + externalId: campaignCreator.id, // your own id, unique in the workspace + metadata: { campaignId: "c_9" }, + }, + { idempotencyKey: `outreach:${campaignCreator.id}` } +); + +// Follow up before they answer, or reply after: content only +await zalify.conversations.reply(conversation.id, { text: "Just checking in!" }); + +// What came back: conversation.message.received +const event = zalify.webhooks.verify(rawBody, req.headers); +if (event.type === "conversation.message.received") { + const { conversation, message } = event.data; + // message.textWithoutQuote: what they wrote this time, without the quoted thread + await zalify.conversations.reply(conversation.id, { text: "Thanks, sending the contract." }); +} + +// Read +await zalify.conversations.list({ externalId: campaignCreator.id }); +await zalify.conversations.list({ contact: "creator@example.com", status: "open" }); +const { data: messages } = await zalify.conversations.messages.list(conversation.id); +await zalify.conversations.update(conversation.id, { status: "closed" }); +``` + +Every received email lands in a conversation: the one it replies to, else a new one (replies to broadcasts and flows, mail out of the blue), so `conversation.message.received` covers everything that comes in. + +Moving threads over from another mailbox provider? Register each one by its Message-IDs and keep replying in it: + +```ts +await zalify.conversations.import({ + inbox: "emma@acme.com", + contact: { email: "creator@example.com" }, + subject: "Spring collab", + messageIds: gmailThread.messages.map((m) => m.messageIdHeader), // oldest first + externalId: campaignCreator.id, +}); +``` + +## Receive email + +The raw received mail is also readable on its own, with a Send email key. Each new email is an `email.received` webhook event too. + +```ts +const { data, nextCursor } = await zalify.emails.inbound.list({ mailbox: "emma@acme.com" }); +const email = await zalify.emails.inbound.get(data[0].id); +// { from, subject, text, html, messageId, references, inReplyToEmailId, attachments, … } + +for (const file of email.attachments) { + const { content, contentType } = await zalify.emails.inbound.getAttachment(email.id, file.id); +} +``` + ## Contacts Create or update a contact by email, e.g. when someone signs up. The key needs the **Manage contacts** permission. @@ -150,7 +232,7 @@ try { | code | status | meaning | | --- | --- | --- | | `unauthorized` | 401 | missing or invalid API key | -| `missing_scope` | 403 | the key lacks the permission: **Send email**, **Manage contacts** or **Track events** | +| `missing_scope` | 403 | the key lacks the permission: **Send email**, **Conversations**, **Manage contacts** or **Track events** | | `email_not_enabled` | 403 | the workspace has no sending set up yet | | `contacts_not_enabled` | 403 | the workspace has no contacts set up yet | | `list_not_found` | 404 | a list in `lists` isn't in your workspace (nothing was written) | @@ -159,6 +241,10 @@ try { | `unverified_sender` | 422 | the from address isn't on a verified domain | | `not_subscribed` | 422 | a marketing recipient isn't a subscribed contact | | `idempotency_conflict` | 409 | the idempotency key was used for a different request | +| `conversation_exists` | 409 | a conversation already has this `externalId` (`details.conversationId`); reply to it | +| `inbox_not_found` | 404 | no inbox with that id or address; see `zalify.inboxes.list()` | +| `inbox_cannot_send` | 422 | the inbox only receives (a catch-all reply domain) | +| `suppressed` | 422 | the recipient bounced hard or complained before | | `rate_limited` | 429 | over 120 requests a minute for this key (a batch counts once) | | `new_recipient_limit` | 429 | the recipient is new to your workspace and today's allowance of new recipients is used; it resets at 00:00 UTC (`retryAfter`) | | `invalid_event` | 422 | an event was refused, e.g. properties over 64 KB or `time` out of range (see `field`) | @@ -188,15 +274,18 @@ new Zalify({ ## Webhooks -Add an endpoint in **Settings → Developer → Webhooks** to get events for email sent through the API: +Add an endpoint in **Settings → Developer → Webhooks** to get events for email sent through the API, and for email you receive: -- `email.sent` +- `email.sent`, with `message_id`: the Message-ID the recipient sees +- `email.failed`, with `reason` - `email.delivered` - `email.bounced`, with `bounce_type` `hard` or `soft` - `email.complained` - `email.opened` - `email.clicked`, with `url` - `contact.unsubscribed` +- `email.received`: `{ inbound_id, in_reply_to_email_id, mailbox, from, subject, preview }`; fetch the whole email with `emails.inbound.get(inbound_id)` +- `conversation.created`, `conversation.message.received`, `conversation.message.updated`, `conversation.updated`: `{ conversation, message? }` (`message.html` left out; read it with `conversations.messages.list`) The signing secret (`whsec_…`) is shown once, when you create the endpoint. diff --git a/package.json b/package.json index 62fe6c2..171d108 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@zalify/sdk", - "version": "0.5.0", + "version": "0.6.0", "description": "Official Node.js / TypeScript SDK for the Zalify API", "keywords": ["zalify", "email", "transactional email", "contacts", "events", "sdk"], "homepage": "https://github.com/zalify/zalify-node#readme", diff --git a/src/client.ts b/src/client.ts index 2520c6e..6397c1f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,10 +1,11 @@ import { Contacts } from "./contacts"; +import { Conversations, Inboxes } from "./conversations"; import { Emails } from "./emails"; import { Events } from "./events"; import { Webhooks } from "./webhooks"; import type { HttpConfig } from "./http"; -export const VERSION = "0.5.0"; +export const VERSION = "0.6.0"; export type ZalifyOptions = { /** A Zalify Public API key (`zalify_api_…`). Defaults to `ZALIFY_API_KEY`. */ @@ -25,6 +26,9 @@ export type ZalifyOptions = { export class Zalify { readonly emails: Emails; + /** Two-way exchanges with one person: start, reply, read. */ + readonly conversations: Conversations; + readonly inboxes: Inboxes; readonly contacts: Contacts; readonly events: Events; readonly webhooks: Webhooks; @@ -59,6 +63,8 @@ export class Zalify { userAgent: `zalify-node/${VERSION}`, }; this.emails = new Emails(http); + this.conversations = new Conversations(http); + this.inboxes = new Inboxes(http); this.contacts = new Contacts(http); this.events = new Events(http); this.webhooks = new Webhooks(options.webhookSecret); diff --git a/src/conversations.ts b/src/conversations.ts new file mode 100644 index 0000000..d9c4576 --- /dev/null +++ b/src/conversations.ts @@ -0,0 +1,308 @@ +import { randomUUID } from "node:crypto"; +import type { EmailAttachment, EmailType, RequestOptions } from "./emails"; +import { type HttpConfig, type RawBody, request } from "./http"; + +/** Channels a conversation can use. Email today; SMS and WhatsApp next. */ +export type Channel = "email"; + +/** Your side of conversations: one per sender email, plus receive-only reply domains. */ +export type Inbox = { + id: string; + name: string; + email: string; + /** False for a receive-only address. */ + canSend: boolean; +}; + +export type ConversationChannel = { + channel: Channel; + /** The inbox's address on this channel. */ + address: string; + /** The other party's address: where replies go. */ + contact: string; + sendable: boolean; + /** Why it can't send, when it can't. */ + reason: string | null; +}; + +export type Conversation = { + id: string; + inboxId: string; + inbox: Inbox; + status: "open" | "closed"; + subject: string; + contact: { email: string | null }; + /** Your own id for what it's about; unique in the workspace. */ + externalId: string | null; + metadata: Record | null; + /** The channel the contact last wrote on; replies default to it. */ + lastChannel: Channel | (string & {}); + channels: ConversationChannel[]; + lastMessageAt: string; + lastInboundAt: string | null; + createdAt: string; +}; + +export type ConversationAttachment = { + id: string; + filename: string; + contentType: string; + size: number; + contentId: string | null; + inline: boolean; +}; + +export type MessageStatus = + | "queued" + | "sent" + | "delayed" + | "delivered" + | "opened" + | "bounced" + | "complained" + | "failed" + | "received"; + +export type ConversationMessage = { + id: string; + conversationId: string; + direction: "inbound" | "outbound"; + channel: Channel | (string & {}); + from: string; + to: string; + text: string | null; + /** Null in webhook events; read it with `messages.list`. */ + html: string | null; + /** Inbound email: what they wrote this time, without the quoted thread. */ + textWithoutQuote: string | null; + attachments: ConversationAttachment[]; + status: MessageStatus | (string & {}); + statusAt: string | null; + /** The bounce type, or why it failed. */ + statusDetail: string | null; + email?: { subject: string; messageId: string | null }; + createdAt: string; +}; + +/** Give `text` or `html` (or both); text alone is sent as simple HTML too. */ +export type MessageContent = { + text?: string; + html?: string; + /** Up to 10 files, 10 MB together. */ + attachments?: EmailAttachment[]; +}; + +export type CreateConversationParams = MessageContent & { + /** An inbox id, or its email address (e.g. `emma@brand.com`). */ + inbox: string; + contact: { email: string }; + channel?: Channel; + subject: string; + /** Your own id for what it's about, e.g. a campaign-creator id. */ + externalId?: string; + /** Your JSON, up to 8 KB. */ + metadata?: Record; + /** Default `transactional`. */ + type?: EmailType; +}; + +export type ReplyParams = MessageContent & { + /** Defaults to the channel the contact last wrote on. */ + channel?: Channel; +}; + +export type ListConversationsParams = { + /** An inbox id or address. */ + inbox?: string; + status?: "open" | "closed"; + /** The contact's email address. */ + contact?: string; + externalId?: string; + /** 1–100, default 25. */ + limit?: number; + cursor?: string; +}; + +export type UpdateConversationParams = { + status?: "open" | "closed"; + /** Null clears it. */ + externalId?: string | null; + /** Replaces it; null clears it. */ + metadata?: Record | null; +}; + +export type ImportConversationParams = { + inbox: string; + contact: { email: string }; + subject: string; + /** The thread's Message-IDs, oldest first, with angle brackets (up to 50). */ + messageIds: string[]; + lastMessageAt?: string; + externalId?: string; + metadata?: Record; +}; + +export type Page = { + data: T[]; + /** Pass as `cursor` for the next page; null on the last. */ + nextCursor: string | null; +}; + +export type ConversationWithMessage = { + conversation: Conversation; + message: ConversationMessage; +}; + +const toBase64 = (content: Uint8Array | string) => + typeof content === "string" + ? content + : Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString( + "base64" + ); + +const toWire = (params: T): T => + params.attachments + ? { + ...params, + attachments: params.attachments.map((file) => ({ + ...file, + content: toBase64(file.content), + })), + } + : params; + +const query = (params: Record) => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null) search.set(key, String(value)); + } + const qs = search.toString(); + return qs ? `?${qs}` : ""; +}; + +const path = (id: string) => `/conversations/${encodeURIComponent(id)}`; + +/** A conversation's messages. */ +export class Messages { + constructor(private readonly http: HttpConfig) {} + + /** Oldest first, every channel together. */ + async list( + conversationId: string, + params: { limit?: number; cursor?: string } = {} + ): Promise> { + return request>(this.http, { + method: "GET", + path: `${path(conversationId)}/messages${query(params)}`, + }); + } + + /** A received attachment's bytes and type. */ + async getAttachment( + conversationId: string, + messageId: string, + attachmentId: string + ): Promise { + return request(this.http, { + method: "GET", + path: `${path(conversationId)}/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`, + raw: true, + }); + } +} + +/** + * Two-way exchanges with one person. Start one, reply in it; what comes back + * arrives as `conversation.message.received` webhook events. Zalify fills in + * the sender, recipient, subject and thread headers. Needs a key with the + * Conversations permission. + */ +export class Conversations { + readonly messages: Messages; + + constructor(private readonly http: HttpConfig) { + this.messages = new Messages(http); + } + + /** Start a conversation with its first message. */ + async create( + params: CreateConversationParams, + options: RequestOptions = {} + ): Promise { + return request(this.http, { + method: "POST", + path: "/conversations", + body: toWire(params), + idempotencyKey: options.idempotencyKey ?? randomUUID(), + }); + } + + /** + * Reply, or follow up before they answer. Goes to the contact, from the + * conversation's inbox, threaded under its newest message. + */ + async reply( + conversationId: string, + params: ReplyParams, + options: RequestOptions = {} + ): Promise { + return request(this.http, { + method: "POST", + path: `${path(conversationId)}/messages`, + body: toWire(params), + idempotencyKey: options.idempotencyKey ?? randomUUID(), + }); + } + + /** Newest activity first. */ + async list(params: ListConversationsParams = {}): Promise> { + return request>(this.http, { + method: "GET", + path: `/conversations${query(params)}`, + }); + } + + /** Throws ZalifyError `not_found` for an unknown id. */ + async get(conversationId: string): Promise { + return request(this.http, { + method: "GET", + path: path(conversationId), + }); + } + + /** Close or reopen it, or change its externalId or metadata. */ + async update( + conversationId: string, + params: UpdateConversationParams + ): Promise { + return request(this.http, { + method: "PATCH", + path: path(conversationId), + body: params, + }); + } + + /** + * Bring over a thread that started with another mailbox provider, so your + * next reply continues it and its replies come back here. + */ + async import(params: ImportConversationParams): Promise { + return request(this.http, { + method: "POST", + path: "/conversations/import", + body: params, + }); + } +} + +/** Where conversations happen. */ +export class Inboxes { + constructor(private readonly http: HttpConfig) {} + + async list(): Promise<{ data: Inbox[] }> { + return request<{ data: Inbox[] }>(this.http, { + method: "GET", + path: "/inboxes", + }); + } +} diff --git a/src/emails.ts b/src/emails.ts index 17abe5c..7382861 100644 --- a/src/emails.ts +++ b/src/emails.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import { ZalifyError } from "./errors"; -import { type HttpConfig, request } from "./http"; +import { type HttpConfig, type RawBody, request } from "./http"; /** * `transactional` (sign-in, password reset, receipts, notifications) goes out @@ -42,6 +42,24 @@ export type EmailMessage = EmailSender & { * `automation_`, `broadcast_` or `message_`. */ tags?: Record; + /** + * Up to 10 extra headers. For back-and-forth with a person, use + * `zalify.conversations`, which threads replies for you. From, To, Cc, + * Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe and + * the like are set by Zalify and refused. + */ + headers?: Record; + /** Up to 10 files, 10 MB together. */ + attachments?: EmailAttachment[]; +}; + +export type EmailAttachment = { + filename: string; + /** The file: bytes (Buffer, Uint8Array) or a base64 string. */ + content: Uint8Array | string; + contentType?: string; + /** Shows the file inline, referenced from the HTML as `cid:`. */ + contentId?: string; }; export type SendEmailParams = EmailMessage & { type?: EmailType }; @@ -98,9 +116,130 @@ export type RequestOptions = { const MAX_BATCH = 100; -export class Emails { +const toBase64 = (content: Uint8Array | string) => + typeof content === "string" + ? content + : Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString( + "base64" + ); + +/** The message as the API takes it: attachments base64-encoded. */ +const toWire = (message: T): T => + message.attachments + ? { + ...message, + attachments: message.attachments.map((file) => ({ + ...file, + content: toBase64(file.content), + })), + } + : message; + +/** A received email in a list. */ +export type InboundEmailSummary = { + id: string; + /** The mailbox it came in on, e.g. support@brand.com. */ + mailbox: string; + from: string; + subject: string; + /** The start of the text body. */ + preview: string; + /** The `id` of your email it replies to, when it answers one you sent. */ + inReplyToEmailId: string | null; + receivedAt: string; +}; + +export type InboundEmailAttachment = { + id: string; + filename: string; + contentType: string; + /** Bytes. */ + size: number; + contentId: string | null; + /** Shown in the HTML (`cid:`) rather than attached. */ + inline: boolean; +}; + +/** A received email, whole. */ +export type InboundEmail = InboundEmailSummary & { + /** The address it was delivered to (the forwarding address for forwarded mail). */ + to: string; + cc: string[]; + replyTo: string | null; + /** Its Message-ID. To answer it, reply in its conversation. */ + messageId: string | null; + references: string | null; + text: string | null; + html: string | null; + /** Every header, names lowercased; a repeated header is an array. */ + headers: Record; + attachments: InboundEmailAttachment[]; +}; + +export type ListInboundParams = { + /** 1–100, default 25. */ + limit?: number; + /** `nextCursor` from the previous page. */ + cursor?: string; + /** Only email that came in on this mailbox (a sender address). */ + mailbox?: string; + /** Only email from this address. */ + from?: string; +}; + +export type ListInboundResult = { + data: InboundEmailSummary[]; + /** Pass as `cursor` for the next page; null on the last. */ + nextCursor: string | null; +}; + +/** + * Email received at your mailboxes: senders forwarded to Zalify and reply + * domains (Settings → Email → Receiving). Each new one is also an + * `email.received` webhook event. Uses the same Send email key. + */ +export class Inbound { constructor(private readonly http: HttpConfig) {} + /** Newest first. */ + async list(params: ListInboundParams = {}): Promise { + const query = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null) query.set(key, String(value)); + } + const qs = query.toString(); + return request(this.http, { + method: "GET", + path: `/email/inbound${qs ? `?${qs}` : ""}`, + }); + } + + /** The whole email. Throws ZalifyError `not_found` for an unknown id. */ + async get(id: string): Promise { + return request(this.http, { + method: "GET", + path: `/email/inbound/${encodeURIComponent(id)}`, + }); + } + + /** An attachment's bytes and type. */ + async getAttachment(id: string, attachmentId: string): Promise { + return request(this.http, { + method: "GET", + path: `/email/inbound/${encodeURIComponent(id)}/attachments/${encodeURIComponent(attachmentId)}`, + raw: true, + }); + } +} + +export class Emails { + /** Email received at your mailboxes. */ + readonly inbound: Inbound; + + constructor(private readonly http: HttpConfig) { + this.inbound = new Inbound(http); + } + /** Send one email. Throws ZalifyError when it isn't accepted. */ async send( params: SendEmailParams, @@ -109,7 +248,7 @@ export class Emails { return request(this.http, { method: "POST", path: "/email/send", - body: params, + body: toWire(params), idempotencyKey: options.idempotencyKey ?? randomUUID(), }); } @@ -130,7 +269,8 @@ export class Emails { params: SendBatchParams | EmailMessage[], options: RequestOptions = {} ): Promise { - const body = Array.isArray(params) ? { messages: params } : params; + const given = Array.isArray(params) ? { messages: params } : params; + const body = { ...given, messages: given.messages.map(toWire) }; if (body.messages.length === 0 || body.messages.length > MAX_BATCH) { throw new ZalifyError({ message: `A batch holds 1 to ${MAX_BATCH} messages, got ${body.messages.length}`, diff --git a/src/errors.ts b/src/errors.ts index 9ed8048..e673eb7 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -26,6 +26,12 @@ export type ZalifyErrorCode = | "daily_limit" | "suppressed" | "rejected" + | "not_found" + | "conversation_exists" + | "inbox_not_found" + | "inbox_cannot_send" + | "channel_unavailable" + | "email_api_not_enabled" | "network_error" | "timeout" | (string & {}); diff --git a/src/http.ts b/src/http.ts index c86c57e..da6c6e1 100644 --- a/src/http.ts +++ b/src/http.ts @@ -12,12 +12,17 @@ export type HttpConfig = { }; type RequestInit = { - method: "GET" | "POST"; + method: "GET" | "POST" | "PATCH"; path: string; body?: unknown; idempotencyKey?: string; + /** Return the body's bytes and type instead of parsing JSON. */ + raw?: boolean; }; +/** A file the API returned as is. */ +export type RawBody = { content: Uint8Array; contentType: string }; + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Exponential backoff with full jitter: 0.5s, 1s, 2s… capped. */ @@ -97,6 +102,15 @@ async function once(config: HttpConfig, init: RequestInit): Promise { clearTimeout(timer); } + if (init.raw && response.ok) { + const raw: RawBody = { + content: new Uint8Array(await response.arrayBuffer()), + contentType: + response.headers.get("content-type") ?? "application/octet-stream", + }; + return raw as T; + } + const text = await response.text(); let body: unknown; try { diff --git a/src/index.ts b/src/index.ts index ee39893..2de877e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,27 @@ export type { TrackOptions, } from "./events"; export type { + Channel, + Conversation, + ConversationAttachment, + ConversationChannel, + ConversationMessage, + Conversations, + ConversationWithMessage, + CreateConversationParams, + ImportConversationParams, + Inbox, + Inboxes, + ListConversationsParams, + MessageContent, + Messages, + MessageStatus, + Page, + ReplyParams, + UpdateConversationParams, +} from "./conversations"; +export type { + EmailAttachment, EmailMessage, EmailSender, EmailSendError, @@ -28,11 +49,21 @@ export type { SendEmailResult, SenderEmail, RequestOptions, + Inbound, + InboundEmail, + InboundEmailAttachment, + InboundEmailSummary, + ListInboundParams, + ListInboundResult, } from "./emails"; +export type { RawBody } from "./http"; export { verifyWebhook, Webhooks, WebhookVerificationError, + type ConversationWebhookEvent, + type EmailWebhookEvent, + type ReceivedWebhookEvent, type VerifyOptions, type WebhookEvent, type WebhookEventType, diff --git a/src/webhooks.ts b/src/webhooks.ts index 75207b9..9f5622c 100644 --- a/src/webhooks.ts +++ b/src/webhooks.ts @@ -1,19 +1,30 @@ import { createHmac, timingSafeEqual } from "node:crypto"; +import type { Conversation, ConversationMessage } from "./conversations"; /** Event types a Zalify webhook endpoint can receive. */ export type WebhookEventType = | "email.sent" + | "email.failed" | "email.delivered" | "email.bounced" | "email.complained" | "email.opened" | "email.clicked" - | "contact.unsubscribed"; + | "contact.unsubscribed" + | "email.received" + | "conversation.created" + | "conversation.message.received" + | "conversation.message.updated" + | "conversation.updated"; -export type WebhookEvent = { +/** What happened to an email you sent through the Email API. */ +export type EmailWebhookEvent = { /** Stable across retries: use it to drop duplicates. */ id: string; - type: WebhookEventType; + type: Exclude< + WebhookEventType, + "email.received" | ConversationWebhookEvent["type"] + >; created_at: string; data: { /** The `id` returned when the email was sent. */ @@ -21,6 +32,10 @@ export type WebhookEvent = { to: string; /** The tags sent with the email. */ tags: Record; + /** email.sent: the Message-ID the recipient sees. */ + message_id?: string; + /** email.failed: why it wasn't sent. */ + reason?: string; /** email.bounced: `hard` (permanent — stop sending) or `soft`. */ bounce_type?: "hard" | "soft" | (string & {}); /** email.clicked: the link that was clicked. */ @@ -28,6 +43,49 @@ export type WebhookEvent = { }; }; +/** An email arrived at one of your mailboxes. */ +export type ReceivedWebhookEvent = { + id: string; + type: "email.received"; + created_at: string; + data: { + /** Fetch the whole email with `emails.inbound.get(inbound_id)`. */ + inbound_id: string; + /** The `email_id` of your email it replies to, when it answers one. */ + in_reply_to_email_id: string | null; + /** The mailbox it came in on, e.g. support@brand.com. */ + mailbox: string; + from: string; + subject: string; + /** The start of the text body. */ + preview: string; + }; +}; + +/** + * A conversation started, a message came in (any channel), a sent message's + * delivery moved on, or a conversation's status or metadata changed. + * `message.html` is left out; read it with `conversations.messages.list`. + */ +export type ConversationWebhookEvent = { + id: string; + type: + | "conversation.created" + | "conversation.message.received" + | "conversation.message.updated" + | "conversation.updated"; + created_at: string; + data: { + conversation: Conversation; + message?: ConversationMessage; + }; +}; + +export type WebhookEvent = + | EmailWebhookEvent + | ReceivedWebhookEvent + | ConversationWebhookEvent; + export class WebhookVerificationError extends Error { constructor(message: string) { super(message); diff --git a/test/conversations.test.ts b/test/conversations.test.ts new file mode 100644 index 0000000..93a7ab7 --- /dev/null +++ b/test/conversations.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { Zalify, ZalifyError } from "../src/index"; + +type Call = { url: string; init: RequestInit }; + +const scripted = (responses: Response[]) => { + const calls: Call[] = []; + const fetchImpl = (async (url: string, init: RequestInit) => { + calls.push({ url, init }); + const next = responses.shift(); + if (!next) throw new Error("no more scripted responses"); + return next; + }) as unknown as typeof fetch; + return { calls, fetchImpl }; +}; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + +const client = (fetchImpl: typeof fetch) => + new Zalify({ apiKey: "zalify_api_test", fetch: fetchImpl, maxRetryDelayMs: 5 }); + +const BASE = "https://app.zalify.com/api/v1"; +const body = (call: Call | undefined) => JSON.parse(String(call?.init.body)); +const header = (call: Call | undefined, name: string) => + new Headers(call?.init.headers).get(name); + +test("create and reply send content only; idempotency keys go along", async () => { + const { calls, fetchImpl } = scripted([ + json({ conversation: { id: "conv_1" }, message: { id: "m1" } }, 201), + json({ conversation: { id: "conv_1" }, message: { id: "m2" } }, 201), + ]); + const zalify = client(fetchImpl); + const { conversation } = await zalify.conversations.create( + { + inbox: "emma@zalify.com", + contact: { email: "creator@example.com" }, + subject: "Collab", + html: "

Hi

", + externalId: "cc_1", + attachments: [{ filename: "brief.pdf", content: Buffer.from("%PDF") }], + }, + { idempotencyKey: "outreach:cc_1" } + ); + await zalify.conversations.reply(conversation.id, { text: "Following up" }); + + assert.equal(calls[0]?.url, `${BASE}/conversations`); + assert.equal(calls[0]?.init.method, "POST"); + assert.equal(header(calls[0], "idempotency-key"), "outreach:cc_1"); + assert.equal(body(calls[0]).attachments[0].content, "JVBERg=="); + assert.equal(calls[1]?.url, `${BASE}/conversations/conv_1/messages`); + assert.deepEqual(body(calls[1]), { text: "Following up" }); + assert.ok(header(calls[1], "idempotency-key"), "a key is made per call"); +}); + +test("list, get, update, messages, import and inboxes hit their routes", async () => { + const { calls, fetchImpl } = scripted([ + json({ data: [], nextCursor: null }), + json({ id: "c 1" }), + json({ id: "c 1", status: "closed" }), + json({ data: [], nextCursor: null }), + json({ id: "c2" }, 201), + json({ data: [] }), + new Response(new Uint8Array([7]), { headers: { "content-type": "image/png" } }), + ]); + const zalify = client(fetchImpl); + await zalify.conversations.list({ externalId: "cc_1", status: "open" }); + await zalify.conversations.get("c 1"); + await zalify.conversations.update("c 1", { status: "closed", metadata: null }); + await zalify.conversations.messages.list("c 1", { limit: 50 }); + await zalify.conversations.import({ + inbox: "emma@zalify.com", + contact: { email: "creator@example.com" }, + subject: "Re: Collab", + messageIds: [""], + }); + await zalify.inboxes.list(); + const file = await zalify.conversations.messages.getAttachment("c 1", "m1", "a1"); + + assert.equal(calls[0]?.url, `${BASE}/conversations?externalId=cc_1&status=open`); + assert.equal(calls[1]?.url, `${BASE}/conversations/c%201`); + assert.equal(calls[2]?.init.method, "PATCH"); + assert.deepEqual(body(calls[2]), { status: "closed", metadata: null }); + assert.equal(calls[3]?.url, `${BASE}/conversations/c%201/messages?limit=50`); + assert.equal(calls[4]?.url, `${BASE}/conversations/import`); + assert.equal(calls[5]?.url, `${BASE}/inboxes`); + assert.equal(calls[6]?.url, `${BASE}/conversations/c%201/messages/m1/attachments/a1`); + assert.equal(file.contentType, "image/png"); +}); + +test("a taken externalId surfaces as conversation_exists", async () => { + const { fetchImpl } = scripted([ + json( + { + error: "A conversation with this externalId already exists.", + code: "conversation_exists", + details: { conversationId: "conv_9" }, + }, + 409 + ), + ]); + await assert.rejects( + client(fetchImpl).conversations.create({ + inbox: "emma@zalify.com", + contact: { email: "a@example.com" }, + subject: "Hi", + text: "Hi", + externalId: "dup", + }), + (error: unknown) => + error instanceof ZalifyError && error.code === "conversation_exists" && error.status === 409 + ); +}); diff --git a/test/inbound.test.ts b/test/inbound.test.ts new file mode 100644 index 0000000..59df7ad --- /dev/null +++ b/test/inbound.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { Zalify, ZalifyError } from "../src/index"; + +type Call = { url: string; init: RequestInit }; + +const scripted = (responses: Response[]) => { + const calls: Call[] = []; + const fetchImpl = (async (url: string, init: RequestInit) => { + calls.push({ url, init }); + const next = responses.shift(); + if (!next) throw new Error("no more scripted responses"); + return next; + }) as unknown as typeof fetch; + return { calls, fetchImpl }; +}; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + +const client = (fetchImpl: typeof fetch) => + new Zalify({ apiKey: "zalify_api_test", fetch: fetchImpl, maxRetryDelayMs: 5 }); + +test("attachments go out base64-encoded, with extra headers", async () => { + const { calls, fetchImpl } = scripted([json({ id: "msg_1" })]); + await client(fetchImpl).emails.send({ + from: "Emma ", + to: "creator@gmail.com", + subject: "Re: Collab", + html: "

Brief attached

", + headers: { "X-Campaign": "c9" }, + attachments: [ + { filename: "brief.pdf", content: Buffer.from("%PDF"), contentType: "application/pdf" }, + { filename: "note.txt", content: "aGk=" }, + ], + }); + const body = JSON.parse(String(calls[0]?.init.body)); + assert.deepEqual(body.headers, { "X-Campaign": "c9" }); + assert.deepEqual(body.attachments, [ + { filename: "brief.pdf", content: "JVBERg==", contentType: "application/pdf" }, + { filename: "note.txt", content: "aGk=" }, + ]); +}); + +test("inbound.list sends filters as a query; get and attachments read back", async () => { + const { calls, fetchImpl } = scripted([ + json({ data: [], nextCursor: null }), + json({ id: "in_1", messageId: "", references: null }), + new Response(new Uint8Array([1, 2, 3]), { + headers: { "content-type": "application/pdf" }, + }), + ]); + const zalify = client(fetchImpl); + await zalify.emails.inbound.list({ mailbox: "emma@zalify.com", limit: 10 }); + const email = await zalify.emails.inbound.get("in_1"); + const file = await zalify.emails.inbound.getAttachment("in_1", "att_1"); + + assert.equal( + calls[0]?.url, + "https://app.zalify.com/api/v1/email/inbound?mailbox=emma%40zalify.com&limit=10" + ); + assert.equal(calls[0]?.init.method, "GET"); + assert.equal(email.messageId, ""); + assert.equal(calls[2]?.url, "https://app.zalify.com/api/v1/email/inbound/in_1/attachments/att_1"); + assert.deepEqual([...file.content], [1, 2, 3]); + assert.equal(file.contentType, "application/pdf"); +}); + +test("an unknown inbound id is a ZalifyError not_found", async () => { + const { fetchImpl } = scripted([json({ error: "No received email", code: "not_found" }, 404)]); + await assert.rejects(client(fetchImpl).emails.inbound.get("x"), (error: unknown) => + error instanceof ZalifyError && error.code === "not_found" && error.status === 404 + ); +});