@sdflc/backend-helpers 1.0.143 → 1.0.145

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,49 @@ 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. Other
1353
+ properties by their internal names in `properties` (`address`, `city`, `state`, `zip`, `country`, a custom one) — never
1354
+ the email the contact is found by.
1355
+ - Scopes the key needs: `crm.objects.contacts.read` / `.write`, `crm.lists.read` / `.write`.
1356
+ - `verify()` reads one contact (nothing is written). The token is scrubbed out of everything returned.
1357
+
1358
+ ### MailchimpGw
1359
+
1360
+ Puts a person into a Mailchimp audience: a member added or updated by email, tags, a note, and the audiences to choose
1361
+ from. The data centre is read from the key (`…-us21` → `https://us21.api.mailchimp.com/3.0`).
1362
+
1363
+ ```typescript
1364
+ const mailchimp = new MailchimpGw().configure({ apiKey });
1365
+
1366
+ await mailchimp.upsertMember(audienceId, { email, mergeFields: { FNAME, LNAME }, statusIfNew: 'transactional' });
1367
+ await mailchimp.addTags(audienceId, email, ['Volunteers']); // added; made in the audience when new
1368
+ await mailchimp.addNote(audienceId, email, 'Signed up to volunteer …'); // cut to Mailchimp's 1,000 characters
1369
+ const audiences = await mailchimp.listAudiences(); // [{ id, name, memberCount }]
1370
+ ```
1371
+
1372
+ - **An existing member's subscription is never changed**: only `status_if_new` is sent (`transactional` by default —
1373
+ on the audience, not subscribed to marketing; `pending` sends a confirmation email; `subscribed` only with consent).
1374
+ - Required merge fields the host added are not demanded (`skip_merge_validation`); an audience id that could leave the
1375
+ path is refused before sending. The key (and the Basic header made of it) is scrubbed out of everything returned.
1376
+ - `mergeFields.ADDRESS` takes an object (`addr1`, `addr2`, `city`, `state`, `zip`, `country`): sent only when addr1,
1377
+ city, state and zip are all there (Mailchimp refuses the member over a partial one), the country only as two letters.
1378
+ - Pure helpers: `mailchimpDataCenterOf(apiKey)`, `mailchimpSubscriberHash(email)`, `mailchimpAddressOf(address)`.
1379
+
1333
1380
  ### HttpWebhookGw
1334
1381
 
1335
1382
  Sends JSON to any URL, for anything without a gateway of its own, optionally **signed**.
@@ -2481,6 +2528,8 @@ START_READY_TIMEOUT_MS; // 60000: startService alerts when the server is not lis
2481
2528
  | `TwilioSettings` / `TwilioMessage` | `TwilioGw` settings and message |
2482
2529
  | `SlackWebhookSettings` / `SlackMessage` | `SlackWebhookGw` settings and message |
2483
2530
  | `DiscordWebhookSettings` / `DiscordMessage` / `DiscordEmbed` | `DiscordWebhookGw` settings, message and embed |
2531
+ | `HubSpotSettings` / `HubSpotContact` / `HubSpotList` | `HubSpotGw` settings, a contact, a static list |
2532
+ | `MailchimpSettings` / `MailchimpMember` / `MailchimpAudience` / `MailchimpStatusIfNew` / `MailchimpAddress` | `MailchimpGw` settings, a member, an audience, a new member's subscription |
2484
2533
  | `HttpWebhookSettings` / `HttpWebhookSend` / `HttpWebhookGwProps` | `HttpWebhookGw` settings, one send, and its constructor props (`allowPrivateNetwork`, `lookup`, `dnsLookup`) |
2485
2534
  | `ExternalUrlOptions` | Options for `checkExternalUrl()`: `{ protocols?, lookup?, field? }` |
2486
2535
  | `GuardedFetchOptions` | Options for `createGuardedFetch()`: `{ dnsLookup?, isBlocked? }` |
@@ -0,0 +1,48 @@
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
+ /** Any other contact properties by their internal names — `address`, `city`, `state`, `zip`, `country`, a custom one. */
16
+ properties?: Record<string, string | null | undefined>;
17
+ }
18
+ /** A static list as `listStaticLists` returns it. */
19
+ export interface HubSpotList {
20
+ id: string;
21
+ name: string;
22
+ processingType: string;
23
+ }
24
+ export declare const HUBSPOT_API_URL = "https://api.hubapi.com";
25
+ declare class HubSpotGw extends BaseExternalApiGateway<HubSpotSettings> {
26
+ constructor(props?: BaseExternalApiGatewayPropsInterface<HubSpotSettings>);
27
+ protected validateSettings(settings: Partial<HubSpotSettings>): string[];
28
+ protected secretValues(): string[];
29
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
30
+ protected errorMessageOf(reply: ExternalApiReply): string;
31
+ private call;
32
+ /**
33
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
34
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
35
+ */
36
+ upsertContact(contact: HubSpotContact): Promise<OpResult>;
37
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
38
+ addToList(listId: string, contactIds: string[]): Promise<OpResult>;
39
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
40
+ addNote(contactId: string, body: string, at?: Date): Promise<OpResult>;
41
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
42
+ listStaticLists(query?: string): Promise<OpResult>;
43
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
44
+ getList(listId: string): Promise<OpResult>;
45
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
46
+ verify(): Promise<OpResult>;
47
+ }
48
+ export { HubSpotGw };
@@ -0,0 +1,183 @@
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
+ // ⓘ After the named ones, so `properties` cannot replace the email the contact is found by.
74
+ ...Object.entries(contact.properties ?? {}).filter(([name]) => /^[a-z0-9_]{1,100}$/.test(name) && name !== 'email'),
75
+ ];
76
+ for (const [name, value] of given) {
77
+ if (text(value)) {
78
+ properties[name] = text(value);
79
+ }
80
+ }
81
+ const result = await this.call('POST', '/crm/v3/objects/contacts/batch/upsert', {
82
+ inputs: [{ idProperty: 'email', id: email, properties }],
83
+ });
84
+ if (result.didFail()) {
85
+ return result;
86
+ }
87
+ const row = result.getDataFirst()?.body?.results?.[0] ?? null;
88
+ if (!row?.id) {
89
+ return OpResult.fail(OP_RESULT_CODES.FAILED, [result.getDataFirst()], 'HubSpot answered without the contact');
90
+ }
91
+ return OpResult.ok([{ contactId: String(row.id), created: row.new === true }]);
92
+ }
93
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
94
+ async addToList(listId, contactIds) {
95
+ if (!this.isConfigured()) {
96
+ return this.notConfigured();
97
+ }
98
+ const id = text(listId);
99
+ const ids = (contactIds ?? []).map(text).filter(Boolean);
100
+ if (!/^\d{1,20}$/.test(id) || ids.length === 0) {
101
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id (a number) and at least one contact are needed');
102
+ }
103
+ const result = await this.call('PUT', `/crm/v3/lists/${id}/memberships/add`, ids);
104
+ return result.didFail()
105
+ ? result
106
+ : OpResult.ok([{ listId: id, added: result.getDataFirst()?.body?.recordIdsAdded ?? ids }]);
107
+ }
108
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
109
+ async addNote(contactId, body, at = new Date()) {
110
+ if (!this.isConfigured()) {
111
+ return this.notConfigured();
112
+ }
113
+ if (!text(contactId) || !text(body)) {
114
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A contact and the note are needed');
115
+ }
116
+ const result = await this.call('POST', '/crm/v3/objects/notes', {
117
+ properties: { hs_timestamp: at.toISOString(), hs_note_body: String(body) },
118
+ associations: [
119
+ {
120
+ to: { id: text(contactId) },
121
+ types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: NOTE_TO_CONTACT }],
122
+ },
123
+ ],
124
+ });
125
+ return result.didFail() ? result : OpResult.ok([{ noteId: String(result.getDataFirst()?.body?.id ?? '') || null }]);
126
+ }
127
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
128
+ async listStaticLists(query = '') {
129
+ if (!this.isConfigured()) {
130
+ return this.notConfigured();
131
+ }
132
+ // ⓘ The schema names listIds and additionalProperties as required: empty — no filter by id, no extra properties.
133
+ const result = await this.call('POST', '/crm/v3/lists/search', {
134
+ query: text(query),
135
+ processingTypes: STATIC_PROCESSING_TYPES,
136
+ listIds: [],
137
+ additionalProperties: [],
138
+ count: 500,
139
+ offset: 0,
140
+ });
141
+ if (result.didFail()) {
142
+ return result;
143
+ }
144
+ const lists = (result.getDataFirst()?.body?.lists ?? [])
145
+ .filter((l) => String(l?.objectTypeId ?? CONTACTS_OBJECT_TYPE) === CONTACTS_OBJECT_TYPE &&
146
+ STATIC_PROCESSING_TYPES.includes(String(l?.processingType)))
147
+ .map((l) => ({
148
+ id: String(l.listId),
149
+ name: text(l.name) || String(l.listId),
150
+ processingType: String(l.processingType),
151
+ }))
152
+ .sort((a, b) => a.name.localeCompare(b.name));
153
+ return OpResult.ok(lists);
154
+ }
155
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
156
+ async getList(listId) {
157
+ if (!this.isConfigured()) {
158
+ return this.notConfigured();
159
+ }
160
+ const id = text(listId);
161
+ if (!/^\d{1,20}$/.test(id)) {
162
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id is a number');
163
+ }
164
+ const result = await this.call('GET', `/crm/v3/lists/${id}`);
165
+ if (result.didFail()) {
166
+ return result;
167
+ }
168
+ const list = result.getDataFirst()?.body?.list ?? result.getDataFirst()?.body ?? {};
169
+ const processingType = String(list.processingType ?? '');
170
+ return OpResult.ok([
171
+ { id, name: text(list.name) || id, processingType, isStatic: STATIC_PROCESSING_TYPES.includes(processingType) },
172
+ ]);
173
+ }
174
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
175
+ async verify() {
176
+ if (!this.isConfigured()) {
177
+ return this.notConfigured();
178
+ }
179
+ const result = await this.call('GET', '/crm/v3/objects/contacts?limit=1&archived=false');
180
+ return result.didFail() ? result : OpResult.ok([{ ok: true }]);
181
+ }
182
+ }
183
+ export { HubSpotGw };
@@ -0,0 +1,76 @@
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
+ /**
14
+ * By merge tag — FNAME, LNAME (every audience has them unless the host removed them), ADDRESS as an object (`addr1`,
15
+ * `addr2`, `city`, `state`, `zip`, `country` — Mailchimp refuses one without addr1, city, state and zip). Empty values
16
+ * are not sent.
17
+ */
18
+ mergeFields?: Record<string, string | MailchimpAddress | null | undefined>;
19
+ /** Default `transactional`: on the audience, not subscribed to marketing. */
20
+ statusIfNew?: MailchimpStatusIfNew;
21
+ }
22
+ /** The ADDRESS merge field's value. */
23
+ export interface MailchimpAddress {
24
+ addr1: string;
25
+ addr2?: string | null;
26
+ city: string;
27
+ state: string;
28
+ zip: string;
29
+ /** Two letters (`CA`); left out, the audience's default country. */
30
+ country?: string | null;
31
+ }
32
+ /** An audience as `listAudiences` returns it. */
33
+ export interface MailchimpAudience {
34
+ id: string;
35
+ name: string;
36
+ memberCount: number | null;
37
+ }
38
+ /** Mailchimp's own limit on a note. */
39
+ export declare const MAILCHIMP_NOTE_MAX = 1000;
40
+ /** A tag's name, at most (Mailchimp's limit). */
41
+ export declare const MAILCHIMP_TAG_MAX = 100;
42
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
43
+ export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
44
+ /**
45
+ * An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
46
+ * only as two letters — or null. Pure.
47
+ */
48
+ export declare const mailchimpAddressOf: (value: Partial<MailchimpAddress> | null | undefined) => Record<string, string> | null;
49
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
50
+ export declare const mailchimpSubscriberHash: (email: string) => string;
51
+ declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
52
+ constructor(props?: BaseExternalApiGatewayPropsInterface<MailchimpSettings>);
53
+ protected validateSettings(settings: Partial<MailchimpSettings>): string[];
54
+ protected secretValues(): string[];
55
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
56
+ protected errorMessageOf(reply: ExternalApiReply): string;
57
+ private call;
58
+ /** An audience id may only be letters and digits — it goes into the path. */
59
+ private badAudience;
60
+ private memberPath;
61
+ /**
62
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
63
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
64
+ * `{ memberId, status }`. Never throws.
65
+ */
66
+ upsertMember(audienceId: string, member: MailchimpMember): Promise<OpResult>;
67
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
68
+ addTags(audienceId: string, email: string, tags: string[]): Promise<OpResult>;
69
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
70
+ addNote(audienceId: string, email: string, note: string): Promise<OpResult>;
71
+ /** The account's audiences (at most 1,000), by name. Never throws. */
72
+ listAudiences(): Promise<OpResult>;
73
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
74
+ getAudience(audienceId: string): Promise<OpResult>;
75
+ }
76
+ export { MailchimpGw };
@@ -0,0 +1,222 @@
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
+ /**
33
+ * An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
34
+ * only as two letters — or null. Pure.
35
+ */
36
+ export const mailchimpAddressOf = (value) => {
37
+ const parts = {
38
+ addr1: text(value?.addr1),
39
+ addr2: text(value?.addr2),
40
+ city: text(value?.city),
41
+ state: text(value?.state),
42
+ zip: text(value?.zip),
43
+ };
44
+ if (!parts.addr1 || !parts.city || !parts.state || !parts.zip) {
45
+ return null;
46
+ }
47
+ const country = text(value?.country).toUpperCase();
48
+ const out = { addr1: parts.addr1, city: parts.city, state: parts.state, zip: parts.zip };
49
+ if (parts.addr2) {
50
+ out.addr2 = parts.addr2;
51
+ }
52
+ if (/^[A-Z]{2}$/.test(country)) {
53
+ out.country = country;
54
+ }
55
+ return out;
56
+ };
57
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
58
+ export const mailchimpSubscriberHash = (email) => createHash('md5').update(text(email).toLowerCase()).digest('hex');
59
+ class MailchimpGw extends BaseExternalApiGateway {
60
+ constructor(props) {
61
+ super(props);
62
+ }
63
+ validateSettings(settings) {
64
+ return mailchimpDataCenterOf(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
65
+ }
66
+ secretValues() {
67
+ const key = text(this.settings.apiKey);
68
+ return [key, Buffer.from(`anystring:${key}`).toString('base64')];
69
+ }
70
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
71
+ errorMessageOf(reply) {
72
+ const body = reply.body;
73
+ if (body && typeof body === 'object') {
74
+ const fields = Array.isArray(body.errors)
75
+ ? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
76
+ : '';
77
+ return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
78
+ }
79
+ return super.errorMessageOf(reply);
80
+ }
81
+ call(method, path, json) {
82
+ const key = text(this.settings.apiKey);
83
+ return this.requestWithRetries({
84
+ url: `https://${mailchimpDataCenterOf(key)}.api.mailchimp.com/3.0${path}`,
85
+ method,
86
+ headers: {
87
+ Authorization: `Basic ${Buffer.from(`anystring:${key}`).toString('base64')}`,
88
+ Accept: 'application/json',
89
+ },
90
+ ...(json === undefined ? {} : { json }),
91
+ });
92
+ }
93
+ /** An audience id may only be letters and digits — it goes into the path. */
94
+ badAudience(audienceId) {
95
+ return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
96
+ ? null
97
+ : OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
98
+ }
99
+ memberPath(audienceId, email) {
100
+ return `/lists/${text(audienceId)}/members/${mailchimpSubscriberHash(email)}`;
101
+ }
102
+ /**
103
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
104
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
105
+ * `{ memberId, status }`. Never throws.
106
+ */
107
+ async upsertMember(audienceId, member) {
108
+ if (!this.isConfigured()) {
109
+ return this.notConfigured();
110
+ }
111
+ const email = text(member?.email).toLowerCase();
112
+ const bad = this.badAudience(audienceId);
113
+ if (bad) {
114
+ return bad;
115
+ }
116
+ if (!email.includes('@')) {
117
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
118
+ }
119
+ const statusIfNew = MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
120
+ ? member.statusIfNew
121
+ : 'transactional';
122
+ const mergeFields = {};
123
+ for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
124
+ if (!/^[A-Z0-9_]{1,10}$/.test(tag)) {
125
+ continue;
126
+ }
127
+ if (value && typeof value === 'object') {
128
+ // An address goes whole or not at all: Mailchimp refuses the member over a partial one.
129
+ const address = mailchimpAddressOf(value);
130
+ if (address) {
131
+ mergeFields[tag] = address;
132
+ }
133
+ }
134
+ else if (text(value)) {
135
+ mergeFields[tag] = text(value);
136
+ }
137
+ }
138
+ const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
139
+ email_address: email,
140
+ status_if_new: statusIfNew,
141
+ ...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
142
+ });
143
+ if (result.didFail()) {
144
+ return result;
145
+ }
146
+ const body = result.getDataFirst()?.body ?? {};
147
+ return OpResult.ok([
148
+ { memberId: body.id ? String(body.id) : mailchimpSubscriberHash(email), status: body.status ?? null },
149
+ ]);
150
+ }
151
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
152
+ async addTags(audienceId, email, tags) {
153
+ if (!this.isConfigured()) {
154
+ return this.notConfigured();
155
+ }
156
+ const bad = this.badAudience(audienceId);
157
+ const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, MAILCHIMP_TAG_MAX)).filter(Boolean)));
158
+ if (bad) {
159
+ return bad;
160
+ }
161
+ if (!text(email).includes('@') || names.length === 0) {
162
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
163
+ }
164
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
165
+ tags: names.map((name) => ({ name, status: 'active' })),
166
+ });
167
+ return result.didFail() ? result : OpResult.ok([{ tags: names }]);
168
+ }
169
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
170
+ async addNote(audienceId, email, note) {
171
+ if (!this.isConfigured()) {
172
+ return this.notConfigured();
173
+ }
174
+ const bad = this.badAudience(audienceId);
175
+ if (bad) {
176
+ return bad;
177
+ }
178
+ if (!text(email).includes('@') || !text(note)) {
179
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
180
+ }
181
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
182
+ note: String(note).slice(0, MAILCHIMP_NOTE_MAX),
183
+ });
184
+ return result.didFail() ? result : OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
185
+ }
186
+ /** The account's audiences (at most 1,000), by name. Never throws. */
187
+ async listAudiences() {
188
+ if (!this.isConfigured()) {
189
+ return this.notConfigured();
190
+ }
191
+ const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
192
+ if (result.didFail()) {
193
+ return result;
194
+ }
195
+ const audiences = (result.getDataFirst()?.body?.lists ?? [])
196
+ .map((l) => ({
197
+ id: String(l?.id ?? ''),
198
+ name: text(l?.name) || String(l?.id ?? ''),
199
+ memberCount: l?.stats?.member_count ?? null,
200
+ }))
201
+ .filter((l) => !!l.id)
202
+ .sort((a, b) => a.name.localeCompare(b.name));
203
+ return OpResult.ok(audiences);
204
+ }
205
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
206
+ async getAudience(audienceId) {
207
+ if (!this.isConfigured()) {
208
+ return this.notConfigured();
209
+ }
210
+ const bad = this.badAudience(audienceId);
211
+ if (bad) {
212
+ return bad;
213
+ }
214
+ const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
215
+ if (result.didFail()) {
216
+ return result;
217
+ }
218
+ const body = result.getDataFirst()?.body ?? {};
219
+ return OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
220
+ }
221
+ }
222
+ 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,48 @@
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
+ /** Any other contact properties by their internal names — `address`, `city`, `state`, `zip`, `country`, a custom one. */
16
+ properties?: Record<string, string | null | undefined>;
17
+ }
18
+ /** A static list as `listStaticLists` returns it. */
19
+ export interface HubSpotList {
20
+ id: string;
21
+ name: string;
22
+ processingType: string;
23
+ }
24
+ export declare const HUBSPOT_API_URL = "https://api.hubapi.com";
25
+ declare class HubSpotGw extends BaseExternalApiGateway<HubSpotSettings> {
26
+ constructor(props?: BaseExternalApiGatewayPropsInterface<HubSpotSettings>);
27
+ protected validateSettings(settings: Partial<HubSpotSettings>): string[];
28
+ protected secretValues(): string[];
29
+ /** HubSpot's error shape: `{ status: 'error', message, category, correlationId }`. */
30
+ protected errorMessageOf(reply: ExternalApiReply): string;
31
+ private call;
32
+ /**
33
+ * The contact with this email, created or updated (one call — HubSpot's upsert by email). Only the values given are
34
+ * written; an empty one never blanks what HubSpot holds. OK with `{ contactId, created }`. Never throws.
35
+ */
36
+ upsertContact(contact: HubSpotContact): Promise<OpResult>;
37
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
38
+ addToList(listId: string, contactIds: string[]): Promise<OpResult>;
39
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
40
+ addNote(contactId: string, body: string, at?: Date): Promise<OpResult>;
41
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
42
+ listStaticLists(query?: string): Promise<OpResult>;
43
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
44
+ getList(listId: string): Promise<OpResult>;
45
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
46
+ verify(): Promise<OpResult>;
47
+ }
48
+ export { HubSpotGw };
@@ -0,0 +1,186 @@
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
+ // ⓘ After the named ones, so `properties` cannot replace the email the contact is found by.
77
+ ...Object.entries(contact.properties ?? {}).filter(([name]) => /^[a-z0-9_]{1,100}$/.test(name) && name !== 'email'),
78
+ ];
79
+ for (const [name, value] of given) {
80
+ if (text(value)) {
81
+ properties[name] = text(value);
82
+ }
83
+ }
84
+ const result = await this.call('POST', '/crm/v3/objects/contacts/batch/upsert', {
85
+ inputs: [{ idProperty: 'email', id: email, properties }],
86
+ });
87
+ if (result.didFail()) {
88
+ return result;
89
+ }
90
+ const row = result.getDataFirst()?.body?.results?.[0] ?? null;
91
+ if (!row?.id) {
92
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, [result.getDataFirst()], 'HubSpot answered without the contact');
93
+ }
94
+ return api_helpers_1.OpResult.ok([{ contactId: String(row.id), created: row.new === true }]);
95
+ }
96
+ /** Puts contacts into a static list (already members are skipped by HubSpot). OK with `{ listId, added }`. Never throws. */
97
+ async addToList(listId, contactIds) {
98
+ if (!this.isConfigured()) {
99
+ return this.notConfigured();
100
+ }
101
+ const id = text(listId);
102
+ const ids = (contactIds ?? []).map(text).filter(Boolean);
103
+ if (!/^\d{1,20}$/.test(id) || ids.length === 0) {
104
+ 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');
105
+ }
106
+ const result = await this.call('PUT', `/crm/v3/lists/${id}/memberships/add`, ids);
107
+ return result.didFail()
108
+ ? result
109
+ : api_helpers_1.OpResult.ok([{ listId: id, added: result.getDataFirst()?.body?.recordIdsAdded ?? ids }]);
110
+ }
111
+ /** A note on a contact, dated `at` (HubSpot shows `body` as rich text — pass HTML, escaped). OK with `{ noteId }`. */
112
+ async addNote(contactId, body, at = new Date()) {
113
+ if (!this.isConfigured()) {
114
+ return this.notConfigured();
115
+ }
116
+ if (!text(contactId) || !text(body)) {
117
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A contact and the note are needed');
118
+ }
119
+ const result = await this.call('POST', '/crm/v3/objects/notes', {
120
+ properties: { hs_timestamp: at.toISOString(), hs_note_body: String(body) },
121
+ associations: [
122
+ {
123
+ to: { id: text(contactId) },
124
+ types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: NOTE_TO_CONTACT }],
125
+ },
126
+ ],
127
+ });
128
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: String(result.getDataFirst()?.body?.id ?? '') || null }]);
129
+ }
130
+ /** The account's static CONTACT lists (the ones that take members), at most 500, by name. Never throws. */
131
+ async listStaticLists(query = '') {
132
+ if (!this.isConfigured()) {
133
+ return this.notConfigured();
134
+ }
135
+ // ⓘ The schema names listIds and additionalProperties as required: empty — no filter by id, no extra properties.
136
+ const result = await this.call('POST', '/crm/v3/lists/search', {
137
+ query: text(query),
138
+ processingTypes: STATIC_PROCESSING_TYPES,
139
+ listIds: [],
140
+ additionalProperties: [],
141
+ count: 500,
142
+ offset: 0,
143
+ });
144
+ if (result.didFail()) {
145
+ return result;
146
+ }
147
+ const lists = (result.getDataFirst()?.body?.lists ?? [])
148
+ .filter((l) => String(l?.objectTypeId ?? CONTACTS_OBJECT_TYPE) === CONTACTS_OBJECT_TYPE &&
149
+ STATIC_PROCESSING_TYPES.includes(String(l?.processingType)))
150
+ .map((l) => ({
151
+ id: String(l.listId),
152
+ name: text(l.name) || String(l.listId),
153
+ processingType: String(l.processingType),
154
+ }))
155
+ .sort((a, b) => a.name.localeCompare(b.name));
156
+ return api_helpers_1.OpResult.ok(lists);
157
+ }
158
+ /** One list by id — OK with `{ id, name, processingType, isStatic }`; NOT_FOUND when HubSpot has none. Never throws. */
159
+ async getList(listId) {
160
+ if (!this.isConfigured()) {
161
+ return this.notConfigured();
162
+ }
163
+ const id = text(listId);
164
+ if (!/^\d{1,20}$/.test(id)) {
165
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A list id is a number');
166
+ }
167
+ const result = await this.call('GET', `/crm/v3/lists/${id}`);
168
+ if (result.didFail()) {
169
+ return result;
170
+ }
171
+ const list = result.getDataFirst()?.body?.list ?? result.getDataFirst()?.body ?? {};
172
+ const processingType = String(list.processingType ?? '');
173
+ return api_helpers_1.OpResult.ok([
174
+ { id, name: text(list.name) || id, processingType, isStatic: STATIC_PROCESSING_TYPES.includes(processingType) },
175
+ ]);
176
+ }
177
+ /** Can the token read contacts? (One contact asked for, nothing written.) OK with `{ ok: true }`. Never throws. */
178
+ async verify() {
179
+ if (!this.isConfigured()) {
180
+ return this.notConfigured();
181
+ }
182
+ const result = await this.call('GET', '/crm/v3/objects/contacts?limit=1&archived=false');
183
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ ok: true }]);
184
+ }
185
+ }
186
+ exports.HubSpotGw = HubSpotGw;
@@ -0,0 +1,76 @@
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
+ /**
14
+ * By merge tag — FNAME, LNAME (every audience has them unless the host removed them), ADDRESS as an object (`addr1`,
15
+ * `addr2`, `city`, `state`, `zip`, `country` — Mailchimp refuses one without addr1, city, state and zip). Empty values
16
+ * are not sent.
17
+ */
18
+ mergeFields?: Record<string, string | MailchimpAddress | null | undefined>;
19
+ /** Default `transactional`: on the audience, not subscribed to marketing. */
20
+ statusIfNew?: MailchimpStatusIfNew;
21
+ }
22
+ /** The ADDRESS merge field's value. */
23
+ export interface MailchimpAddress {
24
+ addr1: string;
25
+ addr2?: string | null;
26
+ city: string;
27
+ state: string;
28
+ zip: string;
29
+ /** Two letters (`CA`); left out, the audience's default country. */
30
+ country?: string | null;
31
+ }
32
+ /** An audience as `listAudiences` returns it. */
33
+ export interface MailchimpAudience {
34
+ id: string;
35
+ name: string;
36
+ memberCount: number | null;
37
+ }
38
+ /** Mailchimp's own limit on a note. */
39
+ export declare const MAILCHIMP_NOTE_MAX = 1000;
40
+ /** A tag's name, at most (Mailchimp's limit). */
41
+ export declare const MAILCHIMP_TAG_MAX = 100;
42
+ /** The data centre at the end of an API key (`us21`), or null. Pure. */
43
+ export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
44
+ /**
45
+ * An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
46
+ * only as two letters — or null. Pure.
47
+ */
48
+ export declare const mailchimpAddressOf: (value: Partial<MailchimpAddress> | null | undefined) => Record<string, string> | null;
49
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
50
+ export declare const mailchimpSubscriberHash: (email: string) => string;
51
+ declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
52
+ constructor(props?: BaseExternalApiGatewayPropsInterface<MailchimpSettings>);
53
+ protected validateSettings(settings: Partial<MailchimpSettings>): string[];
54
+ protected secretValues(): string[];
55
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
56
+ protected errorMessageOf(reply: ExternalApiReply): string;
57
+ private call;
58
+ /** An audience id may only be letters and digits — it goes into the path. */
59
+ private badAudience;
60
+ private memberPath;
61
+ /**
62
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
63
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
64
+ * `{ memberId, status }`. Never throws.
65
+ */
66
+ upsertMember(audienceId: string, member: MailchimpMember): Promise<OpResult>;
67
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
68
+ addTags(audienceId: string, email: string, tags: string[]): Promise<OpResult>;
69
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
70
+ addNote(audienceId: string, email: string, note: string): Promise<OpResult>;
71
+ /** The account's audiences (at most 1,000), by name. Never throws. */
72
+ listAudiences(): Promise<OpResult>;
73
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
74
+ getAudience(audienceId: string): Promise<OpResult>;
75
+ }
76
+ export { MailchimpGw };
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MailchimpGw = exports.mailchimpSubscriberHash = exports.mailchimpAddressOf = 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
+ /**
37
+ * An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
38
+ * only as two letters — or null. Pure.
39
+ */
40
+ const mailchimpAddressOf = (value) => {
41
+ const parts = {
42
+ addr1: text(value?.addr1),
43
+ addr2: text(value?.addr2),
44
+ city: text(value?.city),
45
+ state: text(value?.state),
46
+ zip: text(value?.zip),
47
+ };
48
+ if (!parts.addr1 || !parts.city || !parts.state || !parts.zip) {
49
+ return null;
50
+ }
51
+ const country = text(value?.country).toUpperCase();
52
+ const out = { addr1: parts.addr1, city: parts.city, state: parts.state, zip: parts.zip };
53
+ if (parts.addr2) {
54
+ out.addr2 = parts.addr2;
55
+ }
56
+ if (/^[A-Z]{2}$/.test(country)) {
57
+ out.country = country;
58
+ }
59
+ return out;
60
+ };
61
+ exports.mailchimpAddressOf = mailchimpAddressOf;
62
+ /** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
63
+ const mailchimpSubscriberHash = (email) => (0, crypto_1.createHash)('md5').update(text(email).toLowerCase()).digest('hex');
64
+ exports.mailchimpSubscriberHash = mailchimpSubscriberHash;
65
+ class MailchimpGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
66
+ constructor(props) {
67
+ super(props);
68
+ }
69
+ validateSettings(settings) {
70
+ return (0, exports.mailchimpDataCenterOf)(settings.apiKey) ? [] : ['the API key is missing or not a Mailchimp one (…-us21)'];
71
+ }
72
+ secretValues() {
73
+ const key = text(this.settings.apiKey);
74
+ return [key, buffer_1.Buffer.from(`anystring:${key}`).toString('base64')];
75
+ }
76
+ /** Mailchimp's error shape (problem+json): `{ title, status, detail, errors: [{ field, message }] }`. */
77
+ errorMessageOf(reply) {
78
+ const body = reply.body;
79
+ if (body && typeof body === 'object') {
80
+ const fields = Array.isArray(body.errors)
81
+ ? body.errors.map((e) => [e?.field, e?.message].filter(Boolean).join(' ')).join('; ')
82
+ : '';
83
+ return [body.title, body.detail, fields].filter(Boolean).join(': ').slice(0, 500) || `HTTP ${reply.status}`;
84
+ }
85
+ return super.errorMessageOf(reply);
86
+ }
87
+ call(method, path, json) {
88
+ const key = text(this.settings.apiKey);
89
+ return this.requestWithRetries({
90
+ url: `https://${(0, exports.mailchimpDataCenterOf)(key)}.api.mailchimp.com/3.0${path}`,
91
+ method,
92
+ headers: {
93
+ Authorization: `Basic ${buffer_1.Buffer.from(`anystring:${key}`).toString('base64')}`,
94
+ Accept: 'application/json',
95
+ },
96
+ ...(json === undefined ? {} : { json }),
97
+ });
98
+ }
99
+ /** An audience id may only be letters and digits — it goes into the path. */
100
+ badAudience(audienceId) {
101
+ return /^[A-Za-z0-9]{1,32}$/.test(text(audienceId))
102
+ ? null
103
+ : api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The audience id is not one');
104
+ }
105
+ memberPath(audienceId, email) {
106
+ return `/lists/${text(audienceId)}/members/${(0, exports.mailchimpSubscriberHash)(email)}`;
107
+ }
108
+ /**
109
+ * The member with this email, added or updated (one PUT). A NEW member gets `statusIfNew`; an existing one keeps its
110
+ * subscription. Required merge fields the host added are not demanded (`skip_merge_validation`). OK with
111
+ * `{ memberId, status }`. Never throws.
112
+ */
113
+ async upsertMember(audienceId, member) {
114
+ if (!this.isConfigured()) {
115
+ return this.notConfigured();
116
+ }
117
+ const email = text(member?.email).toLowerCase();
118
+ const bad = this.badAudience(audienceId);
119
+ if (bad) {
120
+ return bad;
121
+ }
122
+ if (!email.includes('@')) {
123
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The member has no email');
124
+ }
125
+ const statusIfNew = exports.MAILCHIMP_STATUSES_IF_NEW.includes(member.statusIfNew)
126
+ ? member.statusIfNew
127
+ : 'transactional';
128
+ const mergeFields = {};
129
+ for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
130
+ if (!/^[A-Z0-9_]{1,10}$/.test(tag)) {
131
+ continue;
132
+ }
133
+ if (value && typeof value === 'object') {
134
+ // An address goes whole or not at all: Mailchimp refuses the member over a partial one.
135
+ const address = (0, exports.mailchimpAddressOf)(value);
136
+ if (address) {
137
+ mergeFields[tag] = address;
138
+ }
139
+ }
140
+ else if (text(value)) {
141
+ mergeFields[tag] = text(value);
142
+ }
143
+ }
144
+ const result = await this.call('PUT', `${this.memberPath(audienceId, email)}?skip_merge_validation=true`, {
145
+ email_address: email,
146
+ status_if_new: statusIfNew,
147
+ ...(Object.keys(mergeFields).length ? { merge_fields: mergeFields } : {}),
148
+ });
149
+ if (result.didFail()) {
150
+ return result;
151
+ }
152
+ const body = result.getDataFirst()?.body ?? {};
153
+ return api_helpers_1.OpResult.ok([
154
+ { memberId: body.id ? String(body.id) : (0, exports.mailchimpSubscriberHash)(email), status: body.status ?? null },
155
+ ]);
156
+ }
157
+ /** Tags ADDED to a member (made in the audience when new; the member's other tags kept). OK with `{ tags }`. */
158
+ async addTags(audienceId, email, tags) {
159
+ if (!this.isConfigured()) {
160
+ return this.notConfigured();
161
+ }
162
+ const bad = this.badAudience(audienceId);
163
+ const names = Array.from(new Set((tags ?? []).map((t) => text(t).slice(0, exports.MAILCHIMP_TAG_MAX)).filter(Boolean)));
164
+ if (bad) {
165
+ return bad;
166
+ }
167
+ if (!text(email).includes('@') || names.length === 0) {
168
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and at least one tag are needed');
169
+ }
170
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/tags`, {
171
+ tags: names.map((name) => ({ name, status: 'active' })),
172
+ });
173
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ tags: names }]);
174
+ }
175
+ /** A note on a member (cut to Mailchimp's 1,000 characters). OK with `{ noteId }`. Never throws. */
176
+ async addNote(audienceId, email, note) {
177
+ if (!this.isConfigured()) {
178
+ return this.notConfigured();
179
+ }
180
+ const bad = this.badAudience(audienceId);
181
+ if (bad) {
182
+ return bad;
183
+ }
184
+ if (!text(email).includes('@') || !text(note)) {
185
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A member and the note are needed');
186
+ }
187
+ const result = await this.call('POST', `${this.memberPath(audienceId, email)}/notes`, {
188
+ note: String(note).slice(0, exports.MAILCHIMP_NOTE_MAX),
189
+ });
190
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ noteId: result.getDataFirst()?.body?.id ?? null }]);
191
+ }
192
+ /** The account's audiences (at most 1,000), by name. Never throws. */
193
+ async listAudiences() {
194
+ if (!this.isConfigured()) {
195
+ return this.notConfigured();
196
+ }
197
+ const result = await this.call('GET', '/lists?count=1000&fields=lists.id,lists.name,lists.stats.member_count');
198
+ if (result.didFail()) {
199
+ return result;
200
+ }
201
+ const audiences = (result.getDataFirst()?.body?.lists ?? [])
202
+ .map((l) => ({
203
+ id: String(l?.id ?? ''),
204
+ name: text(l?.name) || String(l?.id ?? ''),
205
+ memberCount: l?.stats?.member_count ?? null,
206
+ }))
207
+ .filter((l) => !!l.id)
208
+ .sort((a, b) => a.name.localeCompare(b.name));
209
+ return api_helpers_1.OpResult.ok(audiences);
210
+ }
211
+ /** One audience — OK with `{ id, name }`; NOT_FOUND when the account has none by that id. Never throws. */
212
+ async getAudience(audienceId) {
213
+ if (!this.isConfigured()) {
214
+ return this.notConfigured();
215
+ }
216
+ const bad = this.badAudience(audienceId);
217
+ if (bad) {
218
+ return bad;
219
+ }
220
+ const result = await this.call('GET', `/lists/${text(audienceId)}?fields=id,name`);
221
+ if (result.didFail()) {
222
+ return result;
223
+ }
224
+ const body = result.getDataFirst()?.body ?? {};
225
+ return api_helpers_1.OpResult.ok([{ id: String(body.id ?? audienceId), name: text(body.name) || String(audienceId) }]);
226
+ }
227
+ }
228
+ 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.145",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {