Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,38 @@
export { createMailjetProvider, createMailjetProviderFromEnv, mailjetApiBaseUrl, MailjetProvider } from "./mailjet.js";
export { createQueuedMailProvider, createQueuedMailProviderFromEnv, QueuedMailProvider } from "./queue.js";
export type { QueueMailProviderEnv, QueueMailProviderFromEnvOptions, QueueMailProviderOptions, QueueMailProviderWarning } from "./queue.js";
export type { MailjetEnv, MailjetProviderOptions, MailMetricsHook } from "./mailjet.js";
export type {
MailAddress,
MailAddressInput,
MailAttachment,
MailAttachmentDisposition,
MailHeader,
MailPersonalization,
MailProvider,
MailProviderId,
MailTrackingSettings,
SendMailInput,
SendMailResult,
} from "./types.js";
export { MailProviderError } from "./types.js";
// React-Email transactional templates — the canonical render API. The
// pre-19 string-template renderer (`renderTransactionalMailTemplate`)
// was retired alongside the Stripe-19 cleanup; downstream callers that
// need a translator-bound function should go through the host
// application (see apps/web/app/locale/mail-translator.server.ts).
export {
renderTransactionalEmail,
reactTransactionalTemplateNames,
buildBrand,
withBrandDefaults,
defaultMailBrand,
} from "./templates-react/render.js";
export type {
ReactTransactionalTemplateName,
ReactTemplatePropsMap,
RenderedReactEmail,
MailBrand,
} from "./templates-react/render.js";
export { InvalidActionUrlError, assertSafeUrl } from "./templates-react/_layout/Button.js";
@@ -0,0 +1,354 @@
import { describe, expect, test, vi } from "vitest";
import { createMailjetProviderFromEnv, MailjetProvider } from "./mailjet.js";
import { MailProviderError } from "./types.js";
function basicAuth(apiKey: string, secretKey: string): string {
return `Basic ${Buffer.from(`${apiKey}:${secretKey}`, "utf8").toString("base64")}`;
}
function jsonResponse(body: unknown, init: ResponseInit = {}) {
return new Response(JSON.stringify(body), {
headers: { "content-type": "application/json", ...init.headers },
...init,
});
}
function successBody(messageUuid = "uuid-123") {
return { Messages: [{ Status: "success", To: [{ Email: "to@example.com", MessageID: 456, MessageUUID: messageUuid, MessageHref: "https://api.mailjet.com/v3/message/456" }] }] };
}
function captureError(fn: () => unknown): unknown {
try {
fn();
} catch (error) {
return error;
}
throw new Error("Expected function to throw.");
}
function expectRedacted(error: unknown) {
const serialized = JSON.stringify(error, Object.getOwnPropertyNames(error));
expect(serialized).not.toContain("super-secret-secret-key");
}
describe("MailjetProvider", () => {
test("maps send input to the Mailjet v3.1 payload and returns provider diagnostics", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody("uuid-123"), { status: 200 }));
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "default@example.com",
fromName: "Default Sender",
baseUrl: "https://mail.example.com/",
fetch: fetchMock as unknown as typeof fetch,
});
const sendAt = new Date("2026-05-05T12:00:00.000Z");
await expect(
provider.send({
from: { email: "sender@example.com", name: "Sender" },
to: ["user@example.com", { email: "named@example.com", name: "Named Recipient" }],
cc: [{ email: "cc@example.com", name: "CC" }],
bcc: ["bcc@example.com"],
replyTo: { email: "reply@example.com", name: "Reply" },
subject: "Welcome",
text: "Plain text",
html: "<p>Hello</p>",
templateId: "12345",
attachments: [{ content: "YWJj", filename: "file.txt", id: "attachment_1" }],
tags: ["signup"],
personalization: [{ email: "user@example.com", data: { firstName: "Ada" } }],
precedenceBulk: true,
sendAt, // not supported by Mailjet v3.1 send → intentionally dropped
inReplyTo: "previous-message",
references: ["reference-message"],
settings: { trackClicks: true, trackOpens: false, trackContent: true },
headers: [{ name: "X-Test", value: "yes" }],
listUnsubscribe: "<mailto:unsubscribe@example.com>",
})
).resolves.toEqual({
provider: "mailjet",
status: "queued",
messageId: "uuid-123",
});
expect(provider.id).toBe("mailjet");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith("https://mail.example.com/v3.1/send", {
method: "POST",
headers: {
Authorization: basicAuth("api_key", "secret_key"),
"Content-Type": "application/json",
Accept: "application/json",
},
signal: expect.any(AbortSignal),
body: JSON.stringify({
Messages: [
{
From: { Email: "sender@example.com", Name: "Sender" },
To: [{ Email: "user@example.com" }, { Email: "named@example.com", Name: "Named Recipient" }],
Cc: [{ Email: "cc@example.com", Name: "CC" }],
Bcc: [{ Email: "bcc@example.com" }],
ReplyTo: { Email: "reply@example.com", Name: "Reply" },
Subject: "Welcome",
TextPart: "Plain text",
HTMLPart: "<p>Hello</p>",
TemplateID: 12345,
TemplateLanguage: true,
Attachments: [{ ContentType: "text/plain", Filename: "file.txt", Base64Content: "YWJj" }],
Headers: {
"X-Test": "yes",
"In-Reply-To": "previous-message",
References: "reference-message",
"List-Unsubscribe": "<mailto:unsubscribe@example.com>",
Precedence: "bulk",
},
CustomCampaign: "signup",
TrackOpens: "disabled",
TrackClicks: "enabled",
Variables: { firstName: "Ada" },
},
],
}),
});
});
test("creates providers only from explicit Mailjet fixture env", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody("msg_fixture"), { status: 200 }));
const provider = createMailjetProviderFromEnv({
MAILJET_API_KEY: "fixture_api_key",
MAILJET_SECRET_KEY: "fixture_secret_key",
MAILJET_FROM_EMAIL: "sender@example.com",
MAILJET_FROM_NAME: "Fixture Sender",
}) as MailjetProvider;
Object.defineProperty(provider, "fetchImpl", { value: fetchMock });
await expect(provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" })).resolves.toMatchObject({
provider: "mailjet",
status: "queued",
messageId: "msg_fixture",
});
expect(fetchMock).toHaveBeenCalledWith(
"https://api.mailjet.com/v3.1/send",
expect.objectContaining({
headers: expect.objectContaining({ Authorization: basicAuth("fixture_api_key", "fixture_secret_key") }),
body: expect.stringContaining("Fixture Sender"),
})
);
});
test("maps idempotency keys to Mailjet CustomID", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody("msg_idempotent"), { status: 200 }));
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
});
await provider.send({
to: ["user@example.com"],
subject: "Welcome",
text: "Hello",
idempotencyKey: "notification-delivery:delivery_1",
});
expect(fetchMock).toHaveBeenCalledWith(
"https://api.mailjet.com/v3.1/send",
expect.objectContaining({
body: expect.stringContaining('"CustomID":"notification-delivery:delivery_1"'),
})
);
});
test("adds the SandboxMode flag when sandbox is enabled", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody(), { status: 200 }));
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
sandbox: true,
fetch: fetchMock as unknown as typeof fetch,
});
await provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" });
expect(fetchMock).toHaveBeenCalledWith(
"https://api.mailjet.com/v3.1/send",
expect.objectContaining({ body: expect.stringContaining('"SandboxMode":true') })
);
});
test("validates required Mailjet environment variables with key-only reporting", () => {
const missingApiKey = captureError(() => createMailjetProviderFromEnv({ MAILJET_SECRET_KEY: "s", MAILJET_FROM_EMAIL: "sender@example.com" }));
const missingSecretKey = captureError(() => createMailjetProviderFromEnv({ MAILJET_API_KEY: "k", MAILJET_FROM_EMAIL: "sender@example.com" }));
const missingFromEmail = captureError(() => createMailjetProviderFromEnv({ MAILJET_API_KEY: "k", MAILJET_SECRET_KEY: "super-secret-secret-key" }));
expect(missingApiKey).toMatchObject({ message: "MAILJET_API_KEY is required for Mailjet email delivery." });
expect(missingSecretKey).toMatchObject({ message: "MAILJET_SECRET_KEY is required for Mailjet email delivery." });
expect(missingFromEmail).toMatchObject({ message: "MAILJET_FROM_EMAIL is required for Mailjet email delivery." });
expectRedacted(missingFromEmail);
});
test("rejects an empty recipient list before calling Mailjet", async () => {
const fetchMock = vi.fn();
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
});
await expect(provider.send({ to: [], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
provider: "mailjet",
message: "At least one recipient is required.",
});
expect(fetchMock).not.toHaveBeenCalled();
});
test("rejects non-numeric template ids before calling Mailjet", async () => {
const fetchMock = vi.fn();
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
});
await expect(provider.send({ to: ["user@example.com"], templateId: "welcome" })).rejects.toMatchObject({
provider: "mailjet",
message: "Mailjet TemplateID must be numeric.",
});
expect(fetchMock).not.toHaveBeenCalled();
});
test("includes status and response body for failed HTTP responses", async () => {
const responseBody = { ErrorMessage: "Unauthorized", StatusCode: 401 };
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: vi.fn(async () => jsonResponse(responseBody, { status: 401 })) as unknown as typeof fetch,
});
await expect(provider.send({ to: ["bad@example.com"], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
name: "MailProviderError",
provider: "mailjet",
statusCode: 401,
responseBody,
message: "Mailjet email request failed with 401.",
} satisfies Partial<MailProviderError>);
});
test("treats per-message errors in a 200 response as a failure", async () => {
const responseBody = { Messages: [{ Status: "error", Errors: [{ ErrorMessage: "Invalid email" }] }] };
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: vi.fn(async () => jsonResponse(responseBody, { status: 200 })) as unknown as typeof fetch,
});
await expect(provider.send({ to: ["bad@example.com"], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
provider: "mailjet",
message: "Mailjet rejected at least one message.",
responseBody,
});
});
test("caps failed response bodies before adding provider diagnostics", async () => {
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
responseBodyLimitBytes: 16,
fetch: vi.fn(async () => new Response("safe-prefix-token=secret-tail", { status: 500 })) as unknown as typeof fetch,
});
await expect(provider.send({ to: ["bad@example.com"], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
provider: "mailjet",
statusCode: 500,
responseBody: "safe-prefix-toke",
});
});
test("converts aborts into bounded Mailjet timeout errors", async () => {
const abortError = new Error("aborted");
abortError.name = "AbortError";
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
timeoutMs: 1,
fetch: vi.fn(async () => {
throw abortError;
}) as unknown as typeof fetch,
});
await expect(provider.send({ to: ["bad@example.com"], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
provider: "mailjet",
message: "Mailjet email request timed out.",
});
});
test("emits onMetric with status=delivered on a fully accepted send", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody(), { status: 200 }));
const samples: Array<{ provider: string; status: string }> = [];
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
onMetric: (s) => samples.push(s),
});
await provider.send({ to: ["to@example.com"], subject: "x", text: "y" });
expect(samples).toEqual([{ provider: "mailjet", status: "delivered" }]);
});
test("emits onMetric with status=failed on non-2xx response", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ ErrorMessage: "bad" }, { status: 422 }));
const samples: Array<{ provider: string; status: string }> = [];
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
onMetric: (s) => samples.push(s),
});
await expect(provider.send({ to: ["to@example.com"], subject: "x", text: "y" })).rejects.toBeInstanceOf(MailProviderError);
expect(samples).toEqual([{ provider: "mailjet", status: "failed" }]);
});
test("emits onMetric with status=failed when fetch throws", async () => {
const samples: Array<{ provider: string; status: string }> = [];
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: (async () => {
throw new Error("network down");
}) as unknown as typeof fetch,
onMetric: (s) => samples.push(s),
});
await expect(provider.send({ to: ["to@example.com"], subject: "x", text: "y" })).rejects.toThrow("network down");
expect(samples).toEqual([{ provider: "mailjet", status: "failed" }]);
});
test("a throwing onMetric does not block delivery", async () => {
const fetchMock = vi.fn(async () => jsonResponse(successBody(), { status: 200 }));
const provider = new MailjetProvider({
apiKey: "api_key",
secretKey: "secret_key",
fromEmail: "sender@example.com",
fetch: fetchMock as unknown as typeof fetch,
onMetric: () => {
throw new Error("metric write failed");
},
});
const result = await provider.send({ to: ["to@example.com"], subject: "x", text: "y" });
expect(result.status).toBe("queued");
});
});
@@ -0,0 +1,476 @@
import { MailProviderError, type MailAddress, type MailAddressInput, type MailProvider, type SendMailInput, type SendMailResult } from "./types.js";
export const mailjetApiBaseUrl = "https://api.mailjet.com";
const DEFAULT_MAILJET_TIMEOUT_MS = 10_000;
const DEFAULT_RESPONSE_BODY_LIMIT_BYTES = 4_096;
type Fetch = typeof fetch;
type MailjetAddress = {
Email: string;
Name?: string;
};
type MailjetAttachment = {
ContentType: string;
Filename: string;
Base64Content: string;
ContentID?: string;
};
type MailjetMessage = {
From: MailjetAddress;
To: MailjetAddress[];
Cc?: MailjetAddress[];
Bcc?: MailjetAddress[];
ReplyTo?: MailjetAddress;
Subject?: string;
TextPart?: string;
HTMLPart?: string;
TemplateID?: number;
TemplateLanguage?: boolean;
Variables?: Record<string, unknown>;
Attachments?: MailjetAttachment[];
InlinedAttachments?: MailjetAttachment[];
Headers?: Record<string, string>;
CustomCampaign?: string;
TrackOpens?: "enabled" | "disabled";
TrackClicks?: "enabled" | "disabled";
CustomID?: string;
};
type MailjetSendRequest = {
Messages: MailjetMessage[];
SandboxMode?: boolean;
};
export type MailMetricsHook = (input: { provider: "mailjet"; status: "delivered" | "failed" }) => void;
export type MailjetProviderOptions = {
apiKey: string;
secretKey: string;
fromEmail: string;
fromName?: string;
baseUrl?: string;
fetch?: Fetch;
timeoutMs?: number;
responseBodyLimitBytes?: number;
/**
* When true, the request is sent with Mailjet's `SandboxMode` flag so the
* payload is validated (auth, addresses, mapping) without actually
* delivering mail. Wire this to a staging/test toggle — never enable in
* production paths.
*/
sandbox?: boolean;
/**
* Optional hook invoked once per send (`status: "delivered"` on HTTP 2xx
* with all messages accepted, `"failed"` otherwise). The hook MUST NOT throw
* — the provider wraps it in a try/catch so a misbehaving hook can't block
* mail delivery. Wire to mail_sent_total in the host app's metrics package.
*/
onMetric?: MailMetricsHook;
};
export type MailjetEnv = Record<string, string | undefined> & {
MAILJET_API_KEY?: string;
MAILJET_SECRET_KEY?: string;
MAILJET_FROM_EMAIL?: string;
MAILJET_FROM_NAME?: string;
};
export class MailjetProvider implements MailProvider {
readonly id = "mailjet" as const;
private readonly authorization: string;
private readonly defaultFrom: MailAddress;
private readonly baseUrl: string;
private readonly fetchImpl: Fetch;
private readonly timeoutMs: number;
private readonly responseBodyLimitBytes: number;
private readonly sandbox: boolean;
private readonly onMetric: MailMetricsHook | undefined;
constructor(options: MailjetProviderOptions) {
const apiKey = requireNonEmpty(options.apiKey, "MAILJET_API_KEY");
const secretKey = requireNonEmpty(options.secretKey, "MAILJET_SECRET_KEY");
this.authorization = `Basic ${Buffer.from(`${apiKey}:${secretKey}`, "utf8").toString("base64")}`;
this.defaultFrom = {
email: requireNonEmpty(options.fromEmail, "MAILJET_FROM_EMAIL"),
...(options.fromName ? { name: options.fromName } : {}),
};
this.baseUrl = (options.baseUrl ?? mailjetApiBaseUrl).replace(/\/+$/, "");
this.fetchImpl = options.fetch ?? fetch;
this.timeoutMs = normalizePositiveInteger(options.timeoutMs, DEFAULT_MAILJET_TIMEOUT_MS);
this.responseBodyLimitBytes = normalizePositiveInteger(options.responseBodyLimitBytes, DEFAULT_RESPONSE_BODY_LIMIT_BYTES);
this.sandbox = options.sandbox ?? false;
this.onMetric = options.onMetric;
}
private emitMetric(status: "delivered" | "failed"): void {
if (!this.onMetric) return;
try {
this.onMetric({ provider: "mailjet", status });
} catch {
// Metric hook must never abort the send flow.
}
}
async send(input: SendMailInput): Promise<SendMailResult> {
const payload = toMailjetSendRequest(input, this.defaultFrom, this.sandbox);
let response: Response;
try {
response = await fetchWithTimeout(
this.fetchImpl,
`${this.baseUrl}/v3.1/send`,
{
method: "POST",
headers: {
Authorization: this.authorization,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(payload),
},
this.timeoutMs,
);
} catch (error) {
this.emitMetric("failed");
if (isAbortError(error)) {
throw new MailProviderError("Mailjet email request timed out.", { provider: this.id });
}
throw error;
}
const responseBody = await parseResponseBody(response, this.responseBodyLimitBytes);
if (!response.ok) {
this.emitMetric("failed");
throw new MailProviderError(`Mailjet email request failed with ${response.status}.`, {
provider: this.id,
statusCode: response.status,
responseBody,
});
}
// Mailjet returns HTTP 200 even when individual messages fail; the
// per-message Status carries the real outcome.
const messages = extractMessages(responseBody);
const rejected = messages.find((message) => typeof message.Status === "string" && message.Status.toLowerCase() !== "success");
if (rejected) {
this.emitMetric("failed");
throw new MailProviderError("Mailjet rejected at least one message.", {
provider: this.id,
statusCode: response.status,
responseBody,
});
}
this.emitMetric("delivered");
return {
provider: this.id,
status: "queued",
messageId: extractMessageId(messages),
};
}
}
export function createMailjetProvider(options: MailjetProviderOptions): MailProvider {
return new MailjetProvider(options);
}
export function createMailjetProviderFromEnv(env: MailjetEnv, options?: { onMetric?: MailMetricsHook; sandbox?: boolean }): MailProvider {
return new MailjetProvider({
apiKey: requireNonEmpty(env.MAILJET_API_KEY, "MAILJET_API_KEY"),
secretKey: requireNonEmpty(env.MAILJET_SECRET_KEY, "MAILJET_SECRET_KEY"),
fromEmail: requireNonEmpty(env.MAILJET_FROM_EMAIL, "MAILJET_FROM_EMAIL"),
fromName: env.MAILJET_FROM_NAME,
...(options?.onMetric ? { onMetric: options.onMetric } : {}),
...(options?.sandbox ? { sandbox: options.sandbox } : {}),
});
}
function toMailjetSendRequest(input: SendMailInput, defaultFrom: MailAddress, sandbox: boolean): MailjetSendRequest {
if (input.to.length === 0) {
throw new MailProviderError("At least one recipient is required.", { provider: "mailjet" });
}
if (!input.text && !input.html && !input.templateId) {
throw new MailProviderError("Email text, html or templateId is required.", { provider: "mailjet" });
}
const template = normalizeTemplateId(input.templateId);
const { attachments, inlined } = normalizeAttachments(input.attachments);
const headers = buildHeaders(input);
const baseMessage = compactObject<MailjetMessage>({
From: normalizeAddress(input.from ?? defaultFrom),
To: [],
Cc: input.cc?.map(normalizeAddress),
Bcc: input.bcc?.map(normalizeAddress),
ReplyTo: input.replyTo ? normalizeAddress(input.replyTo) : undefined,
Subject: input.subject,
TextPart: input.text,
HTMLPart: input.html,
TemplateID: template,
TemplateLanguage: template !== undefined ? true : undefined,
Attachments: attachments,
InlinedAttachments: inlined,
Headers: headers,
CustomCampaign: input.tags?.[0],
TrackOpens: toTrackingFlag(input.settings?.trackOpens),
TrackClicks: toTrackingFlag(input.settings?.trackClicks),
CustomID: normalizeCustomId(input.idempotencyKey),
});
const personalization = new Map((input.personalization ?? []).map((entry) => [entry.email, entry.data]));
let messages: MailjetMessage[];
if (personalization.size > 1) {
// Per-recipient Variables require one Mailjet message each. Cc/Bcc are
// attached only to the first message so shared recipients aren't copied
// once per personalized message.
messages = input.to.map((addr, index) => {
const recipient = normalizeAddress(addr);
const variables = personalization.get(recipient.Email);
return compactObject<MailjetMessage>({
...baseMessage,
...(index > 0 ? { Cc: undefined, Bcc: undefined } : {}),
To: [recipient],
Variables: variables,
});
});
} else {
messages = [
compactObject<MailjetMessage>({
...baseMessage,
To: input.to.map(normalizeAddress),
Variables: input.personalization?.[0]?.data,
}),
];
}
return compactObject<MailjetSendRequest>({
Messages: messages,
SandboxMode: sandbox ? true : undefined,
});
}
function normalizeAddress(address: MailAddressInput): MailjetAddress {
if (typeof address === "string") {
return { Email: address };
}
return compactObject<MailjetAddress>({
Email: address.email,
Name: address.name,
});
}
function normalizeTemplateId(templateId: string | undefined): number | undefined {
if (templateId === undefined) {
return undefined;
}
const numeric = Number(templateId);
if (!Number.isFinite(numeric)) {
throw new MailProviderError("Mailjet TemplateID must be numeric.", { provider: "mailjet" });
}
return numeric;
}
function normalizeAttachments(attachments: SendMailInput["attachments"]): { attachments?: MailjetAttachment[]; inlined?: MailjetAttachment[] } {
if (!attachments?.length) {
return {};
}
const regular: MailjetAttachment[] = [];
const inlined: MailjetAttachment[] = [];
for (const attachment of attachments) {
const mapped = compactObject<MailjetAttachment>({
ContentType: guessContentType(attachment.filename),
Filename: attachment.filename,
Base64Content: attachment.content,
ContentID: attachment.disposition === "inline" ? attachment.id ?? attachment.filename : undefined,
});
if (attachment.disposition === "inline") {
inlined.push(mapped);
} else {
regular.push(mapped);
}
}
return {
...(regular.length ? { attachments: regular } : {}),
...(inlined.length ? { inlined } : {}),
};
}
function buildHeaders(input: SendMailInput): Record<string, string> | undefined {
const headers: Record<string, string> = {};
for (const header of input.headers ?? []) {
headers[header.name] = header.value;
}
if (input.inReplyTo) {
headers["In-Reply-To"] = input.inReplyTo;
}
if (input.references?.length) {
headers["References"] = input.references.join(" ");
}
if (input.listUnsubscribe) {
headers["List-Unsubscribe"] = input.listUnsubscribe;
}
if (input.precedenceBulk) {
headers["Precedence"] = "bulk";
}
return Object.keys(headers).length > 0 ? headers : undefined;
}
function toTrackingFlag(value: boolean | undefined): "enabled" | "disabled" | undefined {
if (value === undefined) {
return undefined;
}
return value ? "enabled" : "disabled";
}
function normalizeCustomId(idempotencyKey: string | undefined): string | undefined {
if (!idempotencyKey) {
return undefined;
}
// Mailjet caps CustomID at 100 characters.
return idempotencyKey.slice(0, 100);
}
type MailjetResponseMessage = {
Status?: string;
To?: Array<{ MessageUUID?: string; MessageID?: number; MessageHref?: string }>;
};
function extractMessages(responseBody: unknown): MailjetResponseMessage[] {
if (responseBody && typeof responseBody === "object" && "Messages" in responseBody) {
const messages = (responseBody as { Messages?: unknown }).Messages;
if (Array.isArray(messages)) {
return messages as MailjetResponseMessage[];
}
}
return [];
}
function extractMessageId(messages: MailjetResponseMessage[]): string | undefined {
const recipient = messages[0]?.To?.[0];
if (!recipient) {
return undefined;
}
return recipient.MessageUUID ?? (recipient.MessageID !== undefined ? String(recipient.MessageID) : undefined);
}
function guessContentType(filename: string): string {
const extension = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1).toLowerCase() : "";
return CONTENT_TYPE_BY_EXTENSION[extension] ?? "application/octet-stream";
}
const CONTENT_TYPE_BY_EXTENSION: Record<string, string> = {
pdf: "application/pdf",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
svg: "image/svg+xml",
csv: "text/csv",
txt: "text/plain",
html: "text/html",
ics: "text/calendar",
json: "application/json",
xml: "application/xml",
zip: "application/zip",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
function requireNonEmpty(value: string | undefined, name: string): string {
if (!value?.trim()) {
throw new MailProviderError(`${name} is required for Mailjet email delivery.`, { provider: "mailjet" });
}
return value;
}
function compactObject<T extends Record<string, unknown>>(value: T): T {
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;
}
async function parseResponseBody(response: Response, limitBytes: number): Promise<unknown> {
const text = await readLimitedResponseText(response, limitBytes);
if (!text) {
return undefined;
}
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function fetchWithTimeout(fetchImpl: Fetch, input: Parameters<Fetch>[0], init: RequestInit, timeoutMs: number): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetchImpl(input, { ...init, signal: controller.signal });
} finally {
clearTimeout(timeout);
}
}
async function readLimitedResponseText(response: Response, limitBytes: number): Promise<string> {
if (!response.body) {
return "";
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
const chunks: string[] = [];
let bytes = 0;
while (bytes < limitBytes) {
const result = await reader.read();
if (result.done) {
chunks.push(decoder.decode());
return chunks.join("");
}
const chunk = result.value;
const remaining = limitBytes - bytes;
const slice = chunk.byteLength > remaining ? chunk.slice(0, remaining) : chunk;
chunks.push(decoder.decode(slice, { stream: chunk.byteLength <= remaining }));
bytes += slice.byteLength;
if (chunk.byteLength > remaining) {
await reader.cancel();
break;
}
}
chunks.push(decoder.decode());
return chunks.join("");
}
function normalizePositiveInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
}
function isAbortError(error: unknown) {
return error instanceof Error && error.name === "AbortError";
}
@@ -0,0 +1,261 @@
import { describe, expect, test, vi } from "vitest";
import { queueNames, type QueueEnqueueOptions, type TypedQueue } from "@toolctrl/queue";
import { createQueuedMailProvider as createQueuedMailProviderFromIndex } from "./index.js";
import { createQueuedMailProvider, createQueuedMailProviderFromEnv } from "./queue.js";
vi.mock("@toolctrl/queue/runtime", () => ({
createQueue: vi.fn(),
}));
function createQueueMock() {
return {
add: vi.fn(async () => ({ id: "job_123" })),
close: vi.fn(async () => undefined),
} as unknown as TypedQueue<typeof queueNames.email> & {
add: ReturnType<typeof vi.fn>;
close: ReturnType<typeof vi.fn>;
};
}
describe("QueuedMailProvider", () => {
test("exports the queued provider factory from the package index", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProviderFromIndex({ queue });
await expect(provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" })).resolves.toMatchObject({
provider: "queue",
status: "queued",
messageId: "job_123",
});
});
test("maps send input to a transactional mail descriptor and returns enqueue diagnostics", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProvider({ queue });
await expect(
provider.send({
from: { email: "sender@example.com", name: "Sender" },
to: ["user@example.com", { email: "named@example.com", name: "Named" }],
cc: [{ email: "cc@example.com", name: "CC" }],
bcc: ["bcc@example.com"],
replyTo: "reply@example.com",
subject: "Welcome",
text: "Plain text",
html: "<p>Hello</p>",
templateId: "template_123",
attachments: [{ content: "Zm9v", filename: "foo.txt", disposition: "attachment" }],
tags: ["welcome"],
precedenceBulk: true,
sendAt: new Date("2026-05-12T10:00:00.000Z"),
inReplyTo: "message_1",
references: ["message_0"],
settings: { trackClicks: true, trackOpens: false, trackContent: true },
headers: [{ name: "X-Test", value: "1" }],
listUnsubscribe: "<mailto:unsubscribe@example.com>",
personalization: [
{ email: "user@example.com", data: { firstName: "Ada" } },
{ email: "named@example.com", data: { firstName: "Grace" } },
],
})
).resolves.toEqual({
provider: "queue",
status: "queued",
messageId: "job_123",
warnings: {
queueName: queueNames.email,
jobName: "send-transactional-email",
},
});
expect(queue.add).toHaveBeenCalledWith(
"send-transactional-email",
{
kind: "mail.transactional",
from: { email: "sender@example.com", name: "Sender" },
to: ["user@example.com", { email: "named@example.com", name: "Named" }],
cc: [{ email: "cc@example.com", name: "CC" }],
bcc: ["bcc@example.com"],
replyTo: "reply@example.com",
subject: "Welcome",
text: "Plain text",
html: "<p>Hello</p>",
templateId: "template_123",
attachments: [{ content: "Zm9v", filename: "foo.txt", disposition: "attachment" }],
tags: ["welcome"],
precedenceBulk: true,
sendAt: 1_778_580_000,
inReplyTo: "message_1",
references: ["message_0"],
settings: { trackClicks: true, trackOpens: false, trackContent: true },
headers: [{ name: "X-Test", value: "1" }],
listUnsubscribe: "<mailto:unsubscribe@example.com>",
templateData: {
"user@example.com": { firstName: "Ada" },
"named@example.com": { firstName: "Grace" },
},
},
expect.objectContaining({
attempts: 3,
backoff: { type: "exponential", delay: 1_000 },
removeOnComplete: true,
removeOnFail: 1_000,
})
);
});
test("passes caller retry options through enqueueJob", async () => {
const queue = createQueueMock();
const enqueueOptions: QueueEnqueueOptions = { attempts: 9, backoff: { type: "fixed", delay: 250 }, idempotencyKey: "email_1" };
const provider = createQueuedMailProvider({ queue, enqueueOptions });
await provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" });
expect(queue.add).toHaveBeenCalledWith(
"send-transactional-email",
expect.objectContaining({ kind: "mail.transactional" }),
expect.objectContaining({
attempts: 9,
backoff: { type: "fixed", delay: 250 },
jobId: "email_1",
})
);
expect(queue.add.mock.calls[0]?.[2]).not.toHaveProperty("idempotencyKey");
});
test("uses send input idempotency keys for queued mail job ids", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProvider({ queue });
await provider.send({
to: ["user@example.com"],
subject: "Welcome",
text: "Hello",
idempotencyKey: "notification-delivery:delivery_1",
});
expect(queue.add).toHaveBeenCalledWith(
"send-transactional-email",
expect.objectContaining({
metadata: { idempotencyKey: "notification-delivery:delivery_1" },
}),
expect.objectContaining({ jobId: "notification-delivery:delivery_1" })
);
});
test("fails closed when Redis env is absent", async () => {
const provider = createQueuedMailProviderFromEnv({ env: {} });
await expect(provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" })).rejects.toMatchObject({
provider: "queue",
message: "Set BULLMQ_REDIS_URL or REDIS_URL to enqueue transactional email jobs.",
responseBody: {
code: "missing_redis_connection",
message: "Set BULLMQ_REDIS_URL or REDIS_URL to enqueue transactional email jobs.",
requiredEnv: ["BULLMQ_REDIS_URL", "REDIS_URL"],
},
});
});
test("preserves per-recipient personalization for queued mail", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProvider({ queue });
await provider.send({
to: ["user@example.com", "admin@example.com"],
subject: "Welcome",
templateId: "template_123",
personalization: [
{ email: "user@example.com", data: { firstName: "Ada" } },
{ email: "admin@example.com", data: { firstName: "Grace" } },
],
});
expect(queue.add).toHaveBeenCalledWith(
"send-transactional-email",
expect.objectContaining({
templateData: {
"user@example.com": { firstName: "Ada" },
"admin@example.com": { firstName: "Grace" },
},
}),
expect.any(Object)
);
});
test("propagates queue add rejections", async () => {
const queue = createQueueMock();
const error = new Error("redis unavailable");
queue.add.mockRejectedValueOnce(error);
const provider = createQueuedMailProvider({ queue });
await expect(provider.send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" })).rejects.toBe(error);
});
test("closes only internally-created queues after enqueue attempts", async () => {
const { createQueue } = await import("@toolctrl/queue/runtime");
const injectedQueue = createQueueMock();
const internalQueue = createQueueMock();
vi.mocked(createQueue).mockReturnValueOnce(internalQueue);
await createQueuedMailProvider({ queue: injectedQueue }).send({ to: ["user@example.com"], subject: "Welcome", text: "Hello" });
await createQueuedMailProviderFromEnv({ env: { BULLMQ_REDIS_URL: "redis://localhost:6379/0" } }).send({
to: ["user@example.com"],
subject: "Welcome",
text: "Hello",
});
expect(injectedQueue.close).not.toHaveBeenCalled();
expect(internalQueue.close).toHaveBeenCalledTimes(1);
});
test("closes internally-created queues when enqueue fails", async () => {
const { createQueue } = await import("@toolctrl/queue/runtime");
const internalQueue = createQueueMock();
const error = new Error("enqueue failed");
internalQueue.add.mockRejectedValueOnce(error);
vi.mocked(createQueue).mockReturnValueOnce(internalQueue);
await expect(
createQueuedMailProviderFromEnv({ env: { BULLMQ_REDIS_URL: "redis://localhost:6379/0" } }).send({
to: ["user@example.com"],
subject: "Welcome",
text: "Hello",
})
).rejects.toBe(error);
expect(internalQueue.close).toHaveBeenCalledTimes(1);
});
test("forwards tenantId and priorityOverride to enqueueJob options", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProvider({ queue });
await provider.send({
to: ["user@example.com"],
subject: "Reset your password",
text: "Click here",
tenantId: "tenant_priority_1",
priorityOverride: "critical",
});
const forwardedOptions = queue.add.mock.calls[0]?.[2];
expect(forwardedOptions).toMatchObject({ priority: 1 });
expect(forwardedOptions).not.toHaveProperty("tenantId");
expect(forwardedOptions).not.toHaveProperty("priorityOverride");
const payload = queue.add.mock.calls[0]?.[1];
expect(payload).toMatchObject({ tenantId: "tenant_priority_1" });
});
test("inherits empty body validation before enqueueing", async () => {
const queue = createQueueMock();
const provider = createQueuedMailProvider({ queue });
await expect(provider.send({ to: ["user@example.com"], subject: "Welcome" })).rejects.toMatchObject({
provider: "queue",
message: "Email text, html or templateId is required.",
});
expect(queue.add).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,162 @@
import {
buildTransactionalMailJob,
enqueueJob,
queueNames,
resolveRedisConnectionOptions,
type QueueEnqueueOptions,
type ConnectionOptions,
type RedisConnectionEnv,
type TypedQueue,
} from "@toolctrl/queue";
import { MailProviderError, type MailPersonalization, type MailProvider, type SendMailInput, type SendMailResult } from "./types.js";
export type QueueMailProviderWarning = {
code: "missing_redis_connection";
message: string;
requiredEnv: readonly ["BULLMQ_REDIS_URL", "REDIS_URL"];
};
export type QueueMailProviderOptions = {
queue: TypedQueue<typeof queueNames.email>;
enqueueOptions?: QueueEnqueueOptions;
};
export type QueueMailProviderEnv = RedisConnectionEnv;
export type QueueMailProviderFromEnvOptions = {
env?: QueueMailProviderEnv;
enqueueOptions?: QueueEnqueueOptions;
};
type QueueJobResult = Awaited<ReturnType<TypedQueue<typeof queueNames.email>["add"]>>;
export class QueuedMailProvider implements MailProvider {
readonly id = "queue" as const;
private readonly queue: TypedQueue<typeof queueNames.email>;
private readonly enqueueOptions?: QueueEnqueueOptions;
constructor(options: QueueMailProviderOptions) {
this.queue = options.queue;
this.enqueueOptions = options.enqueueOptions;
}
async send(input: SendMailInput): Promise<SendMailResult> {
const descriptor = toTransactionalMailJob(input);
const enqueueOptions: QueueEnqueueOptions = {
...(this.enqueueOptions ?? {}),
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
...(input.priorityOverride !== undefined ? { priorityOverride: input.priorityOverride } : {}),
};
const job = (await enqueueJob(this.queue, descriptor, enqueueOptions)) as QueueJobResult;
return {
provider: this.id,
status: "queued",
messageId: job.id,
warnings: {
queueName: descriptor.queueName,
jobName: descriptor.jobName,
},
};
}
}
export function createQueuedMailProvider(options: QueueMailProviderOptions): MailProvider {
return new QueuedMailProvider(options);
}
export function createQueuedMailProviderFromEnv(options: QueueMailProviderFromEnvOptions = {}): MailProvider {
const connection = resolveRedisConnectionOptions({ env: options.env });
if (!connection) {
return new MissingRedisQueuedMailProvider();
}
return new LazyQueuedMailProvider(connection, options.enqueueOptions);
}
class LazyQueuedMailProvider implements MailProvider {
readonly id = "queue" as const;
constructor(
private readonly connection: ConnectionOptions,
private readonly enqueueOptions?: QueueEnqueueOptions
) {}
async send(input: SendMailInput): Promise<SendMailResult> {
const { createQueue } = await import("@toolctrl/queue/runtime");
const queue = createQueue(queueNames.email, { connection: this.connection });
try {
return await new QueuedMailProvider({ queue, enqueueOptions: this.enqueueOptions }).send(input);
} finally {
await queue.close();
}
}
}
class MissingRedisQueuedMailProvider implements MailProvider {
readonly id = "queue" as const;
async send(): Promise<SendMailResult> {
const warning = missingRedisWarning();
throw new MailProviderError(warning.message, { provider: this.id, responseBody: warning });
}
}
function toTransactionalMailJob(input: SendMailInput) {
if (input.to.length === 0) {
throw new MailProviderError("At least one recipient is required.", { provider: "queue" });
}
if (!input.text && !input.html && !input.templateId) {
throw new MailProviderError("Email text, html or templateId is required.", { provider: "queue" });
}
return buildTransactionalMailJob({
from: input.from,
to: input.to,
cc: input.cc,
bcc: input.bcc,
replyTo: input.replyTo,
subject: input.subject,
text: input.text,
html: input.html,
templateId: input.templateId,
attachments: input.attachments,
tags: input.tags,
precedenceBulk: input.precedenceBulk,
sendAt: normalizeQueuedSendAt(input.sendAt),
inReplyTo: input.inReplyTo,
references: input.references,
settings: input.settings,
headers: input.headers,
listUnsubscribe: input.listUnsubscribe,
...(input.tenantId !== undefined && input.tenantId !== null ? { tenantId: input.tenantId } : {}),
templateData: personalizationToTemplateData(input.personalization),
metadata: input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : undefined,
});
}
function personalizationToTemplateData(personalization: readonly MailPersonalization[] | undefined): Record<string, unknown> | undefined {
if (!personalization?.length) {
return undefined;
}
return Object.fromEntries(personalization.map((entry) => [entry.email, entry.data]));
}
function normalizeQueuedSendAt(sendAt: SendMailInput["sendAt"]): number | undefined {
if (sendAt instanceof Date) {
return Math.floor(sendAt.getTime() / 1000);
}
return sendAt;
}
function missingRedisWarning(): QueueMailProviderWarning {
return {
code: "missing_redis_connection",
message: "Set BULLMQ_REDIS_URL or REDIS_URL to enqueue transactional email jobs.",
requiredEnv: ["BULLMQ_REDIS_URL", "REDIS_URL"],
};
}
@@ -0,0 +1,73 @@
import type { CSSProperties, ReactNode } from "react";
import { Header } from "./Header.js";
import { Footer } from "./Footer.js";
import type { MailBrand } from "./theme.js";
/**
* BaseLayout — root layout for transactional emails. Renders a 560px
* centred card with brand-themed header and footer, plus a hidden
* preview-text harvested by Gmail/Apple Mail as the inbox snippet.
*/
export interface BaseLayoutProps {
readonly brand: MailBrand;
readonly title: string;
readonly previewText?: string;
readonly unsubscribeUrl?: string;
readonly children: ReactNode;
}
const bodyStyle = (brand: MailBrand): CSSProperties => ({
margin: 0,
padding: 0,
backgroundColor: brand.backgroundColor,
color: brand.textColor,
fontFamily: brand.fontFamily,
fontSize: "16px",
lineHeight: "1.5",
});
const containerStyle: CSSProperties = {
width: "100%",
maxWidth: "560px",
margin: "0 auto",
padding: "24px 16px",
};
const cardStyle = (brand: MailBrand): CSSProperties => ({
backgroundColor: brand.surfaceColor,
border: `1px solid ${brand.borderColor}`,
borderRadius: "20px",
padding: "32px",
});
const previewStyle: CSSProperties = {
display: "none",
fontSize: "1px",
lineHeight: "1px",
maxHeight: 0,
maxWidth: 0,
opacity: 0,
overflow: "hidden",
} as CSSProperties;
export function BaseLayout({ brand, title, previewText, unsubscribeUrl, children }: BaseLayoutProps) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
</head>
<body style={bodyStyle(brand)}>
{previewText ? <div style={previewStyle}>{previewText}</div> : null}
<div style={containerStyle}>
<div style={cardStyle(brand)}>
<Header brand={brand} />
{children}
<Footer brand={brand} unsubscribeUrl={unsubscribeUrl} />
</div>
</div>
</body>
</html>
);
}
@@ -0,0 +1,53 @@
import type { CSSProperties, ReactNode } from "react";
import type { MailBrand } from "./theme.js";
/**
* Button — CTA-Button with brand-color theming. Validates href as
* https:// or mailto: to block javascript:/data: URL injection
* (magic-link phishing class).
*/
export interface ButtonProps {
readonly href: string;
readonly brand: MailBrand;
readonly children: ReactNode;
}
const ALLOWED_PROTOCOLS = ["https:", "mailto:"] as const;
export class InvalidActionUrlError extends Error {
constructor(public readonly url: string) {
super(`Refusing to render unsafe action URL: ${url}. Only https:// and mailto: are allowed.`);
this.name = "InvalidActionUrlError";
}
}
export function assertSafeUrl(url: string): void {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new InvalidActionUrlError(url);
}
if (!ALLOWED_PROTOCOLS.includes(parsed.protocol as (typeof ALLOWED_PROTOCOLS)[number])) {
throw new InvalidActionUrlError(url);
}
}
export function Button({ href, brand, children }: ButtonProps) {
assertSafeUrl(href);
const style: CSSProperties = {
display: "inline-block",
backgroundColor: brand.primaryColor,
color: brand.primaryTextColor,
padding: "12px 22px",
borderRadius: "999px",
fontWeight: 700,
fontSize: "15px",
textDecoration: "none",
};
return (
<a href={href} style={style} target="_blank" rel="noopener noreferrer">
{children}
</a>
);
}
@@ -0,0 +1,24 @@
import type { CSSProperties } from "react";
import type { MailBrand } from "./theme.js";
/**
* Eyebrow — small uppercase label rendered above the main heading.
* Used to communicate category (e.g. "Welcome", "Password reset").
*/
export interface EyebrowProps {
readonly brand: MailBrand;
readonly children: string;
}
const style = (brand: MailBrand): CSSProperties => ({
color: brand.mutedTextColor,
fontSize: "13px",
fontWeight: 700,
letterSpacing: "0.08em",
textTransform: "uppercase",
marginBottom: "8px",
});
export function Eyebrow({ brand, children }: EyebrowProps) {
return <div style={style(brand)}>{children}</div>;
}
@@ -0,0 +1,66 @@
import type { CSSProperties } from "react";
import type { MailBrand } from "./theme.js";
/**
* Footer — legal links (privacy, terms, imprint) and support contact.
* Required for DSGVO/CAN-SPAM compliance.
*/
export interface FooterProps {
readonly brand: MailBrand;
readonly unsubscribeUrl?: string;
}
const wrapperStyle: CSSProperties = {
marginTop: "24px",
paddingTop: "16px",
borderTop: "1px solid",
fontSize: "12px",
lineHeight: "1.5",
};
const linkStyle = (color: string): CSSProperties => ({
textDecoration: "underline",
color,
});
export function Footer({ brand, unsubscribeUrl }: FooterProps) {
return (
<div style={{ ...wrapperStyle, borderTopColor: brand.borderColor, color: brand.mutedTextColor }}>
<div>
{brand.privacyUrl ? (
<a href={brand.privacyUrl} style={linkStyle(brand.linkColor)}>
Privacy
</a>
) : null}
{brand.privacyUrl && brand.termsUrl ? <span style={{ margin: "0 6px" }}>·</span> : null}
{brand.termsUrl ? (
<a href={brand.termsUrl} style={linkStyle(brand.linkColor)}>
Terms
</a>
) : null}
{(brand.privacyUrl || brand.termsUrl) && brand.imprintUrl ? (
<span style={{ margin: "0 6px" }}>·</span>
) : null}
{brand.imprintUrl ? (
<a href={brand.imprintUrl} style={linkStyle(brand.linkColor)}>
Imprint
</a>
) : null}
</div>
{unsubscribeUrl ? (
<div style={{ marginTop: "8px" }}>
<a href={unsubscribeUrl} style={linkStyle(brand.linkColor)}>
Unsubscribe
</a>
</div>
) : null}
<div style={{ marginTop: "8px" }}>
Questions? Email us at{" "}
<a href={`mailto:${brand.supportEmail}`} style={linkStyle(brand.linkColor)}>
{brand.supportEmail}
</a>
.
</div>
</div>
);
}
@@ -0,0 +1,42 @@
import type { CSSProperties } from "react";
import type { MailBrand } from "./theme.js";
/**
* Header — brand logo (if configured) or product-name wordmark.
* Stays inline-styled to survive Outlook/Gmail HTML scrubbers.
*/
export interface HeaderProps {
readonly brand: MailBrand;
}
const headerStyle: CSSProperties = {
paddingBottom: "16px",
textAlign: "left",
};
const logoStyle: CSSProperties = {
display: "block",
border: 0,
borderRadius: "12px",
};
export function Header({ brand }: HeaderProps) {
if (brand.logoUrl) {
return (
<div style={headerStyle}>
<img
src={brand.logoUrl}
alt={brand.productName}
width={48}
height={48}
style={logoStyle}
/>
</div>
);
}
return (
<div style={headerStyle}>
<strong style={{ color: brand.textColor, fontSize: "18px" }}>{brand.productName}</strong>
</div>
);
}
@@ -0,0 +1,28 @@
import type { CSSProperties, ReactNode } from "react";
import type { MailBrand } from "./theme.js";
/**
* InfoBox — boxed section for important notices (e.g. "this link expires
* in 15 minutes", "if you didn't request this, ignore the email").
*/
export interface InfoBoxProps {
readonly brand: MailBrand;
readonly tone?: "info" | "warning";
readonly children: ReactNode;
}
const baseStyle: CSSProperties = {
marginTop: "20px",
padding: "14px 16px",
borderRadius: "10px",
fontSize: "14px",
lineHeight: "1.55",
};
export function InfoBox({ brand, tone = "info", children }: InfoBoxProps) {
const style: CSSProperties =
tone === "warning"
? { ...baseStyle, backgroundColor: "#fef3c7", color: "#92400e", border: "1px solid #fde68a" }
: { ...baseStyle, backgroundColor: "#f1f5f9", color: brand.textColor, border: `1px solid ${brand.borderColor}` };
return <div style={style}>{children}</div>;
}
@@ -0,0 +1,14 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`BaseLayout > applies tenant brand overrides (logo + primary color) 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="image" href="https://cdn.acme.test/logo.png"/><title>Hi</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">snippet</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><img src="https://cdn.acme.test/logo.png" alt="Acme" width="48" height="48" style="display:block;border:0;border-radius:12px"/></div><p>Body</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`BaseLayout > renders default-brand snapshot 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Hello</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">A preview</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Eyebrow</div><h1>Title</h1><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`BaseLayout > renders default-brand snapshot 2`] = `
"A preview
ToolCTRL
Eyebrow
Title
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,7 @@
export { BaseLayout, type BaseLayoutProps } from "./BaseLayout.js";
export { Header, type HeaderProps } from "./Header.js";
export { Footer, type FooterProps } from "./Footer.js";
export { Button, InvalidActionUrlError, assertSafeUrl, type ButtonProps } from "./Button.js";
export { InfoBox, type InfoBoxProps } from "./InfoBox.js";
export { Eyebrow, type EyebrowProps } from "./Eyebrow.js";
export { defaultMailBrand, withBrandDefaults, type MailBrand } from "./theme.js";
@@ -0,0 +1,98 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { BaseLayout } from "./BaseLayout.js";
import { Button, InvalidActionUrlError } from "./Button.js";
import { Eyebrow } from "./Eyebrow.js";
import { InfoBox } from "./InfoBox.js";
import { defaultMailBrand, withBrandDefaults } from "./theme.js";
describe("BaseLayout", () => {
test("renders default-brand snapshot", () => {
const result = renderReactEmail(
<BaseLayout brand={defaultMailBrand} title="Hello" previewText="A preview">
<Eyebrow brand={defaultMailBrand}>Eyebrow</Eyebrow>
<h1>Title</h1>
</BaseLayout>
);
expect(result.html).toMatchSnapshot();
expect(result.text).toMatchSnapshot();
});
test("applies tenant brand overrides (logo + primary color)", () => {
const brand = withBrandDefaults({
productName: "Acme",
logoUrl: "https://cdn.acme.test/logo.png",
primaryColor: "#123456",
tenantName: "Acme Inc",
});
const result = renderReactEmail(
<BaseLayout brand={brand} title="Hi" previewText="snippet">
<p>Body</p>
</BaseLayout>
);
expect(result.html).toContain("https://cdn.acme.test/logo.png");
expect(result.html).toContain("Acme");
expect(result.html).toMatchSnapshot();
});
});
describe("Button safety", () => {
test("renders https CTA", () => {
const { html } = renderReactEmail(
<Button brand={defaultMailBrand} href="https://example.com/go">
Go
</Button>
);
expect(html).toContain('href="https://example.com/go"');
});
test("allows mailto: CTA", () => {
const { html } = renderReactEmail(
<Button brand={defaultMailBrand} href="mailto:hi@example.com">
Mail
</Button>
);
expect(html).toContain('href="mailto:hi@example.com"');
});
test.each(["javascript:alert(1)", "http://insecure.test", "data:text/html,<script>", "not a url"])(
"rejects unsafe href %s",
(href) => {
expect(() =>
renderReactEmail(
<Button brand={defaultMailBrand} href={href}>
X
</Button>
)
).toThrow(InvalidActionUrlError);
}
);
});
describe("InfoBox", () => {
test("renders info tone", () => {
const { html } = renderReactEmail(
<InfoBox brand={defaultMailBrand}>Note</InfoBox>
);
expect(html).toContain("Note");
});
test("renders warning tone with accent palette", () => {
const { html } = renderReactEmail(
<InfoBox brand={defaultMailBrand} tone="warning">
Heads up
</InfoBox>
);
expect(html).toContain("Heads up");
expect(html).toMatch(/#fef3c7/i);
});
});
describe("Eyebrow", () => {
test("uppercases via CSS, not value", () => {
const { html } = renderReactEmail(<Eyebrow brand={defaultMailBrand}>welcome</Eyebrow>);
// The visible text is unchanged; transform happens via CSS.
expect(html).toContain(">welcome<");
expect(html).toContain("text-transform:uppercase");
});
});
@@ -0,0 +1,51 @@
/**
* Default brand-theme tokens for React-Email transactional templates.
*
* Templates accept a `brand` prop derived from `@toolctrl/brand`'s
* `BrandTokens`. When undefined we fall back to these defaults so
* preview/storybook renders stay deterministic regardless of tenant
* configuration. Keep this aligned with `packages/brand/src/index.ts`.
*/
export interface MailBrand {
readonly productName: string;
readonly logoUrl?: string;
readonly primaryColor: string;
readonly primaryTextColor: string;
readonly textColor: string;
readonly mutedTextColor: string;
readonly backgroundColor: string;
readonly surfaceColor: string;
readonly borderColor: string;
readonly linkColor: string;
readonly fontFamily: string;
readonly supportEmail: string;
readonly supportFromName: string;
readonly privacyUrl?: string;
readonly termsUrl?: string;
readonly imprintUrl?: string;
readonly tenantName?: string;
}
export const defaultMailBrand: MailBrand = {
productName: "ToolCTRL",
primaryColor: "#2563eb",
primaryTextColor: "#ffffff",
textColor: "#0f172a",
mutedTextColor: "#475569",
backgroundColor: "#f4f5f7",
surfaceColor: "#ffffff",
borderColor: "#e2e8f0",
linkColor: "#2563eb",
fontFamily:
"ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
supportEmail: "info@tool-ctrl.de",
supportFromName: "ToolCTRL Support",
privacyUrl: "https://tool-ctrl.de/privacy",
termsUrl: "https://tool-ctrl.de/terms",
imprintUrl: "https://tool-ctrl.de/imprint",
} as const;
export function withBrandDefaults(override?: Partial<MailBrand>): MailBrand {
if (!override) return defaultMailBrand;
return { ...defaultMailBrand, ...override };
}
@@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import { htmlToPlainText } from "./render-helpers.js";
describe("htmlToPlainText", () => {
test("preserves anchor labels with hrefs for text-mode email clients", () => {
const text = htmlToPlainText(
'<p>Hello Ada,</p><p><a href="https://app.example.com/invite"><strong>Join workspace</strong></a></p>'
);
expect(text).toBe("Hello Ada,\nJoin workspace (https://app.example.com/invite)");
});
test("removes non-body markup and decodes common entities deterministically", () => {
const text = htmlToPlainText(
[
"<head><title>Ignored</title></head>",
"<style>.hidden { display: none; }</style>",
'<script>alert("ignored")</script>',
"<div>ToolCTRL&nbsp;&amp;&nbsp;friends</div>",
"<div>&lt;safe&gt; &#39;quoted&#39; &quot;copy&quot;</div>",
"<br><p>Done</p>",
].join("")
);
expect(text).toBe("ToolCTRL & friends\n<safe> 'quoted' \"copy\"\n\nDone");
});
});
@@ -0,0 +1,54 @@
/**
* Internal render helpers for React-Email transactional templates.
*
* Uses `react-dom/server.renderToStaticMarkup` for deterministic
* SSR output and a small HTML-to-text fallback so we emit a clean
* plain-text alternative without pulling in the full `@react-email/render`
* runtime (which inflates worker images by ~60MB and pins a different
* react-version). See `docs/architecture/email-templates.md`.
*/
import type { ReactElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
export interface RenderedEmail {
readonly html: string;
readonly text: string;
}
/**
* Convert rendered HTML to a plain-text fallback. Preserves anchor URLs
* as `label (url)` so text-mode clients still get the CTA target.
*/
export function htmlToPlainText(html: string): string {
const withAnchorUrls = html.replace(
/<a\s+[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/giu,
(_, href: string, label: string) => `${label.replace(/<[^>]+>/gu, "").trim()} (${href})`
);
return withAnchorUrls
.replace(/<style[\s\S]*?<\/style>/giu, "")
.replace(/<script[\s\S]*?<\/script>/giu, "")
.replace(/<head[\s\S]*?<\/head>/giu, "")
.replace(/<br\s*\/?>(\r?\n)?/giu, "\n")
.replace(/<\/(p|h1|h2|h3|li|div|tr)>/giu, "\n")
.replace(/<[^>]+>/gu, "")
.replace(/&nbsp;/giu, " ")
.replace(/&amp;/giu, "&")
.replace(/&lt;/giu, "<")
.replace(/&gt;/giu, ">")
.replace(/&#39;/giu, "'")
.replace(/&quot;/giu, '"')
.replace(/[ \t]+\n/gu, "\n")
.replace(/\n{3,}/gu, "\n\n")
.trim();
}
/**
* Render a React element to `{ html, text }`. The HTML is prefixed with
* a DOCTYPE so mail clients render in standards mode.
*/
export function renderReactEmail(element: ReactElement): RenderedEmail {
const body = renderToStaticMarkup(element);
const html = `<!DOCTYPE html>${body}`;
const text = htmlToPlainText(body);
return { html, text };
}
@@ -0,0 +1,59 @@
import { describe, expect, test } from "vitest";
import {
reactTransactionalTemplateNames,
renderTransactionalEmail,
withBrandDefaults,
} from "./render.js";
const brand = withBrandDefaults();
describe("renderTransactionalEmail", () => {
test("exposes all 8 template names", () => {
const names = reactTransactionalTemplateNames();
expect(names).toEqual([
"welcome",
"magic-link",
"password-reset",
"invitation",
"subscription-success",
"subscription-failed",
"invoice-sent",
"tenant-notification",
]);
});
test("renders welcome via dispatch", () => {
const result = renderTransactionalEmail("welcome", {
brand,
recipientName: "Ada",
actionUrl: "https://app.example.com/login",
});
expect(result.html).toContain("Welcome to ToolCTRL, Ada!");
expect(result.text).toContain("Welcome to ToolCTRL, Ada!");
});
test("renders invitation via dispatch", () => {
const result = renderTransactionalEmail("invitation", {
brand,
senderName: "Grace",
senderOrganization: "Example Org",
actionUrl: "https://app.example.com/invite",
});
expect(result.html).toContain("Grace invited you to ToolCTRL");
expect(result.text).toContain("Join Example Org");
});
test("throws on unknown template", () => {
expect(() =>
renderTransactionalEmail("unknown" as Parameters<typeof renderTransactionalEmail>[0], {} as never)
).toThrow(/Unknown React transactional template/);
});
test("returns html with <!DOCTYPE html> prefix for SSR mode", () => {
const { html } = renderTransactionalEmail("welcome", {
brand,
actionUrl: "https://app.example.com/login",
});
expect(html.startsWith("<!DOCTYPE html>")).toBe(true);
});
});
@@ -0,0 +1,95 @@
/**
* Public entry-point for React-Email transactional templates.
*
* Dispatches a template-name plus props to the matching React component
* and renders `{ html, text }` deterministically via react-dom/server.
* The canonical entry-point for transactional mail rendering. Called
* directly from the host application's mail wrapper (see
* `apps/web/app/modules/emails/utils/EmailTemplates.ts`).
*
* Each entry intentionally accepts a small, explicit prop shape — we
* do not pipe arbitrary objects into the templates, so a malicious
* caller cannot inject extra React props.
*/
import { createElement, type ReactElement } from "react";
import { renderReactEmail } from "./render-helpers.js";
import { withBrandDefaults, type MailBrand } from "./_layout/theme.js";
import { WelcomeEmail, type WelcomeEmailProps } from "./transactional/Welcome.js";
import { MagicLinkEmail, type MagicLinkEmailProps } from "./transactional/MagicLink.js";
import { PasswordResetEmail, type PasswordResetEmailProps } from "./transactional/PasswordReset.js";
import { InvitationEmail, type InvitationEmailProps } from "./transactional/Invitation.js";
import {
SubscriptionSuccessEmail,
type SubscriptionSuccessEmailProps,
} from "./transactional/SubscriptionSuccess.js";
import {
SubscriptionFailedEmail,
type SubscriptionFailedEmailProps,
} from "./transactional/SubscriptionFailed.js";
import { InvoiceSentEmail, type InvoiceSentEmailProps } from "./transactional/InvoiceSent.js";
import { TenantNotificationEmail, type TenantNotificationEmailProps } from "./transactional/TenantNotification.js";
export type ReactTransactionalTemplateName =
| "welcome"
| "magic-link"
| "password-reset"
| "invitation"
| "subscription-success"
| "subscription-failed"
| "invoice-sent"
| "tenant-notification";
export type ReactTemplatePropsMap = {
welcome: WelcomeEmailProps;
"magic-link": MagicLinkEmailProps;
"password-reset": PasswordResetEmailProps;
invitation: InvitationEmailProps;
"subscription-success": SubscriptionSuccessEmailProps;
"subscription-failed": SubscriptionFailedEmailProps;
"invoice-sent": InvoiceSentEmailProps;
"tenant-notification": TenantNotificationEmailProps;
};
export interface RenderedReactEmail {
readonly html: string;
readonly text: string;
}
type AnyTemplateProps = ReactTemplatePropsMap[ReactTransactionalTemplateName];
const COMPONENTS: { [K in ReactTransactionalTemplateName]: (props: ReactTemplatePropsMap[K]) => ReactElement } = {
welcome: WelcomeEmail,
"magic-link": MagicLinkEmail,
"password-reset": PasswordResetEmail,
invitation: InvitationEmail,
"subscription-success": SubscriptionSuccessEmail,
"subscription-failed": SubscriptionFailedEmail,
"invoice-sent": InvoiceSentEmail,
"tenant-notification": TenantNotificationEmail,
};
export function renderTransactionalEmail<K extends ReactTransactionalTemplateName>(
template: K,
props: ReactTemplatePropsMap[K]
): RenderedReactEmail {
const component = COMPONENTS[template] as (p: AnyTemplateProps) => ReactElement;
if (!component) {
throw new Error(`Unknown React transactional template: ${template}`);
}
const element = createElement<AnyTemplateProps>(
component as (p: AnyTemplateProps) => ReactElement,
props as AnyTemplateProps
);
return renderReactEmail(element);
}
export function reactTransactionalTemplateNames(): readonly ReactTransactionalTemplateName[] {
return Object.keys(COMPONENTS) as ReactTransactionalTemplateName[];
}
export function buildBrand(override?: Partial<MailBrand>): MailBrand {
return withBrandDefaults(override);
}
export { withBrandDefaults, defaultMailBrand } from "./_layout/theme.js";
export type { MailBrand } from "./_layout/theme.js";
@@ -0,0 +1,55 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand, withBrandDefaults } from "../_layout/theme.js";
import { InvitationEmail } from "./Invitation.js";
describe("InvitationEmail", () => {
test("renders default snapshot", () => {
const result = renderReactEmail(
<InvitationEmail
brand={defaultMailBrand}
recipientName="Ada"
senderName="Grace"
senderOrganization="Example Org"
actionUrl="https://app.example.com/invite/abc"
/>
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("uses tenant brand for invite (logo + color)", () => {
const brand = withBrandDefaults({
productName: "Acme",
logoUrl: "https://cdn.acme.test/logo.png",
primaryColor: "#ff5500",
tenantName: "Acme Inc",
});
const { html } = renderReactEmail(
<InvitationEmail
brand={brand}
senderName="Grace"
senderOrganization="Acme Inc"
actionUrl="https://app.acme.test/invite/abc"
/>
);
expect(html).toContain("Grace invited you to Acme");
expect(html).toContain("Join Acme Inc");
expect(html).toContain("#ff5500");
expect(html).toContain("https://cdn.acme.test/logo.png");
});
test("escapes user-supplied sender/org names", () => {
const { html } = renderReactEmail(
<InvitationEmail
brand={defaultMailBrand}
senderName="<script>alert(1)</script>"
senderOrganization="Org & Co"
actionUrl="https://app.example.com/invite/abc"
/>
);
expect(html).not.toContain("<script>alert(1)</script>");
expect(html).toContain("&lt;script&gt;");
expect(html).toContain("Org &amp; Co");
});
});
@@ -0,0 +1,54 @@
import { TransactionalScaffold } from "./shared.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* Invitation email — sent when a workspace member invites a new user.
* Uses tenant brand overrides (logo/primary-color) so the invite
* reflects the inviting org, not the platform default.
*/
export interface InvitationEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly senderName: string;
readonly senderOrganization: string;
readonly actionUrl: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly unsubscribeUrl?: string;
readonly signoffThanks?: string;
}
export function InvitationEmail({
brand,
recipientName,
senderName,
senderOrganization,
actionUrl,
subject,
eyebrow,
title,
intro,
actionLabel,
unsubscribeUrl,
signoffThanks,
}: InvitationEmailProps) {
const resolvedSubject = subject ?? `${senderName} invited you to ${brand.productName}`;
const resolvedTitle = title ?? (recipientName ? `Hello, ${recipientName}!` : "Hello!");
const resolvedIntro = intro ?? `${senderName} with ${senderOrganization} has invited you to use ${brand.productName} to collaborate with them.`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Invitation"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? `Join ${senderOrganization}`}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
/>
);
}
@@ -0,0 +1,80 @@
import { TransactionalScaffold } from "./shared.js";
import { InfoBox } from "../_layout/InfoBox.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* InvoiceSentEmail — notifies a customer that a Stripe invoice PDF
* has been issued. CTA points to the hosted-invoice URL so the user
* can download the PDF without authenticating.
*/
export interface InvoiceSentEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly invoiceNumber: string;
readonly amountFormatted: string;
readonly issueDate: string;
readonly dueDate?: string;
readonly actionUrl: string;
readonly unsubscribeUrl?: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly titleText?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly fieldLabels?: {
readonly invoiceNumber?: string;
readonly amount?: string;
readonly issued?: string;
readonly due?: string;
};
readonly signoffThanks?: string;
}
export function InvoiceSentEmail({
brand,
recipientName,
invoiceNumber,
amountFormatted,
issueDate,
dueDate,
actionUrl,
unsubscribeUrl,
subject,
eyebrow,
titleText,
intro,
actionLabel,
fieldLabels,
signoffThanks,
}: InvoiceSentEmailProps) {
const resolvedSubject = subject ?? `Invoice ${invoiceNumber} from ${brand.productName}`;
const resolvedTitle = titleText ?? (recipientName ? `Hello, ${recipientName}!` : "Your invoice is ready");
const resolvedIntro = intro ?? `Your invoice ${invoiceNumber} for ${amountFormatted} is now available.`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Invoice"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "View invoice PDF"}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
>
<InfoBox brand={brand}>
<strong>{fieldLabels?.invoiceNumber ?? "Invoice number:"}</strong> {invoiceNumber}
<br />
<strong>{fieldLabels?.amount ?? "Amount:"}</strong> {amountFormatted}
<br />
<strong>{fieldLabels?.issued ?? "Issued:"}</strong> {issueDate}
{dueDate ? (
<>
<br />
<strong>{fieldLabels?.due ?? "Due:"}</strong> {dueDate}
</>
) : null}
</InfoBox>
</TransactionalScaffold>
);
}
@@ -0,0 +1,126 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand } from "../_layout/theme.js";
import { InvoiceSentEmail } from "./InvoiceSent.js";
import { TenantNotificationEmail } from "./TenantNotification.js";
describe("InvoiceSentEmail", () => {
test("renders default snapshot with due date", () => {
const result = renderReactEmail(
<InvoiceSentEmail
brand={defaultMailBrand}
recipientName="Ada"
invoiceNumber="INV-2026-0001"
amountFormatted="€99.00"
issueDate="2026-05-17"
dueDate="2026-06-17"
actionUrl="https://invoice.stripe.com/i/abc"
/>
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("supports unicode amounts and invoice numbers", () => {
const { html } = renderReactEmail(
<InvoiceSentEmail
brand={defaultMailBrand}
invoiceNumber="INV-€-001"
amountFormatted="€99.00 🎉"
issueDate="2026-05-17"
actionUrl="https://invoice.stripe.com/i/abc"
/>
);
expect(html).toContain("INV-€-001");
expect(html).toContain("€99.00 🎉");
});
test("accepts localized invoice copy overrides", () => {
const { html } = renderReactEmail(
<InvoiceSentEmail
brand={defaultMailBrand}
recipientName="Ada"
invoiceNumber="RE-2026-0001"
amountFormatted="99,00 €"
issueDate="17.05.2026"
dueDate="17.06.2026"
actionUrl="https://invoice.stripe.com/i/abc"
subject="Rechnung RE-2026-0001 von ToolCTRL"
eyebrow="Rechnung"
titleText="Hallo, Ada!"
intro="Deine Rechnung RE-2026-0001 über 99,00 € ist jetzt verfügbar."
actionLabel="Rechnungs-PDF öffnen"
fieldLabels={{ invoiceNumber: "Rechnungsnummer:", amount: "Betrag:", issued: "Ausgestellt:", due: "Fällig:" }}
signoffThanks="Danke,"
/>
);
expect(html).toContain("Rechnungs-PDF öffnen");
expect(html).toContain("Rechnungsnummer:");
expect(html).toContain("Fällig:");
expect(html).toContain("Danke,");
});
});
describe("TenantNotificationEmail", () => {
test("renders default snapshot with action", () => {
const result = renderReactEmail(
<TenantNotificationEmail
brand={defaultMailBrand}
recipientName="Ada"
title="New comment on Ticket #42"
body="Grace mentioned you in a comment on Ticket #42."
actionUrl="https://app.example.com/tickets/42"
actionLabel="View ticket"
/>
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("falls back to support mailto when actionUrl missing", () => {
const { html } = renderReactEmail(
<TenantNotificationEmail
brand={defaultMailBrand}
title="Weekly digest"
body="You have 3 unread notifications."
/>
);
expect(html).toContain(`mailto:${defaultMailBrand.supportEmail}`);
expect(html).toContain("Contact support");
});
test("accepts localized notification chrome overrides", () => {
const { html } = renderReactEmail(
<TenantNotificationEmail
brand={defaultMailBrand}
recipientName="Ada"
title="Neue Benachrichtigung"
body="Grace hat dich erwähnt."
actionUrl="https://app.example.com/notifications"
eyebrow="Benachrichtigung"
headline="Hallo, Ada!"
defaultActionLabel="Öffnen"
supportActionLabel="Support kontaktieren"
signoffThanks="Danke,"
/>
);
expect(html).toContain("Benachrichtigung");
expect(html).toContain("Hallo, Ada!");
expect(html).toContain("Öffnen");
expect(html).toContain("Danke,");
});
test("escapes html-like content in body", () => {
const { html } = renderReactEmail(
<TenantNotificationEmail
brand={defaultMailBrand}
title="Heads up"
body="<script>alert(1)</script> and <b>bold</b>"
/>
);
expect(html).not.toContain("<script>alert(1)</script>");
expect(html).toContain("&lt;script&gt;");
});
});
@@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand } from "../_layout/theme.js";
import { InvalidActionUrlError } from "../_layout/Button.js";
import { MagicLinkEmail } from "./MagicLink.js";
describe("MagicLinkEmail", () => {
test("renders default snapshot", () => {
const result = renderReactEmail(
<MagicLinkEmail brand={defaultMailBrand} recipientName="Ada" actionUrl="https://app.example.com/magic/abc" />
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("emits expiry InfoBox copy", () => {
const { html } = renderReactEmail(
<MagicLinkEmail brand={defaultMailBrand} actionUrl="https://app.example.com/magic/abc" expiresInMinutes={10} />
);
expect(html).toContain("expires in 10 minutes");
});
test("rejects javascript: action URL", () => {
expect(() =>
renderReactEmail(<MagicLinkEmail brand={defaultMailBrand} actionUrl="javascript:alert(1)" />)
).toThrow(InvalidActionUrlError);
});
});
@@ -0,0 +1,63 @@
import { TransactionalScaffold } from "./shared.js";
import { InfoBox } from "../_layout/InfoBox.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* MagicLink email — passwordless sign-in flow.
* Includes a short expiry-warning InfoBox plus the standard CTA.
*/
export interface MagicLinkEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly actionUrl: string;
readonly expiresInMinutes?: number;
readonly subject?: string;
readonly previewText?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly outro?: string;
readonly expiresText?: string;
readonly unsubscribeUrl?: string;
readonly signoffThanks?: string;
}
export function MagicLinkEmail({
brand,
recipientName,
actionUrl,
expiresInMinutes = 15,
subject,
previewText,
eyebrow,
title,
intro,
actionLabel,
outro,
expiresText,
unsubscribeUrl,
signoffThanks,
}: MagicLinkEmailProps) {
const resolvedSubject = subject ?? `Your sign-in link for ${brand.productName}`;
const resolvedTitle = title ?? (recipientName ? `Hello, ${recipientName}!` : "Hello!");
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
previewText={previewText ?? `Click to sign in to ${brand.productName}`}
eyebrow={eyebrow ?? "Magic link"}
title={resolvedTitle}
intro={intro ?? `Click the button below to sign in to your ${brand.productName} account. No password required.`}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "Sign in"}
outro={outro ?? "If you didn't request this email, you can safely ignore it."}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
>
<InfoBox brand={brand} tone="warning">
{expiresText ?? `This link expires in ${expiresInMinutes} minutes and can only be used once.`}
</InfoBox>
</TransactionalScaffold>
);
}
@@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand } from "../_layout/theme.js";
import { InvalidActionUrlError } from "../_layout/Button.js";
import { PasswordResetEmail } from "./PasswordReset.js";
describe("PasswordResetEmail", () => {
test("renders default snapshot", () => {
const result = renderReactEmail(
<PasswordResetEmail brand={defaultMailBrand} recipientName="Ada" actionUrl="https://app.example.com/reset?t=abc" />
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("includes the ignore-if-not-requested outro", () => {
const { html } = renderReactEmail(
<PasswordResetEmail brand={defaultMailBrand} actionUrl="https://app.example.com/reset?t=abc" />
);
expect(html).toContain("If you did not request a password reset");
});
test("rejects http://", () => {
expect(() =>
renderReactEmail(<PasswordResetEmail brand={defaultMailBrand} actionUrl="http://insecure.example.com/reset" />)
).toThrow(InvalidActionUrlError);
});
});
@@ -0,0 +1,53 @@
import { TransactionalScaffold } from "./shared.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* PasswordReset email — sent on user-initiated password-reset request.
* The outro reminds the recipient to ignore the message if they did
* not request a reset.
*/
export interface PasswordResetEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly actionUrl: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly outro?: string;
readonly unsubscribeUrl?: string;
readonly signoffThanks?: string;
}
export function PasswordResetEmail({
brand,
recipientName,
actionUrl,
subject,
eyebrow,
title,
intro,
actionLabel,
outro,
unsubscribeUrl,
signoffThanks,
}: PasswordResetEmailProps) {
const resolvedSubject = subject ?? `Set up a new password for ${brand.productName}`;
const resolvedTitle = title ?? (recipientName ? `Hello, ${recipientName}!` : "Hello!");
const resolvedIntro = intro ?? `You recently requested to reset your password for your ${brand.productName} account.`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Password reset"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "Reset password"}
outro={outro ?? "If you did not request a password reset, please ignore this email or contact support if you have questions."}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
/>
);
}
@@ -0,0 +1,116 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand } from "../_layout/theme.js";
import { SubscriptionSuccessEmail } from "./SubscriptionSuccess.js";
import { SubscriptionFailedEmail } from "./SubscriptionFailed.js";
describe("SubscriptionSuccessEmail", () => {
test("renders default snapshot with next-billing", () => {
const result = renderReactEmail(
<SubscriptionSuccessEmail
brand={defaultMailBrand}
recipientName="Ada"
planName="Pro"
amountFormatted="$29.00"
nextBillingDate="2026-06-01"
actionUrl="https://app.example.com/billing"
/>
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("omits next-billing row when undefined", () => {
const { html } = renderReactEmail(
<SubscriptionSuccessEmail
brand={defaultMailBrand}
planName="Pro"
amountFormatted="$29.00"
actionUrl="https://app.example.com/billing"
/>
);
expect(html).not.toContain("Next billing:");
});
test("accepts localized copy overrides", () => {
const { html, text } = renderReactEmail(
<SubscriptionSuccessEmail
brand={defaultMailBrand}
recipientName="Ada"
planName="Pro"
amountFormatted="29,00 €"
nextBillingDate="01.06.2026"
actionUrl="https://app.example.com/billing"
subject="Dein ToolCTRL-Abo ist aktiv"
eyebrow="Abo"
title="Danke, Ada!"
intro="Dein Pro-Abo ist jetzt aktiv. Willkommen!"
actionLabel="Dashboard öffnen"
fieldLabels={{ plan: "Tarif:", amount: "Betrag:", nextBilling: "Nächste Abrechnung:" }}
signoffThanks="Danke,"
/>
);
expect(html).toContain("Dein ToolCTRL-Abo ist aktiv");
expect(html).toContain("Dashboard öffnen");
expect(html).toContain("Tarif:");
expect(html).toContain("Nächste Abrechnung:");
expect(text).toContain("Danke,");
});
});
describe("SubscriptionFailedEmail", () => {
test("renders default snapshot with reason + retry", () => {
const result = renderReactEmail(
<SubscriptionFailedEmail
brand={defaultMailBrand}
recipientName="Ada"
planName="Pro"
amountFormatted="$29.00"
failureReason="Card declined"
retryAt="2026-05-20"
actionUrl="https://app.example.com/billing"
/>
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("uses warning-tone InfoBox", () => {
const { html } = renderReactEmail(
<SubscriptionFailedEmail
brand={defaultMailBrand}
planName="Pro"
amountFormatted="$29.00"
actionUrl="https://app.example.com/billing"
/>
);
expect(html).toMatch(/#fef3c7/i);
});
test("accepts localized failure copy overrides", () => {
const { html } = renderReactEmail(
<SubscriptionFailedEmail
brand={defaultMailBrand}
recipientName="Ada"
planName="Pro"
amountFormatted="29,00 €"
failureReason="Karte abgelehnt"
retryAt="20.05.2026"
actionUrl="https://app.example.com/billing"
subject="Aktion erforderlich: Zahlung fehlgeschlagen"
eyebrow="Zahlung fehlgeschlagen"
title="Hallo Ada,"
intro="Aktualisiere bitte deine Zahlungsmethode."
actionLabel="Zahlungsmethode aktualisieren"
fieldLabels={{ plan: "Tarif:", amount: "Betrag:", reason: "Grund:", nextRetry: "Nächster Versuch:" }}
signoffThanks="Danke,"
/>
);
expect(html).toContain("Zahlungsmethode aktualisieren");
expect(html).toContain("Grund:");
expect(html).toContain("Nächster Versuch:");
expect(html).toContain("Danke,");
});
});
@@ -0,0 +1,85 @@
import { TransactionalScaffold } from "./shared.js";
import { InfoBox } from "../_layout/InfoBox.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* SubscriptionFailedEmail — sent after a Stripe `invoice.payment_failed`
* webhook. Surfaces the failure reason and a direct CTA to the
* billing portal so the customer can fix the card before dunning.
*/
export interface SubscriptionFailedEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly planName: string;
readonly amountFormatted: string;
readonly failureReason?: string;
readonly retryAt?: string;
readonly actionUrl: string;
readonly unsubscribeUrl?: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly fieldLabels?: {
readonly plan?: string;
readonly amount?: string;
readonly reason?: string;
readonly nextRetry?: string;
};
readonly signoffThanks?: string;
}
export function SubscriptionFailedEmail({
brand,
recipientName,
planName,
amountFormatted,
failureReason,
retryAt,
actionUrl,
unsubscribeUrl,
subject,
eyebrow,
title,
intro,
actionLabel,
fieldLabels,
signoffThanks,
}: SubscriptionFailedEmailProps) {
const resolvedSubject = subject ?? `Action required: payment failed for ${brand.productName}`;
const resolvedTitle = title ?? (recipientName ? `Hi ${recipientName},` : "We couldn't charge your card");
const resolvedIntro =
intro ?? `We were unable to charge your card for the ${planName} subscription. Please update your payment method to avoid service interruption.`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Payment failed"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "Update payment method"}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
>
<InfoBox brand={brand} tone="warning">
<strong>{fieldLabels?.plan ?? "Plan:"}</strong> {planName}
<br />
<strong>{fieldLabels?.amount ?? "Amount:"}</strong> {amountFormatted}
{failureReason ? (
<>
<br />
<strong>{fieldLabels?.reason ?? "Reason:"}</strong> {failureReason}
</>
) : null}
{retryAt ? (
<>
<br />
<strong>{fieldLabels?.nextRetry ?? "Next retry:"}</strong> {retryAt}
</>
) : null}
</InfoBox>
</TransactionalScaffold>
);
}
@@ -0,0 +1,76 @@
import { TransactionalScaffold } from "./shared.js";
import { InfoBox } from "../_layout/InfoBox.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* SubscriptionSuccessEmail — sent after Stripe checkout completion.
* Surfaces the active plan and next-billing date so customers can
* verify they were charged correctly without opening the billing
* portal.
*/
export interface SubscriptionSuccessEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly planName: string;
readonly amountFormatted: string;
readonly nextBillingDate?: string;
readonly actionUrl: string;
readonly unsubscribeUrl?: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly fieldLabels?: {
readonly plan?: string;
readonly amount?: string;
readonly nextBilling?: string;
};
readonly signoffThanks?: string;
}
export function SubscriptionSuccessEmail({
brand,
recipientName,
planName,
amountFormatted,
nextBillingDate,
actionUrl,
unsubscribeUrl,
subject,
eyebrow,
title,
intro,
actionLabel,
fieldLabels,
signoffThanks,
}: SubscriptionSuccessEmailProps) {
const resolvedSubject = subject ?? `Your ${brand.productName} subscription is active`;
const resolvedTitle = title ?? (recipientName ? `Thanks, ${recipientName}!` : "Thanks for subscribing!");
const resolvedIntro = intro ?? `Your ${planName} subscription is now active. Welcome aboard!`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Subscription"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "Open your dashboard"}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
>
<InfoBox brand={brand}>
<strong>{fieldLabels?.plan ?? "Plan:"}</strong> {planName}
<br />
<strong>{fieldLabels?.amount ?? "Amount:"}</strong> {amountFormatted}
{nextBillingDate ? (
<>
<br />
<strong>{fieldLabels?.nextBilling ?? "Next billing:"}</strong> {nextBillingDate}
</>
) : null}
</InfoBox>
</TransactionalScaffold>
);
}
@@ -0,0 +1,59 @@
import { TransactionalScaffold } from "./shared.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* TenantNotificationEmail — generic tenant notification used to deliver
* in-app notifications via email digest. The `body` is treated as
* plain text (React's default escaping handles XSS); raw HTML is
* intentionally not supported.
*/
export interface TenantNotificationEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly title: string;
readonly body: string;
readonly actionUrl?: string;
readonly actionLabel?: string;
readonly unsubscribeUrl?: string;
readonly eyebrow?: string;
readonly headline?: string;
readonly defaultActionLabel?: string;
readonly supportActionLabel?: string;
readonly signoffThanks?: string;
}
export function TenantNotificationEmail({
brand,
recipientName,
title,
body,
actionUrl,
actionLabel,
unsubscribeUrl,
eyebrow,
headline,
defaultActionLabel,
supportActionLabel,
signoffThanks,
}: TenantNotificationEmailProps) {
const subject = title;
const resolvedHeadline = headline ?? (recipientName ? `Hello, ${recipientName}!` : title);
// Generic notifications may omit the CTA. We always render the
// scaffold's button slot so the visual rhythm is consistent — fall
// back to a no-op support mailto when no action URL was supplied.
const resolvedActionUrl = actionUrl ?? `mailto:${brand.supportEmail}`;
const resolvedActionLabel = actionLabel ?? (actionUrl ? (defaultActionLabel ?? "Open") : (supportActionLabel ?? "Contact support"));
return (
<TransactionalScaffold
brand={brand}
subject={subject}
eyebrow={eyebrow ?? "Notification"}
title={resolvedHeadline}
intro={body}
actionUrl={resolvedActionUrl}
actionLabel={resolvedActionLabel}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
/>
);
}
@@ -0,0 +1,47 @@
import { describe, expect, test } from "vitest";
import { renderReactEmail } from "../render-helpers.js";
import { defaultMailBrand, withBrandDefaults } from "../_layout/theme.js";
import { InvalidActionUrlError } from "../_layout/Button.js";
import { WelcomeEmail } from "./Welcome.js";
describe("WelcomeEmail", () => {
test("renders default-brand named welcome (snapshot)", () => {
const result = renderReactEmail(
<WelcomeEmail brand={defaultMailBrand} recipientName="Ada" actionUrl="https://app.example.com/login" />
);
expect(result.html).toMatchSnapshot("html");
expect(result.text).toMatchSnapshot("text");
});
test("falls back to anonymous greeting when name missing", () => {
const { html } = renderReactEmail(
<WelcomeEmail brand={defaultMailBrand} actionUrl="https://app.example.com/login" />
);
expect(html).toContain("Welcome!");
expect(html).not.toContain("Welcome, ");
});
test("applies tenant brand overrides", () => {
const brand = withBrandDefaults({ productName: "Acme", primaryColor: "#123456", logoUrl: "https://cdn.acme.test/l.png" });
const { html } = renderReactEmail(
<WelcomeEmail brand={brand} recipientName="Ada" actionUrl="https://app.acme.test/login" />
);
expect(html).toContain("Welcome to Acme, Ada!");
expect(html).toContain("#123456");
expect(html).toContain("https://cdn.acme.test/l.png");
});
test("escapes user content via React (XSS-safe)", () => {
const { html } = renderReactEmail(
<WelcomeEmail brand={defaultMailBrand} recipientName="<script>alert(1)</script>" actionUrl="https://app.example.com/login" />
);
expect(html).not.toContain("<script>alert(1)</script>");
expect(html).toContain("&lt;script&gt;");
});
test("rejects insecure action URLs", () => {
expect(() =>
renderReactEmail(<WelcomeEmail brand={defaultMailBrand} actionUrl="javascript:alert(1)" />)
).toThrow(InvalidActionUrlError);
});
});
@@ -0,0 +1,51 @@
import { TransactionalScaffold } from "./shared.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* Welcome transactional email — sent after account activation. Also
* doubles as the post-checkout "account-setup" variant via overridable
* subject/title/intro/actionLabel props (see EmailTemplates wrapper).
*/
export interface WelcomeEmailProps {
readonly brand: MailBrand;
readonly recipientName?: string;
readonly actionUrl: string;
readonly subject?: string;
readonly eyebrow?: string;
readonly title?: string;
readonly intro?: string;
readonly actionLabel?: string;
readonly unsubscribeUrl?: string;
readonly signoffThanks?: string;
}
export function WelcomeEmail({
brand,
recipientName,
actionUrl,
subject,
eyebrow,
title,
intro,
actionLabel,
unsubscribeUrl,
signoffThanks,
}: WelcomeEmailProps) {
const resolvedSubject =
subject ?? (recipientName ? `Welcome to ${brand.productName}, ${recipientName}!` : `Welcome to ${brand.productName}!`);
const resolvedTitle = title ?? (recipientName ? `Welcome, ${recipientName}!` : "Welcome!");
const resolvedIntro = intro ?? `Thanks for trying ${brand.productName}.`;
return (
<TransactionalScaffold
brand={brand}
subject={resolvedSubject}
eyebrow={eyebrow ?? "Welcome"}
title={resolvedTitle}
intro={resolvedIntro}
actionUrl={actionUrl}
actionLabel={actionLabel ?? "Click here to log in"}
unsubscribeUrl={unsubscribeUrl}
signoffThanks={signoffThanks}
/>
);
}
@@ -0,0 +1,16 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`InvitationEmail > renders default snapshot > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Grace invited you to ToolCTRL</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Grace invited you to ToolCTRL</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Invitation</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hello, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Grace with Example Org has invited you to use ToolCTRL to collaborate with them.</p><a href="https://app.example.com/invite/abc" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Join Example Org</a><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`InvitationEmail > renders default snapshot > text 1`] = `
"Grace invited you to ToolCTRL
ToolCTRL
Invitation
Hello, Ada!
Grace with Example Org has invited you to use ToolCTRL to collaborate with them.
Join Example Org (https://app.example.com/invite/abc)Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,35 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`InvoiceSentEmail > renders default snapshot with due date > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Invoice INV-2026-0001 from ToolCTRL</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Invoice INV-2026-0001 from ToolCTRL</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Invoice</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hello, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Your invoice INV-2026-0001 for €99.00 is now available.</p><a href="https://invoice.stripe.com/i/abc" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">View invoice PDF</a><div style="margin-top:20px;padding:14px 16px;border-radius:10px;font-size:14px;line-height:1.55;background-color:#f1f5f9;color:#0f172a;border:1px solid #e2e8f0"><strong>Invoice number:</strong> INV-2026-0001<br/><strong>Amount:</strong> €99.00<br/><strong>Issued:</strong> 2026-05-17<br/><strong>Due:</strong> 2026-06-17</div><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`InvoiceSentEmail > renders default snapshot with due date > text 1`] = `
"Invoice INV-2026-0001 from ToolCTRL
ToolCTRL
Invoice
Hello, Ada!
Your invoice INV-2026-0001 for €99.00 is now available.
View invoice PDF (https://invoice.stripe.com/i/abc)Invoice number: INV-2026-0001
Amount: €99.00
Issued: 2026-05-17
Due: 2026-06-17
Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
exports[`TenantNotificationEmail > renders default snapshot with action > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>New comment on Ticket #42</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">New comment on Ticket #42</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Notification</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hello, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Grace mentioned you in a comment on Ticket #42.</p><a href="https://app.example.com/tickets/42" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">View ticket</a><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`TenantNotificationEmail > renders default snapshot with action > text 1`] = `
"New comment on Ticket #42
ToolCTRL
Notification
Hello, Ada!
Grace mentioned you in a comment on Ticket #42.
View ticket (https://app.example.com/tickets/42)Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,18 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`MagicLinkEmail > renders default snapshot > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Your sign-in link for ToolCTRL</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Click to sign in to ToolCTRL</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Magic link</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hello, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Click the button below to sign in to your ToolCTRL account. No password required.</p><a href="https://app.example.com/magic/abc" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Sign in</a><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#475569">If you didn&#x27;t request this email, you can safely ignore it.</p><div style="margin-top:20px;padding:14px 16px;border-radius:10px;font-size:14px;line-height:1.55;background-color:#fef3c7;color:#92400e;border:1px solid #fde68a">This link expires in 15 minutes and can only be used once.</div><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`MagicLinkEmail > renders default snapshot > text 1`] = `
"Click to sign in to ToolCTRL
ToolCTRL
Magic link
Hello, Ada!
Click the button below to sign in to your ToolCTRL account. No password required.
Sign in (https://app.example.com/magic/abc)If you didn&#x27;t request this email, you can safely ignore it.
This link expires in 15 minutes and can only be used once.
Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,17 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`PasswordResetEmail > renders default snapshot > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Set up a new password for ToolCTRL</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Set up a new password for ToolCTRL</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Password reset</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hello, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">You recently requested to reset your password for your ToolCTRL account.</p><a href="https://app.example.com/reset?t=abc" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Reset password</a><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#475569">If you did not request a password reset, please ignore this email or contact support if you have questions.</p><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`PasswordResetEmail > renders default snapshot > text 1`] = `
"Set up a new password for ToolCTRL
ToolCTRL
Password reset
Hello, Ada!
You recently requested to reset your password for your ToolCTRL account.
Reset password (https://app.example.com/reset?t=abc)If you did not request a password reset, please ignore this email or contact support if you have questions.
Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,38 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`SubscriptionFailedEmail > renders default snapshot with reason + retry > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Action required: payment failed for ToolCTRL</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Action required: payment failed for ToolCTRL</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Payment failed</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Hi Ada,</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">We were unable to charge your card for the Pro subscription. Please update your payment method to avoid service interruption.</p><a href="https://app.example.com/billing" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Update payment method</a><div style="margin-top:20px;padding:14px 16px;border-radius:10px;font-size:14px;line-height:1.55;background-color:#fef3c7;color:#92400e;border:1px solid #fde68a"><strong>Plan:</strong> Pro<br/><strong>Amount:</strong> $29.00<br/><strong>Reason:</strong> Card declined<br/><strong>Next retry:</strong> 2026-05-20</div><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`SubscriptionFailedEmail > renders default snapshot with reason + retry > text 1`] = `
"Action required: payment failed for ToolCTRL
ToolCTRL
Payment failed
Hi Ada,
We were unable to charge your card for the Pro subscription. Please update your payment method to avoid service interruption.
Update payment method (https://app.example.com/billing)Plan: Pro
Amount: $29.00
Reason: Card declined
Next retry: 2026-05-20
Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
exports[`SubscriptionSuccessEmail > renders default snapshot with next-billing > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Your ToolCTRL subscription is active</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Your ToolCTRL subscription is active</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Subscription</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Thanks, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Your Pro subscription is now active. Welcome aboard!</p><a href="https://app.example.com/billing" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Open your dashboard</a><div style="margin-top:20px;padding:14px 16px;border-radius:10px;font-size:14px;line-height:1.55;background-color:#f1f5f9;color:#0f172a;border:1px solid #e2e8f0"><strong>Plan:</strong> Pro<br/><strong>Amount:</strong> $29.00<br/><strong>Next billing:</strong> 2026-06-01</div><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`SubscriptionSuccessEmail > renders default snapshot with next-billing > text 1`] = `
"Your ToolCTRL subscription is active
ToolCTRL
Subscription
Thanks, Ada!
Your Pro subscription is now active. Welcome aboard!
Open your dashboard (https://app.example.com/billing)Plan: Pro
Amount: $29.00
Next billing: 2026-06-01
Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,16 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`WelcomeEmail > renders default-brand named welcome (snapshot) > html 1`] = `"<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Welcome to ToolCTRL, Ada!</title></head><body style="margin:0;padding:0;background-color:#f4f5f7;color:#0f172a;font-family:ui-sans-serif, -apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif;font-size:16px;line-height:1.5"><div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">Welcome to ToolCTRL, Ada!</div><div style="width:100%;max-width:560px;margin:0 auto;padding:24px 16px"><div style="background-color:#ffffff;border:1px solid #e2e8f0;border-radius:20px;padding:32px"><div style="padding-bottom:16px;text-align:left"><strong style="color:#0f172a;font-size:18px">ToolCTRL</strong></div><div style="color:#475569;font-size:13px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;margin-bottom:8px">Welcome</div><h1 style="margin:8px 0 16px;font-size:28px;line-height:1.2;color:#0f172a;font-weight:700">Welcome, Ada!</h1><p style="margin:0 0 24px;font-size:16px;line-height:1.6;color:#0f172a">Thanks for trying ToolCTRL.</p><a href="https://app.example.com/login" style="display:inline-block;background-color:#2563eb;color:#ffffff;padding:12px 22px;border-radius:999px;font-weight:700;font-size:15px;text-decoration:none" target="_blank" rel="noopener noreferrer">Click here to log in</a><p style="margin:24px 0 0;font-size:14px;line-height:1.6;color:#0f172a">Thanks,<br/>-<br/>ToolCTRL Support</p><div style="margin-top:24px;padding-top:16px;border-top:1px solid;font-size:12px;line-height:1.5;border-top-color:#e2e8f0;color:#475569"><div><a href="https://tool-ctrl.de/privacy" style="text-decoration:underline;color:#2563eb">Privacy</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/terms" style="text-decoration:underline;color:#2563eb">Terms</a><span style="margin:0 6px">·</span><a href="https://tool-ctrl.de/imprint" style="text-decoration:underline;color:#2563eb">Imprint</a></div><div style="margin-top:8px">Questions? Email us at <a href="mailto:info@tool-ctrl.de" style="text-decoration:underline;color:#2563eb">info@tool-ctrl.de</a>.</div></div></div></div></body></html>"`;
exports[`WelcomeEmail > renders default-brand named welcome (snapshot) > text 1`] = `
"Welcome to ToolCTRL, Ada!
ToolCTRL
Welcome
Welcome, Ada!
Thanks for trying ToolCTRL.
Click here to log in (https://app.example.com/login)Thanks,
-
ToolCTRL Support
Privacy (https://tool-ctrl.de/privacy)·Terms (https://tool-ctrl.de/terms)·Imprint (https://tool-ctrl.de/imprint)
Questions? Email us at info@tool-ctrl.de (mailto:info@tool-ctrl.de)."
`;
@@ -0,0 +1,90 @@
import type { CSSProperties, ReactNode } from "react";
import { BaseLayout } from "../_layout/BaseLayout.js";
import { Button } from "../_layout/Button.js";
import { Eyebrow } from "../_layout/Eyebrow.js";
import type { MailBrand } from "../_layout/theme.js";
/**
* Shared visual scaffold for all transactional templates.
*
* Every transactional email follows the same shape: eyebrow → headline →
* intro paragraph → CTA → optional outro paragraph → support sign-off.
* Concentrating that into one component keeps per-template files small
* and ensures brand-theme application is uniform.
*/
export interface TransactionalScaffoldProps {
readonly brand: MailBrand;
readonly subject: string;
readonly previewText?: string;
readonly eyebrow: string;
readonly title: string;
readonly intro: ReactNode;
readonly actionUrl: string;
readonly actionLabel: string;
readonly outro?: ReactNode;
readonly children?: ReactNode;
readonly unsubscribeUrl?: string;
readonly signoffThanks?: string;
}
const titleStyle = (brand: MailBrand): CSSProperties => ({
margin: "8px 0 16px",
fontSize: "28px",
lineHeight: 1.2,
color: brand.textColor,
fontWeight: 700,
});
const paragraphStyle = (brand: MailBrand): CSSProperties => ({
margin: "0 0 24px",
fontSize: "16px",
lineHeight: 1.6,
color: brand.textColor,
});
const outroStyle = (brand: MailBrand): CSSProperties => ({
margin: "24px 0 0",
fontSize: "14px",
lineHeight: 1.6,
color: brand.mutedTextColor,
});
const signoffStyle = (brand: MailBrand): CSSProperties => ({
margin: "24px 0 0",
fontSize: "14px",
lineHeight: 1.6,
color: brand.textColor,
});
export function TransactionalScaffold({
brand,
subject,
previewText,
eyebrow,
title,
intro,
actionUrl,
actionLabel,
outro,
children,
unsubscribeUrl,
signoffThanks,
}: TransactionalScaffoldProps) {
return (
<BaseLayout brand={brand} title={subject} previewText={previewText ?? subject} unsubscribeUrl={unsubscribeUrl}>
<Eyebrow brand={brand}>{eyebrow}</Eyebrow>
<h1 style={titleStyle(brand)}>{title}</h1>
<p style={paragraphStyle(brand)}>{intro}</p>
<Button brand={brand} href={actionUrl}>
{actionLabel}
</Button>
{outro ? <p style={outroStyle(brand)}>{outro}</p> : null}
{children}
<p style={signoffStyle(brand)}>
{signoffThanks ?? "Thanks,"}
<br />-<br />
{brand.supportFromName}
</p>
</BaseLayout>
);
}
@@ -0,0 +1,105 @@
export type MailProviderId = "mailjet" | "queue";
export type MailAddress = {
email: string;
name?: string;
};
export type MailAddressInput = string | MailAddress;
export type MailAttachmentDisposition = "attachment" | "inline";
export type MailAttachment = {
content: string;
filename: string;
disposition?: MailAttachmentDisposition;
id?: string;
};
export type MailPersonalization = {
email: string;
data: Record<string, unknown>;
};
export type MailTrackingSettings = {
trackClicks?: boolean;
trackOpens?: boolean;
trackContent?: boolean;
};
export type MailHeader = {
name: string;
value: string;
};
export type SendMailPriorityOverride = "critical" | "high" | "normal" | "low";
export type SendMailInput = {
from?: MailAddressInput;
to: readonly MailAddressInput[];
cc?: readonly MailAddressInput[];
bcc?: readonly MailAddressInput[];
replyTo?: MailAddressInput;
subject?: string;
text?: string;
html?: string;
templateId?: string;
attachments?: readonly MailAttachment[];
tags?: readonly string[];
personalization?: readonly MailPersonalization[];
precedenceBulk?: boolean;
sendAt?: Date | number;
inReplyTo?: string;
references?: readonly string[];
settings?: MailTrackingSettings;
headers?: readonly MailHeader[];
listUnsubscribe?: string;
idempotencyKey?: string;
/**
* Tenant scope used by the queue priority resolver. Pass `null` for
* system-originated mail (no tenant context) so the job runs at CRITICAL.
*/
tenantId?: string | null;
/**
* Explicit priority hint for the BullMQ enqueue. Use `"critical"` for
* password-reset / verification / magic-link mail and `"low"` for
* marketing batches.
*/
priorityOverride?: SendMailPriorityOverride;
};
export type SendMailResult = {
provider: MailProviderId;
status: "queued";
messageId?: string;
warnings?: unknown;
};
export interface MailProvider {
readonly id: MailProviderId;
send(input: SendMailInput): Promise<SendMailResult>;
}
export type MailProviderErrorOptions = {
provider: MailProviderId;
statusCode?: number;
responseBody?: unknown;
messageId?: string;
cause?: unknown;
};
export class MailProviderError extends Error {
readonly provider: MailProviderId;
readonly statusCode?: number;
readonly responseBody?: unknown;
readonly messageId?: string;
constructor(message: string, options: MailProviderErrorOptions) {
super(message, { cause: options.cause });
this.name = "MailProviderError";
this.provider = options.provider;
this.statusCode = options.statusCode;
this.responseBody = options.responseBody;
this.messageId = options.messageId;
}
}