Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
{
"name": "@toolctrl/marketing-outbound",
"name": "@hivegrid/marketing-outbound",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -0,0 +1,445 @@
/**
* Additional coverage for the marketing-outbound adapters, focused on the
* branches the baseline suite leaves untested: adapterFetch error/timeout
* paths, every adapter's `parseConfig` validation, the SSRF-guard
* boundaries, the event-type switch arms, and the per-adapter
* success/error-tag plumbing.
*/
import { describe, expect, it, vi } from "vitest";
import {
adapterFetch,
formatLeadName,
isOutboundUrlAllowed,
maskEmailIfRequested,
MarketingAdapterConfigError,
type MarketingLeadEventType,
type MarketingLeadPayload,
} from "../types.js";
import { adapterRegistry, ADAPTER_TYPES, resolveAdapter } from "../index.js";
import { slackAdapter, buildSlackBlocks } from "./slack.js";
import { discordAdapter, buildDiscordEmbed } from "./discord.js";
import { mailchimpAdapter, buildMailchimpPayload } from "./mailchimp.js";
import { hubspotAdapter, buildHubSpotPayload } from "./hubspot.js";
import { brevoAdapter, buildBrevoPayload } from "./brevo.js";
import { customWebhookAdapter, buildCustomPayload } from "./custom-webhook.js";
const PAYLOAD: MarketingLeadPayload = {
leadId: "lead_1",
email: "patrick@example.com",
firstName: "Patrick",
lastName: "Doe",
company: "Acme",
source: "landing-pro",
utm: { source: "google", medium: "cpc", campaign: "q2-launch" },
referrer: "https://google.com",
landingPage: "/pricing",
tenantId: "tenant_1",
targetStatus: "trial",
conversionPath: "self-service",
planId: "plan_pro",
occurredAt: "2026-05-17T00:00:00Z",
};
/** Bare lead with no enrichment fields — exercises the "fallback" branches. */
const BARE_PAYLOAD: MarketingLeadPayload = {
leadId: "lead_2",
email: "bare@example.com",
};
function mockFetch(status = 200): typeof fetch {
return vi.fn().mockResolvedValue(new Response("ok", { status })) as unknown as typeof fetch;
}
function firstCallInit(fetchImpl: typeof fetch): RequestInit & { headers: Record<string, string> } {
const [, init] = (fetchImpl as unknown as { mock: { calls: unknown[][] } }).mock.calls[0];
return init as RequestInit & { headers: Record<string, string> };
}
function firstCallBody(fetchImpl: typeof fetch): Record<string, unknown> {
return JSON.parse(firstCallInit(fetchImpl).body as string) as Record<string, unknown>;
}
describe("adapterFetch error + timeout paths", () => {
it("tags a thrown Error (not AbortError) as network_error", async () => {
const fetchImpl = vi.fn().mockRejectedValue(new TypeError("fetch failed")) as unknown as typeof fetch;
const res = await adapterFetch("https://example.com/x", { method: "POST" }, { fetch: fetchImpl });
expect(res.ok).toBe(false);
expect(res.errorTag).toBe("network_error");
});
it("tags a non-Error throw as network_error (instanceof false branch)", async () => {
const fetchImpl = vi.fn().mockRejectedValue("boom") as unknown as typeof fetch;
const res = await adapterFetch("https://example.com/x", { method: "POST" }, { fetch: fetchImpl });
expect(res.ok).toBe(false);
expect(res.errorTag).toBe("network_error");
});
it("aborts and returns timeout once timeoutMs elapses", async () => {
vi.useFakeTimers();
try {
// Fetch that only settles when the AbortController fires, mimicking a
// hung upstream so we exercise the real setTimeout -> abort -> reject path.
const fetchImpl = vi.fn((_url: string, init: RequestInit) => {
return new Promise((_resolve, reject) => {
init.signal?.addEventListener("abort", () => {
reject(Object.assign(new Error("aborted"), { name: "AbortError" }));
});
});
}) as unknown as typeof fetch;
const resultP = adapterFetch(
"https://example.com/x",
{ method: "POST" },
{ fetch: fetchImpl, timeoutMs: 50 }
);
await vi.advanceTimersByTimeAsync(60);
const res = await resultP;
expect(res.ok).toBe(false);
expect(res.errorTag).toBe("timeout");
} finally {
vi.useRealTimers();
}
});
it("short-circuits a disallowed URL without ever calling fetch", async () => {
const fetchImpl = mockFetch();
const res = await adapterFetch("http://example.com/x", { method: "POST" }, { fetch: fetchImpl });
expect(res).toEqual({ ok: false, errorTag: "url_rejected_ssrf" });
expect(fetchImpl).not.toHaveBeenCalled();
});
it("returns ok:true with the upstream status on 2xx", async () => {
const fetchImpl = mockFetch(201);
const res = await adapterFetch("https://example.com/x", { method: "POST" }, { fetch: fetchImpl });
expect(res).toEqual({ ok: true, status: 201 });
});
});
describe("isOutboundUrlAllowed boundary cases", () => {
it("rejects link-local, .local, .lan and *.localhost hosts", () => {
expect(isOutboundUrlAllowed("https://169.254.169.254/latest/meta-data")).toBe(false);
expect(isOutboundUrlAllowed("https://printer.local/x")).toBe(false);
expect(isOutboundUrlAllowed("https://nas.lan/x")).toBe(false);
expect(isOutboundUrlAllowed("https://api.localhost/x")).toBe(false);
});
it("applies the 172.16/12 private range only inside its bounds", () => {
expect(isOutboundUrlAllowed("https://172.16.0.1/x")).toBe(false);
expect(isOutboundUrlAllowed("https://172.31.255.254/x")).toBe(false);
// Just outside the private block — must be allowed.
expect(isOutboundUrlAllowed("https://172.15.0.1/x")).toBe(true);
expect(isOutboundUrlAllowed("https://172.32.0.1/x")).toBe(true);
});
});
describe("maskEmailIfRequested edge cases", () => {
it("leaves a non-email string untouched even when masking is on", () => {
expect(maskEmailIfRequested("not-an-email", { maskPii: { email: true } })).toBe("not-an-email");
});
it("leaves a leading-@ value untouched (at index 0 branch)", () => {
expect(maskEmailIfRequested("@example.com", { maskPii: { email: true } })).toBe("@example.com");
});
it("normalises undefined to null", () => {
expect(maskEmailIfRequested(undefined, { maskPii: { email: true } })).toBeNull();
});
});
describe("formatLeadName", () => {
it("joins first + last name", () => {
expect(formatLeadName(PAYLOAD)).toBe("Patrick Doe");
});
it("falls back to email when no name parts are present", () => {
expect(formatLeadName(BARE_PAYLOAD)).toBe("bare@example.com");
});
it("uses only the present name part", () => {
expect(formatLeadName({ ...BARE_PAYLOAD, firstName: "Solo" })).toBe("Solo");
});
});
describe("registry helpers", () => {
it("resolveAdapter returns the registered adapter for a known type", () => {
expect(resolveAdapter("slack")).toBe(adapterRegistry.slack);
expect(resolveAdapter("webhook")).toBe(adapterRegistry.webhook);
});
it("resolveAdapter returns undefined for an unknown type", () => {
expect(resolveAdapter("telegram")).toBeUndefined();
});
it("ADAPTER_TYPES mirrors the registry keys", () => {
expect([...ADAPTER_TYPES].sort()).toEqual(Object.keys(adapterRegistry).sort());
});
});
describe("slack adapter — headlines, empty body, config", () => {
it.each([
["marketing.lead.qualified", "Lead Qualified"],
["marketing.lead.convertedtotrial", "Lead converted to Trial"],
["marketing.lead.convertedtocustomer", "Lead converted to Customer"],
] as const)("renders the %s headline", (eventType, expected) => {
const body = buildSlackBlocks(eventType, PAYLOAD, {}) as { text: string; blocks: unknown[] };
expect(body.text).toContain(expected);
});
it("falls back to a generic headline for an unknown event type", () => {
const body = buildSlackBlocks(
"marketing.lead.unknown" as unknown as MarketingLeadEventType,
PAYLOAD,
{}
) as { text: string };
expect(body.text).toContain("Lead event");
});
it("omits the detail section when the lead has no enrichment fields", () => {
const body = buildSlackBlocks("marketing.lead.captured", BARE_PAYLOAD, {}) as { blocks: unknown[] };
// header + summary only — no third "details" section block.
expect(body.blocks).toHaveLength(2);
});
it("parseConfig throws on a non-object config", () => {
expect(() => slackAdapter.parseConfig("nope")).toThrow(MarketingAdapterConfigError);
expect(() => slackAdapter.parseConfig(null)).toThrow(MarketingAdapterConfigError);
});
it("parseConfig keeps a string channel and drops a non-string one", () => {
expect(slackAdapter.parseConfig({ webhookUrl: "https://hooks.slack.com/x", channel: "#leads" })).toEqual({
webhookUrl: "https://hooks.slack.com/x",
channel: "#leads",
});
expect(slackAdapter.parseConfig({ webhookUrl: "https://hooks.slack.com/x", channel: 5 })).toEqual({
webhookUrl: "https://hooks.slack.com/x",
channel: undefined,
});
});
it("send injects the channel override into the request body", async () => {
const fetchImpl = mockFetch(200);
await slackAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { webhookUrl: "https://hooks.slack.com/x", channel: "#leads" },
ctx: { fetch: fetchImpl },
});
expect(firstCallBody(fetchImpl).channel).toBe("#leads");
});
});
describe("discord adapter — colors, titles, config", () => {
it.each([
["marketing.lead.captured", 0x3b82f6, "New Lead"],
["marketing.lead.qualified", 0x8b5cf6, "Lead Qualified"],
["marketing.lead.convertedtocustomer", 0x10b981, "Converted to Customer"],
] as const)("maps %s to its color + title", (eventType, color, title) => {
const body = buildDiscordEmbed(eventType, PAYLOAD, {}) as { embeds: Array<{ color: number; title: string }> };
expect(body.embeds[0].color).toBe(color);
expect(body.embeds[0].title).toBe(title);
});
it("uses the neutral fallback color + title for an unknown event type", () => {
const body = buildDiscordEmbed(
"marketing.lead.unknown" as unknown as MarketingLeadEventType,
PAYLOAD,
{}
) as { embeds: Array<{ color: number; title: string }> };
expect(body.embeds[0].color).toBe(0x6b7280);
expect(body.embeds[0].title).toBe("Lead event");
});
it("emits only the Email field for a bare lead", () => {
const body = buildDiscordEmbed("marketing.lead.captured", BARE_PAYLOAD, {}) as {
embeds: Array<{ fields: Array<{ name: string }> }>;
};
expect(body.embeds[0].fields).toHaveLength(1);
expect(body.embeds[0].fields[0].name).toBe("Email");
});
it("parseConfig throws on non-object and on a missing webhookUrl", () => {
expect(() => discordAdapter.parseConfig(42)).toThrow(MarketingAdapterConfigError);
expect(() => discordAdapter.parseConfig({ username: "bot" })).toThrow(/webhookUrl/);
});
it("send forwards a configured username", async () => {
const fetchImpl = mockFetch(200);
await discordAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { webhookUrl: "https://discord.com/api/webhooks/x/y", username: "LeadBot" },
ctx: { fetch: fetchImpl },
});
expect(firstCallBody(fetchImpl).username).toBe("LeadBot");
});
});
describe("mailchimp adapter — config validation + send error tagging", () => {
it("parseConfig throws on non-object, missing apiKey, and missing listId", () => {
expect(() => mailchimpAdapter.parseConfig(null)).toThrow(/object/);
expect(() => mailchimpAdapter.parseConfig({ listId: "l1" })).toThrow(/apiKey/);
expect(() => mailchimpAdapter.parseConfig({ apiKey: "k-us1" })).toThrow(/listId/);
});
it("parseConfig normalises status and filters non-string tags", () => {
const cfg = mailchimpAdapter.parseConfig({
apiKey: "k-us1",
listId: "l1",
status: "pending",
tags: ["vip", 7, "eu"],
});
expect(cfg.status).toBe("pending");
expect(cfg.tags).toEqual(["vip", "eu"]);
});
it("parseConfig defaults an unknown status to subscribed", () => {
const cfg = mailchimpAdapter.parseConfig({ apiKey: "k-us1", listId: "l1", status: "garbage" });
expect(cfg.status).toBe("subscribed");
});
it("buildMailchimpPayload derives the DC from the last dash segment", () => {
const built = buildMailchimpPayload(PAYLOAD, { apiKey: "abc-def-us21", listId: "l1" });
expect(built.url).toMatch(/^https:\/\/us21\.api\.mailchimp\.com\//);
});
it("buildMailchimpPayload includes tags when configured and url-encodes the list id", () => {
const built = buildMailchimpPayload(PAYLOAD, {
apiKey: "k-us1",
listId: "list/with space",
tags: ["vip"],
});
expect(built.body.tags).toEqual(["vip"]);
expect(built.url).toContain(encodeURIComponent("list/with space"));
});
it("send returns config_error when the API key has no DC suffix", async () => {
const fetchImpl = mockFetch(200);
const res = await mailchimpAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { apiKey: "nodc", listId: "l1" },
ctx: { fetch: fetchImpl },
});
expect(res.ok).toBe(false);
expect(res.errorTag).toBe("config_error");
expect(fetchImpl).not.toHaveBeenCalled();
});
});
describe("hubspot adapter — config + non-409 passthrough", () => {
it("parseConfig throws on non-object and on a missing accessToken", () => {
expect(() => hubspotAdapter.parseConfig("x")).toThrow(/object/);
expect(() => hubspotAdapter.parseConfig({})).toThrow(/accessToken/);
});
it("parseConfig returns the token for a valid config", () => {
expect(hubspotAdapter.parseConfig({ accessToken: "pat-123" })).toEqual({ accessToken: "pat-123" });
});
it("buildHubSpotPayload maps utm_medium and lowercases the email", () => {
const built = buildHubSpotPayload({ ...PAYLOAD, email: " MiXeD@Example.COM " });
const props = built.body.properties as Record<string, string>;
expect(props.email).toBe("mixed@example.com");
expect(props.utm_medium).toBe("cpc");
});
it("passes a 5xx upstream result straight through (only 409 is rewritten)", async () => {
const fetchImpl = mockFetch(503);
const res = await hubspotAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { accessToken: "tok" },
ctx: { fetch: fetchImpl },
});
expect(res.ok).toBe(false);
expect(res.status).toBe(503);
expect(res.errorTag).toBe("upstream_5xx");
});
it("sends a Bearer token and returns ok on 2xx", async () => {
const fetchImpl = mockFetch(201);
const res = await hubspotAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { accessToken: "tok" },
ctx: { fetch: fetchImpl },
});
expect(res.ok).toBe(true);
expect(firstCallInit(fetchImpl).headers.authorization).toBe("Bearer tok");
});
});
describe("brevo adapter — config validation + payload shaping", () => {
it("parseConfig throws on non-object and on a missing apiKey", () => {
expect(() => brevoAdapter.parseConfig(99)).toThrow(/object/);
expect(() => brevoAdapter.parseConfig({ listIds: [1] })).toThrow(/apiKey/);
});
it("parseConfig returns a normalised config for a valid blob", () => {
expect(brevoAdapter.parseConfig({ apiKey: "k", listIds: [4] })).toEqual({ apiKey: "k", listIds: [4] });
});
it("parseConfig drops non-finite list ids and collapses an empty result to undefined", () => {
expect(brevoAdapter.parseConfig({ apiKey: "k", listIds: [1, "2", Number.NaN, 3, Infinity] }).listIds).toEqual([
1, 3,
]);
expect(brevoAdapter.parseConfig({ apiKey: "k", listIds: ["a", "b"] }).listIds).toBeUndefined();
expect(brevoAdapter.parseConfig({ apiKey: "k" }).listIds).toBeUndefined();
});
it("buildBrevoPayload trims/lowercases the email and omits empty attributes", () => {
const built = buildBrevoPayload({ ...BARE_PAYLOAD, email: " UP@Example.COM " }, { apiKey: "k" });
expect(built.body.email).toBe("up@example.com");
expect(built.body.attributes).toEqual({});
expect(built.body.listIds).toBeUndefined();
});
});
describe("custom-webhook adapter — config validation + signing", () => {
it("parseConfig throws on non-object and on a missing url", () => {
expect(() => customWebhookAdapter.parseConfig(null)).toThrow(/object/);
expect(() => customWebhookAdapter.parseConfig({ url: "" })).toThrow(/url/);
});
it("parseConfig keeps only string headers and ignores an array header blob", () => {
expect(
customWebhookAdapter.parseConfig({ url: "https://x", headers: { a: "1", b: 2, c: "3" } }).headers
).toEqual({ a: "1", c: "3" });
expect(customWebhookAdapter.parseConfig({ url: "https://x", headers: ["a", "b"] }).headers).toEqual({});
});
it("parseConfig drops a non-string signingSecret", () => {
expect(customWebhookAdapter.parseConfig({ url: "https://x", signingSecret: 123 }).signingSecret).toBeUndefined();
expect(customWebhookAdapter.parseConfig({ url: "https://x", signingSecret: "s" }).signingSecret).toBe("s");
});
it("buildCustomPayload defaults occurredAt to an ISO string when absent", () => {
const env = buildCustomPayload("marketing.lead.captured", BARE_PAYLOAD, {});
expect(typeof env.occurredAt).toBe("string");
expect(() => new Date(env.occurredAt as string).toISOString()).not.toThrow();
});
it("send omits the signature header when no signingSecret is configured", async () => {
const fetchImpl = mockFetch(200);
await customWebhookAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { url: "https://example.com/hook", headers: {} },
ctx: { fetch: fetchImpl },
});
expect(firstCallInit(fetchImpl).headers["x-marketing-signature"]).toBeUndefined();
});
it("send signs the exact serialized body it transmits", async () => {
const fetchImpl = mockFetch(200);
await customWebhookAdapter.send({
eventType: "marketing.lead.captured",
payload: PAYLOAD,
config: { url: "https://example.com/hook", signingSecret: "shh", headers: {} },
ctx: { fetch: fetchImpl },
});
const init = firstCallInit(fetchImpl);
const { createHmac } = await import("node:crypto");
const expected = createHmac("sha256", "shh").update(init.body as string).digest("hex");
expect(init.headers["x-marketing-signature"]).toBe(`sha256=${expected}`);
});
});