@sdflc/backend-helpers 1.0.143 → 1.0.144

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,6 +32,8 @@ A comprehensive backend framework for Node.js applications providing database ac
32
32
  - [TwilioGw](#twiliogw)
33
33
  - [SlackWebhookGw](#slackwebhookgw)
34
34
  - [DiscordWebhookGw](#discordwebhookgw)
35
+ - [HubSpotGw](#hubspotgw)
36
+ - [MailchimpGw](#mailchimpgw)
35
37
  - [HttpWebhookGw](#httpwebhookgw)
36
38
  - [Outbound URL safety](#outbound-url-safety)
37
39
  - [Testing a gateway](#testing-a-gateway)
@@ -1211,6 +1213,8 @@ request). `configure()` **replaces** the settings; it never merges them.
1211
1213
  | [`TwilioGw`](#twiliogw) | `accountSid`, `authToken`, `from?`, `messagingServiceSid?` | `sendMessage(message)` | `{ sid, status }` |
1212
1214
  | [`SlackWebhookGw`](#slackwebhookgw) | `webhookUrl` | `postMessage(message)` | `{ messageId: null }` |
1213
1215
  | [`DiscordWebhookGw`](#discordwebhookgw) | `webhookUrl`, `username?`, `avatarUrl?` | `postMessage(message)` | `{ messageId }` |
1216
+ | [`HubSpotGw`](#hubspotgw) | `accessToken` | `upsertContact(contact)`, `addToList`, `addNote`, `listStaticLists`, `getList`, `verify` | `{ contactId, created }` … |
1217
+ | [`MailchimpGw`](#mailchimpgw) | `apiKey` | `upsertMember(audienceId, member)`, `addTags`, `addNote`, `listAudiences`, `getAudience` | `{ memberId, status }` … |
1214
1218
  | [`HttpWebhookGw`](#httpwebhookgw) | `url`, `method?`, `headers?`, `signingSecret?` | `send(request)` | `{ status, body }` |
1215
1219
 
1216
1220
  Every operation answers the same way:
@@ -1330,6 +1334,45 @@ await discord.postMessage({ content: 'Deployed', embeds: [{ title: 'v1.2', color
1330
1334
  - **Nobody is pinged** unless `allowedMentions` says so: `@everyone` in a text stays text.
1331
1335
  - An unknown webhook or a bad webhook token is not retried. The webhook URL is scrubbed out of everything returned.
1332
1336
 
1337
+ ### HubSpotGw
1338
+
1339
+ Puts a person into a HubSpot account: a contact made or updated by email, a note on it, membership of a static list.
1340
+
1341
+ ```typescript
1342
+ const hubspot = new HubSpotGw().configure({ accessToken }); // a service key, or a private app token (pat-…)
1343
+
1344
+ const contact = await hubspot.upsertContact({ email, firstName, lastName, phone, company });
1345
+ const contactId = contact.getDataFirst().contactId;
1346
+
1347
+ await hubspot.addToList(listId, [contactId]); // a static list (MANUAL / SNAPSHOT) only
1348
+ await hubspot.addNote(contactId, '<p>Registered for …</p>', new Date());
1349
+ const lists = await hubspot.listStaticLists(); // [{ id, name, processingType }] — the contact lists that take members
1350
+ ```
1351
+
1352
+ - One upsert by email: only the values given are written — an empty one never blanks what HubSpot holds.
1353
+ - Scopes the key needs: `crm.objects.contacts.read` / `.write`, `crm.lists.read` / `.write`.
1354
+ - `verify()` reads one contact (nothing is written). The token is scrubbed out of everything returned.
1355
+
1356
+ ### MailchimpGw
1357
+
1358
+ Puts a person into a Mailchimp audience: a member added or updated by email, tags, a note, and the audiences to choose
1359
+ from. The data centre is read from the key (`…-us21` → `https://us21.api.mailchimp.com/3.0`).
1360
+
1361
+ ```typescript
1362
+ const mailchimp = new MailchimpGw().configure({ apiKey });
1363
+
1364
+ await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME, LNAME }, statusIfNew: 'transactional' });
1365
+ await mailchimp.addTags(audienceId, email, ['Volunteers']); // added; made in the audience when new
1366
+ await mailchimp.addNote(audienceId, email, 'Signed up to volunteer …'); // cut to Mailchimp's 1,000 characters
1367
+ const audiences = await mailchimp.listAudiences(); // [{ id, name, memberCount }]
1368
+ ```
1369
+
1370
+ - **An existing member's subscription is never changed**: only `status_if_new` is sent (`transactional` by default —
1371
+ on the audience, not subscribed to marketing; `pending` sends a confirmation email; `subscribed` only with consent).
1372
+ - Required merge fields the host added are not demanded (`skip_merge_validation`); an audience id that could leave the
1373
+ path is refused before sending. The key (and the Basic header made of it) is scrubbed out of everything returned.
1374
+ - Pure helpers: `mailchimpDataCenterOf(apiKey)`, `mailchimpSubscriberHash(email)`.
1375
+
1333
1376
  ### HttpWebhookGw
1334
1377
 
1335
1378
  Sends JSON to any URL, for anything without a gateway of its own, optionally **signed**.
@@ -2481,6 +2524,8 @@ START_READY_TIMEOUT_MS; // 60000: startService alerts when the server is not lis
2481
2524
  | `TwilioSettings` / `TwilioMessage` | `TwilioGw` settings and message |
2482
2525
  | `SlackWebhookSettings` / `SlackMessage` | `SlackWebhookGw` settings and message |
2483
2526
  | `DiscordWebhookSettings` / `DiscordMessage` / `DiscordEmbed` | `DiscordWebhookGw` settings, message and embed |
2527
+ | `HubSpotSettings` / `HubSpotContact` / `HubSpotList` | `HubSpotGw` settings, a contact, a static list |
2528
+ | `MailchimpSettings` / `MailchimpMember` / `MailchimpAudience` / `MailchimpStatusIfNew` | `MailchimpGw` settings, a member, an audience, a new member's subscription |
2484
2529
  | `HttpWebhookSettings` / `HttpWebhookSend` / `HttpWebhookGwProps` | `HttpWebhookGw` settings, one send, and its constructor props (`allowPrivateNetwork`, `lookup`, `dnsLookup`) |
2485
2530
  | `ExternalUrlOptions` | Options for `checkExternalUrl()`: `{ protocols?, lookup?, field? }` |
2486
2531
  | `GuardedFetchOptions` | Options for `createGuardedFetch()`: `{ dnsLookup?, isBlocked? }` |
@@ -0,0 +1,46 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface HubSpotSettings {
5
+ /** A service key or a private app token (`pat-na1-…`). */
6
+ accessToken: string;
7
+ }
8
+ export interface HubSpotContact {
9
+ /** The contact is found — or made — by this. */
10
+ email: string;
11
+ firstName?: string | null;
12
+ lastName?: string | null;
13
+ phone?: string | null;
14
+ company?: string | null;
15
+ }
16
+ /** A static list as `listStaticLists` returns it. */
17
+ export interface HubSpotList {
18
+ id: string;
19
+ name: string;
20
+ processingType: string;
21
+ }
22
+ export declare const HUBSPOT_API_URL = "https://api.hubapi.com";
23
+ declare class HubSpotGw extends BaseExternalApiGateway<HubSpotSettings> {
24
+ constructor(props?: BaseExternalApiGatewayPropsInterface<HubSpotSettings>);
25
+ protected validateSettings(settings: Partial<HubSpotSettings>): string[];
26
+ protected secretValues(): string[];
27
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
28
+ protected errorMessageOf(reply: ExternalApiReply): string;
29
+ private call;
30
+ /**
31
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
32
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
33
+ */
34
+ upsertContact(contact: HubSpotContact): Promise<OpResult>;
35
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
36
+ addToList(listId: string, contactIds: string[]): Promise<OpResult>;
37
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
38
+ addNote(contactId: string, body: string, at?: Date): Promise<OpResult>;
39
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
40
+ listStaticLists(query?: string): Promise<OpResult>;
41
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
42
+ getList(listId: string): Promise<OpResult>;
43
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
44
+ verify(): Promise<OpResult>;
45
+ }
46
+ export { HubSpotGw };
@@ -0,0 +1,181 @@
1
+ // ./src/gateways/HubSpotGw.ts
2
+ //
3
+ // HubSpot's CRM (https://developers.hubspot.com/docs/api-reference) — the calls that put a person into a host's HubSpot:
4
+ // a contact created or updated by email, a note on it, and membership of a static list.
5
+ //
6
+ // const hubspot = new HubSpotGw().configure({ accessToken });
7
+ // const contact = await hubspot.upsertContact({ email, firstName, lastName });
8
+ // await hubspot.addToList(listId, [contact.getDataFirst().contactId]);
9
+ // await hubspot.addNote(contact.getDataFirst().contactId, '<p>Registered for …</p>');
10
+ //
11
+ // The token is a SERVICE KEY (HubSpot › Development › Keys › Service keys) or a legacy private app's token — both are
12
+ // sent as `Authorization: Bearer pat-…`. The scopes it needs: crm.objects.contacts.read / .write (contacts and their
13
+ // notes), crm.lists.read / .write (static lists).
14
+ //
15
+ // ⚠ The token IS the credential — it is scrubbed out of every error.
16
+ // ⚠ Only a static list (processingType MANUAL or SNAPSHOT) takes members; HubSpot refuses a dynamic one.
17
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
18
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
19
+ export const HUBSPOT_API_URL = 'https://api.hubapi.com';
20
+ /** The association type of a note to a contact (HUBSPOT_DEFINED). */
21
+ const NOTE_TO_CONTACT = 202;
22
+ /** The contacts object type (lists name it so). */
23
+ const CONTACTS_OBJECT_TYPE = '0-1';
24
+ /** The list types that take members by id. */
25
+ const STATIC_PROCESSING_TYPES = ['MANUAL', 'SNAPSHOT'];
26
+ const text = (value) => String(value ?? '').trim();
27
+ class HubSpotGw extends BaseExternalApiGateway {
28
+ constructor(props) {
29
+ super({ baseUrl: HUBSPOT_API_URL, ...(props ?? {}) });
30
+ }
31
+ validateSettings(settings) {
32
+ return /^[A-Za-z0-9._-]{20,256}$/.test(text(settings.accessToken))
33
+ ? []
34
+ : ['the access token is missing or not a HubSpot one (pat-…)'];
35
+ }
36
+ secretValues() {
37
+ return [text(this.settings.accessToken)];
38
+ }
39
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
40
+ errorMessageOf(reply) {
41
+ const body = reply.body;
42
+ if (body && typeof body === 'object') {
43
+ return [body.category, body.message].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
44
+ }
45
+ return super.errorMessageOf(reply);
46
+ }
47
+ call(method, path, json) {
48
+ return this.requestWithRetries({
49
+ url: `${this.baseUrl}${path}`,
50
+ method,
51
+ headers: { Authorization: `Bearer ${text(this.settings.accessToken)}`, Accept: 'application/json' },
52
+ ...(json === undefined ? {} : { json }),
53
+ });
54
+ }
55
+ /**
56
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
57
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
58
+ */
59
+ async upsertContact(contact) {
60
+ if (!this.isConfigured()) {
61
+ return this.notConfigured();
62
+ }
63
+ const email = text(contact?.email).toLowerCase();
64
+ if (!email.includes('@')) {
65
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The contact has no email');
66
+ }
67
+ const properties = { email };
68
+ const given = [
69
+ ['firstname', contact.firstName],
70
+ ['lastname', contact.lastName],
71
+ ['phone', contact.phone],
72
+ ['company', contact.company],
73
+ ];
74
+ for (const [name, value] of given) {
75
+ if (text(value)) {
76
+ properties[name] = text(value);
77
+ }
78
+ }
79
+ const result = await this.call('POST', '/crm/v3/objects/contacts/batch/upsert', {
80
+ inputs: [{ idProperty: 'email', id: email, properties }],
81
+ });
82
+ if (result.didFail()) {
83
+ return result;
84
+ }
85
+ const row = result.getDataFirst()?.body?.results?.[0] ?? null;
86
+ if (!row?.id) {
87
+ return OpResult.fail(OP_RESULT_CODES.FAILED, [result.getDataFirst()], 'HubSpot answered without the contact');
88
+ }
89
+ return OpResult.ok([{ contactId: String(row.id), created: row.new === true }]);
90
+ }
91
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
92
+ async addToList(listId, contactIds) {
93
+ if (!this.isConfigured()) {
94
+ return this.notConfigured();
95
+ }
96
+ const id = text(listId);
97
+ const ids = (contactIds ?? []).map(text).filter(Boolean);
98
+ if (!/^\d{1,20}$/.test(id) || ids.length === 0) {
99
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id (a number) and at least one contact are needed');
100
+ }
101
+ const result = await this.call('PUT', `/crm/v3/lists/${id}/memberships/add`, ids);
102
+ return result.didFail()
103
+ ? result
104
+ : OpResult.ok([{ listId: id, added: result.getDataFirst()?.body?.recordIdsAdded ?? ids }]);
105
+ }
106
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
107
+ async addNote(contactId, body, at = new Date()) {
108
+ if (!this.isConfigured()) {
109
+ return this.notConfigured();
110
+ }
111
+ if (!text(contactId) || !text(body)) {
112
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A contact and the note are needed');
113
+ }
114
+ const result = await this.call('POST', '/crm/v3/objects/notes', {
115
+ properties: { hs_timestamp: at.toISOString(), hs_note_body: String(body) },
116
+ associations: [
117
+ {
118
+ to: { id: text(contactId) },
119
+ types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: NOTE_TO_CONTACT }],
120
+ },
121
+ ],
122
+ });
123
+ return result.didFail() ? result : OpResult.ok([{ noteId: String(result.getDataFirst()?.body?.id ?? '') || null }]);
124
+ }
125
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
126
+ async listStaticLists(query = '') {
127
+ if (!this.isConfigured()) {
128
+ return this.notConfigured();
129
+ }
130
+ // ⓘ The schema names listIds and additionalProperties as required: empty — no filter by id, no extra properties.
131
+ const result = await this.call('POST', '/crm/v3/lists/search', {
132
+ query: text(query),
133
+ processingTypes: STATIC_PROCESSING_TYPES,
134
+ listIds: [],
135
+ additionalProperties: [],
136
+ count: 500,
137
+ offset: 0,
138
+ });
139
+ if (result.didFail()) {
140
+ return result;
141
+ }
142
+ const lists = (result.getDataFirst()?.body?.lists ?? [])
143
+ .filter((l) => String(l?.objectTypeId ?? CONTACTS_OBJECT_TYPE) === CONTACTS_OBJECT_TYPE &&
144
+ STATIC_PROCESSING_TYPES.includes(String(l?.processingType)))
145
+ .map((l) => ({
146
+ id: String(l.listId),
147
+ name: text(l.name) || String(l.listId),
148
+ processingType: String(l.processingType),
149
+ }))
150
+ .sort((a, b) => a.name.localeCompare(b.name));
151
+ return OpResult.ok(lists);
152
+ }
153
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
154
+ async getList(listId) {
155
+ if (!this.isConfigured()) {
156
+ return this.notConfigured();
157
+ }
158
+ const id = text(listId);
159
+ if (!/^\d{1,20}$/.test(id)) {
160
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id is a number');
161
+ }
162
+ const result = await this.call('GET', `/crm/v3/lists/${id}`);
163
+ if (result.didFail()) {
164
+ return result;
165
+ }
166
+ const list = result.getDataFirst()?.body?.list ?? result.getDataFirst()?.body ?? {};
167
+ const processingType = String(list.processingType ?? '');
168
+ return OpResult.ok([
169
+ { id, name: text(list.name) || id, processingType, isStatic: STATIC_PROCESSING_TYPES.includes(processingType) },
170
+ ]);
171
+ }
172
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
173
+ async verify() {
174
+ if (!this.isConfigured()) {
175
+ return this.notConfigured();
176
+ }
177
+ const result = await this.call('GET', '/crm/v3/objects/contacts?limit=1&archived=false');
178
+ return result.didFail() ? result : OpResult.ok([{ ok: true }]);
179
+ }
180
+ }
181
+ export { HubSpotGw };
@@ -0,0 +1,57 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface MailchimpSettings {
5
+ /** `<32 hex>-<data centre>`, e.g. `…-us21`. */
6
+ apiKey: string;
7
+ }
8
+ /** A new member's subscription. `subscribed` only with the person's consent to marketing email. */
9
+ export type MailchimpStatusIfNew = 'transactional' | 'pending' | 'subscribed';
10
+ export declare const MAILCHIMP_STATUSES_IF_NEW: MailchimpStatusIfNew[];
11
+ export interface MailchimpMember {
12
+ email: string;
13
+ /** By merge tag — FNAME, LNAME (every audience has them unless the host removed them). Empty values are not sent. */
14
+ mergeFields?: Record<string, string | null | undefined>;
15
+ /** Default `transactional`: on the audience, not subscribed to marketing. */
16
+ statusIfNew?: MailchimpStatusIfNew;
17
+ }
18
+ /** An audience as `listAudiences` returns it. */
19
+ export interface MailchimpAudience {
20
+ id: string;
21
+ name: string;
22
+ memberCount: number | null;
23
+ }
24
+ /** Mailchimp's own limit on a note. */
25
+ export declare const MAILCHIMP_NOTE_MAX = 1000;
26
+ /** A tag's name, at most (Mailchimp's limit). */
27
+ export declare const MAILCHIMP_TAG_MAX = 100;
28
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
29
+ export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
30
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
31
+ export declare const mailchimpSubscriberHash: (email: string) => string;
32
+ declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
33
+ constructor(props?: BaseExternalApiGatewayPropsInterface<MailchimpSettings>);
34
+ protected validateSettings(settings: Partial<MailchimpSettings>): string[];
35
+ protected secretValues(): string[];
36
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
37
+ protected errorMessageOf(reply: ExternalApiReply): string;
38
+ private call;
39
+ /** An audience id may only be letters and digits — it goes into the path. */
40
+ private badAudience;
41
+ private memberPath;
42
+ /**
43
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
44
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
45
+ * `{ memberId, status }`. Never throws.
46
+ */
47
+ upsertMember(audienceId: string, member: MailchimpMember): Promise<OpResult>;
48
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
49
+ addTags(audienceId: string, email: string, tags: string[]): Promise<OpResult>;
50
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
51
+ addNote(audienceId: string, email: string, note: string): Promise<OpResult>;
52
+ /** The account's audiences (at most 1,000), by name. Never throws. */
53
+ listAudiences(): Promise<OpResult>;
54
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
55
+ getAudience(audienceId: string): Promise<OpResult>;
56
+ }
57
+ export { MailchimpGw };
@@ -0,0 +1,187 @@
1
+ // ./src/gateways/MailchimpGw.ts
2
+ //
3
+ // Mailchimp's Marketing API (https://mailchimp.com/developer/marketing/api/) — the calls that put a person into a host's
4
+ // audience: a member added or updated by email, tags on it, a note on it, and the audiences to choose from.
5
+ //
6
+ // const mailchimp = new MailchimpGw().configure({ apiKey });
7
+ // await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME: 'Ann' }, statusIfNew: 'transactional' });
8
+ // await mailchimp.addTags(audienceId, email, ['Volunteers']);
9
+ // await mailchimp.addNote(audienceId, email, 'Signed up to volunteer at …');
10
+ //
11
+ // The API key ends with its data centre (`…-us21`), which names the server: https://us21.api.mailchimp.com/3.0.
12
+ //
13
+ // ⚠ The key IS the credential — it (and the Basic header made of it) is scrubbed out of every error.
14
+ // ⚠ An existing member's subscription is never changed: only `status_if_new` is sent, which Mailchimp applies to a NEW
15
+ // member. Someone who unsubscribed stays unsubscribed.
16
+ // ⚠ At most 10 connections at once per Mailchimp user — callers send one member at a time.
17
+ import { createHash } from 'crypto';
18
+ import { Buffer } from 'buffer';
19
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
20
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
21
+ export const MAILCHIMP_STATUSES_IF_NEW = ['transactional', 'pending', 'subscribed'];
22
+ /** Mailchimp's own limit on a note. */
23
+ export const MAILCHIMP_NOTE_MAX = 1000;
24
+ /** A tag's name, at most (Mailchimp's limit). */
25
+ export const MAILCHIMP_TAG_MAX = 100;
26
+ const text = (value) => String(value ?? '').trim();
27
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
28
+ export const mailchimpDataCenterOf = (apiKey) => {
29
+ const match = /^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/i.exec(text(apiKey));
30
+ return match ? match[1].toLowerCase() : null;
31
+ };
32
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
33
+ export const mailchimpSubscriberHash = (email) => createHash('md5').update(text(email).toLowerCase()).digest('hex');
34
+ class MailchimpGw extends BaseExternalApiGateway {
35
+ constructor(props) {
36
+ super(props);
37
+ }
38
+ validateSettings(settings) {
39
+ return mailchimpDataCenterOf(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
40
+ }
41
+ secretValues() {
42
+ const key = text(this.settings.apiKey);
43
+ return [key, Buffer.from(`anystring:${key}`).toString('base64')];
44
+ }
45
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
46
+ errorMessageOf(reply) {
47
+ const body = reply.body;
48
+ if (body && typeof body === 'object') {
49
+ const fields = Array.isArray(body.errors)
50
+ ? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
51
+ : '';
52
+ return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
53
+ }
54
+ return super.errorMessageOf(reply);
55
+ }
56
+ call(method, path, json) {
57
+ const key = text(this.settings.apiKey);
58
+ return this.requestWithRetries({
59
+ url: `https://${mailchimpDataCenterOf(key)}.api.mailchimp.com/3.0${path}`,
60
+ method,
61
+ headers: {
62
+ Authorization: `Basic ${Buffer.from(`anystring:${key}`).toString('base64')}`,
63
+ Accept: 'application/json',
64
+ },
65
+ ...(json === undefined ? {} : { json }),
66
+ });
67
+ }
68
+ /** An audience id may only be letters and digits — it goes into the path. */
69
+ badAudience(audienceId) {
70
+ return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
71
+ ? null
72
+ : OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
73
+ }
74
+ memberPath(audienceId, email) {
75
+ return `/lists/${text(audienceId)}/members/${mailchimpSubscriberHash(email)}`;
76
+ }
77
+ /**
78
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
79
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
80
+ * `{ memberId, status }`. Never throws.
81
+ */
82
+ async upsertMember(audienceId, member) {
83
+ if (!this.isConfigured()) {
84
+ return this.notConfigured();
85
+ }
86
+ const email = text(member?.email).toLowerCase();
87
+ const bad = this.badAudience(audienceId);
88
+ if (bad) {
89
+ return bad;
90
+ }
91
+ if (!email.includes('@')) {
92
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
93
+ }
94
+ const statusIfNew = MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
95
+ ? member.statusIfNew
96
+ : 'transactional';
97
+ const mergeFields = {};
98
+ for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
99
+ if (/^[A-Z0-9_]{1,10}$/.test(tag) && text(value)) {
100
+ mergeFields[tag] = text(value);
101
+ }
102
+ }
103
+ const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
104
+ email_address: email,
105
+ status_if_new: statusIfNew,
106
+ ...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
107
+ });
108
+ if (result.didFail()) {
109
+ return result;
110
+ }
111
+ const body = result.getDataFirst()?.body ?? {};
112
+ return OpResult.ok([
113
+ { memberId: body.id ? String(body.id) : mailchimpSubscriberHash(email), status: body.status ?? null },
114
+ ]);
115
+ }
116
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
117
+ async addTags(audienceId, email, tags) {
118
+ if (!this.isConfigured()) {
119
+ return this.notConfigured();
120
+ }
121
+ const bad = this.badAudience(audienceId);
122
+ const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, MAILCHIMP_TAG_MAX)).filter(Boolean)));
123
+ if (bad) {
124
+ return bad;
125
+ }
126
+ if (!text(email).includes('@') || names.length === 0) {
127
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
128
+ }
129
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
130
+ tags: names.map((name) => ({ name, status: 'active' })),
131
+ });
132
+ return result.didFail() ? result : OpResult.ok([{ tags: names }]);
133
+ }
134
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
135
+ async addNote(audienceId, email, note) {
136
+ if (!this.isConfigured()) {
137
+ return this.notConfigured();
138
+ }
139
+ const bad = this.badAudience(audienceId);
140
+ if (bad) {
141
+ return bad;
142
+ }
143
+ if (!text(email).includes('@') || !text(note)) {
144
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
145
+ }
146
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
147
+ note: String(note).slice(0, MAILCHIMP_NOTE_MAX),
148
+ });
149
+ return result.didFail() ? result : OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
150
+ }
151
+ /** The account's audiences (at most 1,000), by name. Never throws. */
152
+ async listAudiences() {
153
+ if (!this.isConfigured()) {
154
+ return this.notConfigured();
155
+ }
156
+ const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
157
+ if (result.didFail()) {
158
+ return result;
159
+ }
160
+ const audiences = (result.getDataFirst()?.body?.lists ?? [])
161
+ .map((l) => ({
162
+ id: String(l?.id ?? ''),
163
+ name: text(l?.name) || String(l?.id ?? ''),
164
+ memberCount: l?.stats?.member_count ?? null,
165
+ }))
166
+ .filter((l) => !!l.id)
167
+ .sort((a, b) => a.name.localeCompare(b.name));
168
+ return OpResult.ok(audiences);
169
+ }
170
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
171
+ async getAudience(audienceId) {
172
+ if (!this.isConfigured()) {
173
+ return this.notConfigured();
174
+ }
175
+ const bad = this.badAudience(audienceId);
176
+ if (bad) {
177
+ return bad;
178
+ }
179
+ const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
180
+ if (result.didFail()) {
181
+ return result;
182
+ }
183
+ const body = result.getDataFirst()?.body ?? {};
184
+ return OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
185
+ }
186
+ }
187
+ export { MailchimpGw };
@@ -5,5 +5,7 @@ export * from './TelegramGw';
5
5
  export * from './TwilioGw';
6
6
  export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
+ export * from './HubSpotGw';
9
+ export * from './MailchimpGw';
8
10
  export * from './HttpWebhookGw';
9
11
  export * from './guardedFetch';
@@ -5,5 +5,7 @@ export * from './TelegramGw';
5
5
  export * from './TwilioGw';
6
6
  export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
+ export * from './HubSpotGw';
9
+ export * from './MailchimpGw';
8
10
  export * from './HttpWebhookGw';
9
11
  export * from './guardedFetch';
@@ -0,0 +1,46 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface HubSpotSettings {
5
+ /** A service key or a private app token (`pat-na1-…`). */
6
+ accessToken: string;
7
+ }
8
+ export interface HubSpotContact {
9
+ /** The contact is found — or made — by this. */
10
+ email: string;
11
+ firstName?: string | null;
12
+ lastName?: string | null;
13
+ phone?: string | null;
14
+ company?: string | null;
15
+ }
16
+ /** A static list as `listStaticLists` returns it. */
17
+ export interface HubSpotList {
18
+ id: string;
19
+ name: string;
20
+ processingType: string;
21
+ }
22
+ export declare const HUBSPOT_API_URL = "https://api.hubapi.com";
23
+ declare class HubSpotGw extends BaseExternalApiGateway<HubSpotSettings> {
24
+ constructor(props?: BaseExternalApiGatewayPropsInterface<HubSpotSettings>);
25
+ protected validateSettings(settings: Partial<HubSpotSettings>): string[];
26
+ protected secretValues(): string[];
27
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
28
+ protected errorMessageOf(reply: ExternalApiReply): string;
29
+ private call;
30
+ /**
31
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
32
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
33
+ */
34
+ upsertContact(contact: HubSpotContact): Promise<OpResult>;
35
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
36
+ addToList(listId: string, contactIds: string[]): Promise<OpResult>;
37
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
38
+ addNote(contactId: string, body: string, at?: Date): Promise<OpResult>;
39
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
40
+ listStaticLists(query?: string): Promise<OpResult>;
41
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
42
+ getList(listId: string): Promise<OpResult>;
43
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
44
+ verify(): Promise<OpResult>;
45
+ }
46
+ export { HubSpotGw };
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HubSpotGw = exports.HUBSPOT_API_URL = void 0;
4
+ // ./src/gateways/HubSpotGw.ts
5
+ //
6
+ // HubSpot's CRM (https://developers.hubspot.com/docs/api-reference) — the calls that put a person into a host's HubSpot:
7
+ // a contact created or updated by email, a note on it, and membership of a static list.
8
+ //
9
+ // const hubspot = new HubSpotGw().configure({ accessToken });
10
+ // const contact = await hubspot.upsertContact({ email, firstName, lastName });
11
+ // await hubspot.addToList(listId, [contact.getDataFirst().contactId]);
12
+ // await hubspot.addNote(contact.getDataFirst().contactId, '<p>Registered for …</p>');
13
+ //
14
+ // The token is a SERVICE KEY (HubSpot › Development › Keys › Service keys) or a legacy private app's token — both are
15
+ // sent as `Authorization: Bearer pat-…`. The scopes it needs: crm.objects.contacts.read / .write (contacts and their
16
+ // notes), crm.lists.read / .write (static lists).
17
+ //
18
+ // ⚠ The token IS the credential — it is scrubbed out of every error.
19
+ // ⚠ Only a static list (processingType MANUAL or SNAPSHOT) takes members; HubSpot refuses a dynamic one.
20
+ const api_helpers_1 = require("@sdflc/api-helpers");
21
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
22
+ exports.HUBSPOT_API_URL = 'https://api.hubapi.com';
23
+ /** The association type of a note to a contact (HUBSPOT_DEFINED). */
24
+ const NOTE_TO_CONTACT = 202;
25
+ /** The contacts object type (lists name it so). */
26
+ const CONTACTS_OBJECT_TYPE = '0-1';
27
+ /** The list types that take members by id. */
28
+ const STATIC_PROCESSING_TYPES = ['MANUAL', 'SNAPSHOT'];
29
+ const text = (value) => String(value ?? '').trim();
30
+ class HubSpotGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
31
+ constructor(props) {
32
+ super({ baseUrl: exports.HUBSPOT_API_URL, ...(props ?? {}) });
33
+ }
34
+ validateSettings(settings) {
35
+ return /^[A-Za-z0-9._-]{20,256}$/.test(text(settings.accessToken))
36
+ ? []
37
+ : ['the access token is missing or not a HubSpot one (pat-…)'];
38
+ }
39
+ secretValues() {
40
+ return [text(this.settings.accessToken)];
41
+ }
42
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
43
+ errorMessageOf(reply) {
44
+ const body = reply.body;
45
+ if (body && typeof body === 'object') {
46
+ return [body.category, body.message].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
47
+ }
48
+ return super.errorMessageOf(reply);
49
+ }
50
+ call(method, path, json) {
51
+ return this.requestWithRetries({
52
+ url: `${this.baseUrl}${path}`,
53
+ method,
54
+ headers: { Authorization: `Bearer ${text(this.settings.accessToken)}`, Accept: 'application/json' },
55
+ ...(json === undefined ? {} : { json }),
56
+ });
57
+ }
58
+ /**
59
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
60
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
61
+ */
62
+ async upsertContact(contact) {
63
+ if (!this.isConfigured()) {
64
+ return this.notConfigured();
65
+ }
66
+ const email = text(contact?.email).toLowerCase();
67
+ if (!email.includes('@')) {
68
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The contact has no email');
69
+ }
70
+ const properties = { email };
71
+ const given = [
72
+ ['firstname', contact.firstName],
73
+ ['lastname', contact.lastName],
74
+ ['phone', contact.phone],
75
+ ['company', contact.company],
76
+ ];
77
+ for (const [name, value] of given) {
78
+ if (text(value)) {
79
+ properties[name] = text(value);
80
+ }
81
+ }
82
+ const result = await this.call('POST', '/crm/v3/objects/contacts/batch/upsert', {
83
+ inputs: [{ idProperty: 'email', id: email, properties }],
84
+ });
85
+ if (result.didFail()) {
86
+ return result;
87
+ }
88
+ const row = result.getDataFirst()?.body?.results?.[0] ?? null;
89
+ if (!row?.id) {
90
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, [result.getDataFirst()], 'HubSpot answered without the contact');
91
+ }
92
+ return api_helpers_1.OpResult.ok([{ contactId: String(row.id), created: row.new === true }]);
93
+ }
94
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
95
+ async addToList(listId, contactIds) {
96
+ if (!this.isConfigured()) {
97
+ return this.notConfigured();
98
+ }
99
+ const id = text(listId);
100
+ const ids = (contactIds ?? []).map(text).filter(Boolean);
101
+ if (!/^\d{1,20}$/.test(id) || ids.length === 0) {
102
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id (a number) and at least one contact are needed');
103
+ }
104
+ const result = await this.call('PUT', `/crm/v3/lists/${id}/memberships/add`, ids);
105
+ return result.didFail()
106
+ ? result
107
+ : api_helpers_1.OpResult.ok([{ listId: id, added: result.getDataFirst()?.body?.recordIdsAdded ?? ids }]);
108
+ }
109
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
110
+ async addNote(contactId, body, at = new Date()) {
111
+ if (!this.isConfigured()) {
112
+ return this.notConfigured();
113
+ }
114
+ if (!text(contactId) || !text(body)) {
115
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A contact and the note are needed');
116
+ }
117
+ const result = await this.call('POST', '/crm/v3/objects/notes', {
118
+ properties: { hs_timestamp: at.toISOString(), hs_note_body: String(body) },
119
+ associations: [
120
+ {
121
+ to: { id: text(contactId) },
122
+ types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: NOTE_TO_CONTACT }],
123
+ },
124
+ ],
125
+ });
126
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: String(result.getDataFirst()?.body?.id ?? '') || null }]);
127
+ }
128
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
129
+ async listStaticLists(query = '') {
130
+ if (!this.isConfigured()) {
131
+ return this.notConfigured();
132
+ }
133
+ // ⓘ The schema names listIds and additionalProperties as required: empty — no filter by id, no extra properties.
134
+ const result = await this.call('POST', '/crm/v3/lists/search', {
135
+ query: text(query),
136
+ processingTypes: STATIC_PROCESSING_TYPES,
137
+ listIds: [],
138
+ additionalProperties: [],
139
+ count: 500,
140
+ offset: 0,
141
+ });
142
+ if (result.didFail()) {
143
+ return result;
144
+ }
145
+ const lists = (result.getDataFirst()?.body?.lists ?? [])
146
+ .filter((l) => String(l?.objectTypeId ?? CONTACTS_OBJECT_TYPE) === CONTACTS_OBJECT_TYPE &&
147
+ STATIC_PROCESSING_TYPES.includes(String(l?.processingType)))
148
+ .map((l) => ({
149
+ id: String(l.listId),
150
+ name: text(l.name) || String(l.listId),
151
+ processingType: String(l.processingType),
152
+ }))
153
+ .sort((a, b) => a.name.localeCompare(b.name));
154
+ return api_helpers_1.OpResult.ok(lists);
155
+ }
156
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
157
+ async getList(listId) {
158
+ if (!this.isConfigured()) {
159
+ return this.notConfigured();
160
+ }
161
+ const id = text(listId);
162
+ if (!/^\d{1,20}$/.test(id)) {
163
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id is a number');
164
+ }
165
+ const result = await this.call('GET', `/crm/v3/lists/${id}`);
166
+ if (result.didFail()) {
167
+ return result;
168
+ }
169
+ const list = result.getDataFirst()?.body?.list ?? result.getDataFirst()?.body ?? {};
170
+ const processingType = String(list.processingType ?? '');
171
+ return api_helpers_1.OpResult.ok([
172
+ { id, name: text(list.name) || id, processingType, isStatic: STATIC_PROCESSING_TYPES.includes(processingType) },
173
+ ]);
174
+ }
175
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
176
+ async verify() {
177
+ if (!this.isConfigured()) {
178
+ return this.notConfigured();
179
+ }
180
+ const result = await this.call('GET', '/crm/v3/objects/contacts?limit=1&archived=false');
181
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ ok: true }]);
182
+ }
183
+ }
184
+ exports.HubSpotGw = HubSpotGw;
@@ -0,0 +1,57 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface MailchimpSettings {
5
+ /** `<32 hex>-<data centre>`, e.g. `…-us21`. */
6
+ apiKey: string;
7
+ }
8
+ /** A new member's subscription. `subscribed` only with the person's consent to marketing email. */
9
+ export type MailchimpStatusIfNew = 'transactional' | 'pending' | 'subscribed';
10
+ export declare const MAILCHIMP_STATUSES_IF_NEW: MailchimpStatusIfNew[];
11
+ export interface MailchimpMember {
12
+ email: string;
13
+ /** By merge tag — FNAME, LNAME (every audience has them unless the host removed them). Empty values are not sent. */
14
+ mergeFields?: Record<string, string | null | undefined>;
15
+ /** Default `transactional`: on the audience, not subscribed to marketing. */
16
+ statusIfNew?: MailchimpStatusIfNew;
17
+ }
18
+ /** An audience as `listAudiences` returns it. */
19
+ export interface MailchimpAudience {
20
+ id: string;
21
+ name: string;
22
+ memberCount: number | null;
23
+ }
24
+ /** Mailchimp's own limit on a note. */
25
+ export declare const MAILCHIMP_NOTE_MAX = 1000;
26
+ /** A tag's name, at most (Mailchimp's limit). */
27
+ export declare const MAILCHIMP_TAG_MAX = 100;
28
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
29
+ export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
30
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
31
+ export declare const mailchimpSubscriberHash: (email: string) => string;
32
+ declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
33
+ constructor(props?: BaseExternalApiGatewayPropsInterface<MailchimpSettings>);
34
+ protected validateSettings(settings: Partial<MailchimpSettings>): string[];
35
+ protected secretValues(): string[];
36
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
37
+ protected errorMessageOf(reply: ExternalApiReply): string;
38
+ private call;
39
+ /** An audience id may only be letters and digits — it goes into the path. */
40
+ private badAudience;
41
+ private memberPath;
42
+ /**
43
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
44
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
45
+ * `{ memberId, status }`. Never throws.
46
+ */
47
+ upsertMember(audienceId: string, member: MailchimpMember): Promise<OpResult>;
48
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
49
+ addTags(audienceId: string, email: string, tags: string[]): Promise<OpResult>;
50
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
51
+ addNote(audienceId: string, email: string, note: string): Promise<OpResult>;
52
+ /** The account's audiences (at most 1,000), by name. Never throws. */
53
+ listAudiences(): Promise<OpResult>;
54
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
55
+ getAudience(audienceId: string): Promise<OpResult>;
56
+ }
57
+ export { MailchimpGw };
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MailchimpGw = exports.mailchimpSubscriberHash = exports.mailchimpDataCenterOf = exports.MAILCHIMP_TAG_MAX = exports.MAILCHIMP_NOTE_MAX = exports.MAILCHIMP_STATUSES_IF_NEW = void 0;
4
+ // ./src/gateways/MailchimpGw.ts
5
+ //
6
+ // Mailchimp's Marketing API (https://mailchimp.com/developer/marketing/api/) — the calls that put a person into a host's
7
+ // audience: a member added or updated by email, tags on it, a note on it, and the audiences to choose from.
8
+ //
9
+ // const mailchimp = new MailchimpGw().configure({ apiKey });
10
+ // await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME: 'Ann' }, statusIfNew: 'transactional' });
11
+ // await mailchimp.addTags(audienceId, email, ['Volunteers']);
12
+ // await mailchimp.addNote(audienceId, email, 'Signed up to volunteer at …');
13
+ //
14
+ // The API key ends with its data centre (`…-us21`), which names the server: https://us21.api.mailchimp.com/3.0.
15
+ //
16
+ // ⚠ The key IS the credential — it (and the Basic header made of it) is scrubbed out of every error.
17
+ // ⚠ An existing member's subscription is never changed: only `status_if_new` is sent, which Mailchimp applies to a NEW
18
+ // member. Someone who unsubscribed stays unsubscribed.
19
+ // ⚠ At most 10 connections at once per Mailchimp user — callers send one member at a time.
20
+ const crypto_1 = require("crypto");
21
+ const buffer_1 = require("buffer");
22
+ const api_helpers_1 = require("@sdflc/api-helpers");
23
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
24
+ exports.MAILCHIMP_STATUSES_IF_NEW = ['transactional', 'pending', 'subscribed'];
25
+ /** Mailchimp's own limit on a note. */
26
+ exports.MAILCHIMP_NOTE_MAX = 1000;
27
+ /** A tag's name, at most (Mailchimp's limit). */
28
+ exports.MAILCHIMP_TAG_MAX = 100;
29
+ const text = (value) => String(value ?? '').trim();
30
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
31
+ const mailchimpDataCenterOf = (apiKey) => {
32
+ const match = /^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/i.exec(text(apiKey));
33
+ return match ? match[1].toLowerCase() : null;
34
+ };
35
+ exports.mailchimpDataCenterOf = mailchimpDataCenterOf;
36
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
37
+ const mailchimpSubscriberHash = (email) => (0, crypto_1.createHash)('md5').update(text(email).toLowerCase()).digest('hex');
38
+ exports.mailchimpSubscriberHash = mailchimpSubscriberHash;
39
+ class MailchimpGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
40
+ constructor(props) {
41
+ super(props);
42
+ }
43
+ validateSettings(settings) {
44
+ return (0, exports.mailchimpDataCenterOf)(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
45
+ }
46
+ secretValues() {
47
+ const key = text(this.settings.apiKey);
48
+ return [key, buffer_1.Buffer.from(`anystring:${key}`).toString('base64')];
49
+ }
50
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
51
+ errorMessageOf(reply) {
52
+ const body = reply.body;
53
+ if (body && typeof body === 'object') {
54
+ const fields = Array.isArray(body.errors)
55
+ ? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
56
+ : '';
57
+ return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
58
+ }
59
+ return super.errorMessageOf(reply);
60
+ }
61
+ call(method, path, json) {
62
+ const key = text(this.settings.apiKey);
63
+ return this.requestWithRetries({
64
+ url: `https://${(0, exports.mailchimpDataCenterOf)(key)}.api.mailchimp.com/3.0${path}`,
65
+ method,
66
+ headers: {
67
+ Authorization: `Basic ${buffer_1.Buffer.from(`anystring:${key}`).toString('base64')}`,
68
+ Accept: 'application/json',
69
+ },
70
+ ...(json === undefined ? {} : { json }),
71
+ });
72
+ }
73
+ /** An audience id may only be letters and digits — it goes into the path. */
74
+ badAudience(audienceId) {
75
+ return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
76
+ ? null
77
+ : api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
78
+ }
79
+ memberPath(audienceId, email) {
80
+ return `/lists/${text(audienceId)}/members/${(0, exports.mailchimpSubscriberHash)(email)}`;
81
+ }
82
+ /**
83
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
84
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
85
+ * `{ memberId, status }`. Never throws.
86
+ */
87
+ async upsertMember(audienceId, member) {
88
+ if (!this.isConfigured()) {
89
+ return this.notConfigured();
90
+ }
91
+ const email = text(member?.email).toLowerCase();
92
+ const bad = this.badAudience(audienceId);
93
+ if (bad) {
94
+ return bad;
95
+ }
96
+ if (!email.includes('@')) {
97
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
98
+ }
99
+ const statusIfNew = exports.MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
100
+ ? member.statusIfNew
101
+ : 'transactional';
102
+ const mergeFields = {};
103
+ for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
104
+ if (/^[A-Z0-9_]{1,10}$/.test(tag) && text(value)) {
105
+ mergeFields[tag] = text(value);
106
+ }
107
+ }
108
+ const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
109
+ email_address: email,
110
+ status_if_new: statusIfNew,
111
+ ...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
112
+ });
113
+ if (result.didFail()) {
114
+ return result;
115
+ }
116
+ const body = result.getDataFirst()?.body ?? {};
117
+ return api_helpers_1.OpResult.ok([
118
+ { memberId: body.id ? String(body.id) : (0, exports.mailchimpSubscriberHash)(email), status: body.status ?? null },
119
+ ]);
120
+ }
121
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
122
+ async addTags(audienceId, email, tags) {
123
+ if (!this.isConfigured()) {
124
+ return this.notConfigured();
125
+ }
126
+ const bad = this.badAudience(audienceId);
127
+ const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, exports.MAILCHIMP_TAG_MAX)).filter(Boolean)));
128
+ if (bad) {
129
+ return bad;
130
+ }
131
+ if (!text(email).includes('@') || names.length === 0) {
132
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
133
+ }
134
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
135
+ tags: names.map((name) => ({ name, status: 'active' })),
136
+ });
137
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ tags: names }]);
138
+ }
139
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
140
+ async addNote(audienceId, email, note) {
141
+ if (!this.isConfigured()) {
142
+ return this.notConfigured();
143
+ }
144
+ const bad = this.badAudience(audienceId);
145
+ if (bad) {
146
+ return bad;
147
+ }
148
+ if (!text(email).includes('@') || !text(note)) {
149
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
150
+ }
151
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
152
+ note: String(note).slice(0, exports.MAILCHIMP_NOTE_MAX),
153
+ });
154
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
155
+ }
156
+ /** The account's audiences (at most 1,000), by name. Never throws. */
157
+ async listAudiences() {
158
+ if (!this.isConfigured()) {
159
+ return this.notConfigured();
160
+ }
161
+ const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
162
+ if (result.didFail()) {
163
+ return result;
164
+ }
165
+ const audiences = (result.getDataFirst()?.body?.lists ?? [])
166
+ .map((l) => ({
167
+ id: String(l?.id ?? ''),
168
+ name: text(l?.name) || String(l?.id ?? ''),
169
+ memberCount: l?.stats?.member_count ?? null,
170
+ }))
171
+ .filter((l) => !!l.id)
172
+ .sort((a, b) => a.name.localeCompare(b.name));
173
+ return api_helpers_1.OpResult.ok(audiences);
174
+ }
175
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
176
+ async getAudience(audienceId) {
177
+ if (!this.isConfigured()) {
178
+ return this.notConfigured();
179
+ }
180
+ const bad = this.badAudience(audienceId);
181
+ if (bad) {
182
+ return bad;
183
+ }
184
+ const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
185
+ if (result.didFail()) {
186
+ return result;
187
+ }
188
+ const body = result.getDataFirst()?.body ?? {};
189
+ return api_helpers_1.OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
190
+ }
191
+ }
192
+ exports.MailchimpGw = MailchimpGw;
@@ -5,5 +5,7 @@ export * from './TelegramGw';
5
5
  export * from './TwilioGw';
6
6
  export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
+ export * from './HubSpotGw';
9
+ export * from './MailchimpGw';
8
10
  export * from './HttpWebhookGw';
9
11
  export * from './guardedFetch';
@@ -21,5 +21,7 @@ __exportStar(require("./TelegramGw"), exports);
21
21
  __exportStar(require("./TwilioGw"), exports);
22
22
  __exportStar(require("./SlackWebhookGw"), exports);
23
23
  __exportStar(require("./DiscordWebhookGw"), exports);
24
+ __exportStar(require("./HubSpotGw"), exports);
25
+ __exportStar(require("./MailchimpGw"), exports);
24
26
  __exportStar(require("./HttpWebhookGw"), exports);
25
27
  __exportStar(require("./guardedFetch"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.143",
3
+ "version": "1.0.144",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {