@samva/markup 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +42 -35
  2. package/CHANGELOG.md +92 -0
  3. package/README.md +10 -9
  4. package/dist/{assets-tISHaQNF.d.ts → assets-CS5Xa_mr.d.ts} +3 -3
  5. package/dist/{brand-nreeKWxF.js → brand-CIiEqkU7.js} +24 -31
  6. package/dist/{brand-plugin-CHhcei-j.d.ts → brand-plugin-Dj9SMpfS.d.ts} +3 -1
  7. package/dist/brand.d.ts +2 -2
  8. package/dist/brand.js +3 -3
  9. package/dist/compatibility.d.ts +76 -0
  10. package/dist/compatibility.js +807 -0
  11. package/dist/compiled-template-Bc4Dq9zy.d.ts +268 -0
  12. package/dist/compiler.d.ts +58 -225
  13. package/dist/compiler.js +261 -1297
  14. package/dist/{components-3XHjYD3i.js → components-C5850-Qg.js} +37 -29
  15. package/dist/css-B_aVKrDo.js +436 -0
  16. package/dist/css-color-DLM12Osu.js +315 -0
  17. package/dist/{diagnostic-codes-UXwOO3A-.js → diagnostic-codes-DZKb0Xcg.js} +4 -0
  18. package/dist/{diagnostics-CUYlQ_6x.d.ts → diagnostics-D4vSLQrO.d.ts} +1 -10
  19. package/dist/diagnostics.d.ts +6 -2
  20. package/dist/diagnostics.js +3 -3
  21. package/dist/edit.d.ts +10 -9
  22. package/dist/edit.js +12 -11
  23. package/dist/email/jsx-dev-runtime.d.ts +1 -1
  24. package/dist/email/jsx-dev-runtime.js +1 -1
  25. package/dist/email/jsx-runtime.d.ts +2 -2
  26. package/dist/email/jsx-runtime.js +2 -2
  27. package/dist/email.d.ts +1 -1
  28. package/dist/email.js +1 -1
  29. package/dist/html-DJUK2YJF.js +483 -0
  30. package/dist/index.d.ts +1 -1
  31. package/dist/{jsx-runtime-DC7xG0aA.d.ts → jsx-runtime-DL8NVF1f.d.ts} +12 -6
  32. package/dist/{jsx-runtime-CBlexoeR.js → jsx-runtime-qL19u3Fy.js} +17 -10
  33. package/dist/preview-rNoJBEIY.d.ts +104 -0
  34. package/dist/{profile-AatO_SvP.js → profile-JTvgCD6X.js} +614 -24
  35. package/dist/{html-BvRFepeO.js → render-template-DwPDm3Hq.js} +155 -572
  36. package/dist/render.d.ts +40 -28
  37. package/dist/render.js +3 -47
  38. package/dist/selectors-CYWCoxZr.js +157 -0
  39. package/dist/sms.d.ts +1 -1
  40. package/dist/sms.js +1 -1
  41. package/dist/{template-B-UDXK8a.d.ts → template-DmNcoH4Q.d.ts} +2 -9
  42. package/dist/{theme-css-s9QwD5Ko.js → theme-css-P9F5S7Ic.js} +3 -316
  43. package/dist/whatsapp.d.ts +1 -1
  44. package/dist/whatsapp.js +1 -1
  45. package/generated/contract.json +7 -2
  46. package/generated/reference.md +3 -2
  47. package/package.json +5 -1
  48. package/skills/sml/SKILL.md +2 -2
  49. package/dist/ir-DNL6H7jA.js +0 -705
  50. package/dist/render-BdvewoQt.d.ts +0 -564
  51. package/dist/render-DpYouYYG.js +0 -258
package/dist/compiler.js CHANGED
@@ -1,1212 +1,19 @@
1
1
  import { n as isObject } from "./guards-eV1qLbf2.js";
2
2
  import { n as TEMPLATE_NAME_PATTERN } from "./template-zLUjcwfF.js";
3
- import { D as samvaBrandPlugin, T as parseBrandSpecifier, _ as renderIr, w as brandSpecifierPattern } from "./html-BvRFepeO.js";
4
- import { m as PRIMITIVE_CSS } from "./components-3XHjYD3i.js";
5
- import { c as foregroundDefaults, d as downlevelColors, f as formatColor, l as parseBrandCss, n as DEFAULT_THEME_CSS, p as parseColor, u as printBrandCss } from "./theme-css-s9QwD5Ko.js";
6
- import { n as isDarkSchemeCondition, r as isDarkSchemeQuery, t as DARK_SCHEME_MEDIA } from "./dark-scheme-CbCwGDWH.js";
7
- import { a as downlevelMediaQuery, c as renderHeadCss, d as matchesSelector, f as unquote, i as renderDarkRules, l as resolveVariables, o as finalizeValue, r as applyStylesheet, s as foldCalc, u as classListOf } from "./ir-DNL6H7jA.js";
8
- import { i as buildLineMap, s as lineColumn } from "./diagnostic-codes-UXwOO3A-.js";
9
- import { a as lowerProject, d as resolveFromDirectory, f as resolveThemeImports, i as completed, l as Findings, n as introducedProfileErrors, r as loadProject, t as checkStaticProfile, u as projectDirectory } from "./profile-AatO_SvP.js";
10
- import { c as checkAssetBase, i as withoutUnsubscribeRow, l as isAssetPath, n as brandComponents, o as assetEntry, s as assetUrl, t as BRAND_COMPONENT_CLASSES } from "./brand-nreeKWxF.js";
11
- import { t as EmailCompileError } from "./diagnostics-C0Tr8-eQ.js";
12
- import { n as compileEmail, r as renderEmailContent } from "./render-DpYouYYG.js";
13
- import { caniemail, parseHtml, rawData } from "caniemail";
14
- import { generate, ident, parse, walk } from "css-tree";
3
+ import { o as serializeEmailHtml } from "./html-DJUK2YJF.js";
4
+ import { f as samvaBrandPlugin, l as brandSpecifierPattern, n as render, s as emailElement, t as RenderError, u as parseBrandSpecifier } from "./render-template-DwPDm3Hq.js";
5
+ import { r as collectEmailDiagnostics } from "./jsx-runtime-qL19u3Fy.js";
6
+ import { m as PRIMITIVE_CSS } from "./components-C5850-Qg.js";
7
+ import { c as checkAssetBase, l as isAssetPath, n as brandComponents, o as assetEntry, s as assetUrl, t as BRAND_COMPONENT_CLASSES } from "./brand-CIiEqkU7.js";
8
+ import { r as hasBlockingDiagnostic, t as EmailCompileError } from "./diagnostics-C0Tr8-eQ.js";
9
+ import { i as buildLineMap, s as lineColumn } from "./diagnostic-codes-DZKb0Xcg.js";
10
+ import { r as isDarkSchemeQuery, t as DARK_SCHEME_MEDIA } from "./dark-scheme-CbCwGDWH.js";
11
+ import { c as foregroundDefaults, l as parseBrandCss, n as DEFAULT_THEME_CSS, u as printBrandCss } from "./theme-css-P9F5S7Ic.js";
12
+ import { t as parseStylesheet } from "./css-B_aVKrDo.js";
13
+ import { a as lowerProject, d as Findings, f as projectDirectory, i as completed, m as resolveThemeImports, n as introducedErrors, o as applyStylesheet, p as resolveFromDirectory, r as loadProject, s as renderDarkRules, t as checkTemplate } from "./profile-JTvgCD6X.js";
14
+ import { parse } from "css-tree";
15
15
  import { parse as parse$1 } from "@babel/parser";
16
16
  import { compile } from "tailwindcss";
17
- //#region src/email/compatibility-assessment.ts
18
- const VERIFIED_VALUES = /^(?:left|right|center|justify)$/i;
19
- const SIMPLE_COLOR = /^(?:#[\da-f]{3,8}|rgba?\([^()]+\)|transparent|white|black)$/i;
20
- /**
21
- * A feature matrix establishes support, not the effect on a particular message.
22
- * These rules interpret the pinned caniemail@2.0.2 limitations using emitted
23
- * values. Unresolved layout, fallback and client-account behavior stays unverified.
24
- */
25
- const assessCompatibility = (title, client, support, context, blocking) => {
26
- const result = (assessment, heading, explanation) => ({
27
- assessment,
28
- title: heading,
29
- explanation
30
- });
31
- if (client === "outlook.windows" && support === "partial" && (title === "display" || title === "display:none") && context.hiddenContentOffsets.length > 0) return result("risk", "Hidden content becomes visible in classic Outlook", "Classic Outlook ignores display:none on images and does not inherit it onto nested tables. The emitted inline styles contain hidden content without a resolved hiding fallback. Add a supported hiding fallback before publishing.");
32
- if (blocking) return result("risk", `${title} is unavailable in a target client`, "This construct is required for message content, structure or navigation. Replace it with a supported construct before publishing.");
33
- const explained = context.explanation(title, client, support);
34
- if (explained !== void 0) return result(title.startsWith("system-ui,") ? "degradation" : "not-applicable", title.startsWith("system-ui,") ? "A fallback font will be used" : `${title}: limitation avoided`, explained);
35
- const declarations = (property) => context.declarations(property);
36
- const every = (property, predicate) => {
37
- const values = declarations(property);
38
- return context.complete && values.length > 0 && values.every(({ value }) => predicate(value));
39
- };
40
- const attributesAvoid = (attribute, unsupportedElement) => {
41
- const values = context.attributes(attribute);
42
- return values.length > 0 && values.every(({ element }) => element !== unsupportedElement);
43
- };
44
- if (title === "font-size" && support === "partial" && ["outlook.windows", "yahoo.desktop-webmail"].includes(client) && declarations("font-size").some(({ value }) => /\d(?:\.\d+)?rem\b/i.test(value))) return result("risk", "Text sizes use unsupported rem units", "These clients cannot apply the emitted rem font sizes. Use pixel sizes to preserve the intended text size.");
45
- if (title === "target attribute" && context.attributes("target").some(({ value }) => value !== "_blank")) return result("risk", "Links cannot keep the requested window target", "These clients open links in a new window regardless of the requested target. Use a new-window target or remove the dependency on another browsing context.");
46
- if (title.startsWith("system-ui,") && declarations("font-family").some(({ value }) => !/(?:^|,)\s*(?:sans-serif|serif|monospace)\s*$/i.test(value))) return result("risk", "An unsupported font stack has no generic fallback", "Declare a generic fallback so the client has an explicit font choice when the requested system font is unavailable.");
47
- if (title === "border-radius" && support !== "partial") return result("degradation", "Corners may appear square", "CSS corner rounding is unavailable in this client. Uncovered elements appear square; a separate VML shape can retain rounding. This finding does not establish a content or navigation failure.");
48
- if (title === "border-radius" && client === "yahoo.desktop-webmail" && support === "partial") return result("degradation", "Corner shapes may differ", "This client does not support elliptical slash syntax. Review the recorded values if that corner shape is part of the intended design.");
49
- if (title === "background") {
50
- const values = [...declarations("background"), ...declarations("background-color")];
51
- if (context.complete && values.length > 0 && values.every(({ value }) => SIMPLE_COLOR.test(value)) && declarations("background-image").every(({ value }) => value.toLowerCase() === "none")) return result("not-applicable", "Backgrounds use supported color values", "The emitted backgrounds use simple colors. The cited multiple-background and background-size shorthand limitations do not apply.");
52
- }
53
- if (title === "dir attribute" && client === "outlook.windows" && attributesAvoid("dir", "a")) return result("not-applicable", "Direction is set outside links", "The cited direction bug affects anchor elements. No emitted anchor carries a dir attribute.");
54
- if (title === "lang attribute" && client === "yahoo.desktop-webmail" && attributesAvoid("lang", "td")) return result("not-applicable", "Language is set outside table cells", "The cited language-attribute limitation affects table cells. No emitted td carries a lang attribute.");
55
- if (title === "role attribute" && client === "yahoo.desktop-webmail" && context.attributes("role").length > 0 && context.attributes("role").every(({ element }) => element === "table")) return result("not-applicable", "Roles are applied to supported tables", "Every emitted role attribute is on a table, matching this client's supported element scope.");
56
- if (title === "text-align" && support === "partial" && every("text-align", (value) => VERIFIED_VALUES.test(value))) return result("not-applicable", "Text uses supported alignment values", "The emitted alignment values do not use match-parent or flow-relative start/end values.");
57
- if (title === "font-weight" && support === "partial") {
58
- const pattern = client === "outlook.windows" ? /^(?:normal|bold|400|700)$/i : /^(?:normal|bold|[1-9]00)$/i;
59
- if (every("font-weight", (value) => pattern.test(value))) return result("not-applicable", "Font weights avoid the numeric limitation", "The emitted weights use values preserved by this client's pinned numeric-weight rule.");
60
- return result("degradation", "Font weight may be approximated", "This client may substitute a supported weight. Text remains present, but its emphasis can look different.");
61
- }
62
- if (title === "outline" && every("outline", (value) => value === "none" || value === "0")) return result("unverified", "Image outlines need a client check", "The emitted styles remove outlines. The matrix cannot establish whether this client adds its own link or image outline.");
63
- if (title === "width attribute" && client === "outlook.windows" && context.attributes(title.split(" ")[0]).some(({ value, element }) => element === "img" && value.includes("%"))) return result("risk", "Percentage image dimensions use the wrong reference size", "Classic Outlook sizes percentage image attributes against the image file rather than its parent. Use fixed image dimensions with an appropriate responsive fallback.");
64
- if (title === "overflow" && declarations("overflow").some(({ value }) => /^(?:auto|scroll)$/i.test(value))) return result("risk", "Scrollable content may be inaccessible", "These clients cannot reliably expose content hidden behind a scrolling container. Keep required email content visible without scrolling inside an element.");
65
- return result("unverified", {
66
- "<body> element": "Body styling needs a client check",
67
- border: "Borders need an Outlook check",
68
- "color-scheme meta tag": "Dark appearance needs a client check",
69
- display: "Display behavior needs a client check",
70
- "display:none": "Hidden content needs an Outlook check",
71
- "height attribute": "Image sizing needs a high-DPI Outlook check",
72
- "height property": "Element heights need a client check",
73
- "line-height": "Line spacing needs an Outlook check",
74
- margin: "Outer spacing needs a client check",
75
- "max-height property": "Height limits need an Outlook check",
76
- "max-width": "Width limits need a client check",
77
- "@media": "Conditional styles need a client check",
78
- opacity: "Transparent content needs an Outlook check",
79
- overflow: "Clipped content needs a client check",
80
- "overflow-wrap": "Long text wrapping needs a client check",
81
- padding: "Cell spacing needs an Outlook check",
82
- "<style> element": "Retained styles need a client check",
83
- "text-decoration": "Link decoration needs a client check",
84
- "width attribute": "Image sizing needs a high-DPI Outlook check",
85
- "width property": "Element widths need an Outlook check",
86
- "word-break": "Word breaking needs a client check"
87
- }[title] ?? `${title} needs a client check`, "The feature matrix identifies a support difference but does not establish its effect on this message. Check the affected fixtures in the listed clients before relying on this behavior; no automatic source change is justified by this observation alone.");
88
- };
89
- //#endregion
90
- //#region src/email/compatibility-context.ts
91
- const NON_HIDING_VALUES = {
92
- "mso-hide": /^none$/,
93
- visibility: /^visible$/,
94
- opacity: /^(?:1(?:\.0+)?|100(?:\.0+)?%)$/,
95
- overflow: /^visible$/,
96
- "overflow-y": /^visible$/,
97
- "overflow-x": /^visible$/,
98
- clip: /^auto$/,
99
- "clip-path": /^none$/
100
- };
101
- const POSITIVE_FIXED_HEIGHT = /^(?:\d+(?:\.\d+)?|\.\d+)(?:px|pt|pc|in|cm|mm)$/;
102
- /** Evidence from actual declarations and elements, never a text match in email content. */
103
- const compatibilityContext = (html, css) => {
104
- const declarations = /* @__PURE__ */ new Map();
105
- const attributes = /* @__PURE__ */ new Map();
106
- const elements = /* @__PURE__ */ new Map();
107
- let complete = true;
108
- let unresolvedStyles = false;
109
- const hiddenContentOffsets = [];
110
- const addCss = (source, context, offset, element) => {
111
- const inline = /* @__PURE__ */ new Map();
112
- if (context === "stylesheet" && source.trim() !== "") unresolvedStyles = true;
113
- try {
114
- const ast = parse(source, { context });
115
- walk(ast, (node) => {
116
- if (node.type === "Raw") complete = false;
117
- if (node.type !== "Declaration") return;
118
- const property = node.property.toLowerCase();
119
- const entries = declarations.get(property) ?? [];
120
- const value = generate(node.value);
121
- entries.push({
122
- value,
123
- offset,
124
- element
125
- });
126
- if (!inline.get(property)?.important || node.important) inline.set(property, {
127
- value: value.toLowerCase(),
128
- important: Boolean(node.important)
129
- });
130
- declarations.set(property, entries);
131
- });
132
- } catch {
133
- complete = false;
134
- }
135
- return inline;
136
- };
137
- const { document } = parseHtml(html);
138
- const visit = (node, ancestors = []) => {
139
- let descendants = ancestors;
140
- if (node.type === "comment" && /\[if\b/i.test(node.data)) unresolvedStyles = true;
141
- if ("attribs" in node) {
142
- const offset = node.startIndex ?? void 0;
143
- if (offset !== void 0) {
144
- const entries = elements.get(node.name) ?? [];
145
- entries.push(offset);
146
- elements.set(node.name, entries);
147
- }
148
- for (const [name, value] of Object.entries(node.attribs)) {
149
- const entries = attributes.get(name) ?? [];
150
- entries.push({
151
- value,
152
- offset,
153
- element: node.name
154
- });
155
- attributes.set(name, entries);
156
- }
157
- const styles = node.attribs.style === void 0 ? /* @__PURE__ */ new Map() : addCss(node.attribs.style, "declarationList", offset, node.name);
158
- descendants = [...ancestors, {
159
- offset,
160
- styles
161
- }];
162
- const fallback = descendants.some(({ styles: candidate }) => {
163
- const candidateDisplay = candidate.get("display")?.value;
164
- return candidateDisplay !== void 0 && !/^(?:none|block|inline|inline-block|table|table-row|table-cell|table-row-group)$/i.test(candidateDisplay) || candidate.has("all") || Object.entries(NON_HIDING_VALUES).some(([property, neutral]) => {
165
- const value = candidate.get(property)?.value;
166
- return value !== void 0 && !neutral.test(value);
167
- }) || ["height", "max-height"].some((property) => {
168
- const value = candidate.get(property)?.value;
169
- return value !== void 0 && value !== (property === "height" ? "auto" : "none") && !(POSITIVE_FIXED_HEIGHT.test(value) && Number.parseFloat(value) > 0);
170
- });
171
- });
172
- const hiddenAncestor = ancestors.find(({ styles: candidate }) => candidate.get("display")?.value === "none");
173
- const display = styles.get("display")?.value;
174
- if (!fallback && node.name === "img" && display === "none" && hiddenAncestor === void 0 && offset !== void 0) hiddenContentOffsets.push(offset);
175
- if (!fallback && node.name === "table" && hiddenAncestor !== void 0 && display === void 0 && hiddenAncestor.offset !== void 0) hiddenContentOffsets.push(hiddenAncestor.offset);
176
- if (node.name === "style") {
177
- for (const child of node.children) if (child.type === "text") addCss(child.data, "stylesheet");
178
- }
179
- }
180
- if ("children" in node) for (const child of node.children) visit(child, descendants);
181
- };
182
- for (const child of document.children) visit(child);
183
- if (css !== void 0) addCss(css, "stylesheet");
184
- const everyValue = (property, predicate) => {
185
- const entries = declarations.get(property);
186
- return complete && entries !== void 0 && entries.length > 0 && entries.every(({ value }) => predicate(value));
187
- };
188
- return {
189
- /** Known hidden-content failures; unresolved cascade or fallback evidence cannot block. */
190
- get hiddenContentOffsets() {
191
- return complete && !unresolvedStyles ? [...new Set(hiddenContentOffsets)] : [];
192
- },
193
- /** Incomplete CSS cannot prove that every occurrence avoids a limitation. */
194
- get complete() {
195
- return complete;
196
- },
197
- declarations(property) {
198
- return declarations.get(property) ?? [];
199
- },
200
- attributes(name) {
201
- return attributes.get(name) ?? [];
202
- },
203
- /** Bounded exceptions to caniemail@2.0.2's feature-wide matrix, tied to its client rules. */
204
- explanation(title, client, support) {
205
- if (title === "font-size" && support === "partial" && ["outlook.windows", "yahoo.desktop-webmail"].includes(client) && everyValue("font-size", (value) => /^(?:0|(?:\d+(?:\.\d+)?|\.\d+)px)$/i.test(value))) return "All font sizes use pixels; this client's rem-unit limitation does not apply.";
206
- if (title === "border-radius" && support === "partial" && client === "yahoo.desktop-webmail" && everyValue("border-radius", (value) => /^(?:0|(?:\d+(?:\.\d+)?|\.\d+)(?:px|%))(?:\s+(?:0|(?:\d+(?:\.\d+)?|\.\d+)(?:px|%))){0,3}$/i.test(value))) return "These corner radii do not use the unsupported elliptical slash syntax.";
207
- if (title === "target attribute" && [
208
- "gmail.desktop-webmail",
209
- "gmail.ios",
210
- "gmail.android",
211
- "outlook.outlook-com",
212
- "yahoo.desktop-webmail",
213
- "outlook.windows",
214
- "apple-mail.macos",
215
- "apple-mail.ios"
216
- ].includes(client) && attributes.has("target") && attributes.get("target").every(({ value }) => value === "_blank")) return "Links already request a new window, matching the client's enforced behavior.";
217
- if (title === "system-ui, ui-serif, ui-sans-serif, ui-rounded, ui-monospace" && everyValue("font-family", (value) => /(?:^|,)\s*(?:sans-serif|serif|monospace)\s*$/i.test(value))) return "Every font stack ends with a generic fallback. Font appearance can differ in this client.";
218
- },
219
- offsets(title) {
220
- const element = /^<([a-z0-9]+)> element$/i.exec(title);
221
- if (element !== null) return elements.get(element[1]) ?? [];
222
- const attribute = /^([a-z-]+) attribute$/i.exec(title);
223
- const entries = attribute !== null ? attributes.get(attribute[1]) : declarations.get(title.startsWith("system-ui,") ? "font-family" : title.replace(/ property$/, ""));
224
- return [...new Set(entries?.flatMap(({ offset }) => offset === void 0 ? [] : [offset]) ?? [])];
225
- }
226
- };
227
- };
228
- //#endregion
229
- //#region src/email/fonts.ts
230
- const FONT_FILE = /\.woff2$/i;
231
- const WOFF2_FORMAT = /^woff2(?:-variations)?$/i;
232
- const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
233
- const declarationValue = (declaration) => declaration.type === "Declaration" ? generate(declaration.value).trim() : "";
234
- /**
235
- * Validate one `@font-face` and rewrite its project-relative `src` URLs.
236
- * Accepts only WOFF2: a relative URL must name a `.woff2` file the project has,
237
- * and an `https:` URL stays an external reference. `local()` entries pass.
238
- */
239
- const compileFontFace = (node, origin, resolve) => {
240
- const diagnostics = [];
241
- const fail = (code, message) => diagnostics.push({
242
- code,
243
- severity: "error",
244
- message: `${origin}: ${message}`,
245
- origins: []
246
- });
247
- if (node.type !== "Atrule" || node.block === null || node.block.children === null) return {
248
- rule: void 0,
249
- diagnostics
250
- };
251
- let family;
252
- let sources = 0;
253
- for (const declaration of node.block.children) {
254
- if (declaration.type !== "Declaration") continue;
255
- const property = declaration.property.toLowerCase();
256
- if (property === "font-family") family = unquote(declarationValue(declaration));
257
- if (property !== "src") continue;
258
- const authored = declarationValue(declaration);
259
- let value;
260
- try {
261
- value = parse(authored, { context: "value" });
262
- } catch {
263
- fail("email-font-src", "@font-face src could not be parsed.");
264
- continue;
265
- }
266
- walk(value, { enter: (part) => {
267
- if (part.type === "Function" && part.name.toLowerCase() === "format") {
268
- const format = unquote(generate(part).slice(7, -1));
269
- if (!WOFF2_FORMAT.test(format)) fail("email-font-format", `@font-face format(${format}) is not supported. Email fonts are WOFF2 only; convert the file to .woff2.`);
270
- return;
271
- }
272
- if (part.type !== "Url") return;
273
- sources++;
274
- const reference = part.value;
275
- const path = reference.replace(/[?#].*$/, "");
276
- if (/^https:\/\//i.test(reference)) {
277
- if (!FONT_FILE.test(path) && !/format\(\s*['"]?woff2/i.test(generate(value))) fail("email-font-format", `@font-face src ${JSON.stringify(reference)} is not a WOFF2 file. Email fonts are WOFF2 only.`);
278
- return;
279
- }
280
- if (SCHEME.test(reference) || reference.startsWith("//")) {
281
- fail("email-font-src", `@font-face src ${JSON.stringify(reference)} must be a project .woff2 file or an https URL.`);
282
- return;
283
- }
284
- if (!FONT_FILE.test(path)) {
285
- fail("email-font-format", `@font-face src ${JSON.stringify(reference)} is not a .woff2 file. Email fonts are WOFF2 only; convert the file to .woff2.`);
286
- return;
287
- }
288
- const url = resolve?.(reference);
289
- if (url === void 0) {
290
- fail("email-font-missing", `@font-face src ${JSON.stringify(reference)} names no file in the project. Paths resolve from the stylesheet's own directory.`);
291
- return;
292
- }
293
- part.value = url;
294
- } });
295
- declaration.value = {
296
- type: "Raw",
297
- value: generate(value).replace(/\)(?=(?:format|tech)\()/gi, ") ")
298
- };
299
- }
300
- if (family === void 0 || family === "") fail("email-font-family", "@font-face declares no font-family.");
301
- if (sources === 0) fail("email-font-src", "@font-face declares no url() src.");
302
- if (diagnostics.length > 0 || family === void 0) return {
303
- rule: void 0,
304
- diagnostics
305
- };
306
- return {
307
- rule: {
308
- family,
309
- css: generate(node)
310
- },
311
- diagnostics
312
- };
313
- };
314
- //#endregion
315
- //#region src/email/css.ts
316
- const UNLAYERED = Number.MAX_SAFE_INTEGER;
317
- const CONDITIONAL_AT_RULES = /* @__PURE__ */ new Set([
318
- "media",
319
- "supports",
320
- "container"
321
- ]);
322
- const HEAD_AT_RULES = /* @__PURE__ */ new Set([
323
- "page",
324
- "counter-style",
325
- "keyframes"
326
- ]);
327
- const ROOT_SELECTORS = /* @__PURE__ */ new Set([
328
- ":root",
329
- ":host",
330
- "html",
331
- "*",
332
- ":where(:root)"
333
- ]);
334
- const text = (node) => node === null || node === void 0 ? "" : generate(node);
335
- /** The CSS specificity triple for one selector, ignoring the parts email clients drop. */
336
- const specificityOf = (selector) => {
337
- let id = 0;
338
- let cls = 0;
339
- let type = 0;
340
- const visit = (node) => {
341
- switch (node.type) {
342
- case "IdSelector":
343
- id += 1;
344
- break;
345
- case "ClassSelector":
346
- case "AttributeSelector":
347
- cls += 1;
348
- break;
349
- case "PseudoClassSelector":
350
- if (node.name !== "where") cls += 1;
351
- break;
352
- case "TypeSelector":
353
- if (node.name !== "*") type += 1;
354
- break;
355
- case "PseudoElementSelector": type += 1;
356
- }
357
- if ("children" in node && node.children !== null && node.children !== void 0) for (const child of node.children) visit(child);
358
- };
359
- visit(selector);
360
- return [
361
- id,
362
- cls,
363
- type
364
- ];
365
- };
366
- const hasPseudo = (selector) => {
367
- let found = false;
368
- const visit = (node) => {
369
- if (node.type === "PseudoClassSelector" || node.type === "PseudoElementSelector") found = true;
370
- if ("children" in node && node.children !== null && node.children !== void 0) for (const child of node.children) visit(child);
371
- };
372
- visit(selector);
373
- return found;
374
- };
375
- const COMBINATORS = {
376
- " ": "descendant",
377
- ">": "child",
378
- "+": "adjacent",
379
- "~": "sibling"
380
- };
381
- /** Compile a selector into the plain-data matcher the render lane uses. */
382
- const compileSelector = (selector) => {
383
- let ast;
384
- try {
385
- ast = parse(selector, {
386
- context: "selector",
387
- positions: false
388
- });
389
- } catch {
390
- return;
391
- }
392
- if (ast.type !== "Selector" || ast.children === null) return void 0;
393
- const parts = [];
394
- let tag;
395
- let id;
396
- let classes = [];
397
- let attributes = [];
398
- let opaque = false;
399
- const flush = (after) => {
400
- parts.push({
401
- compound: {
402
- tag,
403
- id,
404
- classes,
405
- attributes,
406
- opaque
407
- },
408
- ...after === void 0 ? {} : { after }
409
- });
410
- tag = void 0;
411
- id = void 0;
412
- classes = [];
413
- attributes = [];
414
- opaque = false;
415
- };
416
- for (const node of ast.children) switch (node.type) {
417
- case "TypeSelector":
418
- if (node.name !== "*") tag = node.name.toLowerCase();
419
- break;
420
- case "IdSelector":
421
- id = node.name;
422
- break;
423
- case "ClassSelector":
424
- classes.push(ident.decode(node.name));
425
- break;
426
- case "AttributeSelector":
427
- attributes.push({
428
- name: node.name.name,
429
- operator: node.matcher ?? void 0,
430
- value: node.value === null || node.value === void 0 ? void 0 : node.value.type === "String" ? node.value.value : node.value.name
431
- });
432
- break;
433
- case "Combinator":
434
- flush(COMBINATORS[node.name.trim() === "" ? " " : node.name] ?? "descendant");
435
- break;
436
- default: opaque = true;
437
- }
438
- flush();
439
- return { parts };
440
- };
441
- /** Substitute a nested rule's `&` against its parent selector. */
442
- const nestSelector = (parent, child) => child.includes("&") ? child.replaceAll("&", parent) : `${parent} ${child}`;
443
- /** Parse one stylesheet into rules, keeping layer, order and conditions. */
444
- const parseStylesheet = (source, options = {}) => {
445
- const rules = [];
446
- const headAtRules = [];
447
- const fontFaces = [];
448
- const variables = {};
449
- const darkVariables = {};
450
- const conditionalVariables = /* @__PURE__ */ new Set();
451
- const diagnostics = [];
452
- const layers = /* @__PURE__ */ new Map();
453
- const selectorFacts = /* @__PURE__ */ new Map();
454
- let order = options.startOrder ?? 0;
455
- /** Everything a rule needs from its selector, computed once per distinct string. */
456
- const factsFor = (selector) => {
457
- const cached = selectorFacts.get(selector);
458
- if (cached !== void 0) return cached;
459
- let facts;
460
- try {
461
- const node = parse(selector, {
462
- context: "selector",
463
- positions: false
464
- });
465
- const classes = /* @__PURE__ */ new Set();
466
- walk(node, {
467
- visit: "ClassSelector",
468
- enter: (part) => {
469
- classes.add(ident.decode(part.name));
470
- }
471
- });
472
- facts = {
473
- classes: [...classes],
474
- specificity: specificityOf(node),
475
- pseudo: hasPseudo(node),
476
- matcher: compileSelector(selector)
477
- };
478
- } catch {
479
- facts = {
480
- classes: [],
481
- specificity: [
482
- 0,
483
- 0,
484
- 0
485
- ],
486
- pseudo: true,
487
- matcher: void 0
488
- };
489
- }
490
- selectorFacts.set(selector, facts);
491
- return facts;
492
- };
493
- let ast;
494
- try {
495
- ast = parse(source, {
496
- parseValue: false,
497
- parseCustomProperty: false,
498
- positions: false
499
- });
500
- } catch (cause) {
501
- return {
502
- rules: [],
503
- headAtRules: [],
504
- fontFaces: [],
505
- variables: {},
506
- darkVariables: {},
507
- diagnostics: [{
508
- code: "css-parse-error",
509
- severity: "error",
510
- message: `${options.origin ?? "stylesheet"} could not be parsed: ${String(cause)}`,
511
- origins: []
512
- }]
513
- };
514
- }
515
- const declarationsOf = (block) => {
516
- const output = [];
517
- if (block === null || block.type !== "Block" || block.children === null) return output;
518
- for (const child of block.children) {
519
- if (child.type !== "Declaration") continue;
520
- output.push({
521
- property: child.property,
522
- value: downlevelColors(text(child.value).trim().replace(/[\t\n\r\f]/g, " ")),
523
- important: child.important === true
524
- });
525
- }
526
- return output;
527
- };
528
- const emit = (selector, context, declarations) => {
529
- if (declarations.length === 0) return;
530
- const facts = factsFor(selector);
531
- if (ROOT_SELECTORS.has(selector.trim())) for (const declaration of declarations) {
532
- if (!declaration.property.startsWith("--")) continue;
533
- if (context.conditions.length === 0) variables[declaration.property] = declaration.value;
534
- else if (isDarkSchemeCondition(context.conditions)) darkVariables[declaration.property] = declaration.value;
535
- else conditionalVariables.add(declaration.property);
536
- }
537
- rules.push({
538
- selector,
539
- classes: facts.classes,
540
- specificity: facts.specificity,
541
- declarations,
542
- order: order++,
543
- layer: context.layer,
544
- conditions: context.conditions,
545
- inlinable: context.conditions.length === 0 && !facts.pseudo,
546
- matcher: facts.matcher
547
- });
548
- };
549
- /**
550
- * Declarations directly in a block belong to the enclosing selector, whether
551
- * that block is the rule's own or a `@media` nested inside it — which is
552
- * exactly the shape Tailwind v4 emits for a responsive utility.
553
- */
554
- const walkBlock = (block, context) => {
555
- if (block === null || block.type !== "Block" || block.children === null) return;
556
- const declarations = declarationsOf(block);
557
- if (declarations.length > 0 && context.selector !== void 0) emit(context.selector, context, declarations);
558
- for (const child of block.children) if (child.type !== "Declaration") visitNode(child, context);
559
- };
560
- const visitNode = (node, context) => {
561
- if (node.type === "Rule") {
562
- const prelude = node.prelude;
563
- const selectors = prelude.type === "SelectorList" && prelude.children !== null ? [...prelude.children] : [prelude];
564
- for (const selector of selectors) {
565
- const own = text(selector).trim();
566
- if (own === "") continue;
567
- walkBlock(node.block, {
568
- ...context,
569
- selector: context.selector === void 0 ? own : nestSelector(context.selector, own)
570
- });
571
- }
572
- return;
573
- }
574
- if (node.type !== "Atrule") return;
575
- const name = node.name.toLowerCase();
576
- if (name === "layer") {
577
- const prelude = text(node.prelude).trim();
578
- if (node.block === null) {
579
- for (const declared of prelude.split(",").map((part) => part.trim())) if (declared !== "" && !layers.has(declared)) layers.set(declared, layers.size);
580
- return;
581
- }
582
- const named = prelude.split(",")[0]?.trim() ?? "";
583
- if (named !== "" && !layers.has(named)) layers.set(named, layers.size);
584
- walkBlock(node.block, {
585
- ...context,
586
- layer: layers.get(named) ?? context.layer
587
- });
588
- return;
589
- }
590
- if (name === "theme" || name === "scope") {
591
- const into = context.conditions.length === 0 ? variables : isDarkSchemeCondition(context.conditions) ? darkVariables : void 0;
592
- for (const declaration of declarationsOf(node.block)) if (declaration.property.startsWith("--")) {
593
- if (into === void 0) conditionalVariables.add(declaration.property);
594
- else into[declaration.property] = declaration.value;
595
- }
596
- for (const child of node.block?.children ?? []) if (child.type !== "Declaration") visitNode(child, context);
597
- return;
598
- }
599
- if (name === "property") {
600
- const initial = declarationsOf(node.block).find((declaration) => declaration.property === "initial-value");
601
- const property = text(node.prelude).trim();
602
- if (initial !== void 0 && property.startsWith("--") && !(property in variables)) variables[property] = initial.value;
603
- return;
604
- }
605
- if (CONDITIONAL_AT_RULES.has(name)) {
606
- walkBlock(node.block, {
607
- ...context,
608
- conditions: [...context.conditions, `@${name} ${text(node.prelude).trim()}`]
609
- });
610
- return;
611
- }
612
- if (name === "font-face") {
613
- const face = compileFontFace(node, options.origin ?? "stylesheet", options.resolveFontFile);
614
- if (face.rule !== void 0) fontFaces.push(face.rule);
615
- diagnostics.push(...face.diagnostics);
616
- return;
617
- }
618
- if (HEAD_AT_RULES.has(name)) {
619
- headAtRules.push(generate(node));
620
- return;
621
- }
622
- if (name === "import") {
623
- if (options.themeImports === true) return;
624
- diagnostics.push({
625
- code: "css-import-unresolved",
626
- severity: "error",
627
- message: `${options.origin ?? "stylesheet"} uses @import ${text(node.prelude).trim()}; import the stylesheet from the template module instead so the compiler can resolve it.`,
628
- origins: []
629
- });
630
- return;
631
- }
632
- if (name === "charset" || name === "namespace") return;
633
- diagnostics.push({
634
- code: "css-unsupported-at-rule",
635
- severity: "warning",
636
- message: `@${name} is not applied to email output; remove it or move the declarations into a class rule.`,
637
- origins: []
638
- });
639
- };
640
- if (ast.type === "StyleSheet" && ast.children !== null) for (const child of ast.children) visitNode(child, {
641
- conditions: [],
642
- layer: UNLAYERED
643
- });
644
- for (const property of conditionalVariables) if (property in variables) diagnostics.push({
645
- code: "css-conditional-variable",
646
- severity: "warning",
647
- message: `${property} is redefined inside a conditional at-rule. Inlined declarations take the unconditional value; keep the override on a class rule so the retained head rule can apply it.`,
648
- origins: []
649
- });
650
- return {
651
- rules,
652
- headAtRules,
653
- fontFaces,
654
- variables,
655
- darkVariables,
656
- diagnostics
657
- };
658
- };
659
- //#endregion
660
- //#region src/email/contrast.ts
661
- const CANVAS = {
662
- light: {
663
- r: 1,
664
- g: 1,
665
- b: 1,
666
- a: 1
667
- },
668
- dark: {
669
- r: 18 / 255,
670
- g: 18 / 255,
671
- b: 18 / 255,
672
- a: 1
673
- }
674
- };
675
- /** The ratios `email-contrast` holds a message to, and what counts as large text. */
676
- const CONTRAST_THRESHOLDS = {
677
- /** Text below this is an error at any size. */
678
- textError: 3,
679
- /** Normal-size text below this is a warning (WCAG AA). */
680
- textWarning: 4.5,
681
- /** Text at least this many pixels is large, as is bold text at `largeBoldPx`. */
682
- largePx: 24,
683
- largeBoldPx: 18.5,
684
- /** A filled button below this against its surroundings is an error. */
685
- shapeError: 1.5,
686
- /** A filled button below this is a warning (WCAG 1.4.11). */
687
- shapeWarning: 3,
688
- /** A button border at least this against the surroundings keeps the shape. */
689
- border: 3
690
- };
691
- const TEXT_ERROR = CONTRAST_THRESHOLDS.textError;
692
- const TEXT_WARNING = CONTRAST_THRESHOLDS.textWarning;
693
- const LARGE_PX = CONTRAST_THRESHOLDS.largePx;
694
- const LARGE_BOLD_PX = CONTRAST_THRESHOLDS.largeBoldPx;
695
- const SHAPE_ERROR = CONTRAST_THRESHOLDS.shapeError;
696
- const SHAPE_WARNING = CONTRAST_THRESHOLDS.shapeWarning;
697
- const INSET_BORDER = CONTRAST_THRESHOLDS.border;
698
- const SKIPPED_TAGS = /* @__PURE__ */ new Set([
699
- "head",
700
- "style",
701
- "title",
702
- "script"
703
- ]);
704
- const INVISIBLE = /[\s\u200b-\u200f\ufeff\u00a0\u00ad]|\u034f/g;
705
- const DARK_QUERY = /^@media\b[^{]*\(\s*prefers-color-scheme\s*:\s*dark\s*\)/i;
706
- const clamp = (value) => value < 0 ? 0 : value > 1 ? 1 : value;
707
- const channel = (value) => {
708
- const v = clamp(value);
709
- return v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4;
710
- };
711
- const luminance = (color) => .2126 * channel(color.r) + .7152 * channel(color.g) + .0722 * channel(color.b);
712
- const ratioOf = (left, right) => {
713
- const a = luminance(left);
714
- const b = luminance(right);
715
- return (Math.max(a, b) + .05) / (Math.min(a, b) + .05);
716
- };
717
- const hex = (color) => `#${[
718
- color.r,
719
- color.g,
720
- color.b
721
- ].map((value) => Math.round(clamp(value) * 255).toString(16).padStart(2, "0")).join("")}`;
722
- const over = (top, below) => ({
723
- r: top.r * top.a + below.r * (1 - top.a),
724
- g: top.g * top.a + below.g * (1 - top.a),
725
- b: top.b * top.a + below.b * (1 - top.a),
726
- a: 1
727
- });
728
- const declarationsOf = (source) => {
729
- const found = [];
730
- try {
731
- walk(parse(source, {
732
- context: "declarationList",
733
- positions: false
734
- }), (node) => {
735
- if (node.type === "Declaration") found.push({
736
- property: node.property.toLowerCase(),
737
- value: generate(node.value).trim()
738
- });
739
- });
740
- } catch {
741
- return [];
742
- }
743
- return found;
744
- };
745
- /** Split on whitespace that is not inside parentheses. */
746
- const tokens = (value) => {
747
- const found = [];
748
- let depth = 0;
749
- let current = "";
750
- for (const char of value) {
751
- if (char === "(") depth += 1;
752
- if (char === ")") depth -= 1;
753
- if (/\s/.test(char) && depth === 0) {
754
- if (current !== "") found.push(current);
755
- current = "";
756
- } else current += char;
757
- }
758
- if (current !== "") found.push(current);
759
- return found;
760
- };
761
- const declaredColor = (value) => {
762
- const color = parseColor(value);
763
- return color === void 0 ? "unknown" : color;
764
- };
765
- const pixels = (value) => {
766
- const trimmed = value.trim();
767
- if (/^[+-]?0+(?:\.0+)?$/.test(trimmed)) return 0;
768
- const match = /^(\d+(?:\.\d+)?|\.\d+)px$/i.exec(trimmed);
769
- return match === null ? void 0 : Number(match[1]);
770
- };
771
- const BORDER_STYLES = /^(?:solid|dashed|dotted|double|groove|ridge|inset|outset|none|hidden)$/i;
772
- const WIDTH_KEYWORDS = {
773
- thin: 1,
774
- medium: 3,
775
- thick: 5
776
- };
777
- const resolve = (declarations) => {
778
- let background;
779
- let image = false;
780
- let color;
781
- let display;
782
- let fontSize;
783
- let bold;
784
- const border = {
785
- width: void 0,
786
- visible: void 0,
787
- color: void 0
788
- };
789
- for (const { property, value } of declarations) {
790
- const lower = value.toLowerCase();
791
- switch (property) {
792
- case "background":
793
- image = /url\(|gradient\(/.test(lower);
794
- background = tokens(value).filter((part) => !/^(?:url|[\w-]*gradient)\(/i.test(part)).map(parseColor).find((entry) => entry !== void 0) ?? (/var\(|currentcolor|inherit|initial|unset/.test(lower) ? "unknown" : void 0);
795
- break;
796
- case "background-color":
797
- background = declaredColor(value);
798
- break;
799
- case "background-image":
800
- image = lower !== "none";
801
- break;
802
- case "color":
803
- color = declaredColor(value);
804
- break;
805
- case "display":
806
- display = lower.replace(/\s*!important$/, "");
807
- break;
808
- case "font-size":
809
- fontSize = pixels(value);
810
- break;
811
- case "font-weight": {
812
- const weight = Number(lower);
813
- if (lower === "bold" || lower === "bolder") bold = true;
814
- else if (lower === "normal" || lower === "lighter") bold = false;
815
- else if (!Number.isNaN(weight)) bold = weight >= 700;
816
- break;
817
- }
818
- case "border":
819
- case "border-width":
820
- case "border-color":
821
- case "border-style": {
822
- const parts = tokens(value);
823
- if (property === "border") {
824
- border.width = WIDTH_KEYWORDS.medium;
825
- border.visible = false;
826
- border.color = "unknown";
827
- }
828
- const styles = parts.filter((part) => BORDER_STYLES.test(part));
829
- if (styles.length > 0) border.visible = styles.every((part) => !/^(?:none|hidden)$/i.test(part));
830
- const sizes = parts.map((part) => pixels(part) ?? WIDTH_KEYWORDS[part.toLowerCase()]).filter((entry) => entry !== void 0);
831
- if (sizes.length > 0) border.width = Math.min(...sizes);
832
- else if (property === "border-width") border.width = void 0;
833
- const named = parts.filter((part) => pixels(part) === void 0 && WIDTH_KEYWORDS[part.toLowerCase()] === void 0 && !BORDER_STYLES.test(part));
834
- if (property !== "border-width" && property !== "border-style" && named.length > 0) {
835
- const colors = named.map(parseColor);
836
- border.color = colors.every((entry) => entry !== void 0) ? colors[0] : "unknown";
837
- }
838
- break;
839
- }
840
- }
841
- }
842
- return {
843
- background,
844
- image,
845
- color,
846
- display,
847
- fontSize,
848
- bold,
849
- border
850
- };
851
- };
852
- /** Properties a declaration list sets, for deciding whether an unimportant dark rule can apply. */
853
- const has = (declarations, property) => declarations.some((entry) => entry.property === property);
854
- const advance = (parent, style, tag) => {
855
- let background = parent.background;
856
- let ownBackground;
857
- if (style.image || style.background === "unknown") background = "unknown";
858
- else if (style.background !== void 0 && style.background.a > 0) {
859
- if (style.background.a >= 1) background = style.background;
860
- else if (parent.background !== "unknown") background = over(style.background, parent.background);
861
- else background = "unknown";
862
- if (background !== "unknown") ownBackground = background;
863
- }
864
- let color = tag === "a" ? void 0 : parent.color;
865
- if (style.color === "unknown") color = "unknown";
866
- else if (style.color !== void 0) color = style.color;
867
- return {
868
- ownBackground,
869
- state: {
870
- background,
871
- color,
872
- fontSize: style.fontSize ?? parent.fontSize,
873
- bold: style.bold ?? parent.bold,
874
- hidden: parent.hidden || style.display === "none"
875
- }
876
- };
877
- };
878
- const originsAt$1 = (positions, offset) => {
879
- if (offset === void 0) return [];
880
- let best;
881
- for (const position of positions) {
882
- if (offset < position.start || offset >= position.end) continue;
883
- if (best === void 0 || position.end - position.start < best.end - best.start) best = position;
884
- }
885
- return best?.origins ?? [];
886
- };
887
- const compareRules = (left, right) => {
888
- const important = (rule) => rule.declarations.some((d) => d.important) ? 1 : 0;
889
- return important(left) - important(right) || left.specificity[0] - right.specificity[0] || left.specificity[1] - right.specificity[1] || left.specificity[2] - right.specificity[2] || left.order - right.order;
890
- };
891
- const textOf = (node) => node.children.map((child) => "data" in child ? String(child.data) : "").join("");
892
- const MODE_LABEL = {
893
- light: "Light mode",
894
- dark: "Dark mode"
895
- };
896
- const FIX = "Pair background and text tokens (bg-primary with text-primary-foreground) and give the theme's dark-mode @theme a value for the token, or choose colors that reach";
897
- /**
898
- * Check text and filled-control contrast in the emitted document, in light and
899
- * dark presentation.
900
- */
901
- const checkEmailContrast = (input) => {
902
- const { document } = parseHtml(input.html);
903
- const sheets = input.css === void 0 ? [] : [input.css];
904
- const collect = (nodes) => {
905
- for (const node of nodes) {
906
- if (!("attribs" in node)) continue;
907
- if (node.name === "style") sheets.push(textOf(node));
908
- else collect(node.children);
909
- }
910
- };
911
- collect(document.children);
912
- const darkRules = sheets.flatMap((sheet) => parseStylesheet(sheet).rules).filter((rule) => rule.conditions.length === 1 && DARK_QUERY.test(rule.conditions[0])).toSorted(compareRules);
913
- const findings = /* @__PURE__ */ new Map();
914
- const report = (mode, kind, foreground, background, ratio, required, severity, offset) => {
915
- const origins = originsAt$1(input.positions ?? [], offset);
916
- const measured = ratio.toFixed(2);
917
- const colors = `${hex(foreground)} on ${hex(background)}`;
918
- const message = kind === "text" ? `${MODE_LABEL[mode]}: text ${colors} has a contrast ratio of ${measured}:1; ${required}:1 is required. ${FIX} ${required}:1.` : `${MODE_LABEL[mode]}: the button background ${hex(foreground)} against its surroundings ${hex(background)} has a contrast ratio of ${measured}:1; ${SHAPE_WARNING}:1 is required for the shape to stay visible (below ${SHAPE_ERROR}:1 it disappears). ${FIX} ${SHAPE_WARNING}:1, or give the button a border that does.`;
919
- const key = JSON.stringify([
920
- mode,
921
- kind,
922
- hex(foreground),
923
- hex(background),
924
- measured,
925
- origins
926
- ]);
927
- const existing = findings.get(key);
928
- if (existing !== void 0) {
929
- if (origins.length > 0) existing.occurrences.push(origins);
930
- return;
931
- }
932
- findings.set(key, {
933
- key,
934
- occurrences: origins.length > 0 ? [origins] : [],
935
- diagnostic: {
936
- code: "email-contrast",
937
- severity,
938
- message,
939
- origins,
940
- ...input.fixture === void 0 ? {} : { fixtures: [input.fixture] }
941
- }
942
- });
943
- };
944
- const visit = (node, parents, parentAncestry, previous) => {
945
- const inline = declarationsOf(node.attribs.style ?? "");
946
- const attribute = node.attribs.bgcolor === void 0 ? [] : [{
947
- property: "background-color",
948
- value: node.attribs.bgcolor
949
- }];
950
- const shape = {
951
- type: "Element",
952
- tag: node.name,
953
- props: node.attribs,
954
- children: [],
955
- origins: [],
956
- authored: false
957
- };
958
- const ancestry = {
959
- element: shape,
960
- parent: parentAncestry,
961
- previous
962
- };
963
- const base = [...attribute, ...inline];
964
- const dark = [...base];
965
- for (const rule of darkRules) {
966
- if (!matchesSelector(rule.matcher, ancestry)) continue;
967
- for (const declaration of rule.declarations) {
968
- const property = declaration.property.toLowerCase();
969
- if (declaration.important || !has(inline, property)) dark.push({
970
- property,
971
- value: declaration.value.replace(/\s*!important$/i, "")
972
- });
973
- }
974
- }
975
- const styles = {
976
- light: resolve(base),
977
- dark: resolve(dark)
978
- };
979
- const direct = node.children.some((child) => child.type === "text" && String(child.data).replace(INVISIBLE, "") !== "");
980
- const states = {
981
- light: parents.light,
982
- dark: parents.dark
983
- };
984
- for (const mode of ["light", "dark"]) {
985
- const parent = parents[mode];
986
- const style = styles[mode];
987
- const { state, ownBackground } = advance(parent, style, node.name);
988
- states[mode] = state;
989
- if (state.hidden) continue;
990
- if (node.name === "a" && ownBackground !== void 0 && parent.background !== "unknown" && !style.image) {
991
- const ratio = ratioOf(ownBackground, parent.background);
992
- if (ratio < SHAPE_WARNING) {
993
- const { width, visible, color } = style.border;
994
- const bordered = visible === true && width !== void 0 && width > 0 && color !== void 0;
995
- if (!(bordered && color !== "unknown" && ratioOf(over(color, parent.background), parent.background) >= INSET_BORDER) && !(bordered && color === "unknown")) report(mode, "button", ownBackground, parent.background, ratio, SHAPE_WARNING, ratio < SHAPE_ERROR ? "error" : "warning", node.startIndex ?? void 0);
996
- }
997
- }
998
- if (direct && state.color !== void 0 && state.color !== "unknown" && state.background !== "unknown") {
999
- const ink = over(state.color, state.background);
1000
- const ratio = ratioOf(ink, state.background);
1001
- const required = state.fontSize !== void 0 && (state.fontSize >= LARGE_PX || state.bold && state.fontSize >= LARGE_BOLD_PX) ? TEXT_ERROR : TEXT_WARNING;
1002
- if (ratio < required) report(mode, "text", ink, state.background, ratio, required, ratio < TEXT_ERROR ? "error" : "warning", node.startIndex ?? void 0);
1003
- }
1004
- }
1005
- if (!SKIPPED_TAGS.has(node.name) && (!states.light.hidden || !states.dark.hidden)) {
1006
- let siblings = [];
1007
- for (const child of node.children) {
1008
- if (!("attribs" in child) || SKIPPED_TAGS.has(child.name)) continue;
1009
- const done = visit(child, states, ancestry, siblings);
1010
- siblings = [...siblings, done];
1011
- }
1012
- }
1013
- return shape;
1014
- };
1015
- const root = {
1016
- light: {
1017
- background: CANVAS.light,
1018
- color: void 0,
1019
- fontSize: void 0,
1020
- bold: false,
1021
- hidden: false
1022
- },
1023
- dark: {
1024
- background: CANVAS.dark,
1025
- color: void 0,
1026
- fontSize: void 0,
1027
- bold: false,
1028
- hidden: false
1029
- }
1030
- };
1031
- let siblings = [];
1032
- for (const node of document.children) {
1033
- if (!("attribs" in node) || SKIPPED_TAGS.has(node.name)) continue;
1034
- siblings = [...siblings, visit(node, root, void 0, siblings)];
1035
- }
1036
- return [...findings.values()].map(({ diagnostic, occurrences }) => ({
1037
- ...diagnostic,
1038
- ...occurrences.length > 1 ? { occurrences } : {}
1039
- }));
1040
- };
1041
- //#endregion
1042
- //#region src/email/compatibility.ts
1043
- /**
1044
- * The pinned matrix. Every finding is reported per client, and a client absent
1045
- * from this list is a client Samva makes no claim about.
1046
- */
1047
- const EMAIL_CLIENT_MATRIX = [
1048
- {
1049
- id: "gmail.desktop-webmail",
1050
- label: "Gmail web"
1051
- },
1052
- {
1053
- id: "gmail.ios",
1054
- label: "Gmail iOS"
1055
- },
1056
- {
1057
- id: "gmail.android",
1058
- label: "Gmail Android"
1059
- },
1060
- {
1061
- id: "apple-mail.macos",
1062
- label: "Apple Mail macOS"
1063
- },
1064
- {
1065
- id: "apple-mail.ios",
1066
- label: "Apple Mail iOS"
1067
- },
1068
- {
1069
- id: "yahoo.desktop-webmail",
1070
- label: "Yahoo web"
1071
- },
1072
- {
1073
- id: "outlook.outlook-com",
1074
- label: "Outlook web and new Windows"
1075
- },
1076
- {
1077
- id: "outlook.windows",
1078
- label: "Outlook classic Windows"
1079
- }
1080
- ];
1081
- const LABELS = new Map(EMAIL_CLIENT_MATRIX.map((target) => [target.id, target.label]));
1082
- const COMPATIBILITY_PROVENANCE = {
1083
- rules: "caniemail@2.0.2",
1084
- apiVersion: rawData.api_version,
1085
- lastUpdate: rawData.last_update_date
1086
- };
1087
- /**
1088
- * The constructs whose loss actually breaks a message: the recipient reads
1089
- * something different, in a different order, follows a link that does not work,
1090
- * or sees a layout that has collapsed. A target client dropping one of these
1091
- * blocks publication.
1092
- *
1093
- * The list is deliberately short and enumerated, because the contract is to
1094
- * block *known* failures. Nonessential differences require an assessment of
1095
- * emitted values: a concrete risk warns, expected differences and unverified
1096
- * behavior remain compatibility observations.
1097
- */
1098
- const ESSENTIAL_CONSTRUCTS = /* @__PURE__ */ new Set([
1099
- "<table> element",
1100
- "<div> element",
1101
- "<p> element",
1102
- "<span> element",
1103
- "<ul>, <ol> and <dl>",
1104
- "<h1> to <h6> elements",
1105
- "HTML5 doctype",
1106
- "width attribute",
1107
- "height attribute",
1108
- "align attribute",
1109
- "valign attribute",
1110
- "<img> element",
1111
- "display",
1112
- "mailto: links",
1113
- "Local anchors"
1114
- ]);
1115
- const KNOWN_TITLES = new Set(rawData.data.map((feature) => feature.title));
1116
- /** The innermost recorded node containing an offset, so a finding names its element. */
1117
- const originsAt = (positions, offset) => {
1118
- let best;
1119
- for (const position of positions) {
1120
- if (offset < position.start || offset >= position.end) continue;
1121
- if (best === void 0 || position.end - position.start < best.end - best.start) best = position;
1122
- }
1123
- return best?.origins ?? [];
1124
- };
1125
- const slug = (title) => title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1126
- /**
1127
- * Check the emitted document against the pinned matrix.
1128
- *
1129
- * Findings are grouped by construct rather than repeated per client, so one
1130
- * unsupported property is one diagnostic naming every client that drops it.
1131
- */
1132
- const checkEmailCompatibility = (input) => {
1133
- const targets = input.clients ?? EMAIL_CLIENT_MATRIX;
1134
- const context = compatibilityContext(input.html, input.css);
1135
- const targetClients = targets.map((target) => target.id);
1136
- const reports = [caniemail({
1137
- clients: targetClients,
1138
- html: input.html
1139
- }), ...input.css === void 0 ? [] : [caniemail({
1140
- clients: targetClients,
1141
- css: input.css
1142
- })]];
1143
- const grouped = /* @__PURE__ */ new Map();
1144
- for (const bucket of reports.flatMap((report) => [report.issues.errors, report.issues.warnings])) for (const [client, issues] of bucket) {
1145
- const label = LABELS.get(client) ?? client;
1146
- for (const raw of issues) {
1147
- const hiddenContentFailure = client === "outlook.windows" && raw.support === "partial" && (raw.title === "display" || raw.title === "display:none") && context.hiddenContentOffsets.length > 0;
1148
- const blocking = hiddenContentFailure || raw.support !== "partial" && ESSENTIAL_CONSTRUCTS.has(raw.title);
1149
- const { explanation, ...compatibility } = assessCompatibility(raw.title, client, raw.support, context, blocking);
1150
- const key = JSON.stringify([
1151
- raw.title,
1152
- raw.support,
1153
- compatibility,
1154
- explanation
1155
- ]);
1156
- const offsets = hiddenContentFailure ? context.hiddenContentOffsets : context.offsets(raw.title);
1157
- const entry = grouped.get(key);
1158
- if (entry === void 0) grouped.set(key, {
1159
- title: raw.title,
1160
- support: raw.support,
1161
- clients: /* @__PURE__ */ new Set([label]),
1162
- notes: new Set(raw.notes),
1163
- explanation,
1164
- compatibility,
1165
- blocking,
1166
- offsets
1167
- });
1168
- else {
1169
- entry.clients.add(label);
1170
- for (const note of raw.notes) entry.notes.add(note);
1171
- }
1172
- }
1173
- }
1174
- const findings = [];
1175
- for (const entry of grouped.values()) {
1176
- const severity = entry.blocking ? "error" : entry.compatibility.assessment === "risk" ? "warning" : "info";
1177
- const occurrences = entry.offsets.map((offset) => originsAt(input.positions ?? [], offset)).filter((origins) => origins.length > 0);
1178
- const clients = [...entry.clients].sort();
1179
- const dropped = entry.support === "partial" ? clients.length === 1 ? "partially supports" : "partially support" : clients.length === 1 ? "does not support" : "do not support";
1180
- findings.push({
1181
- code: `caniemail/${slug(entry.title)}`,
1182
- severity,
1183
- message: `${clients.join(", ")} ${dropped} ${entry.title}. ${entry.explanation}`,
1184
- compatibility: entry.compatibility,
1185
- origins: occurrences[0] ?? [],
1186
- ...occurrences.length === 0 ? {} : { occurrences },
1187
- ...input.fixture === void 0 ? {} : { fixtures: [input.fixture] },
1188
- clients,
1189
- ...entry.notes.size === 0 ? {} : { notes: [...entry.notes].join(" ") },
1190
- provenance: `${COMPATIBILITY_PROVENANCE.rules} (caniemail data ${COMPATIBILITY_PROVENANCE.apiVersion}, updated ${COMPATIBILITY_PROVENANCE.lastUpdate})`
1191
- });
1192
- }
1193
- findings.push(...checkEmailContrast(input));
1194
- return findings.sort((left, right) => left.code.localeCompare(right.code));
1195
- };
1196
- /**
1197
- * Constructs the pinned data says nothing about for a target client. These are
1198
- * reported so "we did not check that" is never mistaken for "that works".
1199
- */
1200
- const unknownCoverage = (titles) => [...titles].filter((title) => !KNOWN_TITLES.has(title)).sort().map((title) => ({
1201
- code: "caniemail/unknown-coverage",
1202
- severity: "info",
1203
- message: `The pinned rules say nothing about ${title}, so no client claim is made about it. Verify it in a real client before relying on it.`,
1204
- origins: [],
1205
- provenance: `${COMPATIBILITY_PROVENANCE.rules} (caniemail data ${COMPATIBILITY_PROVENANCE.apiVersion}, updated ${COMPATIBILITY_PROVENANCE.lastUpdate})`
1206
- }));
1207
- /** A publication carrying one of these is refused; the message would arrive broken. */
1208
- const hasBlockingCompatibility = (findings) => findings.some((finding) => finding.severity === "error");
1209
- //#endregion
1210
17
  //#region src/email/tailwind-stylesheets.gen.ts
1211
18
  /** The exact Tailwind release the compiler runs, recorded in every build manifest. */
1212
19
  const TAILWIND_VERSION = "4.3.3";
@@ -1324,7 +131,7 @@ const compileTailwind = async (candidates, options = {}, imports = { stylesheets
1324
131
  base,
1325
132
  content: builtIn
1326
133
  });
1327
- if (parseBrandSpecifier(id, imports.brandPlugin) !== void 0) {
134
+ if (parseBrandSpecifier(id, { brandPlugin: imports.brandPlugin }) !== void 0) {
1328
135
  if (imports.brandCss === void 0) throw new TypeError(`${id} has no brand in this build`);
1329
136
  return Promise.resolve({
1330
137
  path: id,
@@ -1526,7 +333,9 @@ const scriptBrandImports = (path, source, plugin) => {
1526
333
  * the project imports no brand. A project that names two brands gets the
1527
334
  * first here and a refusal from the compile.
1528
335
  */
1529
- const projectBrandSpecifier = (files, themePath = "theme.css", brandPlugin = samvaBrandPlugin) => {
336
+ const projectBrandSpecifier = (files, options = {}) => {
337
+ const themePath = options.themePath ?? "theme.css";
338
+ const brandPlugin = options.brandPlugin ?? samvaBrandPlugin;
1530
339
  const theme = files[themePath];
1531
340
  const fromTheme = typeof theme === "string" ? resolveThemeImports(themePath, theme, files, brandPlugin).brandSpecifiers : [];
1532
341
  const fromScripts = Object.keys(files).sort().filter((path) => SCRIPT.test(path) && typeof files[path] === "string").flatMap((path) => scriptBrandImports(path, files[path], brandPlugin)).map((request) => request.specifier);
@@ -1565,7 +374,7 @@ const resolveTheme = (files, tailwind, brand, brandPlugin) => {
1565
374
  });
1566
375
  else if (specifiers.length === 1) {
1567
376
  const specifier = specifiers[0];
1568
- const named = parseBrandSpecifier(specifier, brandPlugin)?.slug;
377
+ const named = parseBrandSpecifier(specifier, { brandPlugin })?.slug;
1569
378
  const origins = [requests[0].origin];
1570
379
  if (brand === void 0) refusals.push({
1571
380
  code: "brand-unavailable",
@@ -1649,66 +458,8 @@ const transformProject = async (files, options) => {
1649
458
  };
1650
459
  };
1651
460
  //#endregion
1652
- //#region src/email/brand-footer.ts
1653
- /** The brand theme as Tailwind compiles it; a theme outside the grammar is a compile refusal. */
1654
- const brandTheme = (brand, plugin) => {
1655
- const parsed = parseBrandCss(brand.css);
1656
- if (parsed.isErr()) throw new EmailCompileError({ diagnostics: parsed.error.map((finding) => ({
1657
- code: finding.code,
1658
- severity: "error",
1659
- message: `${plugin.specifier}: ${finding.message}`,
1660
- origins: []
1661
- })) });
1662
- return printBrandCss(parsed.value);
1663
- };
1664
- /**
1665
- * Render `BrandFooter` against a brand on its own, for the send path to
1666
- * append to a message whose template renders no footer of its own. It
1667
- * compiles the same component, styled by the same brand theme, a template
1668
- * would get from its brand import. Without `unsubscribe` the unsubscribe row is
1669
- * left out.
1670
- */
1671
- const renderBrandFooter = async (brand, options) => {
1672
- const plugin = options.brandPlugin ?? samvaBrandPlugin;
1673
- const tailwind = await compileTailwind(BRAND_COMPONENT_CLASSES, { css: brandTheme(brand, plugin) });
1674
- const node = brandComponents(brand, plugin).BrandFooter({});
1675
- if (node === null) return {
1676
- html: "",
1677
- text: "",
1678
- headCss: ""
1679
- };
1680
- const styled = applyStylesheet(node, parseStylesheet(tailwind.css, { origin: plugin.specifier }));
1681
- const compiled = compileEmail(styled.tree, { brandPlugin: plugin });
1682
- const rendered = options.unsubscribe ? compiled : withoutUnsubscribeRow({
1683
- html: compiled.html,
1684
- text: compiled.text
1685
- }, plugin);
1686
- const text = (rendered.text ?? "").trim();
1687
- return {
1688
- html: rendered.html ?? "",
1689
- text: text === "" ? "" : `\n\n---\n${text}`,
1690
- headCss: `${renderDarkRules(styled.darkRules)}${styled.headCss}`
1691
- };
1692
- };
1693
- /**
1694
- * Render content against a brand as a project whose `theme.css` imports only
1695
- * the brand renders it: Tailwind compiles the brand theme for
1696
- * the classes the content names, `BrandLogo` and `BrandFooter` are bound to the
1697
- * brand, and the render inlines the result. A brand preview renders through
1698
- * this, so it shows what a template importing the brand compiles to.
1699
- */
1700
- const renderBrandSample = async (brand, sample, brandPlugin = samvaBrandPlugin) => {
1701
- const tailwind = await compileTailwind([...BRAND_COMPONENT_CLASSES, ...sample.classes], { css: `@import ${JSON.stringify(brandPlugin.specifier)};` }, {
1702
- stylesheets: /* @__PURE__ */ new Map(),
1703
- brandCss: brandTheme(brand, brandPlugin),
1704
- brandPlugin
1705
- });
1706
- const components = brandComponents(brand, brandPlugin);
1707
- return renderEmailContent(parseStylesheet(tailwind.css, { origin: brandPlugin.specifier }), () => sample.render(components), { brandPlugin });
1708
- };
1709
- //#endregion
1710
461
  //#region src/sml/compile.ts
1711
- /** Compile a project's entry template to IR without evaluating any of it. */
462
+ /** Compile a project's entry template without evaluating any of it. */
1712
463
  const compileTemplate = async (options) => {
1713
464
  const findings = new Findings();
1714
465
  const project = loadProject(options.files, options.entry, findings, { brandPlugin: options.brandPlugin ?? samvaBrandPlugin });
@@ -1734,38 +485,251 @@ const compileTemplate = async (options) => {
1734
485
  });
1735
486
  };
1736
487
  //#endregion
1737
- //#region src/sml/compatibility.ts
488
+ //#region src/email/text.ts
489
+ const PARAGRAPH = "\n\n";
490
+ const LINE = "\n";
491
+ const INVISIBLE = /\u200b|\u200c|\u200d|\u200e|\u200f|\u2060|\ufeff/g;
492
+ const isLayoutTable = (props) => props.role === "presentation" || props.role === "none";
1738
493
  /**
1739
- * Check what each declared fixture delivers against the pinned client matrix. The rules run on the
1740
- * rendered document, because what a client drops is what the compiler produced, and every finding
1741
- * is located at the source of the element that produced it.
494
+ * A data-table cell that reads as nothing and holds only imagery with empty alt text carries no
495
+ * column of its own; an empty cell without such an image is a positional placeholder.
1742
496
  */
1743
- const checkTemplateCompatibility = (ir, fixtures, options = {}) => {
1744
- if (ir.email === void 0) return [];
1745
- const sources = ir.sources ?? [];
1746
- const findings = [];
1747
- for (const [fixture, input] of Object.entries(fixtures)) {
1748
- const rendered = renderIr(ir, input, { positions: true });
1749
- const positions = (rendered.positions ?? []).map((position, index) => ({
1750
- start: position.start,
1751
- end: position.end,
1752
- tag: position.tag,
1753
- instancePath: String(index),
1754
- authored: true,
1755
- origins: position.src === void 0 ? [] : [{
1756
- fileName: sources[position.src[2] ?? 0] ?? "",
1757
- lineNumber: position.src[0],
1758
- columnNumber: position.src[1]
1759
- }]
1760
- }));
1761
- findings.push(...checkEmailCompatibility({
1762
- html: rendered.html,
1763
- fixture,
1764
- positions,
1765
- ...options.clients === void 0 ? {} : { clients: options.clients }
1766
- }));
497
+ const isDecorativeCell = (cell, context) => {
498
+ const images = collect(cell.children, (tag) => tag === "img", () => true);
499
+ return images.length > 0 && images.every((image) => image.props.alt === "") && childText(cell, context).trim() === "";
500
+ };
501
+ /** Wrap a block's content in separators; empty blocks contribute nothing. */
502
+ const block = (inner, separator) => {
503
+ const trimmed = inner.replace(/^\s+/, "").replace(/\s+$/, "");
504
+ return trimmed === "" ? "" : `${separator}${trimmed}${separator}`;
505
+ };
506
+ const collect = (nodes, keep, descend) => nodes.flatMap((child) => {
507
+ if (child.type === "Fragment") return collect(child.children, keep, descend);
508
+ if (child.type !== "Element") return [];
509
+ if (keep(child.tag)) return [child];
510
+ return descend(child.tag) ? collect(child.children, keep, descend) : [];
511
+ });
512
+ const TABLE_SECTIONS = /* @__PURE__ */ new Set([
513
+ "thead",
514
+ "tbody",
515
+ "tfoot"
516
+ ]);
517
+ const childText = (node, context) => node.children.map((child) => derive(child, context)).join("");
518
+ const derive = (node, context) => {
519
+ switch (node.type) {
520
+ case "Text": return context.preformatted ? node.value : node.value.replace(INVISIBLE, "").replace(/[^\S\n]+/g, " ");
521
+ case "Raw": return node.text;
522
+ case "Fragment": return node.children.map((child) => derive(child, context)).join("");
523
+ case "Element": {
524
+ const spec = emailElement(node.tag);
525
+ if (spec === void 0) return childText(node, context);
526
+ switch (spec.layout) {
527
+ case "metadata": return "";
528
+ case "document":
529
+ case "inline":
530
+ case "list-item": return childText(node, context);
531
+ case "break": return LINE;
532
+ case "rule": return `${PARAGRAPH}---${PARAGRAPH}`;
533
+ case "image": {
534
+ const alt = typeof node.props.alt === "string" ? node.props.alt.trim() : "";
535
+ return alt === "" ? "" : `[${alt}]`;
536
+ }
537
+ case "link": {
538
+ const label = childText(node, context).replace(/\s+/g, " ").trim();
539
+ const href = typeof node.props.href === "string" ? node.props.href : "";
540
+ if (href === "" || href === label) return label;
541
+ return label === "" ? href : `${label} (${href})`;
542
+ }
543
+ case "list": {
544
+ const indent = " ".repeat(context.listDepth);
545
+ const start = Number(node.props.start ?? 1);
546
+ const first = Number.isFinite(start) ? start : 1;
547
+ const nested = {
548
+ ...context,
549
+ listDepth: context.listDepth + 1
550
+ };
551
+ const lines = collect(node.children, (tag) => tag === "li", () => false).map((item, index) => {
552
+ const marker = node.tag === "ol" ? `${first + index}.` : "-";
553
+ const continuation = `${indent}${" ".repeat(marker.length + 1)}`;
554
+ const [head = "", ...rest] = derive(item, nested).replace(/^\s+/, "").replace(/\s+$/, "").replace(/\n{2,}/g, LINE).split("\n");
555
+ return [`${indent}${marker} ${head}`, ...rest.map((line) => line.trim() === "" ? "" : /^\s/.test(line) ? line : `${continuation}${line}`)].join(LINE);
556
+ });
557
+ return block(lines.join(LINE), PARAGRAPH);
558
+ }
559
+ case "table": {
560
+ if (isLayoutTable(node.props)) return childText(node, context);
561
+ const rows = collect(node.children, (tag) => tag === "tr", (tag) => TABLE_SECTIONS.has(tag)).map((row) => collect(row.children, (tag) => tag === "td" || tag === "th", () => false).filter((cell) => !isDecorativeCell(cell, context)).map((cell) => childText(cell, context).replace(/\s+/g, " ").trim()).join(" | "));
562
+ return block(rows.join(LINE), PARAGRAPH);
563
+ }
564
+ case "row": return block(collect(node.children, (tag) => tag === "td" || tag === "th", () => false).map((cell) => childText(cell, context).replace(/^\s+|\s+$/g, "")).filter((cell) => cell !== "").join(LINE), LINE);
565
+ case "table-section":
566
+ case "cell": return block(childText(node, context), LINE);
567
+ case "preformatted": return block(childText(node, {
568
+ ...context,
569
+ preformatted: true
570
+ }), PARAGRAPH);
571
+ case "block": return block(childText(node, context), PARAGRAPH);
572
+ }
573
+ }
574
+ }
575
+ };
576
+ /** Collapse the separators the walk emits into readable plain text. */
577
+ const normalize = (value) => value.replace(/\r\n?/g, "\n").split("\n").map((line) => line.replace(/[^\S\n]+$/, "")).join("\n").replace(/\n{3,}/g, PARAGRAPH).trim();
578
+ /** Derive the plain-text alternative from the semantic tree in reading order. */
579
+ const deriveEmailText = (node) => normalize(derive(node, {
580
+ preformatted: false,
581
+ listDepth: 0
582
+ }));
583
+ //#endregion
584
+ //#region src/email/render.ts
585
+ /**
586
+ * Lower the derived tree to HTML and its plain-text alternative. A blocking finding leaves no
587
+ * output; every finding comes back in `diagnostics`.
588
+ */
589
+ const lowerEmail = (node, options = {}) => {
590
+ const serialized = serializeEmailHtml(node, options);
591
+ const diagnostics = [...collectEmailDiagnostics(node), ...serialized.diagnostics];
592
+ if (hasBlockingDiagnostic(diagnostics)) return {
593
+ output: void 0,
594
+ diagnostics
595
+ };
596
+ return {
597
+ output: {
598
+ html: serialized.html,
599
+ text: deriveEmailText(node),
600
+ diagnostics,
601
+ positions: serialized.positions
602
+ },
603
+ diagnostics
604
+ };
605
+ };
606
+ //#endregion
607
+ //#region src/email/footer.ts
608
+ const EMPTY_FOOTER = {
609
+ html: "",
610
+ text: "",
611
+ headCss: ""
612
+ };
613
+ /**
614
+ * Compile `BrandFooter` against a brand on its own, for the send path to append to a message
615
+ * whose template renders no footer of its own. It compiles the same component, styled by the same
616
+ * brand theme, a template would get from its brand import. The footer always carries the
617
+ * unsubscribe row; the send drops it with `withoutUnsubscribeRow` from `./brand` where the message
618
+ * has none. A brand theme outside the grammar leaves no footer and comes back as diagnostics.
619
+ */
620
+ const compileFooter = async (brand, options = {}) => {
621
+ const plugin = options.brandPlugin ?? samvaBrandPlugin;
622
+ const theme = parseBrandCss(brand.css);
623
+ if (theme.isErr()) return {
624
+ footer: void 0,
625
+ diagnostics: theme.error.map((finding) => ({
626
+ code: finding.code,
627
+ severity: "error",
628
+ message: `${plugin.specifier}: ${finding.message}`,
629
+ origins: []
630
+ }))
631
+ };
632
+ const tailwind = await compileTailwind(BRAND_COMPONENT_CLASSES, { css: printBrandCss(theme.value) });
633
+ const node = brandComponents(brand, plugin).BrandFooter({});
634
+ if (node === null) return {
635
+ footer: EMPTY_FOOTER,
636
+ diagnostics: []
637
+ };
638
+ const styled = applyStylesheet(node, parseStylesheet(tailwind.css, { origin: plugin.specifier }));
639
+ const lowered = lowerEmail(styled.tree, { brandPlugin: plugin });
640
+ const diagnostics = [...styled.diagnostics, ...lowered.diagnostics];
641
+ if (lowered.output === void 0 || hasBlockingDiagnostic(diagnostics)) return {
642
+ footer: void 0,
643
+ diagnostics
644
+ };
645
+ const text = lowered.output.text.trim();
646
+ return {
647
+ footer: {
648
+ html: lowered.output.html,
649
+ text: text === "" ? "" : `\n\n---\n${text}`,
650
+ headCss: `${renderDarkRules(styled.darkRules)}${styled.headCss}`
651
+ },
652
+ diagnostics
653
+ };
654
+ };
655
+ //#endregion
656
+ //#region src/email/brand-preview.ts
657
+ const ENTRY = "sample.tsx";
658
+ const sampleSource = (plugin) => `import { defineTemplate } from "@samva/markup";
659
+ import { Email, Section } from "@samva/markup/email";
660
+ import { jsonSchema } from "@samva/markup/input-schema";
661
+ import { BrandFooter, BrandLogo } from ${JSON.stringify(plugin.specifier)};
662
+
663
+ export default defineTemplate({
664
+ id: "brand-preview",
665
+ schema: jsonSchema({ type: "object", properties: {} }),
666
+ fixtures: { default: {} },
667
+ email: {
668
+ subject: () => "Your order is on its way",
669
+ body: () => (
670
+ <Email className="bg-background font-sans">
671
+ <Section style={{ padding: "32px 24px" }}>
672
+ <BrandLogo />
673
+ <h1 className="text-2xl font-semibold text-foreground font-heading">Your order is on its way</h1>
674
+ <p className="text-base text-foreground font-sans">
675
+ Thanks for your order. Here is a quick summary, and a link to follow it to your door.
676
+ </p>
677
+ <div className="p-4 rounded bg-card text-card-foreground">
678
+ <p className="inline-block px-2 py-1 text-sm font-semibold rounded bg-accent text-accent-foreground">
679
+ Order 1042
680
+ </p>
681
+ <p className="text-sm text-muted-foreground">2 items, arriving Thursday</p>
682
+ </div>
683
+ <p>
684
+ <a
685
+ href="https://example.com/orders/1042"
686
+ className="inline-block px-6 py-3 font-semibold no-underline rounded bg-primary text-primary-foreground"
687
+ >
688
+ Track your order
689
+ </a>
690
+ </p>
691
+ </Section>
692
+ <BrandFooter />
693
+ </Email>
694
+ ),
695
+ },
696
+ });
697
+ `;
698
+ const previewBrand = async (brand, options = {}) => {
699
+ const plugin = options.brandPlugin ?? samvaBrandPlugin;
700
+ const compiled = await compileTemplate({
701
+ files: { [ENTRY]: sampleSource(plugin) },
702
+ entry: ENTRY,
703
+ assetBase: "/",
704
+ tailwind: { css: `@import ${JSON.stringify(plugin.specifier)};` },
705
+ brand,
706
+ brandPlugin: plugin
707
+ });
708
+ if (compiled.template === void 0) return {
709
+ html: void 0,
710
+ diagnostics: compiled.diagnostics
711
+ };
712
+ try {
713
+ const { html } = render(compiled.template, {}, {
714
+ channel: "email",
715
+ brandPlugin: plugin
716
+ });
717
+ return {
718
+ html,
719
+ diagnostics: compiled.diagnostics
720
+ };
721
+ } catch (cause) {
722
+ if (!RenderError.is(cause)) throw cause;
723
+ return {
724
+ html: void 0,
725
+ diagnostics: [...compiled.diagnostics, ...cause.diagnostics.map((finding) => ({
726
+ code: finding.code,
727
+ severity: "error",
728
+ message: finding.message,
729
+ origins: []
730
+ }))]
731
+ };
1767
732
  }
1768
- return findings;
1769
733
  };
1770
734
  //#endregion
1771
- export { COMPATIBILITY_PROVENANCE, EMAIL_CLIENT_MATRIX, ESSENTIAL_CONSTRUCTS, TAILWIND_VERSION, TEMPLATE_NAME_PATTERN, applyStylesheet, checkEmailCompatibility, checkStaticProfile, checkTemplateCompatibility, classListOf, compileSelector, compileTailwind, compileTemplate, discoverClassCandidates, downlevelColors, downlevelMediaQuery, finalizeValue, foldCalc, formatColor, hasBlockingCompatibility, introducedProfileErrors, matchesSelector, parseBrandSpecifier, parseColor, parseStylesheet, projectBrandSpecifier, renderBrandFooter, renderBrandSample, renderHeadCss, resolveVariables, transformProject, unknownCoverage };
735
+ export { TEMPLATE_NAME_PATTERN, checkTemplate, compileFooter, compileTemplate, introducedErrors, parseBrandSpecifier, previewBrand, projectBrandSpecifier };