102 lines
3.6 KiB
TypeScript
102 lines
3.6 KiB
TypeScript
/**
|
|
* Mailchimp list-subscribe adapter (Phase 05 #79).
|
|
*
|
|
* Adds the lead as a `subscribed` (or `pending` if you flip the toggle)
|
|
* contact to the configured audience. Auth is `Authorization: Basic
|
|
* <base64(any:apiKey)>` per Mailchimp's documented scheme. The DC suffix
|
|
* is parsed from the API key (`us12-…` → `us12.api.mailchimp.com`).
|
|
*
|
|
* Idempotent by Mailchimp's email-hash semantics — we PUT to
|
|
* `/lists/{listId}/members/{md5(lowercase-email)}` which upserts.
|
|
*/
|
|
|
|
import { createHash } from "node:crypto";
|
|
import {
|
|
adapterFetch,
|
|
MarketingAdapterConfigError,
|
|
type AdapterResult,
|
|
type MarketingLeadPayload,
|
|
type MarketingOutboundAdapter,
|
|
} from "../types.js";
|
|
|
|
export interface MailchimpConfig {
|
|
apiKey: string;
|
|
listId: string;
|
|
/** `subscribed` (default) | `pending` */
|
|
status?: "subscribed" | "pending";
|
|
/** Optional tags applied to the contact. */
|
|
tags?: string[];
|
|
}
|
|
|
|
function dcFromApiKey(apiKey: string): string {
|
|
const idx = apiKey.lastIndexOf("-");
|
|
if (idx <= 0) throw new MarketingAdapterConfigError("Mailchimp API key missing DC suffix");
|
|
return apiKey.slice(idx + 1);
|
|
}
|
|
|
|
export function buildMailchimpPayload(
|
|
payload: MarketingLeadPayload,
|
|
config: MailchimpConfig
|
|
): { url: string; body: Record<string, unknown>; emailHash: string } {
|
|
const lower = payload.email.trim().toLowerCase();
|
|
const emailHash = createHash("md5").update(lower).digest("hex");
|
|
const dc = dcFromApiKey(config.apiKey);
|
|
const url = `https://${dc}.api.mailchimp.com/3.0/lists/${encodeURIComponent(config.listId)}/members/${emailHash}`;
|
|
const merge_fields: Record<string, string> = {};
|
|
if (payload.firstName) merge_fields.FNAME = payload.firstName;
|
|
if (payload.lastName) merge_fields.LNAME = payload.lastName;
|
|
if (payload.company) merge_fields.COMPANY = payload.company;
|
|
const body: Record<string, unknown> = {
|
|
email_address: lower,
|
|
status_if_new: config.status ?? "subscribed",
|
|
merge_fields,
|
|
};
|
|
if (config.tags && config.tags.length > 0) {
|
|
body.tags = config.tags;
|
|
}
|
|
return { url, body, emailHash };
|
|
}
|
|
|
|
export const mailchimpAdapter: MarketingOutboundAdapter<MailchimpConfig> = {
|
|
type: "mailchimp",
|
|
parseConfig(config: unknown): MailchimpConfig {
|
|
if (!config || typeof config !== "object") {
|
|
throw new MarketingAdapterConfigError("mailchimp config must be an object");
|
|
}
|
|
const c = config as Record<string, unknown>;
|
|
if (typeof c.apiKey !== "string" || c.apiKey.length === 0) {
|
|
throw new MarketingAdapterConfigError("mailchimp config requires apiKey");
|
|
}
|
|
if (typeof c.listId !== "string" || c.listId.length === 0) {
|
|
throw new MarketingAdapterConfigError("mailchimp config requires listId");
|
|
}
|
|
return {
|
|
apiKey: c.apiKey,
|
|
listId: c.listId,
|
|
status: c.status === "pending" ? "pending" : "subscribed",
|
|
tags: Array.isArray(c.tags) ? (c.tags as unknown[]).filter((t) => typeof t === "string") as string[] : undefined,
|
|
};
|
|
},
|
|
async send({ payload, config, ctx }): Promise<AdapterResult> {
|
|
let built: ReturnType<typeof buildMailchimpPayload>;
|
|
try {
|
|
built = buildMailchimpPayload(payload, config);
|
|
} catch (err) {
|
|
return { ok: false, errorTag: err instanceof MarketingAdapterConfigError ? "config_error" : "build_error" };
|
|
}
|
|
const authHeader = `Basic ${Buffer.from(`any:${config.apiKey}`, "utf8").toString("base64")}`;
|
|
return adapterFetch(
|
|
built.url,
|
|
{
|
|
method: "PUT",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
authorization: authHeader,
|
|
},
|
|
body: JSON.stringify(built.body),
|
|
},
|
|
ctx
|
|
);
|
|
},
|
|
};
|