@sdflc/backend-helpers 1.0.142 → 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? }` |
@@ -153,6 +153,13 @@ declare class BaseGateway {
153
153
  * (e.g. a table with a UUID primary key but a separate "slug" as update target).
154
154
  */
155
155
  getIdFieldUpdateRemove(): string;
156
+ /**
157
+ * The column `list()` appends as the last sort term when it applies a limit — so tied rows keep one order across
158
+ * pages. `config.listTieBreaker` when set (a string names the column, `false` turns it off → null); otherwise the id
159
+ * field, qualified with the table's OWN name (the last segment of `config.table`, so `SCHEMA.Table` gives `Table.id`)
160
+ * — a list query that joins another table with an `id` stays unambiguous. Override to compute it differently.
161
+ */
162
+ getListTieBreaker(): string | null;
156
163
  /**
157
164
  * Applies a whereIn or where-equals filter for scalar or array values.
158
165
  *
@@ -18,6 +18,24 @@ const DEFAULT_CHUNCK_SIZE = 2500;
18
18
  * filters must be precise identifiers, not fuzzy searches or time windows.
19
19
  */
20
20
  const UPDATE_REMOVE_SUPPORTED_TYPES = new Set(['array', 'eq', 'bool', 'nullableBool']);
21
+ /** `[table, column]` of a column reference, lower-cased; the table is '' when unqualified. */
22
+ const splitColumn = (reference) => {
23
+ const parts = String(reference || '').split('.');
24
+ const column = (parts.pop() || '').toLowerCase();
25
+ const table = (parts.pop() || '').toLowerCase();
26
+ return [table, column];
27
+ };
28
+ /**
29
+ * Whether a sort already orders by `column` — matched by the column's own name, and by its table when BOTH name one:
30
+ * a bare `id` and `party_appearance.id` are the same column here (a duplicate would be refused by SQL Server).
31
+ */
32
+ const sortNamesColumn = (sortBy, column) => {
33
+ const [table, name] = splitColumn(column);
34
+ return (sortBy || []).some((item) => {
35
+ const [itemTable, itemName] = splitColumn(String(item?.column ?? ''));
36
+ return itemName === name && (!itemTable || !table || itemTable === table);
37
+ });
38
+ };
21
39
  /**
22
40
  * BaseGateway is the foundation for all database-backed gateway classes.
23
41
  *
@@ -229,6 +247,29 @@ class BaseGateway {
229
247
  getIdFieldUpdateRemove() {
230
248
  return this.config.idFieldUpdateRemove || this.config.idField || constants_1.ID_FIELD;
231
249
  }
250
+ /**
251
+ * The column `list()` appends as the last sort term when it applies a limit — so tied rows keep one order across
252
+ * pages. `config.listTieBreaker` when set (a string names the column, `false` turns it off → null); otherwise the id
253
+ * field, qualified with the table's OWN name (the last segment of `config.table`, so `SCHEMA.Table` gives `Table.id`)
254
+ * — a list query that joins another table with an `id` stays unambiguous. Override to compute it differently.
255
+ */
256
+ getListTieBreaker() {
257
+ const configured = this.config.listTieBreaker;
258
+ if (configured === false) {
259
+ return null;
260
+ }
261
+ if (typeof configured === 'string' && configured) {
262
+ return configured;
263
+ }
264
+ const idField = this.getIdField();
265
+ if (idField.includes('.')) {
266
+ return idField;
267
+ }
268
+ const table = String(this.config.table || '')
269
+ .split('.')
270
+ .pop();
271
+ return table ? `${table}.${idField}` : idField;
272
+ }
232
273
  // ─── Protected filter helpers ───────────────────────────────────────────────
233
274
  //
234
275
  // These helpers encode the common WHERE clause patterns used across gateway
@@ -1198,12 +1239,22 @@ class BaseGateway {
1198
1239
  const fieldsToUse = !shouldUseCache && Array.isArray(this.config.selectFields) ? this.config.selectFields : this.getIdField();
1199
1240
  const { query } = await this.buildListQuery({ filter, params, fieldsToUse, useCache: shouldUseCache });
1200
1241
  await this.onListFilter(query, filter);
1201
- if (limit && !isNaN(limit) && limit > 0) {
1242
+ const isLimited = !!limit && !isNaN(limit) && limit > 0;
1243
+ if (isLimited) {
1202
1244
  query.offset(offset).limit(limit);
1203
1245
  }
1204
1246
  if (sortBy) {
1205
1247
  query.orderBy(sortBy);
1206
1248
  }
1249
+ // A limited read ends its order with a unique column, so rows that tie on the sort (one bulk insert's created_at,
1250
+ // a shared order_no or name) come back in the same order on every page: without it Postgres may hand page 2 a row
1251
+ // page 1 already had and never hand over another. Not when the sort already names that column (SQL Server refuses
1252
+ // a column twice in ORDER BY), and not on an unlimited read (it returns every row whatever their order). An empty
1253
+ // sort gets it too — that is exactly the read with no order at all.
1254
+ const tieBreaker = isLimited ? this.getListTieBreaker() : null;
1255
+ if (tieBreaker && !sortNamesColumn(sortBy, tieBreaker)) {
1256
+ query.orderBy(tieBreaker, 'asc');
1257
+ }
1207
1258
  const items = await query;
1208
1259
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
1209
1260
  return result.map((item) => this.transformOnOut(item));
@@ -153,6 +153,13 @@ declare class BaseGateway {
153
153
  * (e.g. a table with a UUID primary key but a separate "slug" as update target).
154
154
  */
155
155
  getIdFieldUpdateRemove(): string;
156
+ /**
157
+ * The column `list()` appends as the last sort term when it applies a limit — so tied rows keep one order across
158
+ * pages. `config.listTieBreaker` when set (a string names the column, `false` turns it off → null); otherwise the id
159
+ * field, qualified with the table's OWN name (the last segment of `config.table`, so `SCHEMA.Table` gives `Table.id`)
160
+ * — a list query that joins another table with an `id` stays unambiguous. Override to compute it differently.
161
+ */
162
+ getListTieBreaker(): string | null;
156
163
  /**
157
164
  * Applies a whereIn or where-equals filter for scalar or array values.
158
165
  *
@@ -12,6 +12,24 @@ const DEFAULT_CHUNCK_SIZE = 2500;
12
12
  * filters must be precise identifiers, not fuzzy searches or time windows.
13
13
  */
14
14
  const UPDATE_REMOVE_SUPPORTED_TYPES = new Set(['array', 'eq', 'bool', 'nullableBool']);
15
+ /** `[table, column]` of a column reference, lower-cased; the table is '' when unqualified. */
16
+ const splitColumn = (reference) => {
17
+ const parts = String(reference || '').split('.');
18
+ const column = (parts.pop() || '').toLowerCase();
19
+ const table = (parts.pop() || '').toLowerCase();
20
+ return [table, column];
21
+ };
22
+ /**
23
+ * Whether a sort already orders by `column` — matched by the column's own name, and by its table when BOTH name one:
24
+ * a bare `id` and `party_appearance.id` are the same column here (a duplicate would be refused by SQL Server).
25
+ */
26
+ const sortNamesColumn = (sortBy, column) => {
27
+ const [table, name] = splitColumn(column);
28
+ return (sortBy || []).some((item) => {
29
+ const [itemTable, itemName] = splitColumn(String(item?.column ?? ''));
30
+ return itemName === name && (!itemTable || !table || itemTable === table);
31
+ });
32
+ };
15
33
  /**
16
34
  * BaseGateway is the foundation for all database-backed gateway classes.
17
35
  *
@@ -223,6 +241,29 @@ class BaseGateway {
223
241
  getIdFieldUpdateRemove() {
224
242
  return this.config.idFieldUpdateRemove || this.config.idField || ID_FIELD;
225
243
  }
244
+ /**
245
+ * The column `list()` appends as the last sort term when it applies a limit — so tied rows keep one order across
246
+ * pages. `config.listTieBreaker` when set (a string names the column, `false` turns it off → null); otherwise the id
247
+ * field, qualified with the table's OWN name (the last segment of `config.table`, so `SCHEMA.Table` gives `Table.id`)
248
+ * — a list query that joins another table with an `id` stays unambiguous. Override to compute it differently.
249
+ */
250
+ getListTieBreaker() {
251
+ const configured = this.config.listTieBreaker;
252
+ if (configured === false) {
253
+ return null;
254
+ }
255
+ if (typeof configured === 'string' && configured) {
256
+ return configured;
257
+ }
258
+ const idField = this.getIdField();
259
+ if (idField.includes('.')) {
260
+ return idField;
261
+ }
262
+ const table = String(this.config.table || '')
263
+ .split('.')
264
+ .pop();
265
+ return table ? `${table}.${idField}` : idField;
266
+ }
226
267
  // ─── Protected filter helpers ───────────────────────────────────────────────
227
268
  //
228
269
  // These helpers encode the common WHERE clause patterns used across gateway
@@ -1192,12 +1233,22 @@ class BaseGateway {
1192
1233
  const fieldsToUse = !shouldUseCache && Array.isArray(this.config.selectFields) ? this.config.selectFields : this.getIdField();
1193
1234
  const { query } = await this.buildListQuery({ filter, params, fieldsToUse, useCache: shouldUseCache });
1194
1235
  await this.onListFilter(query, filter);
1195
- if (limit && !isNaN(limit) && limit > 0) {
1236
+ const isLimited = !!limit && !isNaN(limit) && limit > 0;
1237
+ if (isLimited) {
1196
1238
  query.offset(offset).limit(limit);
1197
1239
  }
1198
1240
  if (sortBy) {
1199
1241
  query.orderBy(sortBy);
1200
1242
  }
1243
+ // A limited read ends its order with a unique column, so rows that tie on the sort (one bulk insert's created_at,
1244
+ // a shared order_no or name) come back in the same order on every page: without it Postgres may hand page 2 a row
1245
+ // page 1 already had and never hand over another. Not when the sort already names that column (SQL Server refuses
1246
+ // a column twice in ORDER BY), and not on an unlimited read (it returns every row whatever their order). An empty
1247
+ // sort gets it too — that is exactly the read with no order at all.
1248
+ const tieBreaker = isLimited ? this.getListTieBreaker() : null;
1249
+ if (tieBreaker && !sortNamesColumn(sortBy, tieBreaker)) {
1250
+ query.orderBy(tieBreaker, 'asc');
1251
+ }
1201
1252
  const items = await query;
1202
1253
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
1203
1254
  return result.map((item) => this.transformOnOut(item));
@@ -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 };