feat: release design system engine, studio and component contracts

This commit is contained in:
Clintchiz committed 2026-10-19 13:09:03 +05:30
1 parent ff1065fb27
commit 3943b946d6
693 files changed
+175546 -3894

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@wrnexus/email-renderer",
"version": "0.1.51",
"version": "0.1.52",
"type": "module",
"description": "WRNexus block email renderers with HTML, text, AMP Email, and MJML interoperability.",
"exports": {
+221 -51
View File
@@ -41,15 +41,20 @@ const mjmlDocumentHead = (node: BlockNode, context: unknown) => {
return `<mj-head><mj-title>${html(meta?.emailSubject)}</mj-title>${meta?.emailPreheader ? `<mj-preview>${html(meta.emailPreheader)}</mj-preview>` : ""}<mj-attributes><mj-all font-family="${html(attrs(node).fontFamily ?? "Arial, sans-serif")}" /><mj-text color="${html(attrs(node).textColor ?? "#111827")}" /><mj-button background-color="${html(attrs(node).linkColor ?? "#2563eb")}" /></mj-attributes></mj-head>`;
};
export const ampLayoutClass = (node: BlockNode) =>
"wrn-layout-" + Array.from(node.id, char => char.codePointAt(0)!.toString(16)).join("-");
"wrn-layout-" + Array.from(node.id, (char) => char.codePointAt(0)!.toString(16)).join("-");
export function ampLayoutCss(node: BlockNode, brandLinkColor?: string): string {
const props = attrs(node);
if (node.type === "content.button")
return `.button.${ampLayoutClass(node)}{background-color:${buttonBackground(node, { brandLinkColor })};${buttonVisualCss(node)}}`;
if (node.type === "layout.section") {
const background = safeCssValue(props.background, /^(#[0-9a-f]{3,8}|rgba?\([0-9., %]+\))$/i) || "#ffffff";
const padding = safeCssValue(props.padding, /^\d+(?:\.\d+)?(?:px|rem|em|%)?(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)?){0,3}$/) || "24px";
const background =
safeCssValue(props.background, /^(#[0-9a-f]{3,8}|rgba?\([0-9., %]+\))$/i) || "#ffffff";
const padding =
safeCssValue(
props.padding,
/^\d+(?:\.\d+)?(?:px|rem|em|%)?(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)?){0,3}$/,
) || "24px";
return `.${ampLayoutClass(node)}{background:${background};padding:${padding}}`;
}
if (node.type === "content.spacer") {
@@ -58,22 +63,37 @@ export function ampLayoutCss(node: BlockNode, brandLinkColor?: string): string {
}
return "";
}
const multilineText = (value: unknown) => html(value).replace(/\r\n?|\n/g, "<br />");
const imageDimension = (fallback: string, minimum = 1): ValueSchema<string> => ({
kind: "string",
defaultValue: fallback,
parse(value = fallback, path = "value") {
return typeof value === "string" && /^\d{1,4}$/.test(value) && Number(value) >= minimum && Number(value) <= 4000
return typeof value === "string" &&
/^\d{1,4}$/.test(value) &&
Number(value) >= minimum &&
Number(value) <= 4000
? { ok: true, value }
: { ok: false, errors: [{code:"email.image-dimension",message:`Dimensions must be between ${minimum} and 4000 pixels.`,severity:"error",path}] };
: {
ok: false,
errors: [
{
code: "email.image-dimension",
message: `Dimensions must be between ${minimum} and 4000 pixels.`,
severity: "error",
path,
},
],
};
},
});
const marketingImage = (node: BlockNode, target: "html" | "amp" | "mjml") => {
const p = attrs(node);
if (!p.image) return "";
const width = html(p.width ?? "600"), height = html(p.height ?? "400");
const src = html(p.image), alt = html(p.title);
if (target === "amp") return `<amp-img class="marketing-image" src="${src}" alt="${alt}" width="${width}" height="${height}" layout="responsive"></amp-img>`;
const width = html(p.width ?? "600"),
height = html(p.height ?? "400");
const src = html(p.image),
alt = html(p.title);
if (target === "amp")
return `<amp-img class="marketing-image" src="${src}" alt="${alt}" width="${width}" height="${height}" layout="responsive"></amp-img>`;
if (target === "mjml") return `<mj-image src="${src}" alt="${alt}" width="${width}px" />`;
return `<img src="${src}" alt="${alt}" width="${width}" style="display:block;height:auto;width:100%;max-width:${width}px;" />`;
};
@@ -126,11 +146,27 @@ const buttonVisualCss = (node: BlockNode) => {
const buttonAlignment = (node: BlockNode, context: unknown) => {
const value = emailStyleValue("textAlign", styleBase(node, "textAlign")) || "start";
const rtl = (context as { direction?: string } | undefined)?.direction === "rtl";
return value === "start" ? (rtl ? "right" : "left") : value === "end" ? (rtl ? "left" : "right") : value;
return value === "start"
? rtl
? "right"
: "left"
: value === "end"
? rtl
? "left"
: "right"
: value;
};
const emailCell = (body: string, node: BlockNode, align?: string) => {
// Button visuals belong to the clickable element, never the full-width cell.
const cellNode = node.type === "content.button" ? { ...node, styles: Object.fromEntries(Object.entries(node.styles).filter(([key]) => ["textAlign", "margin"].includes(key))) } : node;
const cellNode =
node.type === "content.button"
? {
...node,
styles: Object.fromEntries(
Object.entries(node.styles).filter(([key]) => ["textAlign", "margin"].includes(key)),
),
}
: node;
return `<tr><td data-block-id="${html(node.id)}"${align ? ` align="${html(align)}"` : ""} style="padding:0;${semanticStyle(cellNode)}">${body}</td></tr>`;
};
@@ -161,7 +197,18 @@ export const emailDocumentBlock = defineBlock({
id: id(),
type: "layout.email-document",
version: 1,
props: { width: "600", background: "#f3f4f6", contentBackground: "#ffffff", fontFamily: "Arial, sans-serif", textColor: "#111827", linkColor: "#2563eb", logoUrl: "", logoAlt: "", logoWidth: "200", logoHeight: "64" },
props: {
width: "600",
background: "#f3f4f6",
contentBackground: "#ffffff",
fontFamily: "Arial, sans-serif",
textColor: "#111827",
linkColor: "#2563eb",
logoUrl: "",
logoAlt: "",
logoWidth: "200",
logoHeight: "64",
},
styles: {},
slots: { content: [] },
}),
@@ -212,9 +259,10 @@ export const sectionBlock = defineBlock({
),
mjml: ({ node, slots }) => {
const children = node.slots.content ?? [];
const body = children.length === 1 && children[0]?.type === "layout.columns"
? slots.content
: `<mj-column>${slots.content}</mj-column>`;
const body =
children.length === 1 && children[0]?.type === "layout.columns"
? slots.content
: `<mj-column>${slots.content}</mj-column>`;
return `<mj-section background-color="${html(attrs(node).background ?? "#ffffff")}" padding="${html(attrs(node).padding ?? "24px")}">${body}</mj-section>`;
},
},
@@ -256,10 +304,14 @@ export const columnsBlock = defineBlock({
node,
),
ampEmail: ({ node, slots }) =>
emailCell(`<table role="presentation" width="100%"><tr class="wrn-columns">${slots.columns}</tr></table>`, node),
mjml: ({ node, slots, context }) => isEmailRootChild(node, context)
? `<mj-section padding="0">${slots.columns}</mj-section>`
: slots.columns,
emailCell(
`<table role="presentation" width="100%"><tr class="wrn-columns">${slots.columns}</tr></table>`,
node,
),
mjml: ({ node, slots, context }) =>
isEmailRootChild(node, context)
? `<mj-section padding="0">${slots.columns}</mj-section>`
: slots.columns,
},
textRenderer: ({ slots }) => slots.columns,
} satisfies BlockDefinition);
@@ -318,12 +370,16 @@ const leaf = (
create: ({ id }) => ({ id: id(), type, version: 1, props: {}, styles: {}, slots: {} }),
renderers: {
...renderers,
...(renderers?.mjml ? { mjml: async (input) => {
const content = await renderers.mjml!(input);
return isEmailRootChild(input.node, input.context)
? `<mj-section padding="0"><mj-column padding="0">${content}</mj-column></mj-section>`
: content;
} } : {}),
...(renderers?.mjml
? {
mjml: async (input) => {
const content = await renderers.mjml!(input);
return isEmailRootChild(input.node, input.context)
? `<mj-section padding="0"><mj-column padding="0">${content}</mj-column></mj-section>`
: content;
},
}
: {}),
},
textRenderer,
});
@@ -344,7 +400,10 @@ export const headingBlock = leaf(
node,
),
ampEmail: ({ node }) =>
emailCell(`<h${attrs(node).level}>${renderRichText(attrs(node))}</h${attrs(node).level}>`, node),
emailCell(
`<h${attrs(node).level}>${renderRichText(attrs(node))}</h${attrs(node).level}>`,
node,
),
mjml: ({ node }) =>
`<mj-text font-size="24px" font-weight="700">${renderRichText(attrs(node))}</mj-text>`,
},
@@ -465,9 +524,18 @@ export const videoBlock = leaf(
height: imageDimension("338"),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" style="border:0;display:block;height:auto;width:100%;max-width:${html(attrs(node).width)}px;" /></a>`, node),
ampEmail: ({ node }) => emailCell(`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><amp-img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" layout="responsive"></amp-img></a>`, node),
mjml: ({ node }) => `<mj-image href="${html(attrs(node).href)}" src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}px" height="${html(attrs(node).height)}px" />`,
emailHtml: ({ node }) =>
emailCell(
`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" style="border:0;display:block;height:auto;width:100%;max-width:${html(attrs(node).width)}px;" /></a>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<a href="${html(attrs(node).href)}" aria-label="${html(attrs(node).title)}"><amp-img src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}" height="${html(attrs(node).height)}" layout="responsive"></amp-img></a>`,
node,
),
mjml: ({ node }) =>
`<mj-image href="${html(attrs(node).href)}" src="${html(attrs(node).thumbnail)}" alt="${html(attrs(node).alt)}" width="${html(attrs(node).width)}px" height="${html(attrs(node).height)}px" />`,
},
({ node }) => `${String(attrs(node).title)}: ${String(attrs(node).href)}\n\n`,
);
@@ -484,11 +552,53 @@ export const socialBlock = leaf(
x: safeUrl({ schemes: ["https"], optional: true }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<p style="font-family:inherit;margin:0 0 16px;">${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}" style="margin-right:12px;">${name}</a>`).join("")}</p>`, node),
ampEmail: ({ node }) => emailCell(`<p>${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}">${name}</a>`).join(" ")}</p>`, node),
mjml: ({ node }) => `<mj-text>${html(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`<a href="${html(url)}">${name}</a>`).join(" ")}</mj-text>`,
emailHtml: ({ node }) =>
emailCell(
`<p style="font-family:inherit;margin:0 0 16px;">${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}" style="margin-right:12px;">${name}</a>`)
.join("")}</p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<p>${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}">${name}</a>`)
.join(" ")}</p>`,
node,
),
mjml: ({ node }) =>
`<mj-text>${html(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `<a href="${html(url)}">${name}</a>`)
.join(" ")}</mj-text>`,
},
({ node }) => `${String(attrs(node).label)}: ${[["Facebook",attrs(node).facebook],["Instagram",attrs(node).instagram],["LinkedIn",attrs(node).linkedin],["X",attrs(node).x]].filter(([,url])=>url).map(([name,url])=>`${name}: ${url}`).join(" · ")}\n\n`,
({ node }) =>
`${String(attrs(node).label)}: ${[
["Facebook", attrs(node).facebook],
["Instagram", attrs(node).instagram],
["LinkedIn", attrs(node).linkedin],
["X", attrs(node).x],
]
.filter(([, url]) => url)
.map(([name, url]) => `${name}: ${url}`)
.join(" · ")}\n\n`,
);
const countdownUrl = (node: BlockNode, context: unknown): string | undefined => {
@@ -513,57 +623,117 @@ export const countdownBlock = leaf(
{
emailHtml: ({ node, context }) => {
const url = countdownUrl(node, context);
return emailCell(`<p style="font-family:inherit;font-size:20px;font-weight:700;margin:0 0 16px;">${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<img src="${url}" width="320" height="64" alt="${html(attrs(node).label)} — ${html(attrs(node).deadline)}" style="display:block;width:320px;max-width:100%;height:auto;" />` : ""}`, node);
return emailCell(
`<p style="font-family:inherit;font-size:20px;font-weight:700;margin:0 0 16px;">${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<img src="${url}" width="320" height="64" alt="${html(attrs(node).label)} — ${html(attrs(node).deadline)}" style="display:block;width:320px;max-width:100%;height:auto;" />` : ""}`,
node,
);
},
ampEmail: ({ node, context }) => {
const url = countdownUrl(node, context);
return emailCell(`<p>${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<amp-img src="${url}" width="320" height="64" layout="responsive" alt="${html(attrs(node).label)}"></amp-img>` : ""}`, node);
return emailCell(
`<p>${html(attrs(node).label)}: <time datetime="${html(attrs(node).deadline)}">${html(attrs(node).deadline)}</time></p>${url ? `<amp-img src="${url}" width="320" height="64" layout="responsive" alt="${html(attrs(node).label)}"></amp-img>` : ""}`,
node,
);
},
mjml: ({ node, context }) => {
const url = countdownUrl(node, context);
return `<mj-text font-size="20px" font-weight="700">${html(attrs(node).label)}: ${html(attrs(node).deadline)}</mj-text>${url ? `<mj-image src="${url}" width="320px" alt="${html(attrs(node).label)}" />` : ""}`;
},
},
({ node }) => `${String(attrs(node).label)}: ${String(attrs(node).deadline)}\n${String(attrs(node).fallback)}\n\n`,
({ node }) =>
`${String(attrs(node).label)}: ${String(attrs(node).deadline)}\n${String(attrs(node).fallback)}\n\n`,
);
export const surveyBlock = leaf(
"content.survey",
"Survey",
"icon-[lucide--list-checks]",
object({ question: string({ min: 1, max: 500 }), buttonLabel: string({ min: 1, max: 200, default: "Answer survey" }), href: safeUrl({ schemes: ["https"] }) }) as never,
object({
question: string({ min: 1, max: 500 }),
buttonLabel: string({ min: 1, max: 200, default: "Answer survey" }),
href: safeUrl({ schemes: ["https"] }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`<p style="font-family:inherit;margin:0 0 12px;">${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
ampEmail: ({ node }) => emailCell(`<p>${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
mjml: ({ node }) => `<mj-text>${html(attrs(node).question)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
emailHtml: ({ node }) =>
emailCell(
`<p style="font-family:inherit;margin:0 0 12px;">${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`<p>${html(attrs(node).question)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
mjml: ({ node }) =>
`<mj-text>${html(attrs(node).question)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
},
({ node }) => `${String(attrs(node).question)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).question)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
);
export const feedItemBlock = leaf(
"content.feed-item",
"RSS article",
"icon-[lucide--rss]",
object({ width: imageDimension("600"), height: imageDimension("400"), feedUrl: safeUrl({ schemes: ["https"], optional: true }), title: string({ min: 1, max: 500 }), summary: string({ max: 2_000, default: "" }), href: safeUrl({ schemes: ["https"] }), image: safeUrl({ schemes: ["https"], optional: true }) }) as never,
object({
width: imageDimension("600"),
height: imageDimension("400"),
feedUrl: safeUrl({ schemes: ["https"], optional: true }),
title: string({ min: 1, max: 500 }),
summary: string({ max: 2_000, default: "" }),
href: safeUrl({ schemes: ["https"] }),
image: safeUrl({ schemes: ["https"], optional: true }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`${marketingImage(node, "html")}<h2 style="font-family:inherit;"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p style="font-family:inherit;">${html(attrs(node).summary)}</p>`, node),
ampEmail: ({ node }) => emailCell(`${marketingImage(node, "amp")}<h2><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p>${html(attrs(node).summary)}</p>`, node),
mjml: ({ node }) => `${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></mj-text><mj-text>${html(attrs(node).summary)}</mj-text>`,
emailHtml: ({ node }) =>
emailCell(
`${marketingImage(node, "html")}<h2 style="font-family:inherit;"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p style="font-family:inherit;">${html(attrs(node).summary)}</p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`${marketingImage(node, "amp")}<h2><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></h2><p>${html(attrs(node).summary)}</p>`,
node,
),
mjml: ({ node }) =>
`${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700"><a href="${html(attrs(node).href)}">${html(attrs(node).title)}</a></mj-text><mj-text>${html(attrs(node).summary)}</mj-text>`,
},
({ node }) => `${String(attrs(node).title)}\n${String(attrs(node).summary)}\n${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).title)}\n${String(attrs(node).summary)}\n${String(attrs(node).href)}\n\n`,
);
export const productBlock = leaf(
"commerce.product",
"Product",
"icon-[lucide--shopping-bag]",
object({ width: imageDimension("600"), height: imageDimension("400"), provider: choice(["shopify", "woocommerce", "manual"] as const, { default: "manual" }), storeUrl: safeUrl({ schemes: ["https"], optional: true }), productId: string({ max: 300, default: "" }), title: string({ min: 1, max: 500 }), price: string({ max: 100 }), image: safeUrl({ schemes: ["https"] }), href: safeUrl({ schemes: ["https"] }), buttonLabel: string({ max: 200, default: "Shop now" }) }) as never,
object({
width: imageDimension("600"),
height: imageDimension("400"),
provider: choice(["shopify", "woocommerce", "manual"] as const, { default: "manual" }),
storeUrl: safeUrl({ schemes: ["https"], optional: true }),
productId: string({ max: 300, default: "" }),
title: string({ min: 1, max: 500 }),
price: string({ max: 100 }),
image: safeUrl({ schemes: ["https"] }),
href: safeUrl({ schemes: ["https"] }),
buttonLabel: string({ max: 200, default: "Shop now" }),
}) as never,
{
emailHtml: ({ node }) => emailCell(`${marketingImage(node, "html")}<h2 style="font-family:inherit;">${html(attrs(node).title)}</h2><p style="font-family:inherit;font-weight:700;">${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
ampEmail: ({ node }) => emailCell(`${marketingImage(node, "amp")}<h2>${html(attrs(node).title)}</h2><p>${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`, node),
mjml: ({ node }) => `${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700">${html(attrs(node).title)}</mj-text><mj-text>${html(attrs(node).price)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
emailHtml: ({ node }) =>
emailCell(
`${marketingImage(node, "html")}<h2 style="font-family:inherit;">${html(attrs(node).title)}</h2><p style="font-family:inherit;font-weight:700;">${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
ampEmail: ({ node }) =>
emailCell(
`${marketingImage(node, "amp")}<h2>${html(attrs(node).title)}</h2><p>${html(attrs(node).price)}</p><p><a href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</a></p>`,
node,
),
mjml: ({ node }) =>
`${marketingImage(node, "mjml")}<mj-text font-size="22px" font-weight="700">${html(attrs(node).title)}</mj-text><mj-text>${html(attrs(node).price)}</mj-text><mj-button href="${html(attrs(node).href)}">${html(attrs(node).buttonLabel)}</mj-button>`,
},
({ node }) => `${String(attrs(node).title)} — ${String(attrs(node).price)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
({ node }) =>
`${String(attrs(node).title)} — ${String(attrs(node).price)}\n${String(attrs(node).buttonLabel)}: ${String(attrs(node).href)}\n\n`,
);
export const emailCoreBlocks: readonly BlockDefinition[] = [
+30 -13
View File
@@ -1,7 +1,14 @@
/** Browser-safe HTML/text rendering. Production AMP/MJML validation stays on the server. */
import {
DEFAULT_LIMITS, defineDocumentKind, escapeHtml, object, registryForKind,
resolveDocumentVariables, renderTree, string, type BlockDocument,
DEFAULT_LIMITS,
defineDocumentKind,
escapeHtml,
object,
registryForKind,
resolveDocumentVariables,
renderTree,
string,
type BlockDocument,
} from "@wrnexus/blocks";
import { emailCoreBlocks } from "./blocks.ts";
export const emailKind = defineDocumentKind({
@@ -30,18 +37,25 @@ export const emailHtmlHead = (document: BlockDocument, body: string, direction:
return `<!doctype html><html lang="${escapeHtml(document.meta.lang)}" dir="${direction}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="x-apple-disable-message-reformatting"><meta name="color-scheme" content="light dark"><title>${escapeHtml(document.meta.subject)}</title><style>a{color:${linkColor}}@media only screen and (max-width:480px){.wrn-email{width:100%!important}.wrn-columns{display:block!important}.wrn-column{display:block!important;width:100%!important}}</style></head><body style="margin:0;padding:0;color:${textColor};font-family:${fontFamily};">${document.meta.preheader ? `<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${escapeHtml(document.meta.preheader)}</div>` : ""}${body}</body></html>`;
};
export async function renderEmailPreview(document: BlockDocument, options: {
variables?: Record<string, unknown>;
direction?: "ltr" | "rtl";
countdownImageUrl?: string;
} = {}) {
export async function renderEmailPreview(
document: BlockDocument,
options: {
variables?: Record<string, unknown>;
direction?: "ltr" | "rtl";
countdownImageUrl?: string;
} = {},
) {
const resolved = resolveDocumentVariables(document, emailKind.variables, options.variables);
if (!resolved.ok) return resolved;
const source = resolved.value;
const context = {
locale: "en", timezone: "UTC", direction: options.direction ?? "ltr",
locale: "en",
timezone: "UTC",
direction: options.direction ?? "ltr",
brandLinkColor: String(source.root.props.linkColor ?? "#2563eb"),
rootBlockIds: Object.values(source.root.slots).flat().map(node => node.id),
rootBlockIds: Object.values(source.root.slots)
.flat()
.map((node) => node.id),
countdownImageUrl: options.countdownImageUrl,
} as const;
const registry = registryForKind(emailKind).freeze();
@@ -51,8 +65,11 @@ export async function renderEmailPreview(document: BlockDocument, options: {
]);
if (!html.ok) return html;
if (!text.ok) return text;
return { ok: true as const, value: {
html: emailHtmlHead(source, html.value.content, context.direction),
text: text.value.content.trimEnd() + "\n",
} };
return {
ok: true as const,
value: {
html: emailHtmlHead(source, html.value.content, context.direction),
text: text.value.content.trimEnd() + "\n",
},
};
}
+50 -17
View File
@@ -2,24 +2,43 @@ import { createRequire } from "node:module";
const { GIFEncoder } = createRequire(import.meta.url)("gifenc") as {
GIFEncoder(): {
writeFrame(pixels: Uint8Array, width: number, height: number, options: {
palette: number[][]; delay: number; repeat: number;
}): void;
writeFrame(
pixels: Uint8Array,
width: number,
height: number,
options: {
palette: number[][];
delay: number;
repeat: number;
},
): void;
finish(): void;
bytes(): Uint8Array;
};
};
const glyphs: Record<string, string> = {
"0": "111101101101111", "1": "010110010010111", "2": "111001111100111",
"3": "111001111001111", "4": "101101111001001", "5": "111100111001111",
"6": "111100111101111", "7": "111001001001001", "8": "111101111101111",
"9": "111101111001111", ":": "000010000010000", " ": "000000000000000",
D: "110101101101110", H: "101101111101101", M: "101111111101101", S: "111100111001111",
"0": "111101101101111",
"1": "010110010010111",
"2": "111001111100111",
"3": "111001111001111",
"4": "101101111001001",
"5": "111100111001111",
"6": "111100111101111",
"7": "111001001001001",
"8": "111101111101111",
"9": "111101111001111",
":": "000010000010000",
" ": "000000000000000",
D: "110101101101110",
H: "101101111101101",
M: "101111111101101",
S: "111100111001111",
};
export function countdownLabel(deadline: number, now: number): string {
if (!Number.isFinite(deadline) || !Number.isFinite(now)) throw new Error("Invalid countdown time.");
if (!Number.isFinite(deadline) || !Number.isFinite(now))
throw new Error("Invalid countdown time.");
const seconds = Math.max(0, Math.ceil((deadline - now) / 1000));
const days = Math.floor(seconds / 86400);
if (days > 999) throw new Error("Countdown cannot exceed 999 days.");
@@ -29,9 +48,12 @@ export function countdownLabel(deadline: number, now: number): string {
/** A bounded, non-looping animation. The caller injects its clock for deterministic rendering. */
export function renderCountdownGif(deadline: number, now: number, frames = 60): Uint8Array {
if (!Number.isInteger(frames) || frames < 1 || frames > 60) throw new Error("Countdown requires 1–60 frames.");
if (!Number.isInteger(frames) || frames < 1 || frames > 60)
throw new Error("Countdown requires 1–60 frames.");
countdownLabel(deadline, now);
const width = 320, height = 64, scale = 4;
const width = 320,
height = 64,
scale = 4;
const encoder = GIFEncoder();
const count = Math.min(frames, Math.max(1, Math.ceil((deadline - now) / 1000) + 1));
for (let frame = 0; frame < count; frame++) {
@@ -40,14 +62,25 @@ export function renderCountdownGif(deadline: number, now: number, frames = 60):
const left = Math.floor((width - label.length * 4 * scale) / 2);
for (let character = 0; character < label.length; character++) {
const glyph = glyphs[label[character]!]!;
for (let row = 0; row < 5; row++) for (let col = 0; col < 3; col++) {
if (glyph[row * 3 + col] !== "1") continue;
for (let y = 0; y < scale; y++) for (let x = 0; x < scale; x++) {
pixels[(22 + row * scale + y) * width + left + character * 4 * scale + col * scale + x] = 1;
for (let row = 0; row < 5; row++)
for (let col = 0; col < 3; col++) {
if (glyph[row * 3 + col] !== "1") continue;
for (let y = 0; y < scale; y++)
for (let x = 0; x < scale; x++) {
pixels[
(22 + row * scale + y) * width + left + character * 4 * scale + col * scale + x
] = 1;
}
}
}
}
encoder.writeFrame(pixels, width, height, { palette: [[17, 24, 39], [255, 255, 255]], delay: 1000, repeat: -1 });
encoder.writeFrame(pixels, width, height, {
palette: [
[17, 24, 39],
[255, 255, 255],
],
delay: 1000,
repeat: -1,
});
}
encoder.finish();
return encoder.bytes();
+67 -6
View File
@@ -2,21 +2,82 @@ import type { BlockNode } from "@wrnexus/blocks";
import { emailCoreBlocks } from "./blocks.ts";
/** Complete trusted editor pack, including schema-valid content factories. */
export const emailEditorBlocks = emailCoreBlocks.map(definition =>
export const emailEditorBlocks = emailCoreBlocks.map((definition) =>
definition.manifest.category === "content" || definition.manifest.type.startsWith("commerce.")
? { ...definition, create: (context: { id(): string }) => createEmailBlock(definition.manifest.type, context) }
? {
...definition,
create: (context: { id(): string }) => createEmailBlock(definition.manifest.type, context),
}
: definition,
);
/** Canonical initial content for palette blocks; time and instance IDs are injectable. */
export function createEmailBlock(type: string, context: { id(): string; now?: number }): BlockNode {
const now = context.now ?? Date.now();
const defaults: Record<string, Record<string, unknown>> = {"content.heading":{text:'New heading',level:'2'},"content.text":{text:'New paragraph'},"content.button":{label:'Call to action',href:'https://example.com'},"content.image":{src:'https://placehold.co/600x300',alt:'',width:'600',height:'300',decorative:false},"content.divider":{},"content.spacer":{height:'24'},"content.video":{title:'Watch video',href:'https://example.com',thumbnail:'https://placehold.co/600x338',alt:'Video thumbnail',width:'600',height:'338'},"content.social":{label:'Follow us',facebook:'',instagram:'',linkedin:'',x:''},"content.countdown":{label:'Offer ends',deadline:new Date(now+86400000).toISOString(),fallback:'This offer has ended.'},"content.survey":{question:'What do you think?',buttonLabel:'Answer survey',href:'https://example.com'},"content.feed-item":{width:'600',height:'400',feedUrl:'',title:'Latest article',summary:'Article summary',href:'https://example.com',image:''},"commerce.product":{width:'600',height:'400',provider:'manual',storeUrl:'',productId:'',title:'Featured product',price:'$0.00',image:'https://placehold.co/600x400',href:'https://example.com',buttonLabel:'Shop now'}};
const definition = emailCoreBlocks.find(block => block.manifest.type === type);
const defaults: Record<string, Record<string, unknown>> = {
"content.heading": { text: "New heading", level: "2" },
"content.text": { text: "New paragraph" },
"content.button": { label: "Call to action", href: "https://example.com" },
"content.image": {
src: "https://placehold.co/600x300",
alt: "",
width: "600",
height: "300",
decorative: false,
},
"content.divider": {},
"content.spacer": { height: "24" },
"content.video": {
title: "Watch video",
href: "https://example.com",
thumbnail: "https://placehold.co/600x338",
alt: "Video thumbnail",
width: "600",
height: "338",
},
"content.social": { label: "Follow us", facebook: "", instagram: "", linkedin: "", x: "" },
"content.countdown": {
label: "Offer ends",
deadline: new Date(now + 86400000).toISOString(),
fallback: "This offer has ended.",
},
"content.survey": {
question: "What do you think?",
buttonLabel: "Answer survey",
href: "https://example.com",
},
"content.feed-item": {
width: "600",
height: "400",
feedUrl: "",
title: "Latest article",
summary: "Article summary",
href: "https://example.com",
image: "",
},
"commerce.product": {
width: "600",
height: "400",
provider: "manual",
storeUrl: "",
productId: "",
title: "Featured product",
price: "$0.00",
image: "https://placehold.co/600x400",
href: "https://example.com",
buttonLabel: "Shop now",
},
};
const definition = emailCoreBlocks.find((block) => block.manifest.type === type);
if (!definition || !Object.prototype.hasOwnProperty.call(defaults, type))
throw new Error("This block is not available for palette insertion.");
const props = definition.manifest.props.parse(defaults[type], "props");
if (!props.ok) throw new Error(props.errors.map(error => error.message).join("\n"));
if (!props.ok) throw new Error(props.errors.map((error) => error.message).join("\n"));
const node = definition.create(context);
return { ...node, type: definition.manifest.type, version: definition.manifest.version, props: props.value };
return {
...node,
type: definition.manifest.type,
version: definition.manifest.version,
props: props.value,
};
}
+78 -19
View File
@@ -1,18 +1,14 @@
import { createRequire } from "node:module";
import {
DEFAULT_LIMITS,
defineDocumentKind,
escapeHtml,
object,
registryForKind,
resolveDocumentVariables,
renderTree,
string,
type BlockDocument,
type Diagnostic,
type Result,
} from "@wrnexus/blocks";
import { emailCoreBlocks, ampLayoutCss } from "./blocks.ts";
import { ampLayoutCss } from "./blocks.ts";
import { validateMjml } from "./mjml.ts";
interface AmpValidationError {
@@ -58,7 +54,9 @@ export interface EmailRenderBundle {
export { emailKind } from "./browser.ts";
import { emailKind, emailHtmlHead as head } from "./browser.ts";
const ampHead = (document: BlockDocument, body: string, direction: "ltr" | "rtl") => {
const layoutCss = (node: BlockDocument["root"]): string => ampLayoutCss(node, String(document.root.props.linkColor ?? "#2563eb")) + Object.values(node.slots).flat().map(layoutCss).join("");
const layoutCss = (node: BlockDocument["root"]): string =>
ampLayoutCss(node, String(document.root.props.linkColor ?? "#2563eb")) +
Object.values(node.slots).flat().map(layoutCss).join("");
const props = document.root.props as Record<string, unknown>;
const css = `@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}.marketing-image img{object-fit:contain}body{margin:0;color:${props.textColor ?? "#111827"};font-family:${props.fontFamily ?? "Arial, sans-serif"}}a{color:${props.linkColor ?? "#2563eb"}}.brand-logo{max-width:${props.logoWidth ?? "200"}px;width:100%;margin:20px auto}.email-bg{table-layout:fixed;width:100%;background:${props.background ?? "#f3f4f6"}}.email-body{max-width:${props.width ?? "600"}px;width:100%;background:${props.contentBackground ?? "#ffffff"}}`;
return `<!doctype html><html amp4email data-css-strict lang="${escapeHtml(document.meta.lang)}" dir="${direction}"><head><meta charset="utf-8"><script async src="https://cdn.ampproject.org/v0.js"></script><style amp4email-boilerplate>body{visibility:hidden}</style><style amp-custom>${css}${layoutCss(document.root)}.button{background:#2563eb;border-radius:6px;color:#fff;display:inline-block;font-weight:700;padding:12px 20px;text-decoration:none}</style></head><body>${body}</body></html>`;
@@ -104,9 +102,27 @@ export async function renderEmail(
if (options.countdownImageUrl) {
try {
const url = new URL(options.countdownImageUrl);
if (url.username || url.password || (url.protocol !== "https:" && !(url.protocol === "http:" && (url.hostname === "localhost" || url.hostname.endsWith(".localhost"))))) throw new Error();
if (
url.username ||
url.password ||
(url.protocol !== "https:" &&
!(
url.protocol === "http:" &&
(url.hostname === "localhost" || url.hostname.endsWith(".localhost"))
))
)
throw new Error();
} catch {
return { ok: false, errors: [{ code: "countdown.endpoint", message: "Countdown images require HTTPS (or a local development host).", severity: "error" }] };
return {
ok: false,
errors: [
{
code: "countdown.endpoint",
message: "Countdown images require HTTPS (or a local development host).",
severity: "error",
},
],
};
}
}
const source = personalized.value;
@@ -119,13 +135,27 @@ export async function renderEmail(
brandLinkColor: String(source.root.props.linkColor ?? "#2563eb"),
emailSubject: String(source.meta.subject),
emailPreheader: String(source.meta.preheader ?? ""),
rootBlockIds: Object.values(source.root.slots).flat().map(node => node.id),
rootBlockIds: Object.values(source.root.slots)
.flat()
.map((node) => node.id),
};
const [htmlResult, textResult, mjmlResult] = await Promise.all([
renderTree(source, emailKind, registry, { ...base, target: "emailHtml", data: options.variables }),
renderTree(source, emailKind, registry, { ...base, target: "plainText", data: options.variables }),
renderTree(source, emailKind, registry, {
...base,
target: "emailHtml",
data: options.variables,
}),
renderTree(source, emailKind, registry, {
...base,
target: "plainText",
data: options.variables,
}),
options.mjml
? renderTree(source, emailKind, registry, { ...base, target: "mjml", data: options.variables })
? renderTree(source, emailKind, registry, {
...base,
target: "mjml",
data: options.variables,
})
: Promise.resolve(undefined),
]);
if (!htmlResult.ok) return htmlResult;
@@ -151,31 +181,60 @@ export async function renderEmail(
if (mjmlResult?.ok) {
const diagnostics = await validateMjml(mjmlResult.value.content);
if (!diagnostics.length) bundle.exports = { mjml: mjmlResult.value.content };
else warnings.push(...diagnostics.map(diagnostic => ({ ...diagnostic, severity: "warning" as const })));
else
warnings.push(
...diagnostics.map((diagnostic) => ({ ...diagnostic, severity: "warning" as const })),
);
} else if (mjmlResult) {
warnings.push(...mjmlResult.errors.map(diagnostic => ({ ...diagnostic, severity: "warning" as const })));
warnings.push(
...mjmlResult.errors.map((diagnostic) => ({ ...diagnostic, severity: "warning" as const })),
);
}
if (options.amp) {
const amp = await renderTree(source, emailKind, registry, { ...base, target: "ampEmail", data: options.variables });
const amp = await renderTree(source, emailKind, registry, {
...base,
target: "ampEmail",
data: options.variables,
});
if (amp.ok) {
const content = ampHead(source, amp.value.content, base.direction);
let timer: ReturnType<typeof setTimeout> | undefined;
let validation: ValidationReport;
const requestedTimeout = options.ampValidationTimeoutMs ?? 2000;
const timeout = Number.isFinite(requestedTimeout) ? Math.min(10000, Math.max(10, requestedTimeout)) : 2000;
const timeout = Number.isFinite(requestedTimeout)
? Math.min(10000, Math.max(10, requestedTimeout))
: 2000;
try {
validation = await Promise.race([
Promise.resolve().then(() => (options.ampValidator ?? validateAmpEmail)(content)),
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("AMP validation timed out.")), timeout); }),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error("AMP validation timed out.")), timeout);
}),
]);
} catch {
validation = { valid: false, diagnostics: [{code:"amp.validatorUnavailable",message:"AMP validation was unavailable or timed out. HTML and plain text remain available.",severity:"warning"}] };
validation = {
valid: false,
diagnostics: [
{
code: "amp.validatorUnavailable",
message:
"AMP validation was unavailable or timed out. HTML and plain text remain available.",
severity: "warning",
},
],
};
} finally {
if (timer !== undefined) clearTimeout(timer);
}
if (validation.valid)
bundle.parts.amp = { contentType: "text/x-amp-html; charset=utf-8", content, validation };
else warnings.push(...validation.diagnostics.map(diagnostic => ({...diagnostic,severity:"warning" as const})));
else
warnings.push(
...validation.diagnostics.map((diagnostic) => ({
...diagnostic,
severity: "warning" as const,
})),
);
} else
warnings.push(...amp.errors.map((error) => ({ ...error, severity: "warning" as const })));
}
+128 -35
View File
@@ -101,30 +101,65 @@ export function importMjml(
};
}
const errors: MjmlDiagnostic[] = [];
if (!ast || ast.tagName !== "mjml") return { ok: false, errors: [{ code: "mjml.root", message: "MJML requires an mjml root element.", severity: "error" }] };
if (!ast || ast.tagName !== "mjml")
return {
ok: false,
errors: [
{ code: "mjml.root", message: "MJML requires an mjml root element.", severity: "error" },
],
};
const pending = [{ node: ast, depth: 0 }];
let nodeCount = 0;
while (pending.length) {
const { node, depth } = pending.pop()!;
if (++nodeCount > DEFAULT_LIMITS.maxNodes || depth > DEFAULT_LIMITS.maxDepth) {
return { ok: false, errors: [{ code: "mjml.limits", message: "MJML exceeds document node or depth limits.", severity: "error" }] };
return {
ok: false,
errors: [
{
code: "mjml.limits",
message: "MJML exceeds document node or depth limits.",
severity: "error",
},
],
};
}
for (const child of node.children ?? []) pending.push({ node: child, depth: depth + 1 });
}
const decode = (value: string) => value.replace(/&(?:#(x[0-9a-f]+|[0-9]+)|(amp|lt|gt|quot|apos));/gi, (original, numeric: string | undefined, name: string | undefined) => {
if (numeric) {
const point = numeric[0]!.toLowerCase() === "x" ? Number.parseInt(numeric.slice(1), 16) : Number(numeric);
return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : original;
}
return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record<string, string>)[name!.toLowerCase()]!;
});
const decode = (value: string) =>
value.replace(
/&(?:#(x[0-9a-f]+|[0-9]+)|(amp|lt|gt|quot|apos));/gi,
(original, numeric: string | undefined, name: string | undefined) => {
if (numeric) {
const point =
numeric[0]!.toLowerCase() === "x"
? Number.parseInt(numeric.slice(1), 16)
: Number(numeric);
return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
? String.fromCodePoint(point)
: original;
}
return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" } as Record<string, string>)[
name!.toLowerCase()
]!;
},
);
const brand: Record<string, string> = {};
let importedSubject = "", importedPreheader = "";
const attributeError = (node: MjmlAst, attribute?: string) => errors.push({ code: "mjml.header", message: `Unsupported MJML header setting ${node.tagName}${attribute ? `.${attribute}` : ""}.`, severity: "error", element: node.tagName, attribute });
let importedSubject = "",
importedPreheader = "";
const attributeError = (node: MjmlAst, attribute?: string) =>
errors.push({
code: "mjml.header",
message: `Unsupported MJML header setting ${node.tagName}${attribute ? `.${attribute}` : ""}.`,
severity: "error",
element: node.tagName,
attribute,
});
const onlyAttributes = (node: MjmlAst, allowed: string[]) => {
for (const key of Object.keys(node.attributes ?? {})) if (!allowed.includes(key)) attributeError(node, key);
for (const key of Object.keys(node.attributes ?? {}))
if (!allowed.includes(key)) attributeError(node, key);
};
for (const head of (ast.children ?? []).filter(node => node.tagName === "mj-head")) {
for (const head of (ast.children ?? []).filter((node) => node.tagName === "mj-head")) {
onlyAttributes(head, []);
for (const node of head.children ?? []) {
if (node.tagName === "mj-title" || node.tagName === "mj-preview") {
@@ -136,13 +171,15 @@ export function importMjml(
for (const defaults of node.children ?? []) {
if (defaults.tagName === "mj-all") {
onlyAttributes(defaults, ["font-family"]);
if (defaults.attributes?.["font-family"]) brand.fontFamily = decode(defaults.attributes["font-family"]);
if (defaults.attributes?.["font-family"])
brand.fontFamily = decode(defaults.attributes["font-family"]);
} else if (defaults.tagName === "mj-text") {
onlyAttributes(defaults, ["color"]);
if (defaults.attributes?.color) brand.textColor = decode(defaults.attributes.color);
} else if (defaults.tagName === "mj-button") {
onlyAttributes(defaults, ["background-color"]);
if (defaults.attributes?.["background-color"]) brand.linkColor = decode(defaults.attributes["background-color"]);
if (defaults.attributes?.["background-color"])
brand.linkColor = decode(defaults.attributes["background-color"]);
} else attributeError(defaults);
}
} else if (node.tagName === "mj-breakpoint") {
@@ -151,31 +188,67 @@ export function importMjml(
} else attributeError(node);
}
}
const bodyAttributes = (ast.children ?? []).find(node => node.tagName === "mj-body")?.attributes ?? {};
const bodyAttributes =
(ast.children ?? []).find((node) => node.tagName === "mj-body")?.attributes ?? {};
const wrapColumns = (nodes: BlockNode[]): BlockNode[] => {
const output: BlockNode[] = [];
for (let index = 0; index < nodes.length;) {
if (nodes[index]!.type !== "layout.column") { output.push(nodes[index++]!); continue; }
if (nodes[index]!.type !== "layout.column") {
output.push(nodes[index++]!);
continue;
}
const columns: BlockNode[] = [];
while (index < nodes.length && nodes[index]!.type === "layout.column") columns.push(nodes[index++]!);
while (index < nodes.length && nodes[index]!.type === "layout.column")
columns.push(nodes[index++]!);
let explicit = 0;
const missing = columns.filter(column => !column.props.width);
const missing = columns.filter((column) => !column.props.width);
for (const column of columns) {
const width = String(column.props.width || "");
if (!width) continue;
if (!/^\d+(?:\.\d+)?%$/.test(width) || Number.parseFloat(width) <= 0 || Number.parseFloat(width) > 100) {
errors.push({ code: "mjml.column-width", message: "Column width must be a percentage between 0 and 100.", severity: "error", element: "mj-column", attribute: "width" });
if (
!/^\d+(?:\.\d+)?%$/.test(width) ||
Number.parseFloat(width) <= 0 ||
Number.parseFloat(width) > 100
) {
errors.push({
code: "mjml.column-width",
message: "Column width must be a percentage between 0 and 100.",
severity: "error",
element: "mj-column",
attribute: "width",
});
} else explicit += Number.parseFloat(width);
}
if (explicit > 100 || (!missing.length && Math.abs(explicit - 100) > 0.001) || (missing.length && explicit >= 100)) {
errors.push({ code: "mjml.column-width", message: "Column widths must fill one 100% row.", severity: "error", element: "mj-column", attribute: "width" });
if (
explicit > 100 ||
(!missing.length && Math.abs(explicit - 100) > 0.001) ||
(missing.length && explicit >= 100)
) {
errors.push({
code: "mjml.column-width",
message: "Column widths must fill one 100% row.",
severity: "error",
element: "mj-column",
attribute: "width",
});
}
let assigned = 0;
missing.forEach((column, position) => {
const width = position === missing.length - 1 ? 100 - explicit - assigned : Math.round((100 - explicit) / missing.length * 100) / 100;
column.props.width = `${width}%`; assigned += width;
const width =
position === missing.length - 1
? 100 - explicit - assigned
: Math.round(((100 - explicit) / missing.length) * 100) / 100;
column.props.width = `${width}%`;
assigned += width;
});
output.push({
id: options.id(),
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: { columns },
});
output.push({ id: options.id(), type: "layout.columns", version: 1, props: {}, styles: {}, slots: { columns } });
}
return output;
};
@@ -191,7 +264,10 @@ export function importMjml(
return [];
}
const converted = (node.children ?? []).flatMap(convert);
const children = containers.has(node.tagName) && node.tagName !== "mj-column" ? wrapColumns(converted) : converted;
const children =
containers.has(node.tagName) && node.tagName !== "mj-column"
? wrapColumns(converted)
: converted;
if (node.tagName === "mjml" || node.tagName === "mj-head" || node.tagName === "mj-body")
return children;
if (
@@ -262,14 +338,23 @@ export function importMjml(
"font-size": ["fontSize", /^\d+(?:\.\d+)?(?:px|rem|em|%)$/],
"font-weight": ["fontWeight", /^(normal|bold|[1-9]00)$/],
"border-radius": ["borderRadius", /^\d+(?:\.\d+)?(?:px|rem|em|%)$/],
"inner-padding": ["padding", /^\d+(?:\.\d+)?(?:px|rem|em|%)(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)){0,3}$/],
"inner-padding": [
"padding",
/^\d+(?:\.\d+)?(?:px|rem|em|%)(?:\s+\d+(?:\.\d+)?(?:px|rem|em|%)){0,3}$/,
],
};
for (const [attribute, raw] of Object.entries(a)) {
if (attribute === "href") continue;
const mapping = mappings[attribute];
const value = decode(raw).trim();
if (!mapping || value.length > 80 || !mapping[1].test(value)) {
errors.push({ code: "mjml.button-attribute", message: `Unsupported button attribute or value: ${attribute}.`, severity: "error", element: node.tagName, attribute });
errors.push({
code: "mjml.button-attribute",
message: `Unsupported button attribute or value: ${attribute}.`,
severity: "error",
element: node.tagName,
attribute,
});
} else buttonStyles[mapping[0]] = { base: value };
}
return [
@@ -304,7 +389,11 @@ export function importMjml(
id: options.id(),
type: "layout.email-document",
version: 1,
props: { width: (bodyAttributes.width ?? "600").replace(/px$/, ""), background: bodyAttributes["background-color"] ?? "#f3f4f6", ...brand },
props: {
width: (bodyAttributes.width ?? "600").replace(/px$/, ""),
background: bodyAttributes["background-color"] ?? "#f3f4f6",
...brand,
},
styles: {},
slots: {
content: content.map((node) =>
@@ -322,11 +411,15 @@ export function importMjml(
},
};
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: options.subject ?? (importedSubject || "Imported email"), preheader: options.preheader ?? importedPreheader, lang: "en" },
theme: { tokens: {} },
root,
schemaVersion: 1,
kind: "email",
meta: {
subject: options.subject ?? (importedSubject || "Imported email"),
preheader: options.preheader ?? importedPreheader,
lang: "en",
},
theme: { tokens: {} },
root,
};
const validated = validateDocument(document, emailKind, registryForKind(emailKind).freeze());
if (!validated.ok) return { ok: false, errors: validated.errors };
+232 -77
View File
@@ -2,100 +2,255 @@ import type { BlockNode, JsonObject } from "@wrnexus/blocks";
/** Designed compositions made entirely from native, editable email blocks. */
export function createSectionPreset(name: string, id: () => string): BlockNode {
const node = (type: string, props: JsonObject, slots: Record<string, BlockNode[]> = {}, appearance: Record<string, string> = {}): BlockNode => ({
id: id(), type, version: 1, props,
styles: Object.fromEntries(Object.entries(appearance).map(([key, base]) => [key, {base}])), slots,
const node = (
type: string,
props: JsonObject,
slots: Record<string, BlockNode[]> = {},
appearance: Record<string, string> = {},
): BlockNode => ({
id: id(),
type,
version: 1,
props,
styles: Object.fromEntries(Object.entries(appearance).map(([key, base]) => [key, { base }])),
slots,
});
const text = (value: string, appearance: Record<string, string> = {}) =>
node("content.text", {text: value}, {}, {fontSize: "16px", color: "#475569", ...appearance});
node(
"content.text",
{ text: value },
{},
{ fontSize: "16px", color: "#475569", ...appearance },
);
const heading = (value: string, appearance: Record<string, string> = {}) =>
node("content.heading", {text: value, level: "2"}, {}, {fontSize: "22px", color: "#14213d", ...appearance});
const eyebrow = (value: string, color = "#0f766e") => text(value, {fontSize: "11px", fontWeight: "700", color});
const button = (label: string, background = "#14213d", color = "#ffffff", href = "https://example.com") =>
node("content.button", {label, href}, {}, {backgroundColor: background, color, padding: "14px 24px", borderRadius: "8px", fontSize: "14px", fontWeight: "700"});
const space = (height = "16") => node("content.spacer", {height});
const column = (content: BlockNode[], width = "100%") => node("layout.column", {width}, {content});
const row = (columns: BlockNode[]) => node("layout.columns", {}, {columns});
let rows: BlockNode[], background = "#ffffff", padding = "40px";
node(
"content.heading",
{ text: value, level: "2" },
{},
{ fontSize: "22px", color: "#14213d", ...appearance },
);
const eyebrow = (value: string, color = "#0f766e") =>
text(value, { fontSize: "11px", fontWeight: "700", color });
const button = (
label: string,
background = "#14213d",
color = "#ffffff",
href = "https://example.com",
) =>
node(
"content.button",
{ label, href },
{},
{
backgroundColor: background,
color,
padding: "14px 24px",
borderRadius: "8px",
fontSize: "14px",
fontWeight: "700",
},
);
const space = (height = "16") => node("content.spacer", { height });
const column = (content: BlockNode[], width = "100%") =>
node("layout.column", { width }, { content });
const row = (columns: BlockNode[]) => node("layout.columns", {}, { columns });
let rows: BlockNode[],
background = "#ffffff",
padding = "40px";
if (name === "welcome") {
background = "#edf7f3";
rows = [row([column([
eyebrow("A FRESH START"),
heading("Good things start here.", {fontSize: "26px"}),
text("Welcome, {{recipientName|friend}}. A little inspiration, thoughtful discoveries, and more of what you love — all in one place."),
space("8"), button("Make yourself at home", "#0f766e"),
space("24"), text("YOUR NEXT CHAPTER / STARTS TODAY", {fontSize: "10px", color: "#0f766e", fontWeight: "700"}),
])])];
} else if (name === "feature") {
background = "#f4f1eb";
rows = [row([
column([
text("THE EDIT", {fontSize: "11px", fontWeight: "700", color: "#9a3412"}),
heading("Less noise.\nMore possibility.", {fontSize: "23px"}),
text("Meet your next everyday favorite. Thoughtfully made, beautifully simple, and ready for whatever comes next.", {fontSize: "14px"}),
space("8"), button("Discover the collection", "#9a3412"),
], "65%"),
column([
text("01", {fontSize: "64px", fontWeight: "700", color: "#9a3412", textAlign: "center", backgroundColor: "#eadfd1", padding: "24px 8px"}),
text("THOUGHTFULLY\nCURATED", {fontSize: "11px", fontWeight: "700", textAlign: "center", color: "#9a3412", padding: "16px 8px"}),
], "35%"),
])];
} else if (name === "announcement") {
background = "#14213d";
rows = [row([column([
eyebrow("JUST RELEASED", "#a7f3d0"),
heading("Something new.\nMade for you.", {fontSize: "28px", color: "#ffffff"}),
text("A fresh perspective. A better experience. Discover the latest chapter and see what we’ve been working on.", {color: "#cbd5e1"}),
space("12"), button("Take a first look", "#a7f3d0", "#14213d"),
space("20"), text("BE THE FIRST TO EXPLORE", {fontSize: "10px", color: "#a7f3d0", fontWeight: "700"}),
])])];
} else if (name === "testimonial") {
background = "#fff7ed";
rows = [row([column([
eyebrow("FROM OUR COMMUNITY", "#9a3412"),
text("“", {fontSize: "64px", color: "#c2410c", fontWeight: "700"}),
heading("The details make\nall the difference.", {fontSize: "23px", color: "#431407"}),
text("“A thoughtful experience from start to finish. Everything felt effortless — and the result was even better than I imagined.”", {color: "#7c2d12"}),
space("12"), text("CUSTOMER NAME", {fontSize: "12px", fontWeight: "700", color: "#431407"}),
text("Customer story · Replace with an approved quote", {fontSize: "11px", color: "#9a3412"}),
])])];
} else if (name === "two-column") {
rows = [
row([column([eyebrow("A LITTLE INSPIRATION"), heading("Two ways to find your next favorite."), space("12")])]),
row([
column([
text("01 / DISCOVER", {fontSize: "11px", fontWeight: "700", color: "#0f766e", backgroundColor: "#edf7f3", padding: "20px 16px"}),
heading("Fresh perspectives", {fontSize: "16px", padding: "16px 16px 0"}),
text("Ideas and inspiration to make every day feel a little different.", {fontSize: "14px", padding: "0 16px"}),
button("Explore ideas", "#0f766e"),
], "50%"),
eyebrow("A FRESH START"),
heading("Good things start here.", { fontSize: "26px" }),
text(
"Welcome, {{recipientName|friend}}. A little inspiration, thoughtful discoveries, and more of what you love — all in one place.",
),
space("8"),
button("Make yourself at home", "#0f766e"),
space("24"),
text("YOUR NEXT CHAPTER / STARTS TODAY", {
fontSize: "10px",
color: "#0f766e",
fontWeight: "700",
}),
]),
]),
];
} else if (name === "feature") {
background = "#f4f1eb";
rows = [
row([
column(
[
text("THE EDIT", { fontSize: "11px", fontWeight: "700", color: "#9a3412" }),
heading("Less noise.\nMore possibility.", { fontSize: "23px" }),
text(
"Meet your next everyday favorite. Thoughtfully made, beautifully simple, and ready for whatever comes next.",
{ fontSize: "14px" },
),
space("8"),
button("Discover the collection", "#9a3412"),
],
"65%",
),
column(
[
text("01", {
fontSize: "64px",
fontWeight: "700",
color: "#9a3412",
textAlign: "center",
backgroundColor: "#eadfd1",
padding: "24px 8px",
}),
text("THOUGHTFULLY\nCURATED", {
fontSize: "11px",
fontWeight: "700",
textAlign: "center",
color: "#9a3412",
padding: "16px 8px",
}),
],
"35%",
),
]),
];
} else if (name === "announcement") {
background = "#14213d";
rows = [
row([
column([
text("02 / EXPLORE", {fontSize: "11px", fontWeight: "700", color: "#9a3412", backgroundColor: "#fff7ed", padding: "20px 16px"}),
heading("Thoughtful essentials", {fontSize: "16px", padding: "16px 16px 0"}),
text("Considered details. Everyday favorites. Find something that fits.", {fontSize: "14px", padding: "0 16px"}),
button("Find your favorite", "#9a3412"),
], "50%"),
eyebrow("JUST RELEASED", "#a7f3d0"),
heading("Something new.\nMade for you.", { fontSize: "28px", color: "#ffffff" }),
text(
"A fresh perspective. A better experience. Discover the latest chapter and see what we’ve been working on.",
{ color: "#cbd5e1" },
),
space("12"),
button("Take a first look", "#a7f3d0", "#14213d"),
space("20"),
text("BE THE FIRST TO EXPLORE", {
fontSize: "10px",
color: "#a7f3d0",
fontWeight: "700",
}),
]),
]),
];
} else if (name === "testimonial") {
background = "#fff7ed";
rows = [
row([
column([
eyebrow("FROM OUR COMMUNITY", "#9a3412"),
text("“", { fontSize: "64px", color: "#c2410c", fontWeight: "700" }),
heading("The details make\nall the difference.", { fontSize: "23px", color: "#431407" }),
text(
"“A thoughtful experience from start to finish. Everything felt effortless — and the result was even better than I imagined.”",
{ color: "#7c2d12" },
),
space("12"),
text("CUSTOMER NAME", { fontSize: "12px", fontWeight: "700", color: "#431407" }),
text("Customer story · Replace with an approved quote", {
fontSize: "11px",
color: "#9a3412",
}),
]),
]),
];
} else if (name === "two-column") {
rows = [
row([
column([
eyebrow("A LITTLE INSPIRATION"),
heading("Two ways to find your next favorite."),
space("12"),
]),
]),
row([
column(
[
text("01 / DISCOVER", {
fontSize: "11px",
fontWeight: "700",
color: "#0f766e",
backgroundColor: "#edf7f3",
padding: "20px 16px",
}),
heading("Fresh perspectives", { fontSize: "16px", padding: "16px 16px 0" }),
text("Ideas and inspiration to make every day feel a little different.", {
fontSize: "14px",
padding: "0 16px",
}),
button("Explore ideas", "#0f766e"),
],
"50%",
),
column(
[
text("02 / EXPLORE", {
fontSize: "11px",
fontWeight: "700",
color: "#9a3412",
backgroundColor: "#fff7ed",
padding: "20px 16px",
}),
heading("Thoughtful essentials", { fontSize: "16px", padding: "16px 16px 0" }),
text("Considered details. Everyday favorites. Find something that fits.", {
fontSize: "14px",
padding: "0 16px",
}),
button("Find your favorite", "#9a3412"),
],
"50%",
),
]),
];
} else if (name === "footer") {
background = "#f1f5f9";
padding = "32px 40px";
rows = [row([column([
eyebrow("LET’S STAY CONNECTED", "#334155"),
heading("Thanks for being here.", {fontSize: "18px"}),
text("Good things are better shared. We’re glad you’re part of our community.", {fontSize: "13px"}),
node("content.divider", {}),
text("{{organizationAddress|Add your organization address}}", {fontSize: "12px", color: "#64748b"}),
text("You’re receiving this email because you signed up for our updates.", {fontSize: "11px", color: "#64748b"}),
button("Unsubscribe", "#e2e8f0", "#334155", "{{unsubscribeUrl|https://example.com/unsubscribe}}"),
])])];
rows = [
row([
column([
eyebrow("LET’S STAY CONNECTED", "#334155"),
heading("Thanks for being here.", { fontSize: "18px" }),
text("Good things are better shared. We’re glad you’re part of our community.", {
fontSize: "13px",
}),
node("content.divider", {}),
text("{{organizationAddress|Add your organization address}}", {
fontSize: "12px",
color: "#64748b",
}),
text("You’re receiving this email because you signed up for our updates.", {
fontSize: "11px",
color: "#64748b",
}),
button(
"Unsubscribe",
"#e2e8f0",
"#334155",
"{{unsubscribeUrl|https://example.com/unsubscribe}}",
),
]),
]),
];
} else throw new Error("Unknown section preset.");
return node("layout.section", {background, padding}, {content: rows});
return node("layout.section", { background, padding }, { content: rows });
}
export const emailPresets = ["welcome", "feature", "announcement", "testimonial", "two-column", "footer"].map(id => ({
export const emailPresets = [
"welcome",
"feature",
"announcement",
"testimonial",
"two-column",
"footer",
].map((id) => ({
id,
name: {key: "email.presets." + id, fallback: id[0].toUpperCase() + id.slice(1)},
name: { key: "email.presets." + id, fallback: id[0].toUpperCase() + id.slice(1) },
icon: "icon-[lucide--layout-template]",
create: (context: {id(): string}) => createSectionPreset(id, context.id),
create: (context: { id(): string }) => createSectionPreset(id, context.id),
}));
+51 -12
View File
@@ -1,26 +1,65 @@
import type { ValueSchema } from "@wrnexus/blocks";
export interface TextRun { text: string; bold?: boolean; italic?: boolean; underline?: boolean }
export interface TextRun {
text: string;
bold?: boolean;
italic?: boolean;
underline?: boolean;
}
export const richTextSchema: ValueSchema<TextRun[]> = {
kind: "rich-text",
parse(value = [], path = "richText") {
if (!Array.isArray(value) || value.length > 4000 || value.some(run => !run || typeof run !== "object" || typeof run.text !== "string" || Object.keys(run).some(key => !["text", "bold", "italic", "underline"].includes(key)) || ["bold", "italic", "underline"].some(key => run[key] !== undefined && typeof run[key] !== "boolean")) || value.reduce((size, run) => size + run.text.length, 0) > 200000)
return { ok: false, errors: [{code: "email.rich-text", message: "Invalid or oversized rich text.", severity: "error", path}] };
if (
!Array.isArray(value) ||
value.length > 4000 ||
value.some(
(run) =>
!run ||
typeof run !== "object" ||
typeof run.text !== "string" ||
Object.keys(run).some((key) => !["text", "bold", "italic", "underline"].includes(key)) ||
["bold", "italic", "underline"].some(
(key) => run[key] !== undefined && typeof run[key] !== "boolean",
),
) ||
value.reduce((size, run) => size + run.text.length, 0) > 200000
)
return {
ok: false,
errors: [
{
code: "email.rich-text",
message: "Invalid or oversized rich text.",
severity: "error",
path,
},
],
};
return { ok: true, value };
},
};
const escape = (value: string) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;").replace(/\r\n?|\n/g, "<br />");
const escape = (value: string) =>
value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;")
.replace(/\r\n?|\n/g, "<br />");
/** Ignore stale formatting if a plain-text inspector or importer changed the text. */
export function renderRichText(props: Record<string, unknown>): string {
const parsed = richTextSchema.parse(props.richText);
const text = String(props.text ?? "");
if (!parsed.ok || !parsed.value.length || parsed.value.map(run => run.text).join("") !== text) return escape(text);
return parsed.value.map(run => {
let result = escape(run.text);
if (run.underline) result = `<u>${result}</u>`;
if (run.italic) result = `<em>${result}</em>`;
if (run.bold) result = `<strong>${result}</strong>`;
return result;
}).join("");
if (!parsed.ok || !parsed.value.length || parsed.value.map((run) => run.text).join("") !== text)
return escape(text);
return parsed.value
.map((run) => {
let result = escape(run.text);
if (run.underline) result = `<u>${result}</u>`;
if (run.italic) result = `<em>${result}</em>`;
if (run.bold) result = `<strong>${result}</strong>`;
return result;
})
.join("");
}
+26 -10
View File
@@ -1,7 +1,12 @@
const color = /^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\([0-9., %]+\))$/i;
const spacing = /^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))(?:\s+(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))){0,3}$/;
const color =
/^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\([0-9., %]+\))$/i;
const spacing =
/^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))(?:\s+(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))){0,3}$/;
const patterns: Record<string, RegExp> = {
color, backgroundColor: color, padding: spacing, margin: spacing,
color,
backgroundColor: color,
padding: spacing,
margin: spacing,
fontSize: /^\d+(?:\.\d+)?(?:px|rem|em|%)$/,
borderRadius: /^(?:0|\d+(?:\.\d+)?(?:px|rem|em|%))$/,
textAlign: /^(left|center|right|start|end)$/,
@@ -11,11 +16,11 @@ const patterns: Record<string, RegExp> = {
function validColor(value: string): boolean {
if (!/^rgba?\(/i.test(value)) return true;
const match = /^(rgb|rgba)\((.*)\)$/i.exec(value)!;
const channels = match[2]!.split(",").map(part => part.trim());
const channels = match[2]!.split(",").map((part) => part.trim());
if (channels.length !== (match[1]!.toLowerCase() === "rgba" ? 4 : 3)) return false;
const numeric = /^(?:\d+(?:\.\d+)?|\.\d+)%?$/;
if (!channels.every(channel => numeric.test(channel))) return false;
const percentages = channels.slice(0, 3).filter(channel => channel.endsWith("%")).length;
if (!channels.every((channel) => numeric.test(channel))) return false;
const percentages = channels.slice(0, 3).filter((channel) => channel.endsWith("%")).length;
if (percentages !== 0 && percentages !== 3) return false;
return channels.every((channel, index) => {
const maximum = channel.endsWith("%") ? 100 : index === 3 ? 1 : 255;
@@ -27,13 +32,24 @@ function validColor(value: string): boolean {
export function emailStyleValue(key: string, value: unknown): string {
if (typeof value !== "string") return "";
const candidate = value.trim();
if (candidate.length > 80 || !Object.prototype.hasOwnProperty.call(patterns, key) || !patterns[key]!.test(candidate)) return "";
if (
candidate.length > 80 ||
!Object.prototype.hasOwnProperty.call(patterns, key) ||
!patterns[key]!.test(candidate)
)
return "";
if ((key === "color" || key === "backgroundColor") && !validColor(candidate)) return "";
if (["padding", "margin", "fontSize", "borderRadius"].includes(key) &&
candidate.split(/\s+/).some(part => Number.parseFloat(part) > 4000)) return "";
if (
["padding", "margin", "fontSize", "borderRadius"].includes(key) &&
candidate.split(/\s+/).some((part) => Number.parseFloat(part) > 4000)
)
return "";
return candidate;
}
export function validateEmailStyleValue(key: string, value: string): void {
if (!emailStyleValue(key, value)) throw new Error(`styles.${key}: Unsupported style value. Use an email-safe value with units where required.`);
if (!emailStyleValue(key, value))
throw new Error(
`styles.${key}: Unsupported style value. Use an email-safe value with units where required.`,
);
}
+23 -4
View File
@@ -4,10 +4,29 @@ import { renderEmail } from "../src/email.ts";
import type { BlockDocument } from "@wrnexus/blocks";
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Local preview", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Hello {{recipientName|friend}}" }, styles: {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Local preview", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Hello {{recipientName|friend}}" },
styles: {},
slots: {},
},
],
},
},
};
test("browser preview matches production HTML/text without server validators", async () => {
+131 -24
View File
@@ -5,18 +5,55 @@ import { renderEmail, validateMjml } from "../src/index.ts";
test("button alignment maps physical and logical positions consistently in LTR and RTL", async () => {
for (const direction of ["ltr", "rtl"] as const) {
for (const alignment of [undefined, "left", "center", "right", "start", "end"]) {
const expected = !alignment || alignment === "start" ? (direction === "rtl" ? "right" : "left") : alignment === "end" ? (direction === "rtl" ? "left" : "right") : alignment;
const expected =
!alignment || alignment === "start"
? direction === "rtl"
? "right"
: "left"
: alignment === "end"
? direction === "rtl"
? "left"
: "right"
: alignment;
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Alignment", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "cta", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: alignment ? { textAlign: { base: alignment } } : {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Alignment", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: alignment ? { textAlign: { base: alignment } } : {},
slots: {},
},
],
},
},
};
const rendered = await renderEmail(document, { direction, amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const rendered = await renderEmail(document, {
direction,
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) continue;
expect(rendered.value.parts.html.content).toContain(`<table role="presentation" align="${expected}" cellpadding="0"`);
expect(rendered.value.parts.amp?.content).toContain(`data-block-id="cta" align="${expected}"`);
expect(rendered.value.parts.html.content).toContain(
`<table role="presentation" align="${expected}" cellpadding="0"`,
);
expect(rendered.value.parts.amp?.content).toContain(
`data-block-id="cta" align="${expected}"`,
);
expect(rendered.value.parts.amp?.validation.valid).toBe(true);
expect(rendered.value.exports?.mjml).toContain(`<mj-button align="${expected}"`);
}
@@ -25,24 +62,62 @@ test("button alignment maps physical and logical positions consistently in LTR a
test("button typography and corners reach the clickable element in every target", async () => {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Styled CTA", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: {
content: [{ id: "cta", type: "content.button", version: 1, props: { label: "Read more", href: "https://example.com" }, styles: {
color: { base: "#123456" }, fontSize: { base: "22px" }, fontWeight: { base: "400" }, borderRadius: { base: "18px" },
}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Styled CTA", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Read more", href: "https://example.com" },
styles: {
color: { base: "#123456" },
fontSize: { base: "22px" },
fontWeight: { base: "400" },
borderRadius: { base: "18px" },
},
slots: {},
},
],
},
},
};
const before = structuredClone(document);
const result = await renderEmail(document, { amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const result = await renderEmail(document, {
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const anchor = result.value.parts.html.content.match(/<a href="https:\/\/example.com" style="([^"]+)"/)?.[1];
for (const declaration of ["color:#123456", "font-size:22px", "font-weight:400", "border-radius:18px"]) {
const anchor = result.value.parts.html.content.match(
/<a href="https:\/\/example.com" style="([^"]+)"/,
)?.[1];
for (const declaration of [
"color:#123456",
"font-size:22px",
"font-weight:400",
"border-radius:18px",
]) {
expect(anchor).toContain(declaration);
expect(result.value.parts.amp?.content).toContain(declaration);
}
expect(result.value.parts.amp?.validation.valid).toBe(true);
for (const attribute of ['color="#123456"', 'font-size="22px"', 'font-weight="400"', 'border-radius="18px"']) {
for (const attribute of [
'color="#123456"',
'font-size="22px"',
'font-weight="400"',
'border-radius="18px"',
]) {
expect(result.value.exports?.mjml).toContain(attribute);
}
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
@@ -52,14 +127,46 @@ test("button typography and corners reach the clickable element in every target"
test("button background inherits brand color with explicit semantic overrides across formats", async () => {
for (const override of [undefined, "#aabbcc"]) {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Brand", lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { linkColor: "#125634" }, styles: {}, slots: {
content: [{ id: "button", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: override ? { backgroundColor: { base: override } } : {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: "Brand", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { linkColor: "#125634" },
styles: {},
slots: {
content: [
{
id: "button",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: override ? { backgroundColor: { base: override } } : {},
slots: {},
},
],
},
},
};
document.root.slots.content = [{ id: "section", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: document.root.slots.content } }];
document.root.slots.content = [
{
id: "section",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: { content: document.root.slots.content },
},
];
const before = structuredClone(document);
const rendered = await renderEmail(document, { amp: true, mjml: true, ampValidationTimeoutMs: 10000 });
const rendered = await renderEmail(document, {
amp: true,
mjml: true,
ampValidationTimeoutMs: 10000,
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
const color = override ?? "#125634";
@@ -2,8 +2,19 @@ import { expect, test } from "bun:test";
import { buttonBlock, ampLayoutCss } from "../src/blocks.ts";
test("button visuals target the clickable surface rather than the full-width wrapper", async () => {
const node = {id:"cta",type:"content.button",version:1,props:{label:"Act",href:"https://example.com"},styles:{backgroundColor:{base:"#123456"},padding:{base:"8px 32px"},borderRadius:{base:"20px"}},slots:{}};
const context = {node,context:{},slots:{}} as never;
const node = {
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: {
backgroundColor: { base: "#123456" },
padding: { base: "8px 32px" },
borderRadius: { base: "20px" },
},
slots: {},
};
const context = { node, context: {}, slots: {} } as never;
const html = String(await buttonBlock.renderers!.emailHtml!(context));
const wrapper = html.match(/<td data-block-id="cta"[^>]*>/)![0];
expect(wrapper).not.toContain("#123456");
@@ -12,7 +12,7 @@ test("countdown ticks across boundaries and stops at zero", () => {
test("countdown generates deterministic bounded non-looping GIF output", () => {
const first = renderCountdownGif(60000, 0);
expect(first).toEqual(renderCountdownGif(60000, 0));
expect(new TextDecoder().decode(first.subarray(0,6))).toBe("GIF89a");
expect(new TextDecoder().decode(first.subarray(0, 6))).toBe("GIF89a");
expect(first[6]! + first[7]! * 256).toBe(320);
expect(first[8]! + first[9]! * 256).toBe(64);
expect(first.at(-1)).toBe(0x3b);
+7 -3
View File
@@ -4,15 +4,19 @@ import { emailCoreBlocks } from "../src/blocks.ts";
test("palette factory produces schema-valid independent blocks with injected IDs and time", () => {
let sequence = 0;
for (const definition of emailCoreBlocks.filter(block => /^(content|commerce)\./.test(block.manifest.type))) {
for (const definition of emailCoreBlocks.filter((block) =>
/^(content|commerce)\./.test(block.manifest.type),
)) {
const context = { id: () => `node-${++sequence}`, now: Date.parse("2026-09-05T00:00:00Z") };
const first = createEmailBlock(definition.manifest.type, context), second = createEmailBlock(definition.manifest.type, context);
const first = createEmailBlock(definition.manifest.type, context),
second = createEmailBlock(definition.manifest.type, context);
expect(definition.manifest.props.parse(first.props).ok).toBe(true);
expect(first.id).not.toBe(second.id);
expect(first.props).toEqual(second.props);
expect(first.props).not.toBe(second.props);
expect(first.version).toBe(definition.manifest.version);
if (first.type === "content.countdown") expect(first.props.deadline).toBe("2026-09-06T00:00:00.000Z");
if (first.type === "content.countdown")
expect(first.props.deadline).toBe("2026-09-06T00:00:00.000Z");
}
expect(() => createEmailBlock("untrusted.block", { id: () => "id" })).toThrow();
});
@@ -4,7 +4,9 @@ import { emailPresets } from "../src/presets.ts";
test("published email editor content factories return valid independent instances", () => {
let id = 0;
for (const definition of emailEditorBlocks.filter(block => block.manifest.category === "content")) {
for (const definition of emailEditorBlocks.filter(
(block) => block.manifest.category === "content",
)) {
const first = definition.create({ id: () => String(++id) });
const second = definition.create({ id: () => String(++id) });
expect(first.id).not.toBe(second.id);
+143 -38
View File
@@ -16,19 +16,35 @@ test("AMP section and spacer CSS retains configured layout values", async () =>
const draft = structuredClone(document);
const section = draft.root.slots.content[0]!;
section.props = { background: "#abcdef", padding: "12px 30px" };
const spacer = { id: 'spacer:one"', type: "content.spacer", version: 1, props: { height: "77" }, styles: {}, slots: {} };
const spacer = {
id: 'spacer:one"',
type: "content.spacer",
version: 1,
props: { height: "77" },
styles: {},
slots: {},
};
section.slots.content = [spacer];
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
const amp = result.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
expect(amp?.content).toContain(`.${ampLayoutClass(section)}{background:#abcdef;padding:12px 30px}`);
expect(amp?.content).toContain(`.${ampLayoutClass(spacer)}{height:77px;line-height:77px;font-size:1px}`);
expect(amp?.content).toContain(
`.${ampLayoutClass(section)}{background:#abcdef;padding:12px 30px}`,
);
expect(amp?.content).toContain(
`.${ampLayoutClass(spacer)}{height:77px;line-height:77px;font-size:1px}`,
);
expect(amp?.content).toContain(`class="${ampLayoutClass(spacer)}"`);
expect(result.value.parts.html.content).toContain("height:77px");
expect(result.value.exports?.mjml).toContain('height="77px"');
expect(ampLayoutCss({ ...section, props: { background: "red;}body{display:none", padding: "</style>" } })).not.toContain("display:none");
expect(
ampLayoutCss({
...section,
props: { background: "red;}body{display:none", padding: "</style>" },
}),
).not.toContain("display:none");
});
const document: BlockDocument = {
@@ -78,33 +94,66 @@ const document: BlockDocument = {
describe("email renderer", () => {
test("optional AMP validation failures preserve HTML/text fallbacks", async () => {
for (const ampValidator of [async () => {throw new Error("network unavailable")}, () => new Promise<never>(() => {})]) {
const result=await renderEmail(document,{amp:true,ampValidator,ampValidationTimeoutMs:10});
for (const ampValidator of [
async () => {
throw new Error("network unavailable");
},
() => new Promise<never>(() => {}),
]) {
const result = await renderEmail(document, {
amp: true,
ampValidator,
ampValidationTimeoutMs: 10,
});
expect(result.ok).toBe(true);
if(!result.ok)continue;
if (!result.ok) continue;
expect(result.value.parts.amp).toBeUndefined();
expect(result.value.parts.html.content).toContain("Hello &lt;world&gt;");
expect(result.value.parts.text.content).toContain("Hello <world>");
expect(result.value.warnings.some(item=>item.code==="amp.validatorUnavailable"&&item.severity==="warning")).toBe(true);
expect(
result.value.warnings.some(
(item) => item.code === "amp.validatorUnavailable" && item.severity === "warning",
),
).toBe(true);
}
});
test("builder column rows export without nesting mj-column inside mj-column", async () => {
for (const count of [1,2,3,4]) {
const draft=structuredClone(document);
const content=draft.root.slots.content[0]!.slots.content;
draft.root.slots.content[0]!.slots.content=[{id:"columns",type:"layout.columns",version:1,props:{},styles:{},slots:{columns:Array.from({length:count},(_,index)=>({id:`column-${index}`,type:"layout.column",version:1,props:{width:`${100/count}%`},styles:{},slots:{content:index===0?content:[]}}))}}];
const result=await renderEmail(draft,{mjml:true,amp:true});
for (const count of [1, 2, 3, 4]) {
const draft = structuredClone(document);
const content = draft.root.slots.content[0]!.slots.content;
draft.root.slots.content[0]!.slots.content = [
{
id: "columns",
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: {
columns: Array.from({ length: count }, (_, index) => ({
id: `column-${index}`,
type: "layout.column",
version: 1,
props: { width: `${100 / count}%` },
styles: {},
slots: { content: index === 0 ? content : [] },
})),
},
},
];
const result = await renderEmail(draft, { mjml: true, amp: true });
expect(result.ok).toBe(true);
if(!result.ok)continue;
const mjml=result.value.exports!.mjml!;
if (!result.ok) continue;
const mjml = result.value.exports!.mjml!;
expect(mjml.match(/<mj-column\b/g)).toHaveLength(count);
expect(await validateMjml(mjml)).toEqual([]);
expect(mjml).toContain("Hello &lt;world&gt;");
const amp=result.value.parts.amp;
const amp = result.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
expect(amp?.content.match(/class="wrn-column"/g)).toHaveLength(count);
expect(amp?.content).toContain('class="wrn-columns"');
expect(amp?.content).toContain('@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}');
expect(amp?.content).toContain(
"@media only screen and (max-width:480px){.email-body .wrn-columns{display:block}.email-body .wrn-column{display:block;width:100%}}",
);
}
});
test("global brand logo survives HTML, AMP, and strict MJML export", async () => {
@@ -113,10 +162,14 @@ describe("email renderer", () => {
draft.root.props.logoAlt = 'Brand & "Company"';
draft.root.props.logoWidth = "180";
draft.root.props.logoHeight = "90";
const result = await renderEmail(draft,{amp:true,mjml:true});
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content,result.value.parts.amp?.content,result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain('src="https://example.com/logo.png"');
expect(output).toContain('alt="Brand &amp; &quot;Company&quot;"');
}
@@ -124,8 +177,12 @@ describe("email renderer", () => {
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect(result.value.parts.html.content).toContain('width="180" height="90"');
expect(result.value.parts.amp?.content).toContain('width="180" height="90"');
expect(result.value.parts.amp?.content).toContain('width="180" height="90" layout="responsive"');
expect(result.value.parts.amp?.content).toContain('.brand-logo{max-width:180px;width:100%;margin:20px auto}');
expect(result.value.parts.amp?.content).toContain(
'width="180" height="90" layout="responsive"',
);
expect(result.value.parts.amp?.content).toContain(
".brand-logo{max-width:180px;width:100%;margin:20px auto}",
);
expect(result.value.exports?.mjml).toContain('width="180px" height="90px"');
for (const value of ["0", "4001", "180px", "1;display:none"]) {
const invalid = structuredClone(draft);
@@ -133,7 +190,7 @@ describe("email renderer", () => {
expect((await renderEmail(invalid)).ok).toBe(false);
}
draft.root.props.logoUrl = "";
const empty = await renderEmail(draft,{amp:true,mjml:true});
const empty = await renderEmail(draft, { amp: true, mjml: true });
expect(empty.ok).toBe(true);
if (empty.ok) {
expect(empty.value.parts.amp?.content).not.toContain("<amp-img");
@@ -143,13 +200,21 @@ describe("email renderer", () => {
test("text line breaks survive all formats without interpreting entered markup", async () => {
const draft = structuredClone(document);
const text = 'First line\r\nSecond line\n\n<script>alert("x")</script>\rLast line';
draft.root.slots.content[0]!.slots.content = [{id:"text",type:"content.text",version:1,props:{text},styles:{},slots:{}}];
const rendered = await renderEmail(draft,{amp:true,mjml:true});
draft.root.slots.content[0]!.slots.content = [
{ id: "text", type: "content.text", version: 1, props: { text }, styles: {}, slots: {} },
];
const rendered = await renderEmail(draft, { amp: true, mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
for (const output of [rendered.value.parts.html.content,rendered.value.parts.amp?.content,rendered.value.exports?.mjml]) {
expect(output).toContain('First line<br />Second line<br /><br />&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;<br />Last line');
expect(output).not.toContain('<script>alert');
for (const output of [
rendered.value.parts.html.content,
rendered.value.parts.amp?.content,
rendered.value.exports?.mjml,
]) {
expect(output).toContain(
"First line<br />Second line<br /><br />&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;<br />Last line",
);
expect(output).not.toContain("<script>alert");
}
expect(rendered.value.parts.text.content).toContain(text);
expect(rendered.value.parts.amp?.validation.valid).toBe(true);
@@ -157,21 +222,44 @@ describe("email renderer", () => {
});
test("AMP inherits the saved brand font, colors and body width", async () => {
const draft = structuredClone(document);
Object.assign(draft.root.props, {width:"720",fontFamily:"Georgia, serif",textColor:"#112233",linkColor:"#445566",background:"#eeeeee",contentBackground:"#fafafa"});
const rendered = await renderEmail(draft, {amp:true});
Object.assign(draft.root.props, {
width: "720",
fontFamily: "Georgia, serif",
textColor: "#112233",
linkColor: "#445566",
background: "#eeeeee",
contentBackground: "#fafafa",
});
const rendered = await renderEmail(draft, { amp: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
const amp = rendered.value.parts.amp;
expect(amp?.validation.valid).toBe(true);
for (const style of ["font-family:Georgia, serif", "color:#112233", "a{color:#445566}", "background:#eeeeee", "background:#fafafa", "max-width:720px"]) expect(amp?.content).toContain(style);
for (const style of [
"font-family:Georgia, serif",
"color:#112233",
"a{color:#445566}",
"background:#eeeeee",
"background:#fafafa",
"max-width:720px",
])
expect(amp?.content).toContain(style);
});
test("brand fields reject arbitrary CSS and invalid widths before rendering", async () => {
for (const [key,value] of [["fontFamily","Arial;position:fixed"],["fontFamily","</style><script>alert(1)</script>"],["textColor","red;background:url(https://example.com)"],["background","#fff;display:none"],["width","600;position:absolute"],["width","9999"]]) {
for (const [key, value] of [
["fontFamily", "Arial;position:fixed"],
["fontFamily", "</style><script>alert(1)</script>"],
["textColor", "red;background:url(https://example.com)"],
["background", "#fff;display:none"],
["width", "600;position:absolute"],
["width", "9999"],
]) {
const draft = structuredClone(document);
draft.root.props[key!] = value!;
const rendered = await renderEmail(draft, {amp:true});
const rendered = await renderEmail(draft, { amp: true });
expect(rendered.ok).toBe(false);
if (!rendered.ok) expect(rendered.errors.some(error => error.code === "email.brand")).toBe(true);
if (!rendered.ok)
expect(rendered.errors.some((error) => error.code === "email.brand")).toBe(true);
}
});
test("responsive stacking begins below the desktop email width", async () => {
@@ -184,9 +272,22 @@ describe("email renderer", () => {
});
test("countdown URLs are derived for HTML AMP and MJML without mutating the document", async () => {
const draft = structuredClone(document);
draft.root.slots.content[0]!.slots.content = [{id:"timer",type:"content.countdown",version:1,props:{label:"Offer ends",deadline:"2026-10-01T00:00:00Z",fallback:"Offer ended"},styles:{},slots:{}}];
draft.root.slots.content[0]!.slots.content = [
{
id: "timer",
type: "content.countdown",
version: 1,
props: { label: "Offer ends", deadline: "2026-10-01T00:00:00Z", fallback: "Offer ended" },
styles: {},
slots: {},
},
];
const before = JSON.stringify(draft);
const result = await renderEmail(draft, {amp:true,mjml:true,countdownImageUrl:"https://email.example.com/api/countdown"});
const result = await renderEmail(draft, {
amp: true,
mjml: true,
countdownImageUrl: "https://email.example.com/api/countdown",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const image = "https://email.example.com/api/countdown?deadline=1790812800000";
@@ -194,7 +295,7 @@ describe("email renderer", () => {
expect(result.value.parts.amp?.content).toContain(image);
expect(result.value.exports?.mjml).toContain(image);
expect(JSON.stringify(draft)).toBe(before);
expect((await renderEmail(draft, {countdownImageUrl:"javascript:alert(1)"})).ok).toBe(false);
expect((await renderEmail(draft, { countdownImageUrl: "javascript:alert(1)" })).ok).toBe(false);
});
test("content inherits the selected brand font instead of overriding it", async () => {
const branded = structuredClone(document);
@@ -214,9 +315,13 @@ describe("email renderer", () => {
const tree = parse(rendered.value.parts.html.content);
const ancestry = new Map<string, string[]>();
const walk = (node: DefaultTreeAdapterMap["node"], parents: string[]) => {
const id = "attrs" in node ? node.attrs.find(attr => attr.name === "data-block-id")?.value : undefined;
const id =
"attrs" in node
? node.attrs.find((attr) => attr.name === "data-block-id")?.value
: undefined;
if (id) ancestry.set(id, parents);
if ("childNodes" in node) for (const child of node.childNodes) walk(child, id ? [...parents, id] : parents);
if ("childNodes" in node)
for (const child of node.childNodes) walk(child, id ? [...parents, id] : parents);
};
walk(tree, []);
expect(ancestry.get("heading")).toEqual(["root", "section"]);
@@ -3,10 +3,37 @@ import { renderEmail } from "../src/index.ts";
test("explicit heading sizes are not multiplied by browser heading defaults", async () => {
for (const size of [undefined, "36px", "expression(1)"]) {
const result = await renderEmail({schemaVersion:1,kind:"email",meta:{subject:"Typography",lang:"en"},theme:{tokens:{}},root:{id:"root",type:"layout.email-document",version:1,props:{width:"600"},styles:{},slots:{content:[{id:"heading",type:"content.heading",version:1,props:{text:"Design that works",level:"1"},styles:size?{fontSize:{base:size}}:{},slots:{}}]}}}, {amp:false,mjml:false});
const result = await renderEmail(
{
schemaVersion: 1,
kind: "email",
meta: { subject: "Typography", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "heading",
type: "content.heading",
version: 1,
props: { text: "Design that works", level: "1" },
styles: size ? { fontSize: { base: size } } : {},
slots: {},
},
],
},
},
},
{ amp: false, mjml: false },
);
expect(result.ok).toBe(true);
if (!result.ok) continue;
const html=result.value.parts.html.content;
const html = result.value.parts.html.content;
expect(html.includes("font-size:inherit;line-height:1.2;")).toBe(size === "36px");
expect(html).not.toContain("expression(");
}
@@ -2,7 +2,37 @@ import { expect, test } from "bun:test";
import type { BlockDocument, BlockNode } from "@wrnexus/blocks";
import { renderEmail, importMjml } from "../src/index.ts";
const documentFor = (decorative: boolean): BlockDocument => ({ schemaVersion: 1, kind: "email", meta: { subject: "Images" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600" }, styles: {}, slots: { content: [{ id: "image", type: "content.image", version: 1, props: { src: "https://example.com/image.png", alt: "Accessible & descriptive", width: "320", height: "180", decorative }, styles: {}, slots: {} }] } } });
const documentFor = (decorative: boolean): BlockDocument => ({
schemaVersion: 1,
kind: "email",
meta: { subject: "Images" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: {
content: [
{
id: "image",
type: "content.image",
version: 1,
props: {
src: "https://example.com/image.png",
alt: "Accessible & descriptive",
width: "320",
height: "180",
decorative,
},
styles: {},
slots: {},
},
],
},
},
});
test("decorative image descriptions stay omitted across HTML text and MJML", async () => {
const rendered = await renderEmail(documentFor(true), { mjml: true });
@@ -23,7 +53,8 @@ test("meaningful image alt and explicit dimensions survive MJML round trip", asy
let id = 0;
const imported = importMjml(rendered.value.exports!.mjml!, { id: () => `n${++id}` });
if (!imported.ok) throw new Error("Import failed");
const find = (node: BlockNode): BlockNode | undefined => node.type === "content.image" ? node : Object.values(node.slots).flat().map(find).find(Boolean);
const find = (node: BlockNode): BlockNode | undefined =>
node.type === "content.image" ? node : Object.values(node.slots).flat().map(find).find(Boolean);
expect(find(imported.value.root)!.props.width).toBe("320");
expect(find(imported.value.root)!.props.height).toBe("180");
expect(find(imported.value.root)!.props.alt).toBe("Accessible & descriptive");
@@ -115,12 +115,23 @@ test("marketing image dimensions reject invalid or injected values", async () =>
});
test("video exports preserve thumbnail proportions, safe destination and accessible text", async () => {
const draft = document("content.video", { title: "Watch & learn", href: "https://example.com/watch?a=1&b=2", thumbnail: "https://example.com/poster.png", alt: 'Demo & "preview"', width: "360", height: "240" });
const draft = document("content.video", {
title: "Watch & learn",
href: "https://example.com/watch?a=1&b=2",
thumbnail: "https://example.com/poster.png",
alt: 'Demo & "preview"',
width: "360",
height: "240",
});
const before = JSON.stringify(draft);
const result = await renderEmail(draft, { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content, result.value.parts.amp?.content, result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain('href="https://example.com/watch?a=1&amp;b=2"');
expect(output).toContain('src="https://example.com/poster.png"');
expect(output).toContain('alt="Demo &amp; &quot;preview&quot;"');
@@ -128,29 +139,46 @@ test("video exports preserve thumbnail proportions, safe destination and accessi
expect(result.value.parts.html.content).toContain('width="360" height="240"');
expect(result.value.parts.amp?.content).toContain('width="360" height="240" layout="responsive"');
expect(result.value.exports?.mjml).toContain('width="360px" height="240px"');
expect(result.value.parts.text.content).toContain("Watch & learn: https://example.com/watch?a=1&b=2");
expect(result.value.parts.text.content).toContain(
"Watch & learn: https://example.com/watch?a=1&b=2",
);
expect(result.value.parts.amp?.validation.valid).toBe(true);
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect(JSON.stringify(draft)).toBe(before);
});
test("social exports include only configured networks and retain safe links in plain text", async () => {
const props = { label: "Follow & connect", facebook: "https://example.com/facebook?a=1&b=2", linkedin: "https://example.com/linkedin", instagram: "", x: "" };
const props = {
label: "Follow & connect",
facebook: "https://example.com/facebook?a=1&b=2",
linkedin: "https://example.com/linkedin",
instagram: "",
x: "",
};
const result = await renderEmail(document("content.social", props), { amp: true, mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
for (const output of [result.value.parts.html.content, result.value.parts.amp?.content, result.value.exports?.mjml]) {
for (const output of [
result.value.parts.html.content,
result.value.parts.amp?.content,
result.value.exports?.mjml,
]) {
expect(output).toContain("Follow &amp; connect");
expect(output).toContain('href="https://example.com/facebook?a=1&amp;b=2"');
expect(output).toContain('href="https://example.com/linkedin"');
expect(output).not.toContain(">Instagram</a>");
expect(output).not.toContain(">X</a>");
}
expect(result.value.parts.text.content).toContain("Facebook: https://example.com/facebook?a=1&b=2");
expect(result.value.parts.text.content).toContain(
"Facebook: https://example.com/facebook?a=1&b=2",
);
expect(result.value.parts.text.content).toContain("LinkedIn: https://example.com/linkedin");
expect(result.value.parts.amp?.validation.valid).toBe(true);
expect(await validateMjml(result.value.exports!.mjml!)).toEqual([]);
expect((await renderEmail(document("content.social", { ...props, facebook: "javascript:alert(1)" }))).ok).toBe(false);
expect(
(await renderEmail(document("content.social", { ...props, facebook: "javascript:alert(1)" })))
.ok,
).toBe(false);
});
test("basic images, video thumbnails and spacers validate dimensions before rendering", async () => {
@@ -7,18 +7,50 @@ const compile = createRequire(import.meta.url)("mjml");
test("MJML preserves document metadata and global typography in compiled HTML", async () => {
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: 'Brand & "News" <today>', preheader: 'Preview <safe> & useful', lang: "en" }, theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600", fontFamily: "Georgia, serif", textColor: "#123456", linkColor: "#a12345" }, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Brand text" }, styles: {}, slots: {} }, { id: "button", type: "content.button", version: 1, props: { label: "Brand action", href: "https://example.com" }, styles: {}, slots: {} }],
} },
schemaVersion: 1,
kind: "email",
meta: { subject: 'Brand & "News" <today>', preheader: "Preview <safe> & useful", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {
width: "600",
fontFamily: "Georgia, serif",
textColor: "#123456",
linkColor: "#a12345",
},
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Brand text" },
styles: {},
slots: {},
},
{
id: "button",
type: "content.button",
version: 1,
props: { label: "Brand action", href: "https://example.com" },
styles: {},
slots: {},
},
],
},
},
};
const before = structuredClone(document);
const result = await renderEmail(document, { mjml: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
const source = result.value.exports!.mjml!;
expect(source).toContain('<mj-title>Brand &amp; &quot;News&quot; &lt;today&gt;</mj-title>');
expect(source).toContain('<mj-preview>Preview &lt;safe&gt; &amp; useful</mj-preview>');
expect(source).toContain("<mj-title>Brand &amp; &quot;News&quot; &lt;today&gt;</mj-title>");
expect(source).toContain("<mj-preview>Preview &lt;safe&gt; &amp; useful</mj-preview>");
expect(source).toContain('<mj-all font-family="Georgia, serif" />');
const compiled = await compile(source, { validationLevel: "strict", minify: false });
expect(compiled.errors).toEqual([]);
@@ -46,10 +78,15 @@ test("MJML header import rejects unsupported globals and unsafe typography", ()
'<mj-attributes><mj-all padding="20px" /></mj-attributes>',
'<mj-attributes><mj-all font-family="Arial;position:fixed" /></mj-attributes>',
'<mj-attributes><mj-text font-size="20px" /></mj-attributes>',
'<mj-style>.test{color:red}</mj-style>',
"<mj-style>.test{color:red}</mj-style>",
'<mj-breakpoint width="900px" />',
]) {
let id = 0;
expect(importMjml(`<mjml><mj-head>${header}</mj-head><mj-body><mj-section><mj-column><mj-text>Text</mj-text></mj-column></mj-section></mj-body></mjml>`, { id: () => `n${++id}` }).ok).toBe(false);
expect(
importMjml(
`<mjml><mj-head>${header}</mj-head><mj-body><mj-section><mj-column><mj-text>Text</mj-text></mj-column></mj-section></mj-body></mjml>`,
{ id: () => `n${++id}` },
).ok,
).toBe(false);
}
});
@@ -2,21 +2,39 @@ import { expect, test } from "bun:test";
import type { BlockNode } from "@wrnexus/blocks";
import { importMjml, renderEmail } from "../src/index.ts";
const source = (attributes: string) => `<mjml><mj-body><mj-section><mj-column><mj-button href="https://example.com/?a=1&amp;b=2" ${attributes}>Buy &amp; save &#33;</mj-button></mj-column></mj-section></mj-body></mjml>`;
const findButton = (node: BlockNode): BlockNode | undefined => node.type === "content.button" ? node : Object.values(node.slots).flat().map(findButton).find(Boolean);
const source = (attributes: string) =>
`<mjml><mj-body><mj-section><mj-column><mj-button href="https://example.com/?a=1&amp;b=2" ${attributes}>Buy &amp; save &#33;</mj-button></mj-column></mj-section></mj-body></mjml>`;
const findButton = (node: BlockNode): BlockNode | undefined =>
node.type === "content.button"
? node
: Object.values(node.slots).flat().map(findButton).find(Boolean);
test("imported button preserves supported appearance and escaped label/link across export", async () => {
let id = 0;
const imported = importMjml(source('align="right" background-color="#123456" color="#abcdef" font-size="22px" font-weight="400" border-radius="12px"'), { id: () => `n${++id}` });
const imported = importMjml(
source(
'align="right" background-color="#123456" color="#abcdef" font-size="22px" font-weight="400" border-radius="12px"',
),
{ id: () => `n${++id}` },
);
expect(imported.ok).toBe(true);
if (!imported.ok) return;
const button = findButton(imported.value.root)!;
expect(button.props).toEqual({ label: "Buy & save !", href: "https://example.com/?a=1&b=2" });
expect(button.styles).toEqual({ textAlign: { base: "right" }, backgroundColor: { base: "#123456" }, color: { base: "#abcdef" }, fontSize: { base: "22px" }, fontWeight: { base: "400" }, borderRadius: { base: "12px" } });
expect(button.styles).toEqual({
textAlign: { base: "right" },
backgroundColor: { base: "#123456" },
color: { base: "#abcdef" },
fontSize: { base: "22px" },
fontWeight: { base: "400" },
borderRadius: { base: "12px" },
});
const rendered = await renderEmail(imported.value, { mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.parts.html.content).toContain("font-size:22px;font-weight:400;border-radius:12px");
expect(rendered.value.parts.html.content).toContain(
"font-size:22px;font-weight:400;border-radius:12px",
);
expect(rendered.value.parts.text.content).toContain("Buy & save !");
const again = importMjml(rendered.value.exports!.mjml!, { id: () => `n${++id}` });
expect(again.ok).toBe(true);
@@ -28,10 +46,17 @@ test("imported button preserves supported appearance and escaped label/link acro
});
test("unsupported or unsafe button attributes produce explicit diagnostics", () => {
for (const attributes of ['color="red;position:fixed"', 'align="justify"', 'font-size="expression(1)"', 'onclick="alert(1)"', 'padding="20px"']) {
for (const attributes of [
'color="red;position:fixed"',
'align="justify"',
'font-size="expression(1)"',
'onclick="alert(1)"',
'padding="20px"',
]) {
let id = 0;
const result = importMjml(source(attributes), { id: () => `n${++id}` });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.errors.some(error => error.code === "mjml.button-attribute")).toBe(true);
if (!result.ok)
expect(result.errors.some((error) => error.code === "mjml.button-attribute")).toBe(true);
}
});
@@ -3,18 +3,40 @@ import { importMjml, renderEmail } from "../src/index.ts";
const parse = (columns: string) => {
let id = 0;
return importMjml(`<mjml><mj-body><mj-section>${columns}</mj-section></mj-body></mjml>`, { subject: "Imported", id: () => `n${++id}` });
return importMjml(`<mjml><mj-body><mj-section>${columns}</mj-section></mj-body></mjml>`, {
subject: "Imported",
id: () => `n${++id}`,
});
};
test("imported columns form one native row with preserved order and exact width totals", async () => {
for (const widths of [["", ""], ["33%", ""], ["", "", ""], ["25%", "75%"]]) {
const result = parse(widths.map((width, index) => `<mj-column${width ? ` width="${width}"` : ""}><mj-text>Column ${index}</mj-text></mj-column>`).join(""));
for (const widths of [
["", ""],
["33%", ""],
["", "", ""],
["25%", "75%"],
]) {
const result = parse(
widths
.map(
(width, index) =>
`<mj-column${width ? ` width="${width}"` : ""}><mj-text>Column ${index}</mj-text></mj-column>`,
)
.join(""),
);
expect(result.ok).toBe(true);
if (!result.ok) continue;
const row = result.value.root.slots.content[0]!.slots.content[0]!;
expect(row.type).toBe("layout.columns");
expect(row.slots.columns.map(column => column.slots.content[0]!.props.text)).toEqual(widths.map((_, index) => `Column ${index}`));
expect(row.slots.columns.reduce((sum, column) => sum + Number.parseFloat(String(column.props.width)), 0)).toBeCloseTo(100, 8);
expect(row.slots.columns.map((column) => column.slots.content[0]!.props.text)).toEqual(
widths.map((_, index) => `Column ${index}`),
);
expect(
row.slots.columns.reduce(
(sum, column) => sum + Number.parseFloat(String(column.props.width)),
0,
),
).toBeCloseTo(100, 8);
const rendered = await renderEmail(result.value, { mjml: true });
expect(rendered.ok).toBe(true);
if (rendered.ok) expect(rendered.value.exports?.mjml).toContain("<mj-column");
@@ -27,12 +49,23 @@ test("import rejects invalid URLs, dimensions, widths, and native slot limits",
'<mj-column><mj-image src="https://example.com/x.png" width="99999px" /></mj-column>',
'<mj-column width="75%"></mj-column><mj-column width="75%"></mj-column>',
'<mj-column width="400px"></mj-column>',
Array(5).fill('<mj-column><mj-text>X</mj-text></mj-column>').join(""),
]) expect(parse(input).ok).toBe(false);
Array(5).fill("<mj-column><mj-text>X</mj-text></mj-column>").join(""),
])
expect(parse(input).ok).toBe(false);
});
test("import enforces depth limits and rejects repeated instance IDs", () => {
const nested = '<mjml><mj-body>' + '<mj-wrapper>'.repeat(100) + '<mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section>' + '</mj-wrapper>'.repeat(100) + '</mj-body></mjml>';
const nested =
"<mjml><mj-body>" +
"<mj-wrapper>".repeat(100) +
"<mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section>" +
"</mj-wrapper>".repeat(100) +
"</mj-body></mjml>";
expect(importMjml(nested, { subject: "Depth", id: () => "id" }).ok).toBe(false);
expect(importMjml('<mjml><mj-body><mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section></mj-body></mjml>', { subject: "IDs", id: () => "same" }).ok).toBe(false);
expect(
importMjml(
"<mjml><mj-body><mj-section><mj-column><mj-text>X</mj-text></mj-column></mj-section></mj-body></mjml>",
{ subject: "IDs", id: () => "same" },
).ok,
).toBe(false);
});
@@ -7,9 +7,28 @@ test("every designed preset renders natively without remote placeholder assets",
for (const preset of emailPresets) {
let id = 0;
const section = createSectionPreset(preset.id, () => `preset-${++id}`);
const document: BlockDocument = {schemaVersion:1,kind:"email",meta:{subject:"Preset QA"},theme:{tokens:{}},root:{id:"root",type:"layout.email-document",version:1,props:{width:"600"},styles:{},slots:{content:[section]}}};
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Preset QA" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600" },
styles: {},
slots: { content: [section] },
},
};
const before = JSON.stringify(document);
const result = await renderEmailPreview(document, {variables:{recipientName:"Alex",organizationAddress:"Company address",unsubscribeUrl:"https://example.com/unsubscribe"}});
const result = await renderEmailPreview(document, {
variables: {
recipientName: "Alex",
organizationAddress: "Company address",
unsubscribeUrl: "https://example.com/unsubscribe",
},
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.html).not.toContain("placehold.co");
+15 -5
View File
@@ -2,9 +2,19 @@ import { expect, test } from "bun:test";
import { renderRichText, richTextSchema } from "../src/rich-text.ts";
test("semantic text is escaped, bounded, and rejects arbitrary markup properties", () => {
expect(renderRichText({text:"<hello>\nworld",richText:[{text:"<hello>",bold:true},{text:"\nworld",italic:true,underline:true}]})).toBe("<strong>&lt;hello&gt;</strong><em><u><br />world</u></em>");
expect(richTextSchema.parse([{text:"hello",html:"<script>"}]).ok).toBe(false);
expect(richTextSchema.parse([{text:"hello",bold:"yes"}]).ok).toBe(false);
expect(richTextSchema.parse([{text:"a".repeat(200001)}]).ok).toBe(false);
expect(renderRichText({text:"Changed",richText:[{text:"Old",bold:true}]})).toBe("Changed");
expect(
renderRichText({
text: "<hello>\nworld",
richText: [
{ text: "<hello>", bold: true },
{ text: "\nworld", italic: true, underline: true },
],
}),
).toBe("<strong>&lt;hello&gt;</strong><em><u><br />world</u></em>");
expect(richTextSchema.parse([{ text: "hello", html: "<script>" }]).ok).toBe(false);
expect(richTextSchema.parse([{ text: "hello", bold: "yes" }]).ok).toBe(false);
expect(richTextSchema.parse([{ text: "a".repeat(200001) }]).ok).toBe(false);
expect(renderRichText({ text: "Changed", richText: [{ text: "Old", bold: true }] })).toBe(
"Changed",
);
});
+91 -5
View File
@@ -2,22 +2,108 @@ import { expect, test } from "bun:test";
import type { BlockDocument, BlockNode } from "@wrnexus/blocks";
import { renderEmail, validateMjml } from "../src/index.ts";
const text = (id: string): BlockNode => ({ id, type: "content.text", version: 1, props: { text: id }, styles: {}, slots: {} });
const columns = (id: string): BlockNode => ({ id, type: "layout.columns", version: 1, props: {}, styles: {}, slots: { columns: [0, 1].map(index => ({ id: `${id}-${index}`, type: "layout.column", version: 1, props: { width: "50%" }, styles: {}, slots: { content: [text(`${id}-text-${index}`)] } })) } });
const text = (id: string): BlockNode => ({
id,
type: "content.text",
version: 1,
props: { text: id },
styles: {},
slots: {},
});
const columns = (id: string): BlockNode => ({
id,
type: "layout.columns",
version: 1,
props: {},
styles: {},
slots: {
columns: [0, 1].map((index) => ({
id: `${id}-${index}`,
type: "layout.column",
version: 1,
props: { width: "50%" },
styles: {},
slots: { content: [text(`${id}-text-${index}`)] },
})),
},
});
test("invalid nested MJML is diagnosed and omitted while HTML and text remain usable", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Nested", lang: "en" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: { content: [{ id: "outer", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: [{ id: "inner", type: "layout.section", version: 1, props: {}, styles: {}, slots: { content: [text("Retained nested content")] } }] } }] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Nested", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "outer",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "inner",
type: "layout.section",
version: 1,
props: {},
styles: {},
slots: { content: [text("Retained nested content")] },
},
],
},
},
],
},
},
};
const rendered = await renderEmail(document, { mjml: true });
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.exports?.mjml).toBeUndefined();
expect(rendered.value.warnings.some(warning => warning.code === "mjml.validation")).toBe(true);
expect(rendered.value.warnings.some((warning) => warning.code === "mjml.validation")).toBe(true);
expect(rendered.value.parts.html.content).toContain("Retained nested content");
expect(rendered.value.parts.text.content).toContain("Retained nested content");
});
test("root content and separate column rows produce valid ordered MJML without changing the document", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Root blocks", lang: "en" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: { content: [text("intro"), columns("first"), columns("second"), { id: "cta", type: "content.button", version: 1, props: { label: "Act", href: "https://example.com" }, styles: {}, slots: {} }, text("end")] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Root blocks", lang: "en" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
text("intro"),
columns("first"),
columns("second"),
{
id: "cta",
type: "content.button",
version: 1,
props: { label: "Act", href: "https://example.com" },
styles: {},
slots: {},
},
text("end"),
],
},
},
};
const before = structuredClone(document);
const rendered = await renderEmail(document, { mjml: true });
expect(rendered.ok).toBe(true);
@@ -2,20 +2,51 @@ import { expect, test } from "bun:test";
import { emailStyleValue, validateEmailStyleValue } from "../src/style-values.ts";
test("base style syntax rejects ignored or injected values and accepts supported units", () => {
for (const [key, value] of [["padding","12"],["padding","1px 2px 3px 4px 5px"],["color","#12345"],["fontWeight","heavy"],["fontSize","12px;color:red"],["position","fixed"],["constructor","x"]]) {
for (const [key, value] of [
["padding", "12"],
["padding", "1px 2px 3px 4px 5px"],
["color", "#12345"],
["fontWeight", "heavy"],
["fontSize", "12px;color:red"],
["position", "fixed"],
["constructor", "x"],
]) {
expect(emailStyleValue(key!, value)).toBe("");
expect(() => validateEmailStyleValue(key!, value!)).toThrow();
}
for (const [key, value] of [["padding","0 12px"],["margin","1rem 2%"],["color","#1234"],["fontWeight","700"],["fontSize","16px"],["borderRadius","0"],["textAlign","end"]]) {
for (const [key, value] of [
["padding", "0 12px"],
["margin", "1rem 2%"],
["color", "#1234"],
["fontWeight", "700"],
["fontSize", "16px"],
["borderRadius", "0"],
["textAlign", "end"],
]) {
expect(emailStyleValue(key!, value)).toBe(value!);
expect(() => validateEmailStyleValue(key!, value!)).not.toThrow();
}
});
test("RGB functions require correct channel counts, units and bounded components", () => {
for (const value of ["rgb(1)", "rgb(1,2,3,4)", "rgba(1,2,3)", "rgb(256,0,0)", "rgb(100%,0,0)", "rgba(1,2,3,1.1)", "rgb(1..2,2,3)", "rgba(0,0,0,101%)"])
for (const value of [
"rgb(1)",
"rgb(1,2,3,4)",
"rgba(1,2,3)",
"rgb(256,0,0)",
"rgb(100%,0,0)",
"rgba(1,2,3,1.1)",
"rgb(1..2,2,3)",
"rgba(0,0,0,101%)",
])
expect(emailStyleValue("color", value)).toBe("");
for (const value of ["rgb(255, 0, 12)", "rgb(100%, 0%, 50%)", "rgba(0,0,0,.5)", "rgba(0,0,0,50%)", "transparent"])
for (const value of [
"rgb(255, 0, 12)",
"rgb(100%, 0%, 50%)",
"rgba(0,0,0,.5)",
"rgba(0,0,0,50%)",
"transparent",
])
expect(emailStyleValue("backgroundColor", value)).toBe(value);
expect(emailStyleValue("padding", "0 4000px")).toBe("0 4000px");
expect(emailStyleValue("padding", "0 4001px")).toBe("");
@@ -5,10 +5,40 @@ import { renderEmail } from "../src/index.ts";
const compile = createRequire(import.meta.url)("mjml");
test("survey MJML button inherits brand color and preserves safe text fallback", async () => {
const document: BlockDocument = { schemaVersion: 1, kind: "email", meta: { subject: "Survey" }, theme: { tokens: {} }, root: { id: "root", type: "layout.email-document", version: 1, props: { width: "600", linkColor: "#a12345" }, styles: {}, slots: { content: [{ id: "survey", type: "content.survey", version: 1, props: { question: "How was your visit?", buttonLabel: "Answer & share", href: "https://example.com/survey" }, styles: {}, slots: {} }] } } };
const document: BlockDocument = {
schemaVersion: 1,
kind: "email",
meta: { subject: "Survey" },
theme: { tokens: {} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: { width: "600", linkColor: "#a12345" },
styles: {},
slots: {
content: [
{
id: "survey",
type: "content.survey",
version: 1,
props: {
question: "How was your visit?",
buttonLabel: "Answer & share",
href: "https://example.com/survey",
},
styles: {},
slots: {},
},
],
},
},
};
const result = await renderEmail(document, { mjml: true });
if (!result.ok) throw new Error("Render failed");
expect(result.value.parts.text.content).toContain("How was your visit?\nAnswer & share: https://example.com/survey");
expect(result.value.parts.text.content).toContain(
"How was your visit?\nAnswer & share: https://example.com/survey",
);
const compiled = await compile(result.value.exports!.mjml!, { validationLevel: "strict" });
expect(compiled.errors).toEqual([]);
expect(compiled.html).toContain("background:#a12345");
@@ -3,16 +3,38 @@ import { resolveDocumentVariables, type BlockDocument } from "@wrnexus/blocks";
import { renderEmail } from "../src/index.ts";
const document: BlockDocument = {
schemaVersion: 1, kind: "email", meta: { subject: "Hi {{recipientName|friend}}", lang: "en" },
schemaVersion: 1,
kind: "email",
meta: { subject: "Hi {{recipientName|friend}}", lang: "en" },
theme: { tokens: {} },
root: { id: "root", type: "layout.email-document", version: 1, props: {}, styles: {}, slots: {
content: [{ id: "text", type: "content.text", version: 1, props: { text: "Hello {{recipientName|friend}}" }, styles: {}, slots: {} }],
} },
root: {
id: "root",
type: "layout.email-document",
version: 1,
props: {},
styles: {},
slots: {
content: [
{
id: "text",
type: "content.text",
version: 1,
props: { text: "Hello {{recipientName|friend}}" },
styles: {},
slots: {},
},
],
},
},
};
test("template rendering preserves fallback tokens rather than baking in sample or fallback values", async () => {
const before = structuredClone(document);
const rendered = await renderEmail(document, { preserveVariables: true, mjml: true, variables: { recipientName: "Preview only" } });
const rendered = await renderEmail(document, {
preserveVariables: true,
mjml: true,
variables: { recipientName: "Preview only" },
});
expect(rendered.ok).toBe(true);
if (!rendered.ok) return;
expect(rendered.value.subject).toBe("Hi {{recipientName|friend}}");
@@ -20,13 +42,25 @@ test("template rendering preserves fallback tokens rather than baking in sample
expect(rendered.value.parts.text.content).toContain("Hello {{recipientName|friend}}");
expect(rendered.value.exports?.mjml).toContain("Hello {{recipientName|friend}}");
expect(document).toEqual(before);
const resolved = await renderEmail(document, { variables: { recipientName: "Ada" }, requireVariables: true });
const resolved = await renderEmail(document, {
variables: { recipientName: "Ada" },
requireVariables: true,
});
expect(resolved.ok && resolved.value.subject).toBe("Hi Ada");
});
test("preservation still validates token allowlists and cannot masquerade as resolved delivery", () => {
const unknown = structuredClone(document);
unknown.meta.subject = "{{unregistered}}";
expect(resolveDocumentVariables(unknown, { recipientName: "string" }, {}, { preserveTokens: true }).ok).toBe(false);
expect(resolveDocumentVariables(document, { recipientName: "string" }, {}, { preserveTokens: true, requireValues: true }).ok).toBe(false);
expect(
resolveDocumentVariables(unknown, { recipientName: "string" }, {}, { preserveTokens: true }).ok,
).toBe(false);
expect(
resolveDocumentVariables(
document,
{ recipientName: "string" },
{},
{ preserveTokens: true, requireValues: true },
).ok,
).toBe(false);
});