From d1bdad662d7d548350a281a202417e7ea02428bb Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:58:22 +0100 Subject: [PATCH 1/3] Add Subscription Topics and topic fields Email Marketing's subscription topics let a contact leave one kind of email without unsubscribing from all of them. The API exposes them on topics, campaigns, contacts, imports, suppressions, email logs and webhooks, so the SDK types and calls follow: - client.subscriptionTopics is token-scoped, like emailCampaigns, and passes a null page token through as "not set", like templates. - A campaign's subscription_topic_id is optional and never nullable in requests, since the API refuses null: a topic can change, not go. - Contact topic fields are optional: they are absent on accounts without topics, which still read and write contacts as before. - include_topic_unsubscriptions goes out as the literal true the API checks for, and only when set. - topic unsubscription rows can't be created or deleted, so create's type no longer follows the read type. - The examples look topics up at run time and handle the 403 of an account without topics, so they run on either kind of account. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + examples/contact-imports/everything.ts | 36 +++- examples/contacts/everything.ts | 45 ++++ examples/email-campaigns/everything.ts | 31 ++- examples/email-logs/everything.ts | 8 + examples/sending/suppressions.ts | 15 +- examples/subscription-topics/everything.ts | 52 +++++ examples/webhooks/everything.ts | 10 + .../lib/api/SubscriptionTopics.test.ts | 16 ++ .../lib/api/resources/ContactImports.test.ts | 27 +++ .../lib/api/resources/Contacts.test.ts | 108 ++++++++++ .../lib/api/resources/EmailCampaigns.test.ts | 31 +++ .../lib/api/resources/EmailLogs.test.ts | 36 +++- .../api/resources/SubscriptionTopics.test.ts | 196 ++++++++++++++++++ .../lib/api/resources/Suppressions.test.ts | 42 +++- .../lib/api/resources/Webhooks.test.ts | 33 +++ src/__tests__/lib/mailtrap-client.test.ts | 15 ++ src/lib/MailtrapClient.ts | 8 + src/lib/api/SubscriptionTopics.ts | 15 ++ src/lib/api/resources/Contacts.ts | 8 +- src/lib/api/resources/SubscriptionTopics.ts | 59 ++++++ src/lib/api/resources/Suppressions.ts | 3 + src/types/api/contact-imports.ts | 31 ++- src/types/api/contacts.ts | 21 ++ src/types/api/email-campaigns.ts | 16 ++ src/types/api/email-logs.ts | 13 ++ src/types/api/subscription-topics.ts | 38 ++++ src/types/api/suppressions.ts | 22 +- src/types/api/webhooks.ts | 8 +- 29 files changed, 923 insertions(+), 21 deletions(-) create mode 100644 examples/subscription-topics/everything.ts create mode 100644 src/__tests__/lib/api/SubscriptionTopics.test.ts create mode 100644 src/__tests__/lib/api/resources/SubscriptionTopics.test.ts create mode 100644 src/lib/api/SubscriptionTopics.ts create mode 100644 src/lib/api/resources/SubscriptionTopics.ts create mode 100644 src/types/api/subscription-topics.ts diff --git a/README.md b/README.md index c29517fd..a7ee2dc6 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,7 @@ Contact management: Email Marketing: - Email campaigns CRUD, lifecycle & stats – [`email-campaigns/everything.ts`](examples/email-campaigns/everything.ts) +- Subscription topics (list & get) – [`subscription-topics/everything.ts`](examples/subscription-topics/everything.ts) - Email Marketing stats (campaigns and automations, aggregated) – [`marketing-stats/everything.ts`](examples/marketing-stats/everything.ts) General API: diff --git a/examples/contact-imports/everything.ts b/examples/contact-imports/everything.ts index c1aecf4f..ad609cb5 100644 --- a/examples/contact-imports/everything.ts +++ b/examples/contact-imports/everything.ts @@ -8,11 +8,45 @@ const client = new MailtrapClient({ accountId: ACCOUNT_ID }); +// An account without subscription topics answers `403` with an empty body. +const isForbidden = (error: unknown) => + (error as { cause?: { response?: { status?: number } } }).cause?.response + ?.status === 403; + +// A preference for the account's first subscription topic, on the topic's +// domain or, for an "All domains" topic, on the account's first domain. +// Returns `undefined` on an account without subscription topics. +async function findTopicPreference() { + try { + const topics = await client.subscriptionTopics.getList({ per_page: 1 }); + const topic = topics.data[0]; + if (!topic) return undefined; + + const domainId = + topic.domain_id ?? (await client.domains.getList()).data[0]?.id; + if (domainId === undefined) return undefined; + + return { + subscription_topic_id: topic.id, + domain_id: domainId, + status: "unsubscribed" as const, + }; + } catch (error) { + if (isForbidden(error)) return undefined; + throw error; + } +} + async function runContactImportsFlow() { + // A contact's `subscription_topics` sets its status for each topic and + // domain pair given; an import that sends them fails on an account without + // subscription topics. + const topicPreference = await findTopicPreference(); const importData = { contacts: [ { - email: "customer1@example.com" + email: "customer1@example.com", + ...(topicPreference && { subscription_topics: [topicPreference] }) }, { email: "customer2@example.com" diff --git a/examples/contacts/everything.ts b/examples/contacts/everything.ts index fa73047a..615b4cdc 100644 --- a/examples/contacts/everything.ts +++ b/examples/contacts/everything.ts @@ -8,6 +8,35 @@ const client = new MailtrapClient({ accountId: ACCOUNT_ID }); +// An account without subscription topics answers `403` with an empty body. +const isForbidden = (error: unknown) => + (error as { cause?: { response?: { status?: number } } }).cause?.response + ?.status === 403; + +// A preference for the account's first subscription topic, on the topic's +// domain or, for an "All domains" topic, on the account's first domain. +// Returns `undefined` on an account without subscription topics. +async function findTopicPreference() { + try { + const topics = await client.subscriptionTopics.getList({ per_page: 1 }); + const topic = topics.data[0]; + if (!topic) return undefined; + + const domainId = + topic.domain_id ?? (await client.domains.getList()).data[0]?.id; + if (domainId === undefined) return undefined; + + return { + subscription_topic_id: topic.id, + domain_id: domainId, + status: "unsubscribed" as const, + }; + } catch (error) { + if (isForbidden(error)) return undefined; + throw error; + } +} + const contactData = { email: "john.smith@example.com", fields: { @@ -38,6 +67,22 @@ client.contacts }) console.log("Contact updated:", updateResponse.data); + // Unsubscribe the contact from one subscription topic on one domain. The + // topic and domain pairs left out keep their status. Contact responses + // list every pair in `subscription_topics`: it is absent on an account + // without subscription topics, and `null` when they couldn't be read. + const topicPreference = await findTopicPreference(); + if (topicPreference) { + const topicsResponse = await client.contacts.update(contactId, { + email: contactData.email, + subscription_topics: [topicPreference], + }); + console.log( + "Contact subscription topics:", + topicsResponse.data.subscription_topics + ); + } + // Delete contact await client.contacts.delete(contactId); console.log("Contact deleted"); diff --git a/examples/email-campaigns/everything.ts b/examples/email-campaigns/everything.ts index 11763319..eeaa295f 100644 --- a/examples/email-campaigns/everything.ts +++ b/examples/email-campaigns/everything.ts @@ -8,6 +8,26 @@ const SENDING_DOMAIN_ID = ""; // The Email Campaigns API is token-scoped — no `accountId` is needed. const client = new MailtrapClient({ token: TOKEN }); +// An account without subscription topics answers `403` with an empty body. +const isForbidden = (error: unknown) => + (error as { cause?: { response?: { status?: number } } }).cause?.response + ?.status === 403; + +// A campaign's subscription topic must cover its domain: an "All domains" +// topic (`domain_id: null`) or one of that domain. Returns `undefined` when +// the account has no such topic, or no subscription topics at all. +async function findSubscriptionTopicId(domainId: number) { + try { + const topics = await client.subscriptionTopics.getList({ per_page: 100 }); + return topics.data.find( + (topic) => topic.domain_id === null || topic.domain_id === domainId + )?.id; + } catch (error) { + if (isForbidden(error)) return undefined; + throw error; + } +} + async function emailCampaignsFlow() { try { const scheduledAt = new Date(Date.now() + 60 * 60 * 1000).toISOString(); @@ -22,8 +42,13 @@ async function emailCampaignsFlow() { console.log("Campaigns:", JSON.stringify(list.data, null, 2)); console.log("Pagination:", JSON.stringify(list.pagination, null, 2)); + const subscriptionTopicId = await findSubscriptionTopicId( + Number(SENDING_DOMAIN_ID) + ); + // Create a campaign. It starts in the `draft` state. Single-campaign - // responses are wrapped in a `{ data }` envelope. + // responses are wrapped in a `{ data }` envelope. `subscription_topic_id` + // is optional; leave it out rather than sending `null`. const created = await client.emailCampaigns.create({ name: "Spring Sale", domain_id: Number(SENDING_DOMAIN_ID), @@ -35,8 +60,12 @@ async function emailCampaignsFlow() { domain: "acme.com", }, template_attributes: { subject: "Spring is here — 30% off" }, + ...(subscriptionTopicId !== undefined && { + subscription_topic_id: subscriptionTopicId, + }), }); console.log("Created campaign:", JSON.stringify(created.data, null, 2)); + console.log("Subscription topic:", created.data.subscription_topic_id); const campaignId = created.data.id; diff --git a/examples/email-logs/everything.ts b/examples/email-logs/everything.ts index 8e36dab0..8ab67eec 100644 --- a/examples/email-logs/everything.ts +++ b/examples/email-logs/everything.ts @@ -44,6 +44,14 @@ async function emailLogsFlow() { const messageId = list.messages[0].message_id; const message = await client.emailLogs.get(messageId); console.log("Single message:", message.subject, "events:", message.events?.length ?? 0); + + // Narrow events by `event_type`. A recipient's unsubscribe from, or + // resubscribe to, one subscription topic names the topic. + for (const event of message.events ?? []) { + if (event.event_type === "topic_unsubscribe" || event.event_type === "topic_resubscribe") { + console.log(event.event_type, "topic:", event.details.subscription_topic_id); + } + } } } catch (error) { console.error("Error in emailLogsFlow:", error instanceof Error ? error.message : String(error)); diff --git a/examples/sending/suppressions.ts b/examples/sending/suppressions.ts index 24b8575f..ebae1050 100644 --- a/examples/sending/suppressions.ts +++ b/examples/sending/suppressions.ts @@ -17,6 +17,17 @@ async function suppressionsFlow() { const filteredSuppressions = await client.suppressions.getList({email: "test@example.com"}); console.log("Filtered suppressions:", filteredSuppressions); + // Include contacts' unsubscriptions from single subscription topics, as + // "topic unsubscription" rows with their `subscription_topic_id`. Needs a + // token that can read contacts; without subscription topics there are none. + const withTopics = await client.suppressions.getList({ + include_topic_unsubscriptions: true + }); + console.log( + "Topic unsubscriptions:", + withTopics.filter((suppression) => suppression.type === "topic unsubscription") + ); + // Add an email to the suppression list. `type` defaults to "manual import". const created = await client.suppressions.create({ email: "suppressed@example.com", @@ -25,7 +36,9 @@ async function suppressionsFlow() { }); console.log("Created suppression:", created.data); - // Delete a suppression by ID (if any exist) + // Delete a suppression by ID (if any exist). The list without + // `include_topic_unsubscriptions` has no topic unsubscriptions, which can't + // be deleted. if (suppressions.length > 0) { const suppressionToDelete = suppressions[0]; await client.suppressions.delete(suppressionToDelete.id); diff --git a/examples/subscription-topics/everything.ts b/examples/subscription-topics/everything.ts new file mode 100644 index 00000000..61e4197b --- /dev/null +++ b/examples/subscription-topics/everything.ts @@ -0,0 +1,52 @@ +import { MailtrapClient } from "mailtrap"; + +const TOKEN = ""; + +// The Subscription Topics API is token-scoped — no `accountId` is needed. +const client = new MailtrapClient({ token: TOKEN }); + +// An account without subscription topics answers `403` with an empty body. +const isForbidden = (error: unknown) => + (error as { cause?: { response?: { status?: number } } }).cause?.response + ?.status === 403; + +async function subscriptionTopicsFlow() { + try { + // List every topic, one page at a time (page-token pagination). The list + // leaves out deleted topics. A `domain_id` of `null` means the topic + // covers every domain. + const topics = []; + let token: number | null = 1; + while (token !== null) { + const page = await client.subscriptionTopics.getList({ + per_page: 50, + token, + }); + topics.push(...page.data); + token = page.pagination.next_token; + } + console.log("Subscription topics:", JSON.stringify(topics, null, 2)); + + if (topics.length === 0) { + console.log("No subscription topics found for this account."); + return; + } + + // Get one topic by ID. `get` also returns a deleted topic, with + // `deleted_at` set. + const topic = await client.subscriptionTopics.get(topics[0].id); + console.log("One topic:", JSON.stringify(topic.data, null, 2)); + } catch (error) { + if (isForbidden(error)) { + console.error("Subscription topics are not available for this account."); + return; + } + + console.error( + "Error in subscriptionTopicsFlow:", + error instanceof Error ? error.message : String(error) + ); + } +} + +subscriptionTopicsFlow(); diff --git a/examples/webhooks/everything.ts b/examples/webhooks/everything.ts index e5ffe122..9ff7265e 100644 --- a/examples/webhooks/everything.ts +++ b/examples/webhooks/everything.ts @@ -45,6 +45,16 @@ async function webhooksFlow() { // Delete the webhook const deleted = await client.webhooks.delete(webhookId); console.log("Deleted webhook:", JSON.stringify(deleted, null, 2)); + + // Campaigns webhooks, and email-sending webhooks on the bulk stream, can + // also report a contact's subscription topic preference changes. + const campaignsWebhook = await client.webhooks.create({ + url: "https://example.com/webhooks/mailtrap/campaigns", + webhook_type: "campaigns", + event_types: ["unsubscribe", "subscription_preferences_update"], + }); + console.log("Created campaigns webhook:", JSON.stringify(campaignsWebhook, null, 2)); + await client.webhooks.delete(campaignsWebhook.data.id); } catch (error) { console.error("Error in webhooksFlow:", error instanceof Error ? error.message : String(error)); } diff --git a/src/__tests__/lib/api/SubscriptionTopics.test.ts b/src/__tests__/lib/api/SubscriptionTopics.test.ts new file mode 100644 index 00000000..50a86f20 --- /dev/null +++ b/src/__tests__/lib/api/SubscriptionTopics.test.ts @@ -0,0 +1,16 @@ +import axios from "axios"; + +import SubscriptionTopicsBaseAPI from "../../../lib/api/SubscriptionTopics"; + +describe("lib/api/SubscriptionTopics: ", () => { + const subscriptionTopicsAPI = new SubscriptionTopicsBaseAPI(axios); + + describe("class SubscriptionTopicsBaseAPI(): ", () => { + describe("init: ", () => { + it("initializes with all necessary params.", () => { + expect(subscriptionTopicsAPI).toHaveProperty("getList"); + expect(subscriptionTopicsAPI).toHaveProperty("get"); + }); + }); + }); +}); diff --git a/src/__tests__/lib/api/resources/ContactImports.test.ts b/src/__tests__/lib/api/resources/ContactImports.test.ts index 3980ae0d..dbd21e3f 100644 --- a/src/__tests__/lib/api/resources/ContactImports.test.ts +++ b/src/__tests__/lib/api/resources/ContactImports.test.ts @@ -116,6 +116,33 @@ describe("lib/api/resources/ContactImports: ", () => { expect(result).toEqual(expectedResponseData); }); + it("sends each contact's subscription topics.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/imports`; + const topicsRequest: ImportContactsRequest = { + contacts: [ + { + email: "customer1@example.com", + subscription_topics: [ + { + subscription_topic_id: 12, + domain_id: 4321, + status: "unsubscribed", + }, + ], + }, + { email: "customer2@example.com" }, + ], + }; + + expect.assertions(2); + + mock.onPost(endpoint, topicsRequest).reply(200, createImportResponse); + const result = await contactImportsAPI.create(topicsRequest); + + expect(JSON.parse(mock.history.post[0].data)).toEqual(topicsRequest); + expect(result).toEqual(createImportResponse); + }); + it("fails with error.", async () => { const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/imports`; const expectedErrorMessage = "Request failed with status code 400"; diff --git a/src/__tests__/lib/api/resources/Contacts.test.ts b/src/__tests__/lib/api/resources/Contacts.test.ts index cba424af..60ec6d63 100644 --- a/src/__tests__/lib/api/resources/Contacts.test.ts +++ b/src/__tests__/lib/api/resources/Contacts.test.ts @@ -4,6 +4,7 @@ import AxiosMockAdapter from "axios-mock-adapter"; import ContactsApi from "../../../../lib/api/resources/Contacts"; import handleSendingError from "../../../../lib/axios-logger"; import MailtrapError from "../../../../lib/MailtrapError"; +import { ContactSubscriptionTopic } from "../../../../types/api/contacts"; import CONFIG from "../../../../config"; @@ -70,6 +71,15 @@ describe("lib/api/resources/Contacts: ", () => { }, }; + const subscriptionTopics: ContactSubscriptionTopic[] = [ + { subscription_topic_id: 12, domain_id: 4321, status: "subscribed" }, + { subscription_topic_id: 12, domain_id: 4322, status: "unsubscribed" }, + ]; + + const topicWriteFailedMessage = + "The contact was saved, but its subscription topic preferences were not. " + + "Send them again in an update of contact 018dd5e3-f6d2-7c00-8f9b-e5c3f2d8a132."; + describe("class ContactsApi(): ", () => { describe("init: ", () => { it("initializes with all necessary params.", () => { @@ -124,6 +134,24 @@ describe("lib/api/resources/Contacts: ", () => { expect(result).toEqual(expectedResponseData); }); + it.each([ + ["a list of topic statuses", subscriptionTopics], + ["null when they couldn't be read", null], + ])("returns subscription_topics as %s.", async (_description, topics) => { + const email = "john.smith@example.com"; + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/${email}`; + const responseData = { + data: { ...createContactResponse.data, subscription_topics: topics }, + }; + + expect.assertions(1); + + mock.onGet(endpoint).reply(200, responseData); + const result = await contactsAPI.get(email); + + expect(result.data.subscription_topics).toEqual(topics); + }); + it("fails with error when getting a contact.", async () => { const email = "nonexistent@example.com"; const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/${email}`; @@ -160,6 +188,64 @@ describe("lib/api/resources/Contacts: ", () => { expect(result).toEqual(expectedResponseData); }); + it("sends subscription_topics and reads them back.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts`; + const contact = { + ...createContactRequest.contact, + subscription_topics: subscriptionTopics, + }; + const responseData = { + data: { + ...createContactResponse.data, + subscription_topics: subscriptionTopics, + }, + }; + + expect.assertions(2); + + mock.onPost(endpoint, { contact }).reply(201, responseData); + const result = await contactsAPI.create(contact); + + expect(JSON.parse(mock.history.post[0].data)).toEqual({ contact }); + expect(result).toEqual(responseData); + }); + + it.each([ + [ + 422, + { + errors: { + subscription_topics: ["are not available for this account"], + }, + }, + "subscription_topics: are not available for this account", + ], + [503, { errors: topicWriteFailedMessage }, topicWriteFailedMessage], + ])( + "fails with the topic error on %i.", + async (statusCode, body, expectedErrorMessage) => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts`; + + expect.assertions(3); + + mock.onPost(endpoint).reply(statusCode, body); + + try { + await contactsAPI.create({ + ...createContactRequest.contact, + subscription_topics: subscriptionTopics, + }); + } catch (error) { + expect(error).toBeInstanceOf(MailtrapError); + if (error instanceof MailtrapError) { + expect(error.message).toEqual(expectedErrorMessage); + // @ts-expect-error ES5 types don't know about cause property + expect(error.cause?.response?.status).toEqual(statusCode); + } + } + } + ); + it("fails with error.", async () => { const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts`; const expectedErrorMessage = "Request failed with status code 400"; @@ -200,6 +286,28 @@ describe("lib/api/resources/Contacts: ", () => { expect(result).toEqual(expectedResponseData); }); + it("updates only the subscription topics.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/${contactId}`; + const contact = { + email: "john.smith111@example.com", + subscription_topics: [subscriptionTopics[1]], + }; + const responseData = { + data: { + ...updateContactResponse.data, + subscription_topics: subscriptionTopics, + }, + }; + + expect.assertions(2); + + mock.onPatch(endpoint, { contact }).reply(200, responseData); + const result = await contactsAPI.update(contactId, contact); + + expect(JSON.parse(mock.history.patch[0].data)).toEqual({ contact }); + expect(result.data.subscription_topics).toEqual(subscriptionTopics); + }); + it("fails with error.", async () => { const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/${contactId}`; const expectedErrorMessage = "Request failed with status code 404"; diff --git a/src/__tests__/lib/api/resources/EmailCampaigns.test.ts b/src/__tests__/lib/api/resources/EmailCampaigns.test.ts index 6bd7cf6d..0de455f9 100644 --- a/src/__tests__/lib/api/resources/EmailCampaigns.test.ts +++ b/src/__tests__/lib/api/resources/EmailCampaigns.test.ts @@ -45,6 +45,7 @@ describe("lib/api/resources/EmailCampaigns: ", () => { '

Hi {{first_name}}!

Unsubscribe

', body_text: null, }, + subscription_topic_id: null, }; describe("class EmailCampaignsApi(): ", () => { @@ -180,6 +181,21 @@ describe("lib/api/resources/EmailCampaigns: ", () => { expect(result).toEqual(responseData); }); + it("sends subscription_topic_id and reads it back.", async () => { + const topicParams = { ...params, subscription_topic_id: 12 }; + const topicResponse = { + data: { ...campaign, subscription_topic_id: 12 }, + }; + + expect.assertions(2); + + mock.onPost(endpoint, topicParams).reply(201, topicResponse); + const result = await emailCampaignsAPI.create(topicParams); + + expect(JSON.parse(mock.history.post[0].data)).toEqual(topicParams); + expect(result.data.subscription_topic_id).toBe(12); + }); + it("fails with error.", async () => { const expectedErrorMessage = "domain_id: must exist"; @@ -271,6 +287,21 @@ describe("lib/api/resources/EmailCampaigns: ", () => { expect(result).toEqual(responseData); }); + it("changes the campaign's subscription topic.", async () => { + const topicParams = { subscription_topic_id: 13 }; + const topicResponse = { + data: { ...campaign, subscription_topic_id: 13 }, + }; + + expect.assertions(2); + + mock.onPatch(updateEndpoint, topicParams).reply(200, topicResponse); + const result = await emailCampaignsAPI.update(campaignId, topicParams); + + expect(JSON.parse(mock.history.patch[0].data)).toEqual(topicParams); + expect(result.data.subscription_topic_id).toBe(13); + }); + it("fails with error.", async () => { const expectedErrorMessage = "from_local_part: can't be blank"; diff --git a/src/__tests__/lib/api/resources/EmailLogs.test.ts b/src/__tests__/lib/api/resources/EmailLogs.test.ts index e02abc03..59d552f0 100644 --- a/src/__tests__/lib/api/resources/EmailLogs.test.ts +++ b/src/__tests__/lib/api/resources/EmailLogs.test.ts @@ -60,6 +60,22 @@ describe("lib/api/resources/EmailLogs: ", () => { web_ip_address: "198.51.100.50", }, }, + { + event_type: "topic_unsubscribe", + created_at: "2025-01-15T10:40:00Z", + details: { + web_ip_address: "198.51.100.50", + subscription_topic_id: 12, + }, + }, + { + event_type: "topic_resubscribe", + created_at: "2025-01-15T10:45:00Z", + details: { + web_ip_address: null, + subscription_topic_id: 12, + }, + }, ], }; @@ -230,7 +246,25 @@ describe("lib/api/resources/EmailLogs: ", () => { expect(mock.history.get[0].url).toEqual(endpoint); expect(result).toEqual(mockMessageDetails); expect(result.raw_message_url).toBeDefined(); - expect(result.events).toHaveLength(1); + expect(result.events).toHaveLength(3); + }); + + it("passes an event type it doesn't know through as is.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/email_logs/${messageId}`; + const unknownEvent = { + event_type: "future_event", + created_at: "2025-01-15T10:50:00Z", + details: { anything: "goes" }, + }; + + expect.assertions(1); + + mock + .onGet(endpoint) + .reply(200, { ...mockMessageDetails, events: [unknownEvent] }); + const result = await emailLogsAPI.get(messageId); + + expect(result.events).toEqual([unknownEvent]); }); it("fails with not found (404).", async () => { diff --git a/src/__tests__/lib/api/resources/SubscriptionTopics.test.ts b/src/__tests__/lib/api/resources/SubscriptionTopics.test.ts new file mode 100644 index 00000000..5e4f920f --- /dev/null +++ b/src/__tests__/lib/api/resources/SubscriptionTopics.test.ts @@ -0,0 +1,196 @@ +import axios from "axios"; +import AxiosMockAdapter from "axios-mock-adapter"; + +import SubscriptionTopicsApi from "../../../../lib/api/resources/SubscriptionTopics"; +import handleSendingError from "../../../../lib/axios-logger"; +import MailtrapError from "../../../../lib/MailtrapError"; +import { + ListSubscriptionTopicsResponse, + SubscriptionTopic, +} from "../../../../types/api/subscription-topics"; + +import CONFIG from "../../../../config"; + +const { CLIENT_SETTINGS } = CONFIG; +const { GENERAL_ENDPOINT } = CLIENT_SETTINGS; + +describe("lib/api/resources/SubscriptionTopics: ", () => { + let mock: AxiosMockAdapter; + const subscriptionTopicsAPI = new SubscriptionTopicsApi(axios); + const endpoint = `${GENERAL_ENDPOINT}/api/subscription_topics`; + + const allDomainsTopic: SubscriptionTopic = { + id: 12, + name: "Product updates", + description: "News about features we ship", + domain_id: null, + deleted_at: null, + created_at: "2026-10-01T10:00:00.000Z", + updated_at: "2026-10-01T10:00:00.000Z", + }; + + const oneDomainTopic: SubscriptionTopic = { + id: 13, + name: "Weekly digest", + description: null, + domain_id: 4321, + deleted_at: null, + created_at: "2026-10-02T10:00:00.000Z", + updated_at: "2026-10-02T10:00:00.000Z", + }; + + const listResponse: ListSubscriptionTopicsResponse = { + data: [allDomainsTopic, oneDomainTopic], + pagination: { + token: 1, + prev_token: null, + next_token: 2, + first_url: `${endpoint}?per_page=2&token=1`, + prev_url: null, + current_url: `${endpoint}?per_page=2&token=1`, + next_url: `${endpoint}?per_page=2&token=2`, + }, + }; + + describe("class SubscriptionTopicsApi(): ", () => { + describe("init: ", () => { + it("initializes with all necessary params.", () => { + expect(subscriptionTopicsAPI).toHaveProperty("getList"); + expect(subscriptionTopicsAPI).toHaveProperty("get"); + }); + }); + }); + + beforeAll(() => { + /** + * Init Axios interceptors for handling response.data, errors. + */ + axios.interceptors.response.use( + (response) => response.data, + handleSendingError + ); + mock = new AxiosMockAdapter(axios); + }); + + afterEach(() => { + mock.reset(); + }); + + describe("getList(): ", () => { + it("gets a page of topics wrapped in a data/pagination envelope.", async () => { + expect.assertions(3); + + mock.onGet(endpoint).reply(200, listResponse); + const result = await subscriptionTopicsAPI.getList(); + + expect(mock.history.get[0].url).toEqual(endpoint); + expect(mock.history.get[0].params).toEqual({}); + expect(result).toEqual(listResponse); + }); + + it("serializes per_page and token as query params.", async () => { + const params = { per_page: 2, token: 2 }; + + expect.assertions(2); + + mock.onGet(endpoint, { params }).reply(200, listResponse); + const result = await subscriptionTopicsAPI.getList(params); + + expect(mock.history.get[0].params).toEqual(params); + expect(result).toEqual(listResponse); + }); + + it("omits a null token, so pagination.next_token can be passed as is.", async () => { + expect.assertions(1); + + mock.onGet(endpoint).reply(200, listResponse); + await subscriptionTopicsAPI.getList({ per_page: 2, token: null }); + + expect(mock.history.get[0].params).toEqual({ per_page: 2 }); + }); + + it("fails with a MailtrapError on the empty 403 of an account without subscription topics.", async () => { + expect.assertions(3); + + mock.onGet(endpoint).reply(403, ""); + + try { + await subscriptionTopicsAPI.getList(); + } catch (error) { + expect(error).toBeInstanceOf(MailtrapError); + + if (error instanceof MailtrapError) { + expect(error.message).toEqual("Request failed with status code 403"); + // @ts-expect-error ES5 types don't know about cause property + expect(error.cause?.response?.status).toEqual(403); + } + } + }); + + it("fails with error.", async () => { + const expectedErrorMessage = "Incorrect API token"; + + expect.assertions(2); + + mock.onGet(endpoint).reply(401, { error: expectedErrorMessage }); + + try { + await subscriptionTopicsAPI.getList(); + } catch (error) { + expect(error).toBeInstanceOf(MailtrapError); + + if (error instanceof MailtrapError) { + expect(error.message).toEqual(expectedErrorMessage); + } + } + }); + }); + + describe("get(): ", () => { + const getEndpoint = `${endpoint}/${oneDomainTopic.id}`; + + it("gets a topic by id wrapped in a data envelope.", async () => { + const responseData = { data: oneDomainTopic }; + + expect.assertions(2); + + mock.onGet(getEndpoint).reply(200, responseData); + const result = await subscriptionTopicsAPI.get(oneDomainTopic.id); + + expect(mock.history.get[0].url).toEqual(getEndpoint); + expect(result).toEqual(responseData); + }); + + it("gets a deleted topic with its deleted_at.", async () => { + const deletedAt = "2026-11-01T10:00:00.000Z"; + const responseData = { + data: { ...oneDomainTopic, deleted_at: deletedAt }, + }; + + expect.assertions(1); + + mock.onGet(getEndpoint).reply(200, responseData); + const result = await subscriptionTopicsAPI.get(oneDomainTopic.id); + + expect(result.data.deleted_at).toEqual(deletedAt); + }); + + it("fails with error.", async () => { + const expectedErrorMessage = "Not Found"; + + expect.assertions(2); + + mock.onGet(getEndpoint).reply(404, { error: expectedErrorMessage }); + + try { + await subscriptionTopicsAPI.get(oneDomainTopic.id); + } catch (error) { + expect(error).toBeInstanceOf(MailtrapError); + + if (error instanceof MailtrapError) { + expect(error.message).toEqual(expectedErrorMessage); + } + } + }); + }); +}); diff --git a/src/__tests__/lib/api/resources/Suppressions.test.ts b/src/__tests__/lib/api/resources/Suppressions.test.ts index 40fde7ae..2600bf95 100644 --- a/src/__tests__/lib/api/resources/Suppressions.test.ts +++ b/src/__tests__/lib/api/resources/Suppressions.test.ts @@ -100,15 +100,55 @@ describe("lib/api/resources/Suppressions: ", () => { it("successfully gets suppressions (up to 1000 per request).", async () => { const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/suppressions`; - expect.assertions(2); + expect.assertions(3); mock.onGet(endpoint).reply(200, mockSuppressions); const result = await suppressionsAPI.getList(); expect(mock.history.get[0].url).toEqual(endpoint); + expect(mock.history.get[0].params).toEqual({}); expect(result).toEqual(mockSuppressions); }); + it("includes topic unsubscriptions when asked to.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/suppressions`; + const topicUnsubscription: Suppression = { + ...mockSuppression, + id: "3", + type: "topic unsubscription", + sending_stream: "bulk", + message_bounce_category: null, + subscription_topic_id: 12, + }; + + expect.assertions(3); + + mock + .onGet(endpoint, { params: { include_topic_unsubscriptions: true } }) + .reply(200, [...mockSuppressions, topicUnsubscription]); + const result = await suppressionsAPI.getList({ + include_topic_unsubscriptions: true, + }); + + const { url, params } = mock.history.get[0]; + expect(axios.getUri({ url, params })).toEqual( + `${endpoint}?include_topic_unsubscriptions=true` + ); + expect(result[2].type).toEqual("topic unsubscription"); + expect(result[2].subscription_topic_id).toEqual(12); + }); + + it("sends nothing for include_topic_unsubscriptions: false.", async () => { + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/suppressions`; + + expect.assertions(1); + + mock.onGet(endpoint).reply(200, mockSuppressions); + await suppressionsAPI.getList({ include_topic_unsubscriptions: false }); + + expect(mock.history.get[0].params).toEqual({}); + }); + it("successfully gets suppressions filtered by email.", async () => { const email = "test@example.com"; const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/suppressions`; diff --git a/src/__tests__/lib/api/resources/Webhooks.test.ts b/src/__tests__/lib/api/resources/Webhooks.test.ts index 0823742c..991af43c 100644 --- a/src/__tests__/lib/api/resources/Webhooks.test.ts +++ b/src/__tests__/lib/api/resources/Webhooks.test.ts @@ -4,6 +4,7 @@ import AxiosMockAdapter from "axios-mock-adapter"; import WebhooksApi from "../../../../lib/api/resources/Webhooks"; import handleSendingError from "../../../../lib/axios-logger"; import MailtrapError from "../../../../lib/MailtrapError"; +import { CreateWebhookParams } from "../../../../types/api/webhooks"; import CONFIG from "../../../../config"; @@ -178,6 +179,38 @@ describe("lib/api/resources/Webhooks: ", () => { expect(JSON.parse(mock.history.post[0].data)).toEqual(expectedBody); expect(result).toEqual(inboundResponseData); }); + + it("creates a campaigns webhook for subscription preference updates.", async () => { + const campaignsParams: CreateWebhookParams = { + url: "https://example.com/mailtrap/webhooks", + webhook_type: "campaigns", + event_types: ["unsubscribe", "subscription_preferences_update"], + }; + const campaignsResponseData = { + data: { + id: 4, + url: "https://example.com/mailtrap/webhooks", + active: true, + webhook_type: "campaigns", + payload_format: "json", + event_types: ["unsubscribe", "subscription_preferences_update"], + signing_secret: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", + }, + }; + const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/webhooks`; + const expectedBody = { webhook: campaignsParams }; + + expect.assertions(2); + + mock.onPost(endpoint, expectedBody).reply(200, campaignsResponseData); + const result = await webhooksAPI.create(campaignsParams); + + expect(JSON.parse(mock.history.post[0].data)).toEqual(expectedBody); + expect(result.data.event_types).toEqual([ + "unsubscribe", + "subscription_preferences_update", + ]); + }); }); describe("get(): ", () => { diff --git a/src/__tests__/lib/mailtrap-client.test.ts b/src/__tests__/lib/mailtrap-client.test.ts index c071f128..617bae21 100644 --- a/src/__tests__/lib/mailtrap-client.test.ts +++ b/src/__tests__/lib/mailtrap-client.test.ts @@ -21,6 +21,7 @@ import SendingDomainsBaseAPI from "../../lib/api/SendingDomains"; import EmailLogsBaseAPI from "../../lib/api/EmailLogs"; import ContactEventsBaseAPI from "../../lib/api/ContactEvents"; import MarketingStatsBaseAPI from "../../lib/api/MarketingStats"; +import SubscriptionTopicsBaseAPI from "../../lib/api/SubscriptionTopics"; import warnDeprecated from "../../lib/deprecation"; jest.mock("../../lib/deprecation"); @@ -1049,6 +1050,20 @@ describe("lib/mailtrap-client: ", () => { expect(client.marketingStats).toBeInstanceOf(MarketingStatsBaseAPI); }); }); + + describe("get subscriptionTopics(): ", () => { + it("returns subscription topics API object without an accountId.", () => { + expect.assertions(1); + + const client = new MailtrapClient({ + token: "MY_API_TOKEN", + }); + + expect(client.subscriptionTopics).toBeInstanceOf( + SubscriptionTopicsBaseAPI + ); + }); + }); }); describe("deprecated names: ", () => { diff --git a/src/lib/MailtrapClient.ts b/src/lib/MailtrapClient.ts index 611a5ec6..509a7384 100644 --- a/src/lib/MailtrapClient.ts +++ b/src/lib/MailtrapClient.ts @@ -22,6 +22,7 @@ import MarketingStatsBaseAPI from "./api/MarketingStats"; import DomainsBaseAPI from "./api/Domains"; import SendingDomainsBaseAPI from "./api/SendingDomains"; import StatsBaseAPI from "./api/Stats"; +import SubscriptionTopicsBaseAPI from "./api/SubscriptionTopics"; import SuppressionsBaseAPI from "./api/Suppressions"; import TrackingOptOutsBaseAPI from "./api/TrackingOptOuts"; import OrganizationsBaseAPI from "./api/Organizations"; @@ -306,6 +307,13 @@ export default class MailtrapClient { return new EmailCampaignsBaseAPI(this.axios); } + /** + * Getter for Subscription Topics API. Scoped to the token's account, so no accountId is required. + */ + get subscriptionTopics() { + return new SubscriptionTopicsBaseAPI(this.axios); + } + /** * Getter for Email Marketing Stats API. Scoped to the token's account, so no accountId is required. */ diff --git a/src/lib/api/SubscriptionTopics.ts b/src/lib/api/SubscriptionTopics.ts new file mode 100644 index 00000000..70c11d1a --- /dev/null +++ b/src/lib/api/SubscriptionTopics.ts @@ -0,0 +1,15 @@ +import { AxiosInstance } from "axios"; + +import SubscriptionTopicsApi from "./resources/SubscriptionTopics"; + +export default class SubscriptionTopicsBaseAPI { + public getList: SubscriptionTopicsApi["getList"]; + + public get: SubscriptionTopicsApi["get"]; + + constructor(client: AxiosInstance) { + const subscriptionTopics = new SubscriptionTopicsApi(client); + this.getList = subscriptionTopics.getList.bind(subscriptionTopics); + this.get = subscriptionTopics.get.bind(subscriptionTopics); + } +} diff --git a/src/lib/api/resources/Contacts.ts b/src/lib/api/resources/Contacts.ts index 6b518ecc..3095cfb5 100644 --- a/src/lib/api/resources/Contacts.ts +++ b/src/lib/api/resources/Contacts.ts @@ -30,7 +30,9 @@ export default class ContactsApi { } /** - * Creates a new contact. + * Creates a new contact. When it is saved but its `subscription_topics` + * are not, the request fails with `503` and a message naming the contact's + * ID: send the topics again in an `update` of that contact. */ public async create(contact: ContactData) { return this.client.post( @@ -40,7 +42,9 @@ export default class ContactsApi { } /** - * Updates an existing contact by ID or email. + * Updates an existing contact by ID or email. When it is saved but its + * `subscription_topics` are not, the request fails with `503`: send them + * again in another update. */ public async update(identifier: string, contact: ContactUpdateData) { const url = `${this.contactsURL}/${identifier}`; diff --git a/src/lib/api/resources/SubscriptionTopics.ts b/src/lib/api/resources/SubscriptionTopics.ts new file mode 100644 index 00000000..e7b1b6b7 --- /dev/null +++ b/src/lib/api/resources/SubscriptionTopics.ts @@ -0,0 +1,59 @@ +import { AxiosInstance } from "axios"; + +import CONFIG from "../../../config"; +import { + GetSubscriptionTopicResponse, + ListSubscriptionTopicsParams, + ListSubscriptionTopicsResponse, +} from "../../../types/api/subscription-topics"; + +const { CLIENT_SETTINGS } = CONFIG; +const { GENERAL_ENDPOINT } = CLIENT_SETTINGS; + +/** + * Subscription Topics API. On an account without subscription topics, both + * methods fail with a `MailtrapError` for the `403` response. + */ +export default class SubscriptionTopicsApi { + private client: AxiosInstance; + + private subscriptionTopicsURL: string; + + constructor(client: AxiosInstance) { + this.client = client; + // Token-scoped: the account is resolved from the API token server-side, + // so the path takes no account id. + this.subscriptionTopicsURL = `${GENERAL_ENDPOINT}/api/subscription_topics`; + } + + /** + * Lists the account's subscription topics, leaving out deleted ones. The + * result is wrapped in a `{ data, pagination }` envelope; pagination is + * page-token based. + */ + public async getList(params?: ListSubscriptionTopicsParams) { + const url = this.subscriptionTopicsURL; + const query = { + ...(params?.per_page != null && { per_page: params.per_page }), + ...(params?.token != null && { token: params.token }), + }; + + return this.client.get< + ListSubscriptionTopicsResponse, + ListSubscriptionTopicsResponse + >(url, { params: query }); + } + + /** + * Get a subscription topic by ID. A deleted topic is returned too, with + * `deleted_at` set. + */ + public async get(id: number) { + const url = `${this.subscriptionTopicsURL}/${id}`; + + return this.client.get< + GetSubscriptionTopicResponse, + GetSubscriptionTopicResponse + >(url); + } +} diff --git a/src/lib/api/resources/Suppressions.ts b/src/lib/api/resources/Suppressions.ts index 5d9e420a..923d1f40 100644 --- a/src/lib/api/resources/Suppressions.ts +++ b/src/lib/api/resources/Suppressions.ts @@ -27,6 +27,9 @@ export default class SuppressionsApi { public async getList(options?: ListOptions) { const params = { ...(options?.email && { email: options.email }), + ...(options?.include_topic_unsubscriptions && { + include_topic_unsubscriptions: true, + }), }; return this.client.get(this.suppressionsURL, { diff --git a/src/types/api/contact-imports.ts b/src/types/api/contact-imports.ts index 86b624fd..48a6ffea 100644 --- a/src/types/api/contact-imports.ts +++ b/src/types/api/contact-imports.ts @@ -1,3 +1,5 @@ +import { ContactSubscriptionTopic } from "./contacts"; + export type ContactImportResponse = { id: number; status: "created" | "started" | "finished" | "failed"; @@ -6,16 +8,23 @@ export type ContactImportResponse = { contacts_over_limit_count?: number; }; +export type ImportContact = { + email: string; + fields?: { + first_name?: string; + last_name?: string; + zip_code?: number; + [key: string]: string | number | undefined; + }; + list_ids_included?: number[]; + list_ids_excluded?: number[]; + /** + * Topic and domain pairs to set; the pairs left out keep their status. The + * import fails with `422` on an account without subscription topics. + */ + subscription_topics?: ContactSubscriptionTopic[]; +}; + export type ImportContactsRequest = { - contacts: { - email: string; - fields?: { - first_name?: string; - last_name?: string; - zip_code?: number; - [key: string]: string | number | undefined; - }; - list_ids_included?: number[]; - list_ids_excluded?: number[]; - }[]; + contacts: ImportContact[]; }; diff --git a/src/types/api/contacts.ts b/src/types/api/contacts.ts index 74f5fa8d..a0408f14 100644 --- a/src/types/api/contacts.ts +++ b/src/types/api/contacts.ts @@ -1,3 +1,14 @@ +export type SubscriptionTopicStatus = "subscribed" | "unsubscribed"; + +/** A contact's status for one subscription topic on one domain. */ +export interface ContactSubscriptionTopic { + /** ID of the topic, as returned by `client.subscriptionTopics`. */ + subscription_topic_id: number; + /** ID of the domain, as returned by `client.domains`. */ + domain_id: number; + status: SubscriptionTopicStatus; +} + export interface Contact { id: string; email: string; @@ -6,6 +17,11 @@ export interface Contact { list_ids: number[]; status: "subscribed" | "unsubscribed"; fields: Record; + /** + * One entry per topic and domain. Absent on an account without + * subscription topics; `null` when they couldn't be read, so retry later. + */ + subscription_topics?: ContactSubscriptionTopic[] | null; } export interface ContactData { @@ -13,6 +29,11 @@ export interface ContactData { fields?: Record; list_ids?: number[]; unsubscribed?: boolean; + /** + * Topic and domain pairs to set; the pairs left out keep their status. The + * request fails with `422` on an account without subscription topics. + */ + subscription_topics?: ContactSubscriptionTopic[]; } export interface ContactUpdateData extends ContactData { diff --git a/src/types/api/email-campaigns.ts b/src/types/api/email-campaigns.ts index 52b6ed08..f66be418 100644 --- a/src/types/api/email-campaigns.ts +++ b/src/types/api/email-campaigns.ts @@ -112,6 +112,11 @@ export type EmailCampaign = { delivery_mode: DeliveryMode; delivery_options: DeliveryOptions; template: CampaignTemplate; + /** + * ID of the campaign's subscription topic, as returned by + * `client.subscriptionTopics`; `null` when it has none. + */ + subscription_topic_id: number | null; }; export type ListEmailCampaignsParams = { @@ -135,6 +140,12 @@ export type CreateEmailCampaignParams = { delivery_options?: DeliveryOptions; contact_list_ids?: number[]; contact_segment_ids?: number[]; + /** + * ID of a subscription topic, as returned by `client.subscriptionTopics`. + * The topic must cover the campaign's domain. Ignored on an account without + * subscription topics. + */ + subscription_topic_id?: number; }; export type UpdateEmailCampaignParams = { @@ -149,6 +160,11 @@ export type UpdateEmailCampaignParams = { delivery_options?: DeliveryOptions; contact_list_ids?: number[]; contact_segment_ids?: number[]; + /** + * ID of a subscription topic, as returned by `client.subscriptionTopics`. + * A campaign's topic can be changed but not removed. + */ + subscription_topic_id?: number; }; export type ScheduleEmailCampaignParams = { diff --git a/src/types/api/email-logs.ts b/src/types/api/email-logs.ts index 81708987..b7d851de 100644 --- a/src/types/api/email-logs.ts +++ b/src/types/api/email-logs.ts @@ -45,6 +45,7 @@ export type EmailLogMessageEvent = | EmailLogMessageEventBounce | EmailLogMessageEventSpam | EmailLogMessageEventUnsubscribe + | EmailLogMessageEventTopicSubscription | EmailLogMessageEventReject; export type EmailLogMessageEventDeliveryDetails = { @@ -115,6 +116,18 @@ export type EmailLogMessageEventUnsubscribe = { details: EmailLogMessageEventUnsubscribeDetails; }; +export type EmailLogMessageEventTopicSubscriptionDetails = { + web_ip_address: string | null; + subscription_topic_id: number | null; +}; + +/** The recipient unsubscribed from, or resubscribed to, one subscription topic. */ +export type EmailLogMessageEventTopicSubscription = { + event_type: "topic_unsubscribe" | "topic_resubscribe"; + created_at: string; + details: EmailLogMessageEventTopicSubscriptionDetails; +}; + export type EmailLogMessageEventRejectDetails = { reject_reason: string | null; }; diff --git a/src/types/api/subscription-topics.ts b/src/types/api/subscription-topics.ts new file mode 100644 index 00000000..518e3211 --- /dev/null +++ b/src/types/api/subscription-topics.ts @@ -0,0 +1,38 @@ +import { Pagination } from "./common"; + +export type SubscriptionTopic = { + id: number; + name: string; + description: string | null; + /** + * ID of the domain the topic is limited to, as returned by `client.domains`; + * `null` when the topic covers every domain. + */ + domain_id: number | null; + /** Set on a deleted topic, which only `get` returns; the list leaves it out. */ + deleted_at: string | null; + created_at: string; + updated_at: string; +}; + +export type ListSubscriptionTopicsParams = { + /** + * Page number to retrieve (page-token pagination). Defaults to 1. Accepts + * `pagination.next_token` as is; `null` is the same as leaving it out. + */ + token?: number | null; + /** + * Number of topics per page. Maximum 100, defaults to 50. Pass the same + * value on every page. + */ + per_page?: number | null; +}; + +export type ListSubscriptionTopicsResponse = { + data: SubscriptionTopic[]; + pagination: Pagination; +}; + +export type GetSubscriptionTopicResponse = { + data: SubscriptionTopic; +}; diff --git a/src/types/api/suppressions.ts b/src/types/api/suppressions.ts index e95a72b6..5cd06766 100644 --- a/src/types/api/suppressions.ts +++ b/src/types/api/suppressions.ts @@ -1,6 +1,17 @@ +/** + * `topic unsubscription` rows are listed only with + * `include_topic_unsubscriptions`, and can't be created or deleted. + */ +export type SuppressionType = + | "hard bounce" + | "spam complaint" + | "unsubscription" + | "manual import" + | "topic unsubscription"; + export type Suppression = { id: string; - type: "hard bounce" | "spam complaint" | "unsubscription" | "manual import"; + type: SuppressionType; created_at: string; email: string; sending_stream: "transactional" | "bulk"; @@ -15,17 +26,24 @@ export type Suppression = { message_recipient_mx_name: string | null; message_sender_email: string | null; message_subject: string | null; + /** The unsubscribed topic of a `topic unsubscription`, otherwise `null`. */ + subscription_topic_id?: number | null; }; export type ListOptions = { email?: string; + /** + * Adds the contacts' unsubscriptions from single subscription topics, as + * `topic unsubscription` rows. Needs a token that can read contacts. + */ + include_topic_unsubscriptions?: boolean; }; export type CreateSuppressionParams = { email: string; domain_id: number; sending_stream: "transactional" | "bulk"; - type?: Suppression["type"]; + type?: Exclude; }; export type CreateSuppressionResponse = { diff --git a/src/types/api/webhooks.ts b/src/types/api/webhooks.ts index 27b8773c..5fb5b8c9 100644 --- a/src/types/api/webhooks.ts +++ b/src/types/api/webhooks.ts @@ -8,6 +8,11 @@ export type PayloadFormat = "json" | "jsonlines"; export type SendingStream = "transactional" | "bulk"; +/** + * `subscription_preferences_update` (a contact changed their subscription + * topic preferences) applies only to `email_sending` webhooks on the `bulk` + * stream and to `campaigns` webhooks. + */ export type WebhookEventType = | "delivery" | "soft_bounce" @@ -17,7 +22,8 @@ export type WebhookEventType = | "open" | "spam_complaint" | "click" - | "reject"; + | "reject" + | "subscription_preferences_update"; export type Webhook = { id: number; From 9ac8756beea1a1f653d5c78fcd1679f49ebc5189 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:27:55 +0100 Subject: [PATCH 2/3] Share page-token list params between templates and subscription topics Decisions: - ListTemplatesParams and ListSubscriptionTopicsParams were word-for-word copies; one PageTokenParams in the shared types keeps the pagination contract in one place - Examples: drop a log line the full campaign dump already prints, and fetch 100 topics per page in the fetch-all loop Co-Authored-By: Claude Opus 5.5 --- examples/email-campaigns/everything.ts | 1 - examples/subscription-topics/everything.ts | 2 +- src/types/api/common.ts | 14 ++++++++++++++ src/types/api/subscription-topics.ts | 15 ++------------- src/types/api/templates.ts | 15 ++------------- 5 files changed, 19 insertions(+), 28 deletions(-) diff --git a/examples/email-campaigns/everything.ts b/examples/email-campaigns/everything.ts index eeaa295f..ef3fb0df 100644 --- a/examples/email-campaigns/everything.ts +++ b/examples/email-campaigns/everything.ts @@ -65,7 +65,6 @@ async function emailCampaignsFlow() { }), }); console.log("Created campaign:", JSON.stringify(created.data, null, 2)); - console.log("Subscription topic:", created.data.subscription_topic_id); const campaignId = created.data.id; diff --git a/examples/subscription-topics/everything.ts b/examples/subscription-topics/everything.ts index 61e4197b..63b4cd23 100644 --- a/examples/subscription-topics/everything.ts +++ b/examples/subscription-topics/everything.ts @@ -19,7 +19,7 @@ async function subscriptionTopicsFlow() { let token: number | null = 1; while (token !== null) { const page = await client.subscriptionTopics.getList({ - per_page: 50, + per_page: 100, token, }); topics.push(...page.data); diff --git a/src/types/api/common.ts b/src/types/api/common.ts index 439ab3fb..598a5811 100644 --- a/src/types/api/common.ts +++ b/src/types/api/common.ts @@ -11,3 +11,17 @@ export type Pagination = { current_url: string; next_url: string | null; }; + +/** Query params of a list endpoint with page-token pagination. */ +export type PageTokenParams = { + /** + * Page number to retrieve. Defaults to 1. Accepts `pagination.next_token` + * as is; `null` is the same as leaving it out. + */ + token?: number | null; + /** + * Number of items per page. Maximum 100, defaults to 50. Pass the same + * value on every page. + */ + per_page?: number | null; +}; diff --git a/src/types/api/subscription-topics.ts b/src/types/api/subscription-topics.ts index 518e3211..57581f78 100644 --- a/src/types/api/subscription-topics.ts +++ b/src/types/api/subscription-topics.ts @@ -1,4 +1,4 @@ -import { Pagination } from "./common"; +import { PageTokenParams, Pagination } from "./common"; export type SubscriptionTopic = { id: number; @@ -15,18 +15,7 @@ export type SubscriptionTopic = { updated_at: string; }; -export type ListSubscriptionTopicsParams = { - /** - * Page number to retrieve (page-token pagination). Defaults to 1. Accepts - * `pagination.next_token` as is; `null` is the same as leaving it out. - */ - token?: number | null; - /** - * Number of topics per page. Maximum 100, defaults to 50. Pass the same - * value on every page. - */ - per_page?: number | null; -}; +export type ListSubscriptionTopicsParams = PageTokenParams; export type ListSubscriptionTopicsResponse = { data: SubscriptionTopic[]; diff --git a/src/types/api/templates.ts b/src/types/api/templates.ts index e900e80b..f534962d 100644 --- a/src/types/api/templates.ts +++ b/src/types/api/templates.ts @@ -1,4 +1,4 @@ -import { Pagination } from "./common"; +import { PageTokenParams, Pagination } from "./common"; export type Template = { id: number; @@ -14,18 +14,7 @@ export type Template = { updated_at: string; }; -export type ListTemplatesParams = { - /** - * Page number to retrieve (page-token pagination). Defaults to 1. Accepts - * `pagination.next_token` as is; `null` is the same as leaving it out. - */ - token?: number | null; - /** - * Number of templates per page. Maximum 100, defaults to 50. Pass the same - * value on every page. - */ - per_page?: number | null; -}; +export type ListTemplatesParams = PageTokenParams; export type CreateTemplateParams = { name: string; From 0ae67422f7e6ba5d5faca2b6add41f70bff71c34 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:39:11 +0100 Subject: [PATCH 3/3] Search every page for a campaign's subscription topic in the example Decisions: - The helper promised undefined only when no topic covers the domain, but it read the first 100 topics only, so a match on a later page was missed Co-Authored-By: Claude Opus 5.5 --- examples/email-campaigns/everything.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/examples/email-campaigns/everything.ts b/examples/email-campaigns/everything.ts index ef3fb0df..aa974863 100644 --- a/examples/email-campaigns/everything.ts +++ b/examples/email-campaigns/everything.ts @@ -18,10 +18,19 @@ const isForbidden = (error: unknown) => // the account has no such topic, or no subscription topics at all. async function findSubscriptionTopicId(domainId: number) { try { - const topics = await client.subscriptionTopics.getList({ per_page: 100 }); - return topics.data.find( - (topic) => topic.domain_id === null || topic.domain_id === domainId - )?.id; + let token: number | null = 1; + while (token !== null) { + const page = await client.subscriptionTopics.getList({ + per_page: 100, + token, + }); + const topic = page.data.find( + ({ domain_id }) => domain_id === null || domain_id === domainId + ); + if (topic) return topic.id; + token = page.pagination.next_token; + } + return undefined; } catch (error) { if (isForbidden(error)) return undefined; throw error;