@emailens/cli 0.13.19 → 0.14.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.
@@ -0,0 +1,2264 @@
1
+ import { createRequire as __cr } from "node:module";
2
+ const require = __cr(import.meta.url);
3
+ import {
4
+ EMAIL_CLIENTS,
5
+ load,
6
+ resolveMsoBranch,
7
+ transformForClient
8
+ } from "./chunk-NGCLN4RF.js";
9
+ import {
10
+ __spreadProps,
11
+ __spreadValues
12
+ } from "./chunk-JKHKS7VL.js";
13
+ import "./chunk-K6T7YHQE.js";
14
+
15
+ // node_modules/@emailens/engine/dist/design/index.js
16
+ import { mkdirSync, readFileSync, writeFileSync, existsSync } from "fs";
17
+ import { homedir } from "os";
18
+ import { join } from "path";
19
+ var keyOf = (n) => n.text ? `t:${n.text}` : n.tag === "img" ? "img" : null;
20
+ function matchNodes(real, sim) {
21
+ const a = real.filter(keyOf);
22
+ const b = sim.filter(keyOf);
23
+ const ka = a.map(keyOf);
24
+ const kb = b.map(keyOf);
25
+ const L = Array.from(
26
+ { length: a.length + 1 },
27
+ () => new Uint16Array(b.length + 1)
28
+ );
29
+ for (let i2 = a.length - 1; i2 >= 0; i2--)
30
+ for (let j2 = b.length - 1; j2 >= 0; j2--)
31
+ L[i2][j2] = ka[i2] === kb[j2] ? L[i2 + 1][j2 + 1] + 1 : Math.max(L[i2 + 1][j2], L[i2][j2 + 1]);
32
+ const pairs = [];
33
+ const realOnly = [];
34
+ const simOnly = [];
35
+ let i = 0;
36
+ let j = 0;
37
+ while (i < a.length && j < b.length) {
38
+ if (ka[i] === kb[j]) pairs.push([a[i++], b[j++]]);
39
+ else if (L[i + 1][j] >= L[i][j + 1]) realOnly.push(a[i++]);
40
+ else simOnly.push(b[j++]);
41
+ }
42
+ realOnly.push(...a.slice(i));
43
+ simOnly.push(...b.slice(j));
44
+ return { pairs, realOnly, simOnly };
45
+ }
46
+ var PX = /^(-?[\d.]+)px$/;
47
+ var family = (v) => v.toLowerCase().replace(/["'\s]/g, "");
48
+ function sameValue(prop, a, b) {
49
+ if (prop === "font-family") return family(a) === family(b);
50
+ const [pa, pb] = [PX.exec(a), PX.exec(b)];
51
+ if (pa && pb) return Math.abs(Number(pa[1]) - Number(pb[1])) <= 0.5;
52
+ return a === b;
53
+ }
54
+ async function markPictures(root, nodes) {
55
+ const els = [...root.querySelectorAll("*")];
56
+ const url = (el) => {
57
+ var _a, _b;
58
+ return (_b = ((_a = el.ownerDocument.defaultView) != null ? _a : window).getComputedStyle(el).backgroundImage.match(/^url\("?(.*?)"?\)$/)) == null ? void 0 : _b[1];
59
+ };
60
+ const tries = /* @__PURE__ */ new Map();
61
+ const decodes = (src) => {
62
+ if (!tries.has(src)) {
63
+ const img = new Image();
64
+ img.src = src;
65
+ const timeout = new Promise(
66
+ (r) => setTimeout(() => r(false), 5e3)
67
+ );
68
+ tries.set(
69
+ src,
70
+ Promise.race([
71
+ img.decode().then(
72
+ () => true,
73
+ () => false
74
+ ),
75
+ timeout
76
+ ])
77
+ );
78
+ }
79
+ return tries.get(src);
80
+ };
81
+ await Promise.all(
82
+ els.map(async (el, i) => {
83
+ const src = url(el);
84
+ if (src) nodes[i].picture = await decodes(src);
85
+ })
86
+ );
87
+ return nodes;
88
+ }
89
+ function dumpDom(root) {
90
+ var _a, _b, _c;
91
+ const PROPS = [
92
+ "display",
93
+ "visibility",
94
+ "position",
95
+ "float",
96
+ "width",
97
+ "height",
98
+ "max-width",
99
+ "margin-top",
100
+ "margin-right",
101
+ "margin-bottom",
102
+ "margin-left",
103
+ "padding-top",
104
+ "padding-right",
105
+ "padding-bottom",
106
+ "padding-left",
107
+ "border-top-width",
108
+ "border-top-style",
109
+ "border-top-color",
110
+ "border-radius",
111
+ "font-family",
112
+ "font-size",
113
+ "font-weight",
114
+ "font-style",
115
+ "line-height",
116
+ "letter-spacing",
117
+ "text-align",
118
+ "text-decoration-line",
119
+ "text-transform",
120
+ "vertical-align",
121
+ "color",
122
+ "background-color",
123
+ "background-image",
124
+ "background-size",
125
+ "box-shadow",
126
+ "opacity"
127
+ ];
128
+ const view = (_a = root.ownerDocument.defaultView) != null ? _a : window;
129
+ const origin = root.getBoundingClientRect();
130
+ const out = [];
131
+ for (const el of root.querySelectorAll("*")) {
132
+ const r = el.getBoundingClientRect();
133
+ const cs = view.getComputedStyle(el);
134
+ const style = {};
135
+ for (const p of PROPS) style[p] = cs.getPropertyValue(p);
136
+ let own = "";
137
+ for (const c of el.childNodes) if (c.nodeType === 3) own += c.textContent;
138
+ const node = {
139
+ tag: el.tagName.toLowerCase(),
140
+ text: own.replace(/\s+/g, " ").trim().slice(0, 80),
141
+ x: Math.round((r.left - origin.left) * 10) / 10,
142
+ y: Math.round((r.top - origin.top) * 10) / 10,
143
+ w: Math.round(r.width * 10) / 10,
144
+ h: Math.round(r.height * 10) / 10,
145
+ style,
146
+ inline: (_b = el.getAttribute("style")) != null ? _b : ""
147
+ };
148
+ if (el.tagName === "IMG")
149
+ node.src = ((_c = el.getAttribute("src")) != null ? _c : "").split(/[?#]/)[0].split("/").pop();
150
+ out.push(node);
151
+ }
152
+ return out;
153
+ }
154
+ var ASPECTS = {
155
+ // max-width is not listed: what it does shows in the width (an image's
156
+ // max-width:100% read as a change on every image, 2026-11-11).
157
+ layout: ["display", "float", "width", "text-align"],
158
+ spacing: [
159
+ "padding-top",
160
+ "padding-right",
161
+ "padding-bottom",
162
+ "padding-left",
163
+ "margin-top",
164
+ "margin-right",
165
+ "margin-bottom",
166
+ "margin-left"
167
+ ],
168
+ corners: ["border-radius"],
169
+ borders: ["border-top-width", "border-top-style", "border-top-color"],
170
+ color: ["color", "background-color", "background-image"],
171
+ type: [
172
+ "font-family",
173
+ "font-size",
174
+ "font-weight",
175
+ "font-style",
176
+ "line-height",
177
+ "letter-spacing",
178
+ "text-transform"
179
+ ],
180
+ effects: ["box-shadow", "opacity"]
181
+ };
182
+ var drawn = (n) => n.w > 0 && n.h > 0;
183
+ var picture = (n) => {
184
+ var _a;
185
+ return (_a = n.style["background-image"].match(/([^/"()]+)"?\)$/)) == null ? void 0 : _a[1];
186
+ };
187
+ var label = (n) => n.text || n.src || picture(n) || n.tag;
188
+ function pictured(design, client, paired) {
189
+ const free = client.filter((c) => c.style["background-image"] !== "none");
190
+ return design.flatMap((d) => {
191
+ if (paired.has(d) || !d.picture) return [];
192
+ const i = free.findIndex(
193
+ (c) => c.style["background-image"] === d.style["background-image"]
194
+ );
195
+ return i < 0 ? [] : [[d, free.splice(i, 1)[0]]];
196
+ });
197
+ }
198
+ var CLEAR = /^(rgba\(0, 0, 0, 0\)|transparent)$/;
199
+ var cornerShows = (n) => !CLEAR.test(n.style["background-color"]) || n.style["background-image"] !== "none" || n.style["border-top-width"] !== "0px";
200
+ var PX2 = /^(-?[\d.]+)px$/;
201
+ var near = (a, b) => {
202
+ const [pa, pb] = [PX2.exec(a), PX2.exec(b)];
203
+ if (!pa || !pb) return false;
204
+ const [x, y] = [Number(pa[1]), Number(pb[1])];
205
+ return Math.abs(x - y) <= Math.max(0.5, 0.02 * Math.max(Math.abs(x), Math.abs(y)));
206
+ };
207
+ function differs(aspect, p, d, c) {
208
+ const [dv, cv] = [d.style[p], c.style[p]];
209
+ if (dv === void 0 || cv === void 0 || sameValue(p, dv, cv) || near(dv, cv))
210
+ return false;
211
+ if (aspect === "type") return d.text !== "";
212
+ return aspect !== "corners" || cornerShows(d) || cornerShows(c);
213
+ }
214
+ function changedOf(pairs) {
215
+ var _a;
216
+ const changed = {};
217
+ for (const [d, c] of pairs)
218
+ for (const [aspect, props] of Object.entries(ASPECTS))
219
+ for (const p of props) {
220
+ if (!differs(aspect, p, d, c)) continue;
221
+ const [dv, cv] = [d.style[p], c.style[p]];
222
+ (_a = changed[aspect]) != null ? _a : changed[aspect] = {
223
+ count: 0,
224
+ example: { text: label(d), prop: p, design: dv, client: cv }
225
+ };
226
+ changed[aspect].count++;
227
+ }
228
+ return changed;
229
+ }
230
+ var apart = (a, b) => a.x + a.w <= b.x + 1 || b.x + b.w <= a.x + 1;
231
+ var besides = (a, b) => {
232
+ const shared = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
233
+ return apart(a, b) && shared >= Math.min(a.h, b.h) / 2;
234
+ };
235
+ function columnsOf(boxes) {
236
+ const rows = boxes.flatMap(
237
+ (p, i) => boxes.slice(i + 1).filter((q) => besides(p[0], q[0])).map((q) => [p, q])
238
+ );
239
+ const kept = rows.filter(([p, q]) => apart(p[1], q[1]));
240
+ return rows.length ? kept.length / rows.length : 1;
241
+ }
242
+ var left = (ns) => Math.min(...ns.map((n) => n.x));
243
+ var extent = (ns) => ns.length ? Math.max(...ns.map((n) => n.x + n.w)) - left(ns) : 1;
244
+ var filled = (n) => !CLEAR.test(n.style["background-color"]) || n.style["background-image"] !== "none";
245
+ var MOVED = 0.03;
246
+ var [SMALLER, LARGER] = [0.8, 1.2];
247
+ var FAR_MOVED = 0.15;
248
+ var FAR_RESIZED = 0.5;
249
+ var across = (n, f) => (n.x + n.w / 2 - f.x0) / f.w;
250
+ var pct = (v) => `centre at ${Math.round(v * 100)}%`;
251
+ function componentsOf(boxes, fd, fc, zoom) {
252
+ return boxes.flatMap(([d, c]) => [
253
+ ...d.tag === "img" || cornerShows(d) ? placed(d, c, fd, fc, zoom) : [],
254
+ ...painted(d, c)
255
+ ]);
256
+ }
257
+ function seen(n, all, colour, f) {
258
+ const box = all.filter(
259
+ (o) => drawn(o) && o.style["background-color"] === colour && o.w <= f.w / 2 && holds(o, n)
260
+ ).reduce((a, o) => a.w * a.h >= o.w * o.h ? a : o, n);
261
+ return box === n ? n : __spreadProps(__spreadValues({}, box), { text: n.text, src: n.src });
262
+ }
263
+ function asSeen(pairs, design, client, fd, fc) {
264
+ return pairs.map(([d, c]) => {
265
+ const colour = d.style["background-color"];
266
+ if (d.tag === "img" || !d.text || CLEAR.test(colour)) return [d, c];
267
+ return [seen(d, design, colour, fd), seen(c, client, colour, fc)];
268
+ });
269
+ }
270
+ function placed(d, c, fd, fc, zoom) {
271
+ const out = [];
272
+ const text = label(d);
273
+ const [ad, ac] = [across(d, fd), across(c, fc)];
274
+ const off = +Math.abs(ad - ac).toFixed(4);
275
+ if (off > MOVED)
276
+ out.push({
277
+ text,
278
+ kind: "moved",
279
+ design: pct(ad),
280
+ client: pct(ac),
281
+ breaks: off > FAR_MOVED
282
+ });
283
+ const cw = c.w / zoom;
284
+ if (cw / d.w < SMALLER || cw / d.w > LARGER)
285
+ out.push({
286
+ text,
287
+ kind: "resized",
288
+ design: `${Math.round(d.w)}px`,
289
+ client: `${Math.round(cw)}px`,
290
+ breaks: Math.abs(Math.log(cw / d.w)) > FAR_RESIZED
291
+ });
292
+ return out;
293
+ }
294
+ var holds = (o, n) => o.x <= n.x + 0.5 && o.y <= n.y + 0.5 && o.x + o.w >= n.x + n.w - 0.5 && o.y + o.h >= n.y + n.h - 0.5;
295
+ var smallest = (ns) => ns.reduce(
296
+ (a, n) => a && a.w * a.h <= n.w * n.h ? a : n,
297
+ void 0
298
+ );
299
+ var [INSET, FLUSH] = [8, 2];
300
+ function insetOf(n, all, f) {
301
+ var _a;
302
+ const fills = all.filter((o) => drawn(o) && filled(o) && holds(o, n));
303
+ const colour = (_a = smallest(fills)) == null ? void 0 : _a.style["background-color"];
304
+ const card = smallest(
305
+ fills.filter((o) => o.style["background-color"] !== colour)
306
+ );
307
+ const paint = fills.filter(
308
+ (o) => o.style["background-color"] === colour && (!card || holds(card, o))
309
+ ).reduce(
310
+ (a, o) => a && a.w * a.h >= o.w * o.h ? a : o,
311
+ void 0
312
+ );
313
+ if (!paint || !card || paint.w > f.w / 2) return void 0;
314
+ return Math.min(paint.x - card.x, card.x + card.w - paint.x - paint.w);
315
+ }
316
+ function flushOf(pairs, design, client, fd, fc, zoom) {
317
+ const out = /* @__PURE__ */ new Map();
318
+ for (const [d, c] of pairs) {
319
+ if (!d.text || out.has(label(d))) continue;
320
+ const di = insetOf(d, design, fd);
321
+ const ci = insetOf(c, client, fc);
322
+ if (di === void 0 || ci === void 0) continue;
323
+ if (di >= INSET && ci / zoom <= FLUSH)
324
+ out.set(label(d), {
325
+ text: label(d),
326
+ kind: "flush",
327
+ design: `${Math.round(di)}px`,
328
+ client: `${Math.round(ci / zoom)}px`,
329
+ // Also when the whole card's padding goes (Protocol in Outlook
330
+ // Classic, graded broken by the owner): the text touches the edge too.
331
+ breaks: true
332
+ });
333
+ }
334
+ return [...out.values()];
335
+ }
336
+ function painted(d, c) {
337
+ const out = [];
338
+ const text = label(d);
339
+ const fill = ["background-color", "background-image"].find(
340
+ (p) => !sameValue(p, d.style[p], c.style[p])
341
+ );
342
+ if (filled(d) && fill)
343
+ out.push({
344
+ text,
345
+ kind: "fill",
346
+ design: d.style[fill],
347
+ client: c.style[fill],
348
+ breaks: false
349
+ });
350
+ const [ds, cs] = [d.style["background-size"], c.style["background-size"]];
351
+ if (d.picture === true && ds !== void 0 && cs !== void 0 && ds !== cs)
352
+ out.push({
353
+ text,
354
+ kind: "resized",
355
+ design: `background-size: ${ds}`,
356
+ client: `background-size: ${cs}`,
357
+ breaks: true
358
+ });
359
+ if (differs("corners", "border-radius", d, c) && cornerShows(d))
360
+ out.push({
361
+ text,
362
+ kind: "corners",
363
+ design: d.style["border-radius"],
364
+ client: c.style["border-radius"],
365
+ breaks: false
366
+ });
367
+ return out;
368
+ }
369
+ function keptOf(design, client, zoom = 1) {
370
+ const { pairs, realOnly } = matchNodes(design, client);
371
+ const shown = pairs.filter(([d]) => drawn(d));
372
+ const kept = shown.filter(([, c]) => drawn(c));
373
+ const lost = [
374
+ ...realOnly.filter(drawn),
375
+ ...shown.filter(([, c]) => !drawn(c)).map(([d]) => d)
376
+ ];
377
+ const total = kept.length + lost.length;
378
+ const boxes = kept.filter(
379
+ ([d]) => d.tag === "img" || d.style.display !== "inline"
380
+ );
381
+ const sized = boxes.filter(([d]) => d.w > 2 && d.h > 2);
382
+ const [sd, sc] = [sized.map(([d]) => d), sized.map(([, c]) => c)];
383
+ const [fd, fc] = [
384
+ { x0: left(sd), w: extent(sd) },
385
+ { x0: left(sc), w: extent(sc) }
386
+ ];
387
+ const [wd, wc] = [fd.w, fc.w / zoom];
388
+ return {
389
+ content: total ? kept.length / total : 1,
390
+ columns: columnsOf(boxes),
391
+ width: Math.min(wd, wc) / Math.max(wd, wc),
392
+ changed: changedOf(kept),
393
+ lost: lost.map(label),
394
+ components: [
395
+ ...componentsOf(asSeen(sized, design, client, fd, fc), fd, fc, zoom),
396
+ ...flushOf(kept, design, client, fd, fc, zoom),
397
+ ...pictured(design, client, new Set(pairs.map(([d]) => d))).flatMap(
398
+ ([d, c]) => painted(d, c)
399
+ )
400
+ ]
401
+ };
402
+ }
403
+ var CONTENT = 0.95;
404
+ var COLUMNS = 0.9;
405
+ var WIDTH = 0.85;
406
+ var SAME = 0.025;
407
+ function verdictOf(k, pixelDiff) {
408
+ if (k.content < CONTENT || k.columns < COLUMNS || k.width < WIDTH || k.components.some((c) => c.breaks))
409
+ return "broken";
410
+ const looksSame = pixelDiff === void 0 ? !Object.keys(k.changed).length : pixelDiff < SAME;
411
+ return looksSame && !k.components.length ? "kept" : "changed";
412
+ }
413
+ function isEmail(html) {
414
+ var _a, _b;
415
+ const body = ((_b = (_a = /<body\b[\s\S]*/i.exec(html)) == null ? void 0 : _a[0]) != null ? _b : html).replace(
416
+ /<(script|style)\b[\s\S]*?<\/\1>/gi,
417
+ ""
418
+ );
419
+ return /<img\b/i.test(body) || /\S/.test(body.replace(/<[^>]*>/g, ""));
420
+ }
421
+ function hasDesign(html) {
422
+ const head = html.slice(0, 300);
423
+ return isEmail(html) && !/^\s*(---|import\s)|<extends|<x-|<mj-/.test(head) && !/<html[^>]*(⚡|amp)4email/i.test(head);
424
+ }
425
+ var SHOWN = 5;
426
+ var ASPECT_NAMES = {
427
+ layout: "Layout",
428
+ spacing: "Spacing",
429
+ corners: "Corners",
430
+ borders: "Borders",
431
+ color: "Colours",
432
+ type: "Text style",
433
+ effects: "Shadows and opacity"
434
+ };
435
+ var differs2 = (aspect) => `${ASPECT_NAMES[aspect]} ${/s$/.test(ASPECT_NAMES[aspect]) ? "differ" : "differs"}`;
436
+ var IMAGE = /\.(png|jpe?g|gif|webp|svg|avif)$/i;
437
+ var TAGS = /* @__PURE__ */ new Set([
438
+ "td",
439
+ "th",
440
+ "tr",
441
+ "table",
442
+ "div",
443
+ "a",
444
+ "span",
445
+ "p",
446
+ "center",
447
+ "section"
448
+ ]);
449
+ var short = (s) => s.length > 40 ? `${s.slice(0, 39)}\u2026` : s;
450
+ function fileName(src, max = 34) {
451
+ var _a, _b;
452
+ let name = src;
453
+ try {
454
+ name = decodeURIComponent(src);
455
+ } catch (e) {
456
+ }
457
+ const ext = (_b = (_a = IMAGE.exec(name)) == null ? void 0 : _a[1]) != null ? _b : "";
458
+ return name.length > max ? `${name.slice(0, max - 4)}\u2026${ext}` : name;
459
+ }
460
+ var machineMade = (src) => {
461
+ var _a, _b;
462
+ const stem = (_b = (_a = fileName(src, 999).split("/").pop()) == null ? void 0 : _a.replace(IMAGE, "")) != null ? _b : "";
463
+ return /^[0-9a-f-]{16,}$/i.test(stem) || stem.length >= 16 && /\d/.test(stem) && !/[-_ .]/.test(stem);
464
+ };
465
+ function named(label2, max = 40) {
466
+ if (IMAGE.test(label2))
467
+ return machineMade(label2) ? "an image" : `the image \u201C${fileName(label2, max - 6)}\u201D`;
468
+ if (TAGS.has(label2)) return "a box";
469
+ return `\u201C${label2.length > max ? `${label2.slice(0, max - 1)}\u2026` : label2}\u201D`;
470
+ }
471
+ var propName = (p) => p === "font-family" ? "font" : p.replace(/-/g, " ");
472
+ var drawnValue = (p, v) => short(p === "font-family" ? v.split(",")[0].replace(/["']/g, "").trim() : v);
473
+ var placed2 = (v) => v === "none" ? "hidden" : v.startsWith("inline") ? "in the line of text" : /^(block|flex|grid|table)$/.test(v) ? "on a line of its own" : `laid out as ${v}`;
474
+ function changeOf(label2, prop, design, client) {
475
+ if (prop !== "display")
476
+ return `has ${propName(prop)} ${drawnValue(prop, client)} instead of ${drawnValue(prop, design)}`;
477
+ const now = placed2(client);
478
+ const verb = now === "hidden" ? "is" : now.startsWith("laid") ? "is" : "sits";
479
+ const gap = IMAGE.test(label2) && now === "in the line of text" && placed2(design) !== now ? ", which can leave a gap under it" : "";
480
+ return `${verb} ${now} instead of ${placed2(design)}${gap}`;
481
+ }
482
+ var aspectExample = (x) => `${named(x.text)} ${changeOf(x.text, x.prop, x.design, x.client)}`;
483
+ function aspectLine(aspect, count, x) {
484
+ const what = aspectExample(x);
485
+ return count > 1 ? `${differs2(aspect)} in ${count} places. For example, ${what}.` : `${differs2(aspect)}: ${what}.`;
486
+ }
487
+ var cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
488
+ var NONE = /^(none|transparent|rgba\(0, 0, 0, 0\))$/;
489
+ function wrong(c) {
490
+ switch (c.kind) {
491
+ case "moved":
492
+ return `is moved (${c.design} \u2192 ${c.client.replace("centre at ", "")} across the email)`;
493
+ case "resized":
494
+ return c.design.startsWith("background-size:") ? `has its picture drawn at the wrong size (${c.design.replace("background-size: ", "")} \u2192 ${c.client.replace("background-size: ", "")})` : `is ${c.client} wide instead of ${c.design}`;
495
+ case "fill":
496
+ return `loses its background (${short(c.design)} \u2192 ${NONE.test(c.client) ? "none" : short(c.client)})`;
497
+ case "flush":
498
+ return `touches the edge of its card (${c.design} \u2192 ${c.client} from the edge)`;
499
+ case "corners":
500
+ return c.client === "0px" ? `loses its rounded corners (${c.design} \u2192 square)` : `has ${c.client} corners instead of ${c.design}`;
501
+ }
502
+ }
503
+ function sentenceOf(label2, parts) {
504
+ const ps = parts.map((p, i) => i > 0 ? p.replace(/^is /, "") : p);
505
+ const list = ps.length < 3 ? ps.join(" and ") : `${ps.slice(0, -1).join(", ")}, and ${ps.at(-1)}`;
506
+ return `${cap(named(label2))} ${list}.`;
507
+ }
508
+ function elements(components) {
509
+ var _a;
510
+ const by = /* @__PURE__ */ new Map();
511
+ for (const c of components) by.set(c.text, [...(_a = by.get(c.text)) != null ? _a : [], c]);
512
+ const all = [...by].map(([label2, cs]) => ({
513
+ breaks: cs.some((c) => c.breaks),
514
+ // Copies of one element (four social icons named alike) say it once.
515
+ line: sentenceOf(label2, [...new Set(cs.map(wrong))])
516
+ }));
517
+ return [...all.filter((e) => e.breaks), ...all.filter((e) => !e.breaks)];
518
+ }
519
+ function lostLine(lost) {
520
+ const copies = (l) => lost.filter((x) => x === l).length;
521
+ const unique = [...new Set(lost)];
522
+ const names = unique.slice(0, 3).map(
523
+ (l) => copies(l) > 1 ? `${named(l)} (${copies(l)} copies)` : named(l)
524
+ );
525
+ const rest = unique.length - names.length;
526
+ const list = rest ? `${names.join(", ")} and ${rest} more` : names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0];
527
+ return lost.length === 1 ? `1 part of your email does not show: ${list}.` : `${lost.length} parts of your email do not show: ${list}.`;
528
+ }
529
+ function explainDesign(check, name) {
530
+ const k = check.kept;
531
+ const els = elements(k.components);
532
+ const all = [
533
+ ...k.content < CONTENT && k.lost.length ? [lostLine(k.lost)] : [],
534
+ ...k.columns < COLUMNS ? [
535
+ "Columns that sit side by side in your design stack on top of each other."
536
+ ] : [],
537
+ ...k.width < WIDTH ? [
538
+ `The email is drawn at a very different width from your design (${Math.round(k.width * 100)}% of it).`
539
+ ] : [],
540
+ ...els.map((e) => e.line),
541
+ ...Object.entries(k.changed).filter(
542
+ ([aspect]) => aspect !== "corners" || !k.components.some((c) => c.kind === "corners")
543
+ ).map(([aspect, { count, example: x }]) => aspectLine(aspect, count, x))
544
+ ];
545
+ const sentence = check.verdict === "broken" ? `${name} breaks your design.` : check.verdict === "changed" ? `${name} keeps your layout but changes how it looks.` : `${name} keeps your layout, sizes, colours and fonts as you set them.`;
546
+ return {
547
+ sentence,
548
+ reasons: all.slice(0, SHOWN),
549
+ more: Math.max(0, all.length - SHOWN)
550
+ };
551
+ }
552
+ var ALIGNED = 0.7;
553
+ var ALIGNED_AT_1_1 = 0.55;
554
+ var ONE_TO_ONE = 0.03;
555
+ var aligned = (g) => g.match >= ALIGNED || g.match >= ALIGNED_AT_1_1 && Math.abs(g.scale - 1) <= ONE_TO_ONE;
556
+ var BAND = 32;
557
+ var PARTS = 0.1;
558
+ var TOP = 600;
559
+ function shrink(img, f) {
560
+ if (f === 1) return img;
561
+ const width = Math.max(1, Math.floor(img.width / f));
562
+ const height = Math.max(1, Math.floor(img.height / f));
563
+ const data = new Uint8Array(width * height);
564
+ for (let y = 0; y < height; y++)
565
+ for (let x = 0; x < width; x++) {
566
+ let sum = 0;
567
+ for (let dy = 0; dy < f; dy++) {
568
+ const row = (y * f + dy) * img.width + x * f;
569
+ for (let dx = 0; dx < f; dx++) sum += img.data[row + dx];
570
+ }
571
+ data[y * width + x] = sum / (f * f);
572
+ }
573
+ return { data, width, height };
574
+ }
575
+ function resample(img, scale, rows = img.height) {
576
+ const width = Math.max(1, Math.round(img.width * scale));
577
+ const height = Math.max(1, Math.round(Math.min(rows, img.height) * scale));
578
+ const data = new Uint8Array(width * height);
579
+ for (let y = 0; y < height; y++) {
580
+ const fy = Math.min(img.height - 1, y / scale);
581
+ const y0 = Math.floor(fy);
582
+ const y1 = Math.min(img.height - 1, y0 + 1);
583
+ const wy = fy - y0;
584
+ for (let x = 0; x < width; x++) {
585
+ const fx = Math.min(img.width - 1, x / scale);
586
+ const x0 = Math.floor(fx);
587
+ const x1 = Math.min(img.width - 1, x0 + 1);
588
+ const wx = fx - x0;
589
+ const top = img.data[y0 * img.width + x0] * (1 - wx) + img.data[y0 * img.width + x1] * wx;
590
+ const bot = img.data[y1 * img.width + x0] * (1 - wx) + img.data[y1 * img.width + x1] * wx;
591
+ data[y * width + x] = top * (1 - wy) + bot * wy;
592
+ }
593
+ }
594
+ return { data, width, height };
595
+ }
596
+ function ncc(t, img, ox, oy) {
597
+ let st = 0;
598
+ let si = 0;
599
+ let stt = 0;
600
+ let sii = 0;
601
+ let sti = 0;
602
+ const n = t.width * t.height;
603
+ for (let y = 0; y < t.height; y++) {
604
+ const trow = y * t.width;
605
+ const irow = (y + oy) * img.width + ox;
606
+ for (let x = 0; x < t.width; x++) {
607
+ const a = t.data[trow + x];
608
+ const b = img.data[irow + x];
609
+ st += a;
610
+ si += b;
611
+ stt += a * a;
612
+ sii += b * b;
613
+ sti += a * b;
614
+ }
615
+ }
616
+ const vt = stt - st * st / n;
617
+ const vi = sii - si * si / n;
618
+ if (vt <= 0 || vi <= 0) return vt === vi ? 1 : 0;
619
+ return (sti - st * si / n) / Math.sqrt(vt * vi);
620
+ }
621
+ function search(sim, real, f, scales, near2) {
622
+ const s = shrink(sim, f);
623
+ const r = shrink(real, f);
624
+ let best = { scale: 1, x: 0, y: 0, match: -2 };
625
+ for (const scale of scales) {
626
+ const t = resample(s, scale, Math.ceil(TOP / f));
627
+ if (t.width > r.width || t.height > r.height) continue;
628
+ const x0 = near2 ? Math.max(0, Math.floor(near2.x / f) - near2.r) : 0;
629
+ const x1 = near2 ? Math.min(r.width - t.width, Math.ceil(near2.x / f) + near2.r) : r.width - t.width;
630
+ const y0 = near2 ? Math.max(0, Math.floor(near2.y / f) - near2.r) : 0;
631
+ const y1 = near2 ? Math.min(r.height - t.height, Math.ceil(near2.y / f) + near2.r) : Math.min(r.height - t.height, Math.ceil(SLACK / f));
632
+ for (let y = y0; y <= y1; y++)
633
+ for (let x = x0; x <= x1; x++) {
634
+ const m = ncc(t, r, x, y);
635
+ if (m > best.match) best = { scale, x: x * f, y: y * f, match: m };
636
+ }
637
+ }
638
+ return best;
639
+ }
640
+ var range = (from, to, step) => Array.from(
641
+ { length: Math.round((to - from) / step) + 1 },
642
+ (_, i) => +(from + i * step).toFixed(4)
643
+ );
644
+ function compare(sim, real, fit) {
645
+ const bands = [];
646
+ for (let y0 = 0; y0 < sim.height; y0 += BAND) {
647
+ let sum = 0;
648
+ let n = 0;
649
+ for (let y = y0; y < Math.min(sim.height, y0 + BAND); y += 2) {
650
+ const ry = Math.round(fit.y + y * fit.scale);
651
+ if (ry >= real.height) break;
652
+ for (let x = 0; x < sim.width; x += 2) {
653
+ const rx = Math.round(fit.x + x * fit.scale);
654
+ if (rx >= real.width) break;
655
+ sum += Math.abs(
656
+ sim.data[y * sim.width + x] - real.data[ry * real.width + rx]
657
+ );
658
+ n++;
659
+ }
660
+ }
661
+ if (n === 0) break;
662
+ bands.push({ y: y0, diff: sum / n / 255 });
663
+ }
664
+ let partsAt = null;
665
+ for (let i = 0; i + 1 < bands.length; i++)
666
+ if (bands[i].diff > PARTS && bands[i + 1].diff > PARTS) {
667
+ partsAt = bands[i].y;
668
+ break;
669
+ }
670
+ const diff = bands.length ? bands.reduce((a, b) => a + b.diff, 0) / bands.length : 1;
671
+ return { bands, partsAt, diff };
672
+ }
673
+ function emailColumns(sim) {
674
+ const rows = Math.min(sim.height, TOP);
675
+ const flat = (x, edgeX) => {
676
+ for (let y = 0; y < rows; y++) {
677
+ const edge = sim.data[y * sim.width + edgeX];
678
+ if (Math.abs(sim.data[y * sim.width + x] - edge) > 8) return false;
679
+ }
680
+ return true;
681
+ };
682
+ let left2 = 0;
683
+ while (left2 < sim.width - 1 && flat(left2, 0)) left2++;
684
+ let right = sim.width - 1;
685
+ while (right > left2 && flat(right, sim.width - 1)) right--;
686
+ const width = right - left2 + 1;
687
+ if (width === sim.width) return { left: 0, img: sim };
688
+ const data = new Uint8Array(width * sim.height);
689
+ for (let y = 0; y < sim.height; y++)
690
+ data.set(
691
+ sim.data.subarray(y * sim.width + left2, y * sim.width + right + 1),
692
+ y * width
693
+ );
694
+ return { left: left2, img: { data, width, height: sim.height } };
695
+ }
696
+ var SLACK = 320;
697
+ function measureGap(pane, real) {
698
+ const { left: left2, img: sim } = emailColumns(pane);
699
+ const coarse = search(sim, real, 8, range(0.7, 1.4, 0.04));
700
+ const mid = search(
701
+ sim,
702
+ real,
703
+ 4,
704
+ range(coarse.scale - 0.04, coarse.scale + 0.04, 0.01),
705
+ {
706
+ x: coarse.x,
707
+ y: coarse.y,
708
+ r: 3
709
+ }
710
+ );
711
+ const fine = search(
712
+ sim,
713
+ real,
714
+ 2,
715
+ range(mid.scale - 0.01, mid.scale + 0.01, 25e-4),
716
+ {
717
+ x: mid.x,
718
+ y: mid.y,
719
+ r: 3
720
+ }
721
+ );
722
+ const full = search(
723
+ sim,
724
+ real,
725
+ 1,
726
+ range(fine.scale - 25e-4, fine.scale + 25e-4, 125e-5),
727
+ { x: fine.x, y: fine.y, r: 2 }
728
+ );
729
+ const x = Math.round(full.x - left2 * full.scale);
730
+ return __spreadValues(__spreadProps(__spreadValues({}, full), { x }), compare(sim, real, full));
731
+ }
732
+ var CLIENT_VIEWPORTS = {
733
+ // Desktop web clients , all at 2x for consistent quality.
734
+ // A width here is the one the email's media queries see, for a typical
735
+ // reader, which is not always the pane. A probe turning one row per 20px
736
+ // from "no" to "yes" (real-device run iZKliVgqbOoW, 2026-10-28) showed what
737
+ // each client measures against: Gmail and Yahoo web the browser window,
738
+ // Proton its message frame (880 in a 1280 window), Apple Mail and Outlook
739
+ // for Mac the message view (1420 and 1380 in the capture rig's full-width
740
+ // window, a best case readers rarely have).
741
+ // So: Gmail and Yahoo at 1280, the low end of common desktop windows
742
+ // (1366-1920 are typical); Proton at 880, its frame in that window; the
743
+ // Mac clients at 900, an estimate (no usage data) of the message pane in
744
+ // the default three-column layout on a 13-14" MacBook. What decides a
745
+ // layout is which side of the email's breakpoint the width falls, and
746
+ // breakpoints sit at 480-700px: the old 620-640px fell inside that band and
747
+ // stacked columns the real clients showed side by side (8 of 17 breaks in
748
+ // the 2026-10-28 agreement run). Not measured: the rest keep earlier
749
+ // estimates.
750
+ "gmail-web": { width: 1280, height: 900, deviceScaleFactor: 2 },
751
+ "outlook-web": { width: 680, height: 900, deviceScaleFactor: 2 },
752
+ "outlook-windows": { width: 620, height: 900, deviceScaleFactor: 2 },
753
+ // Word lays out at 600px. Measured on the John Lewis Testi shots: 96 DPI content
754
+ // is 692px wide, 120 DPI is 866px (1.25x), 150 DPI is 1038px (1.50x). Same
755
+ // breaks, scaled. One viewport covers every DPI variant.
756
+ "outlook-windows-legacy": { width: 1139, height: 900, deviceScaleFactor: 2 },
757
+ "apple-mail-macos": { width: 900, height: 900, deviceScaleFactor: 2 },
758
+ "yahoo-mail": { width: 1280, height: 900, deviceScaleFactor: 2 },
759
+ thunderbird: { width: 660, height: 900, deviceScaleFactor: 2 },
760
+ "hey-mail": { width: 580, height: 900, deviceScaleFactor: 2 },
761
+ superhuman: { width: 600, height: 900, deviceScaleFactor: 2 },
762
+ "outlook-macos": { width: 900, height: 900, deviceScaleFactor: 2 },
763
+ protonmail: { width: 880, height: 900, deviceScaleFactor: 2 },
764
+ aol: { width: 680, height: 900, deviceScaleFactor: 2 },
765
+ fastmail: { width: 600, height: 900, deviceScaleFactor: 2 },
766
+ // Mobile clients , real per-device CSS (device-independent px) widths, 2x.
767
+ // iOS = iPhone 14/15/16 class (393). Android Gmail/Outlook = Pixel class (412).
768
+ // Samsung = Galaxy S class (360). These drive both the live preview frame
769
+ // width and the screenshot viewport, so they must be the true device widths.
770
+ // Gmail Android is the width of its message view, not the screen: a probe on
771
+ // the worker's Pixel-class Gmail painted a full-width bar 956 of 1038 device
772
+ // px at 2.625 px per CSS px (2026-11-04).
773
+ "gmail-android": {
774
+ width: 396,
775
+ height: 915,
776
+ deviceScaleFactor: 2,
777
+ isMobile: true
778
+ },
779
+ "gmail-ios": {
780
+ width: 393,
781
+ height: 852,
782
+ deviceScaleFactor: 2,
783
+ isMobile: true
784
+ },
785
+ "outlook-ios": {
786
+ width: 393,
787
+ height: 852,
788
+ deviceScaleFactor: 2,
789
+ isMobile: true
790
+ },
791
+ "outlook-android": {
792
+ width: 412,
793
+ height: 915,
794
+ deviceScaleFactor: 2,
795
+ isMobile: true
796
+ },
797
+ "apple-mail-ios": {
798
+ width: 393,
799
+ height: 852,
800
+ deviceScaleFactor: 2,
801
+ isMobile: true
802
+ },
803
+ // Yahoo's two apps had no entry here at all and fell through to
804
+ // DEFAULT_VIEWPORT, a 640px desktop pane, so the engine called them mobile
805
+ // (both are category "mobile", and the mobile-only findings are scoped off
806
+ // that) while the preview drew them as a desktop client. Same device sizes as
807
+ // their platform siblings above: there is nothing Yahoo-specific about the
808
+ // hardware.
809
+ "yahoo-mail-android": {
810
+ width: 412,
811
+ height: 915,
812
+ deviceScaleFactor: 2,
813
+ isMobile: true
814
+ },
815
+ "yahoo-mail-ios": {
816
+ width: 393,
817
+ height: 852,
818
+ deviceScaleFactor: 2,
819
+ isMobile: true
820
+ },
821
+ "samsung-mail": {
822
+ width: 360,
823
+ height: 800,
824
+ deviceScaleFactor: 2,
825
+ isMobile: true
826
+ }
827
+ };
828
+ var DEFAULT_VIEWPORT = {
829
+ width: 640,
830
+ height: 900,
831
+ deviceScaleFactor: 2
832
+ };
833
+ var MOBILE_SHRINK_WIDTH = 640;
834
+ var PREFERS_COLOR_SCHEME_CLIENTS = /* @__PURE__ */ new Set([
835
+ "apple-mail-macos",
836
+ "apple-mail-ios",
837
+ "samsung-mail",
838
+ "hey-mail",
839
+ "superhuman",
840
+ "outlook-macos",
841
+ "protonmail",
842
+ "fastmail"
843
+ ]);
844
+ function clientTriggersPrefersColorScheme(clientId) {
845
+ return PREFERS_COLOR_SCHEME_CLIENTS.has(clientId);
846
+ }
847
+ var CLIENT_SHELLS = {
848
+ "gmail-web": {
849
+ // The message body's own font and colour, not Gmail's interface font:
850
+ // 99 of 103 worker captures (the rest set their own), 2026-11-09.
851
+ fontFamily: "Arial, Helvetica, sans-serif",
852
+ paneBg: "#ffffff",
853
+ paneBgDark: "#1f1f1f",
854
+ // No inset: real captures (agreement run 2026-10-28) show an email's own
855
+ // background running to the edges of the message view.
856
+ paddingX: 0,
857
+ paddingY: 0,
858
+ // The message body (div.a3s) in a 1280px window: 796px wide in every one
859
+ // of 103 worker captures (fidelity bench, 2026-11-09). A fluid email
860
+ // fills that, not the window.
861
+ maxWidth: 796,
862
+ // Gmail wraps in .a3s.aiL with overflow:hidden
863
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 13px, on lines 1.5 times the font size.
864
+ extraCss: "word-wrap:break-word;overflow:hidden;font-size:13px;line-height:1.5;color:#222;"
865
+ },
866
+ "gmail-android": {
867
+ fontFamily: "Roboto, sans-serif",
868
+ paneBg: "#ffffff",
869
+ paneBgDark: "#131313",
870
+ paddingX: 16,
871
+ paddingY: 0,
872
+ // Unstyled text, fitted on real run C93iCoVV5yas (2026-11-03): only 12px
873
+ // reproduces its six paragraph wraps and its alt-text boxes.
874
+ extraCss: "word-wrap:break-word;overflow:hidden;font-size:12px;"
875
+ },
876
+ "gmail-ios": {
877
+ fontFamily: "-apple-system, Roboto, Helvetica, Arial, sans-serif",
878
+ paneBg: "#ffffff",
879
+ paneBgDark: "#202125",
880
+ paddingX: 16,
881
+ paddingY: 0,
882
+ extraCss: "word-wrap:break-word;overflow:hidden;"
883
+ },
884
+ "outlook-web": {
885
+ fontFamily: "'Segoe UI', 'Segoe UI Web (West European)', 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif",
886
+ paneBg: "#ffffff",
887
+ paneBgDark: "#292929",
888
+ paddingX: 20,
889
+ paddingY: 16,
890
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 15px.
891
+ extraCss: "line-height:normal;font-size:15px;"
892
+ },
893
+ "outlook-windows": {
894
+ fontFamily: "'Segoe UI', Calibri, Arial, sans-serif",
895
+ paneBg: "#ffffff",
896
+ paneBgDark: "#292929",
897
+ // None: the viewport is the pane's body area, edge to edge on the real
898
+ // client (worker's new Outlook, pane 620 CSS px, 2026-11-10).
899
+ paddingX: 0,
900
+ paddingY: 12,
901
+ // Unstyled text on the worker's new Outlook (heldout-theresanaiforthat,
902
+ // 2026-11-10): 15px, as on the web, in Fluent's #242424.
903
+ textColor: "#242424",
904
+ extraCss: "line-height:normal;font-size:15px;"
905
+ },
906
+ "outlook-ios": {
907
+ fontFamily: "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
908
+ paneBg: "#ffffff",
909
+ paneBgDark: "#111111",
910
+ paddingX: 16,
911
+ paddingY: 0,
912
+ extraCss: "line-height:normal;"
913
+ },
914
+ "outlook-android": {
915
+ fontFamily: "Roboto, 'Segoe UI', Helvetica, Arial, sans-serif",
916
+ paneBg: "#ffffff",
917
+ paneBgDark: "#111111",
918
+ paddingX: 16,
919
+ paddingY: 0,
920
+ extraCss: "line-height:normal;"
921
+ },
922
+ "outlook-windows-legacy": {
923
+ // Word's default on current Outlook is Aptos (probe outlook-word-flow,
924
+ // 2026-10-31). It is not bundled; Selawik is the nearest metric.
925
+ fontFamily: "Aptos, 'Segoe UI', Selawik, sans-serif",
926
+ paneBg: "#ffffff",
927
+ paneBgDark: "#262626",
928
+ paddingX: 16,
929
+ paddingY: 12,
930
+ extraCss: "line-height:normal;"
931
+ },
932
+ "apple-mail-macos": {
933
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif",
934
+ paneBg: "#ffffff",
935
+ // Apple leaves authored colors alone. The message canvas stays white.
936
+ paneBgDark: "#ffffff",
937
+ // No inset: real captures (agreement run 2026-10-28) show an email's own
938
+ // background running to the edges of the message view.
939
+ paddingX: 0,
940
+ paddingY: 0,
941
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 12px.
942
+ extraCss: "font-size:12px;",
943
+ // And rem is measured from the same 12px: every gap two React Email
944
+ // templates wrote in rem came out 0.70 to 0.90 of a 16px rem on a real
945
+ // Apple Mail, text heights unchanged (AI Fix real-device round,
946
+ // 2026-10-23). Previewed at 16px, the design was 30% taller than the
947
+ // one readers see, and a fix matched to it overshot.
948
+ rootFontSize: 12
949
+ },
950
+ "apple-mail-ios": {
951
+ fontFamily: "-apple-system, 'Helvetica Neue', Helvetica, Arial, sans-serif",
952
+ paneBg: "#ffffff",
953
+ paneBgDark: "#ffffff",
954
+ paddingX: 16,
955
+ paddingY: 8
956
+ },
957
+ "yahoo-mail": {
958
+ fontFamily: "'Helvetica Neue', Helvetica, Arimo, Arial, sans-serif",
959
+ paneBg: "#ffffff",
960
+ paneBgDark: "#323232",
961
+ // No inset: real captures (agreement run 2026-10-28) show an email's own
962
+ // background running to the edges of the message view.
963
+ paddingX: 0,
964
+ paddingY: 0,
965
+ // Yahoo collapses margins on the wrapper
966
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 13px.
967
+ extraCss: "margin:0;font-size:13px;"
968
+ },
969
+ "yahoo-mail-android": {
970
+ fontFamily: "Roboto, sans-serif",
971
+ paneBg: "#ffffff",
972
+ paneBgDark: "#323232",
973
+ paddingX: 16,
974
+ paddingY: 0,
975
+ // Same wrapper margin collapse as Yahoo on the web: it is the same renderer.
976
+ extraCss: "margin:0;"
977
+ },
978
+ "yahoo-mail-ios": {
979
+ fontFamily: "-apple-system, 'Helvetica Neue', Helvetica, Arial, sans-serif",
980
+ paneBg: "#ffffff",
981
+ paneBgDark: "#323232",
982
+ paddingX: 16,
983
+ paddingY: 8,
984
+ extraCss: "margin:0;"
985
+ },
986
+ "samsung-mail": {
987
+ fontFamily: "Roboto, sans-serif",
988
+ paneBg: "#ffffff",
989
+ paneBgDark: "#1a1a1a",
990
+ paddingX: 16,
991
+ paddingY: 0
992
+ },
993
+ thunderbird: {
994
+ fontFamily: "system-ui, -apple-system, sans-serif",
995
+ paneBg: "#ffffff",
996
+ paneBgDark: "#18181a",
997
+ paddingX: 8,
998
+ paddingY: 0
999
+ },
1000
+ "hey-mail": {
1001
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
1002
+ paneBg: "#ffffff",
1003
+ paneBgDark: "#1a1a1a",
1004
+ paddingX: 24,
1005
+ paddingY: 16,
1006
+ maxWidth: 680
1007
+ },
1008
+ superhuman: {
1009
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
1010
+ paneBg: "#ffffff",
1011
+ paneBgDark: "#1a1a1a",
1012
+ paddingX: 20,
1013
+ paddingY: 12
1014
+ },
1015
+ "outlook-macos": {
1016
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
1017
+ paneBg: "#ffffff",
1018
+ paneBgDark: "#111111",
1019
+ // No inset: real captures (agreement run 2026-10-28) show an email's own
1020
+ // background running to the edges of the message view.
1021
+ paddingX: 0,
1022
+ paddingY: 0,
1023
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 11pt.
1024
+ extraCss: "line-height:normal;font-size:14.67px;"
1025
+ },
1026
+ protonmail: {
1027
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
1028
+ paneBg: "#ffffff",
1029
+ paneBgDark: "#1b1b24",
1030
+ // No inset: real captures (agreement run 2026-10-28) show an email's own
1031
+ // background running to the edges of the message view.
1032
+ paddingX: 0,
1033
+ paddingY: 0
1034
+ },
1035
+ aol: {
1036
+ fontFamily: "'Helvetica Neue', Helvetica, Arimo, Arial, sans-serif",
1037
+ paneBg: "#ffffff",
1038
+ paneBgDark: "#323232",
1039
+ paddingX: 20,
1040
+ paddingY: 0,
1041
+ // Unstyled text, measured on the real client (fidelity sheet 04-typography c01, c20): 13px.
1042
+ extraCss: "margin:0;font-size:13px;"
1043
+ },
1044
+ fastmail: {
1045
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
1046
+ paneBg: "#ffffff",
1047
+ paneBgDark: "#1e1e1e",
1048
+ paddingX: 20,
1049
+ paddingY: 16
1050
+ }
1051
+ };
1052
+ var DEFAULT_SHELL = {
1053
+ fontFamily: "Arial, Helvetica, Arimo, sans-serif",
1054
+ paneBg: "#ffffff",
1055
+ paneBgDark: "#1a1a1a",
1056
+ paddingX: 16,
1057
+ paddingY: 0
1058
+ };
1059
+ var NO_IMAGE_CONSTRAINT = /* @__PURE__ */ new Set([
1060
+ "outlook-windows-legacy",
1061
+ "gmail-web",
1062
+ "yahoo-mail",
1063
+ "protonmail"
1064
+ ]);
1065
+ var MUNGE_CLIENTS = /* @__PURE__ */ new Set(["gmail-android"]);
1066
+ function isMungeClient(clientId) {
1067
+ return MUNGE_CLIENTS.has(clientId);
1068
+ }
1069
+ var MUNGE_STYLE = `<style>table{width:auto!important;table-layout:auto!important;max-width:100%!important}td,th{width:auto!important;white-space:normal!important}img{max-width:100%!important;height:auto!important}</style>`;
1070
+ var EMAIL_WIDTH = 600;
1071
+ function shellBackgrounds(shell, mode, canvas) {
1072
+ const pane = mode === "dark" ? shell.paneBgDark : shell.paneBg;
1073
+ const columnBg = shell.maxWidth && canvas ? `background:${canvas};` : "";
1074
+ return { bg: columnBg ? pane : canvas != null ? canvas : pane, columnBg };
1075
+ }
1076
+ function sidePadding(clientId, paddingX) {
1077
+ const vp = CLIENT_VIEWPORTS[clientId];
1078
+ if (!vp || vp.isMobile) return paddingX;
1079
+ return Math.min(
1080
+ paddingX,
1081
+ Math.max(0, Math.floor((vp.width - EMAIL_WIDTH) / 2))
1082
+ );
1083
+ }
1084
+ function buildShellStyle(clientId, mode, authoredFont = false, canvas) {
1085
+ var _a, _b;
1086
+ const shell = (_a = CLIENT_SHELLS[clientId]) != null ? _a : DEFAULT_SHELL;
1087
+ const { bg, columnBg } = shellBackgrounds(shell, mode, canvas);
1088
+ const maxWidthRule = shell.maxWidth ? `max-width:${shell.maxWidth}px;` : "";
1089
+ const extra = (_b = shell.extraCss) != null ? _b : "";
1090
+ const paddingX = sidePadding(clientId, shell.paddingX);
1091
+ const imgRule = NO_IMAGE_CONSTRAINT.has(clientId) ? "" : ".emailens-shell img{max-width:100%;height:auto}";
1092
+ const rootRule = shell.rootFontSize ? `html{font-size:${shell.rootFontSize}px}` : "";
1093
+ return `<style>
1094
+ ${rootRule}
1095
+ html,body{margin:0!important;padding:0!important;background:${bg}!important}
1096
+ .emailens-shell{
1097
+ ${authoredFont ? "" : `font-family:${shell.fontFamily};`}
1098
+ padding:${shell.paddingY}px ${paddingX}px;
1099
+ ${columnBg}
1100
+ ${maxWidthRule}
1101
+ width:100%;
1102
+ box-sizing:border-box;
1103
+ ${mode === "light" && shell.textColor ? `color:${shell.textColor};` : ""}
1104
+ ${extra}
1105
+ }
1106
+ ${imgRule}
1107
+ </style>`;
1108
+ }
1109
+ function injectStyleIntoHtml(html, style) {
1110
+ if (html.includes("</head")) {
1111
+ return html.replace(/<\/head>/i, `${style}</head>`);
1112
+ }
1113
+ if (html.includes("<head")) {
1114
+ return html.replace(/<head([^>]*)>/i, `<head$1>${style}`);
1115
+ }
1116
+ return `<!DOCTYPE html><html><head>${style}</head><body>${html}</body></html>`;
1117
+ }
1118
+ function isResponsiveEmail(html) {
1119
+ if (/<meta[^>]+name=["']viewport["'][^>]*>/i.test(html) && /width=device-width/i.test(html)) {
1120
+ return true;
1121
+ }
1122
+ const styleBlocks = html.match(/<style[^>]*>[\s\S]*?<\/style>/gi) || [];
1123
+ for (const block of styleBlocks) {
1124
+ if (/@media[^{]*(max-width|min-width)\s*:\s*\d{1,3}(px|em|rem)/i.test(block)) {
1125
+ return true;
1126
+ }
1127
+ }
1128
+ return false;
1129
+ }
1130
+ var INHERITED_TEXT = /^(color|font|font-family|font-size|font-style|font-weight|line-height|letter-spacing|word-spacing|text-align|text-transform)$/;
1131
+ var propOf = (d) => {
1132
+ var _a, _b;
1133
+ return (_b = (_a = d.split(":")[0]) == null ? void 0 : _a.trim().toLowerCase()) != null ? _b : "";
1134
+ };
1135
+ function bodyTextStyle(bodyAttrs) {
1136
+ var _a, _b;
1137
+ const attr = bodyAttrs.match(/\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
1138
+ return ((_b = (_a = attr == null ? void 0 : attr[1]) != null ? _a : attr == null ? void 0 : attr[2]) != null ? _b : "").replace(/&quot;|&#34;|&#39;|&apos;|"/gi, "'").split(";").filter((d) => INHERITED_TEXT.test(propOf(d))).join(";");
1139
+ }
1140
+ function withoutShellLayout(bodyAttrs) {
1141
+ return bodyAttrs.replace(
1142
+ /\s+style\s*=\s*["']([^"']*)["']/gi,
1143
+ (_match, styles) => {
1144
+ const cleaned = styles.split(";").filter(
1145
+ (s) => !/^(display|flex|grid|justify|align-items|align-content|position|overflow)/.test(
1146
+ propOf(s)
1147
+ )
1148
+ ).join(";").trim();
1149
+ return cleaned ? ` style="${cleaned}"` : "";
1150
+ }
1151
+ );
1152
+ }
1153
+ function wrapInShell(html) {
1154
+ const bodyMatch = html.match(/(<body)([^>]*)(>)([\s\S]*?)(<\/body>)/i);
1155
+ if (bodyMatch) {
1156
+ const inherited = bodyTextStyle(bodyMatch[2]);
1157
+ const inner = inherited ? `<div style="${inherited}">${bodyMatch[4]}</div>` : bodyMatch[4];
1158
+ const bodyAttrs = withoutShellLayout(bodyMatch[2]);
1159
+ return html.replace(
1160
+ bodyMatch[0],
1161
+ `${bodyMatch[1]}${bodyAttrs}${bodyMatch[3]}<div class="emailens-shell">${inner}</div>${bodyMatch[5]}`
1162
+ );
1163
+ }
1164
+ return `<div class="emailens-shell">${html}</div>`;
1165
+ }
1166
+ var GMAIL_STYLE_LIMIT = 16384;
1167
+ var PROTON_DROPPED = /* @__PURE__ */ new Set([
1168
+ "flex",
1169
+ "flex-grow",
1170
+ "flex-shrink",
1171
+ "flex-basis",
1172
+ "flex-direction",
1173
+ "flex-wrap",
1174
+ "flex-flow",
1175
+ "justify-content",
1176
+ "align-items",
1177
+ "align-self",
1178
+ "align-content",
1179
+ "place-items",
1180
+ "order",
1181
+ "gap",
1182
+ "row-gap",
1183
+ "grid-template-columns",
1184
+ "box-shadow",
1185
+ "transform",
1186
+ "text-shadow",
1187
+ "aspect-ratio",
1188
+ "filter"
1189
+ ]);
1190
+ function dropProtonMixedProperties(html) {
1191
+ return html.replace(
1192
+ /(\sstyle\s*=\s*")([^"]*)(")/gi,
1193
+ (all, open2, style, close) => {
1194
+ const decls = style.split(";").map((d) => d.trim()).filter(Boolean);
1195
+ const dropped = (d) => PROTON_DROPPED.has(d.slice(0, d.indexOf(":")).trim().toLowerCase());
1196
+ if (decls.every(dropped) || !decls.some(dropped)) return all;
1197
+ const kept = decls.filter((d) => !dropped(d)).map((d) => d.replace(/\s*:\s*/, ":"));
1198
+ return `${open2}${kept.join(";")}${close}`;
1199
+ }
1200
+ );
1201
+ }
1202
+ function applyClientMutations(html, clientId) {
1203
+ let result = html;
1204
+ if (isGmailClient(clientId)) {
1205
+ result = applyGmailMutations(result);
1206
+ if (clientId !== "gmail-android") result = undoInlinedWidthMedia(result);
1207
+ } else if (isYahooClient(clientId)) {
1208
+ result = applyYahooMutations(result);
1209
+ } else if (clientId === "outlook-windows-legacy") {
1210
+ result = applyOutlookClassicMutations(result);
1211
+ } else if (clientId === "protonmail") {
1212
+ result = dropProtonMixedProperties(result);
1213
+ }
1214
+ if (clientId === "outlook-ios" || clientId === "thunderbird") {
1215
+ result = lockInlineDisplayNone(result);
1216
+ }
1217
+ if (clientId === "outlook-web" || clientId === "outlook-windows-legacy") {
1218
+ result = dropHiddenBreaks(result);
1219
+ }
1220
+ if (clientId === "outlook-web") {
1221
+ result = injectStyleIntoHtml(
1222
+ result,
1223
+ `<style>a{overflow-wrap:anywhere}</style>`
1224
+ );
1225
+ }
1226
+ if (isMungeClient(clientId) && !isResponsiveEmail(html)) {
1227
+ result = injectStyleIntoHtml(result, MUNGE_STYLE);
1228
+ }
1229
+ if (clientId === "gmail-android")
1230
+ result = zoomText(result, GMAIL_ANDROID_TEXT_ZOOM);
1231
+ return applyClientTargeting(result, clientId);
1232
+ }
1233
+ var GMAIL_ANDROID_TEXT_ZOOM = 1.073;
1234
+ function zoomText(html, zoom) {
1235
+ return html.replace(
1236
+ /\b(font-size|line-height)(\s*:\s*)(\d*\.?\d+)(px|pt)\b/gi,
1237
+ (_, prop, sep, n, unit) => `${prop}${sep}${Math.round(Number(n) * zoom * 100) / 100}${unit}`
1238
+ );
1239
+ }
1240
+ function isGmailClient(clientId) {
1241
+ return clientId === "gmail-web" || clientId === "gmail-android" || clientId === "gmail-ios";
1242
+ }
1243
+ function isYahooClient(clientId) {
1244
+ return clientId === "yahoo-mail" || clientId === "yahoo-mail-android" || clientId === "yahoo-mail-ios";
1245
+ }
1246
+ function applyGmailMutations(html) {
1247
+ let result = html;
1248
+ result = result.replace(
1249
+ /<style[^>]*>[\s\S]*?<\/style>/gi,
1250
+ (block) => /\\0/.test(block) ? "" : block
1251
+ );
1252
+ const styleBlocks = result.match(/<style[^>]*>[\s\S]*?<\/style>/gi) || [];
1253
+ const totalStyleBytes = styleBlocks.reduce((sum, block) => {
1254
+ const content = block.replace(/<\/?style[^>]*>/gi, "");
1255
+ return sum + new TextEncoder().encode(content).byteLength;
1256
+ }, 0);
1257
+ if (totalStyleBytes > GMAIL_STYLE_LIMIT) {
1258
+ result = result.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
1259
+ }
1260
+ result = result.replace(
1261
+ /(<[a-z][a-z0-9]*\s[^>]*?)\s+id\s*=\s*["'][^"']*["']/gi,
1262
+ "$1"
1263
+ );
1264
+ result = result.replace(
1265
+ /(<a\s)([^>]*?)(>)/gi,
1266
+ (match, open2, attrs, close) => {
1267
+ const withoutTarget = attrs.replace(
1268
+ /\s*target\s*=\s*["'][^"']*["']/gi,
1269
+ ""
1270
+ );
1271
+ return `${open2}${withoutTarget} target="_blank"${close}`;
1272
+ }
1273
+ );
1274
+ const bodyMatch = result.match(/(<body[^>]*>)([\s\S]*?)(<\/body>)/i);
1275
+ if (bodyMatch) {
1276
+ result = result.replace(
1277
+ bodyMatch[0],
1278
+ `${bodyMatch[1]}<div class="a3s aiL">${bodyMatch[2]}</div>${bodyMatch[3]}`
1279
+ );
1280
+ }
1281
+ return result;
1282
+ }
1283
+ function widthMediaClassDecls(css) {
1284
+ var _a, _b;
1285
+ const drops = /* @__PURE__ */ new Map();
1286
+ let i = 0;
1287
+ while (i < css.length) {
1288
+ const at = css.toLowerCase().indexOf("@media", i);
1289
+ if (at === -1) break;
1290
+ const open2 = css.indexOf("{", at);
1291
+ if (open2 === -1) break;
1292
+ let depth = 1;
1293
+ let j = open2 + 1;
1294
+ while (j < css.length && depth > 0) {
1295
+ if (css[j] === "{") depth++;
1296
+ else if (css[j] === "}") depth--;
1297
+ j++;
1298
+ }
1299
+ const prelude = css.slice(at, open2);
1300
+ const body = css.slice(open2 + 1, j - 1);
1301
+ i = j;
1302
+ if (prelude.includes(NEVER_MATCHES) || prelude.includes(ALWAYS_MATCHES))
1303
+ continue;
1304
+ if (!/(?:min|max)-width/i.test(prelude)) continue;
1305
+ for (const rule of body.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
1306
+ const decls = rule[2].split(";").map((d) => d.trim()).filter(Boolean);
1307
+ if (decls.length === 0) continue;
1308
+ for (const sel of rule[1].split(",")) {
1309
+ const name = (_a = sel.trim().match(/^\.([A-Za-z_][\w-]*)$/)) == null ? void 0 : _a[1];
1310
+ if (!name) continue;
1311
+ drops.set(name, [...(_b = drops.get(name)) != null ? _b : [], ...decls]);
1312
+ }
1313
+ }
1314
+ }
1315
+ return drops;
1316
+ }
1317
+ function undoInlinedWidthMedia(html) {
1318
+ const css = [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join("\n");
1319
+ const drops = widthMediaClassDecls(css);
1320
+ if (drops.size === 0) return html;
1321
+ const norm = (s) => s.replace(/\s+/g, "").toLowerCase();
1322
+ return html.replace(
1323
+ /<([a-z][\w:-]*)\b([^>]*?)>/gi,
1324
+ (whole, _tag, attrs) => {
1325
+ var _a, _b, _c;
1326
+ const classes = (_c = (_b = (_a = /class\s*=\s*(["'])([\s\S]*?)\1/i.exec(attrs)) == null ? void 0 : _a[2]) == null ? void 0 : _b.split(/\s+/)) != null ? _c : [];
1327
+ const banned = new Set(
1328
+ classes.flatMap((name) => {
1329
+ var _a2;
1330
+ return (_a2 = drops.get(name)) != null ? _a2 : [];
1331
+ }).map(norm)
1332
+ );
1333
+ if (banned.size === 0 || !/\sstyle\s*=/i.test(attrs)) return whole;
1334
+ return whole.replace(
1335
+ /(\sstyle\s*=\s*)(["'])([\s\S]*?)\2/i,
1336
+ (_s, lead, quote, style) => {
1337
+ const next = style.split(";").map((part) => part.trim()).filter((part) => part && !banned.has(norm(part))).join("; ");
1338
+ return `${lead}${quote}${next}${quote}`;
1339
+ }
1340
+ );
1341
+ }
1342
+ );
1343
+ }
1344
+ function retouchStyle(html, edit) {
1345
+ return html.replace(
1346
+ /(\sstyle\s*=\s*)(["'])([\s\S]*?)\2/gi,
1347
+ (whole, lead, quote, style) => {
1348
+ const next = edit(style);
1349
+ return next == null ? whole : `${lead}${quote}${next}${quote}`;
1350
+ }
1351
+ );
1352
+ }
1353
+ function lockInlineDisplayNone(html) {
1354
+ return retouchStyle(
1355
+ html,
1356
+ (style) => /display\s*:\s*none/i.test(style) && !/display\s*:\s*none\s*!important/i.test(style) ? style.replace(/display\s*:\s*none/gi, "display:none!important") : null
1357
+ );
1358
+ }
1359
+ function applyYahooMutations(html) {
1360
+ const prefix = YAHOO_WRAPPER_ID;
1361
+ let result = html;
1362
+ result = result.replace(
1363
+ /\bclass\s*=\s*"([^"]*)"/gi,
1364
+ (_match, classes) => {
1365
+ const prefixed = classes.split(/\s+/).filter(Boolean).map((c) => c === "emailens-shell" ? c : `${prefix}${c}`).join(" ");
1366
+ return `class="${prefixed}"`;
1367
+ }
1368
+ );
1369
+ result = result.replace(
1370
+ /\bid\s*=\s*"([^"]*)"/gi,
1371
+ (_match, id) => `id="${prefix}${id}"`
1372
+ );
1373
+ result = result.replace(
1374
+ /(<style[^>]*>)([\s\S]*?)(<\/style>)/gi,
1375
+ (_match, open2, css, close) => {
1376
+ const prefixedCss = css.replace(
1377
+ /\.([a-zA-Z_][\w-]*)/g,
1378
+ (_m, name) => name === "emailens-shell" ? `.${name}` : `.${prefix}${name}`
1379
+ ).replace(
1380
+ /#([a-zA-Z_][\w-]*)(?=[^{};]*\{)/g,
1381
+ (_m, name) => `#${prefix}${name}`
1382
+ );
1383
+ return `${open2}${prefixedCss}${close}`;
1384
+ }
1385
+ );
1386
+ return activateAmpersandTarget(applyYahooCssQuirks(result), prefix);
1387
+ }
1388
+ function prepareWordSource(html) {
1389
+ return preserveWordHidden(dropRowlessConditionalTables(html));
1390
+ }
1391
+ function preserveWordHidden(html) {
1392
+ return html.replace(
1393
+ /(<(?:td|th|tr|span)\b[^>]*?\sstyle\s*=\s*)(["'])([\s\S]*?)\2/gi,
1394
+ (whole, lead, quote, style) => !/display\s*:\s*none/i.test(style) || /mso-hide\s*:\s*all/i.test(style) || // The engine keeps a hidden cell's padding, and needs it untagged to see it.
1395
+ /^<t[dh]\s/i.test(lead) && /padding/i.test(style) ? whole : `${lead}${quote}${style}${/;\s*$/.test(style) ? "" : ";"}mso-hide:all${quote}`
1396
+ );
1397
+ }
1398
+ function dropHiddenBreaks(html) {
1399
+ const css = stripMediaQueries(
1400
+ [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join("\n")
1401
+ );
1402
+ const hidden = /* @__PURE__ */ new Set();
1403
+ for (const match of css.matchAll(
1404
+ /\.([A-Za-z_][\w-]*)\s*\{[^}]*display\s*:\s*none/gi
1405
+ )) {
1406
+ hidden.add(match[1]);
1407
+ }
1408
+ if (hidden.size === 0) return html;
1409
+ return html.replace(/\s*<br\b([^>]*)>\s*/gi, (whole, attrs) => {
1410
+ var _a, _b, _c;
1411
+ const classes = (_c = (_b = (_a = /class\s*=\s*(["'])([\s\S]*?)\1/i.exec(attrs)) == null ? void 0 : _a[2]) == null ? void 0 : _b.split(/\s+/)) != null ? _c : [];
1412
+ return classes.some((name) => hidden.has(name)) ? "" : whole;
1413
+ });
1414
+ }
1415
+ var WORD_IGNORED_SELECTOR = /\[|>|:first-child|:nth-child|:not\(|::?before|\.[\w-]+\.[\w-]/;
1416
+ function stripWordCss(css) {
1417
+ return css.replace(
1418
+ /([^{}@]+)\{([^{}]*)\}/g,
1419
+ (full, selectors, declarations) => {
1420
+ const sel = selectors.split(",").filter((one) => !WORD_IGNORED_SELECTOR.test(one)).join(",");
1421
+ if (!sel.trim()) return "";
1422
+ const body = declarations.replace(/(?:^|;)[^;{}]*var\([^;{}]*/gi, "");
1423
+ const noRadius = body.replace(/border-radius\s*:[^;}]*/gi, "");
1424
+ return `${sel}{${noRadius}}`;
1425
+ }
1426
+ );
1427
+ }
1428
+ function stripMediaQueries(css, atRule = "@media") {
1429
+ let out = "";
1430
+ let i = 0;
1431
+ while (i < css.length) {
1432
+ const at = css.toLowerCase().indexOf(atRule, i);
1433
+ if (at === -1) {
1434
+ out += css.slice(i);
1435
+ break;
1436
+ }
1437
+ out += css.slice(i, at);
1438
+ const open2 = css.indexOf("{", at);
1439
+ if (open2 === -1) {
1440
+ break;
1441
+ }
1442
+ let depth = 1;
1443
+ let j = open2 + 1;
1444
+ while (j < css.length && depth > 0) {
1445
+ if (css[j] === "{") depth++;
1446
+ else if (css[j] === "}") depth--;
1447
+ j++;
1448
+ }
1449
+ i = j;
1450
+ }
1451
+ return out;
1452
+ }
1453
+ var LONE_TABLE_BLOCK = /<!--\[if ([^\]]*)\]>\s*(<table\b[^>]*>|<\/table>)\s*<!\[endif\]-->/gi;
1454
+ var TABLE_TAG = /<(?:tr|tbody|thead|tfoot|caption|colgroup|col|td|th)\b/iy;
1455
+ function tableContentAt(html, from) {
1456
+ let at = from;
1457
+ for (; ; ) {
1458
+ while (at < html.length && /\s/.test(html[at])) at++;
1459
+ if (!html.startsWith("<!--", at)) break;
1460
+ const close = html.indexOf("-->", at + 4);
1461
+ if (close < 0) return false;
1462
+ at = close + 3;
1463
+ }
1464
+ TABLE_TAG.lastIndex = at;
1465
+ return TABLE_TAG.test(html);
1466
+ }
1467
+ function dropRowlessConditionalTables(html) {
1468
+ const open2 = [];
1469
+ const drop = [];
1470
+ for (const m of html.matchAll(LONE_TABLE_BLOCK)) {
1471
+ if (!/mso/i.test(m[1]) || m[1].includes("!")) continue;
1472
+ const start = m.index;
1473
+ const end = start + m[0].length;
1474
+ if (!m[2].startsWith("</")) {
1475
+ open2.push({ start, end, rowless: !tableContentAt(html, end) });
1476
+ continue;
1477
+ }
1478
+ const table = open2.pop();
1479
+ if (table == null ? void 0 : table.rowless) drop.push([table.start, table.end], [start, end]);
1480
+ }
1481
+ let out = html;
1482
+ for (const [start, end] of drop.sort((a, b) => b[0] - a[0]))
1483
+ out = out.slice(0, start) + out.slice(end);
1484
+ return out;
1485
+ }
1486
+ function applyOutlookClassicMutations(html) {
1487
+ let result = html;
1488
+ result = result.replace(
1489
+ /(<body[^>]*>\s*(?:<div[^>]*display\s*:\s*none[^>]*>\s*<\/div>\s*)?)(<span[^>]*display\s*:\s*none)/i,
1490
+ '$1<div style="height:21px"></div>$2'
1491
+ );
1492
+ result = resolveMsoBranch(result);
1493
+ result = mapStyleBlocks(
1494
+ result,
1495
+ (css) => css.replace(/\{[^{}]*\}/g, (block) => {
1496
+ const stop = block.match(
1497
+ /mso-style-textfill-fill-gradientfill-stoplist\s*:\s*["']?\s*[\d.]+\s+(#[0-9a-f]{3,8})/i
1498
+ );
1499
+ return stop ? `${block.slice(0, -1).replace(/(^|[{;\s])color\s*:[^;}]*;?/gi, "$1")};color:${stop[1]}!important}` : block;
1500
+ })
1501
+ );
1502
+ result = result.replace(
1503
+ /line-height\s*:\s*(\d*\.?\d+)\s*(?=[;"'}!]|$)/gi,
1504
+ (whole, value) => Number(value) <= 0 ? whole : Number(value) < 1 ? `line-height:0;visibility:hidden` : Number.isInteger(Number(value)) && Number(value) > 1 ? `line-height:${Number(value) * 1.15}` : "line-height:normal"
1505
+ );
1506
+ result = result.replace(
1507
+ /(<br\b[^>]*>\s*)<br\b[^>]*>\s*(<\/(?:p|div)>)/gi,
1508
+ '$1<span style="display:block;height:1em"></span>$2'
1509
+ );
1510
+ const percentLine = (percent, single) => `line-height:${Number((Number(percent) / 100 * single).toFixed(3))}`;
1511
+ result = result.replace(/\bstyle\s*=\s*"[^"]*"/gi, (style) => {
1512
+ var _a, _b;
1513
+ const family2 = (_b = (_a = /font-family\s*:\s*([^;"]*)/i.exec(style)) == null ? void 0 : _a[1]) != null ? _b : "";
1514
+ const face = WORD_SINGLE_SPACING.map(
1515
+ ([name, single]) => [family2.indexOf(name), single]
1516
+ ).filter(([at]) => at >= 0).sort((a, b) => a[0] - b[0])[0];
1517
+ return style.replace(
1518
+ /line-height\s*:\s*(\d+(?:\.\d+)?)%/gi,
1519
+ (_whole, percent) => {
1520
+ var _a2;
1521
+ return percentLine(percent, (_a2 = face == null ? void 0 : face[1]) != null ? _a2 : 1.19);
1522
+ }
1523
+ );
1524
+ });
1525
+ result = result.replace(
1526
+ /line-height\s*:\s*(\d+(?:\.\d+)?)%/gi,
1527
+ (_whole, percent) => percentLine(percent, 1.19)
1528
+ );
1529
+ result = result.replace(/<div\b[^>]*>/gi, (full) => {
1530
+ if (/display\s*:\s*none/i.test(full)) return full;
1531
+ if (!new RegExp("(?<![\\w-])(?:max-)?height\\s*:\\s*0", "i").test(full)) return full;
1532
+ return full.replace(
1533
+ new RegExp("(?<![\\w-])(?:max-)?height\\s*:\\s*0(?:px)?\\s*;?\\s*", "gi"),
1534
+ ""
1535
+ );
1536
+ });
1537
+ result = result.replace(
1538
+ /(<style[^>]*>)([\s\S]*?)(<\/style>)/gi,
1539
+ (_m, open2, css, close) => (
1540
+ // @supports blocks are ignored like @media (probe sheet 07, same run).
1541
+ `${open2}${stripWordCss(stripMediaQueries(stripMediaQueries(css), "@supports"))}${close}`
1542
+ )
1543
+ );
1544
+ result = injectStyleIntoHtml(
1545
+ result,
1546
+ // The align rules sit here, after the stylesheet filter above, because that
1547
+ // filter drops attribute selectors, as Word does.
1548
+ // React Email's mso-font-width spacers rebuild a button's padding in Word
1549
+ // (Neon, local Outlook, 2026-11-02), so those links keep theirs, as do bordered ones.
1550
+ // Word lays every table out by its content and sizes a column to its longest
1551
+ // word: run J9vFS4nm_LGl's 1067px image pushed the text column aside, whole words.
1552
+ // Word drops CSS letter-spacing everywhere, any element, any unit (local
1553
+ // Outlook probe 2026-11-04; run 5EKcFWnZc92w's 5px eyebrow drew unspaced).
1554
+ // Word ignores a table's height, attribute or CSS, and keeps a cell's (same probe day).
1555
+ `<style>a:not(:has(i[style*="mso-font-width"])):not([data-word-box]){padding:0!important;margin:0!important;border-radius:0!important;min-width:0!important;min-height:0!important;display:inline!important}table[align="center" i]{margin-left:auto!important;margin-right:auto!important}table[align="right" i]{margin-left:auto!important}table{table-layout:auto!important;height:auto!important}*{word-break:normal!important;overflow-wrap:break-word!important}*{letter-spacing:normal!important}[style*="line-height:0;visibility:hidden"] *{line-height:0!important}</style>`
1556
+ );
1557
+ return result;
1558
+ }
1559
+ var WEBKIT_TARGET = /_:-webkit-full-screen\s*,\s*_::-webkit-full-page-media\s*,\s*_:future\s*,\s*/gi;
1560
+ var YAHOO_WRAPPER_ID = "yiv0123456789";
1561
+ function mapStyleBlocks(html, edit) {
1562
+ return html.replace(
1563
+ /(<style[^>]*>)([\s\S]*?)(<\/style>)/gi,
1564
+ (_, open2, css, close) => `${open2}${edit(css)}${close}`
1565
+ );
1566
+ }
1567
+ function wrapBodyInner(html, open2, close) {
1568
+ return html.replace(
1569
+ /(<body[^>]*>)([\s\S]*?)(<\/body>)/i,
1570
+ `$1${open2}$2${close}$3`
1571
+ );
1572
+ }
1573
+ function addBodyClass(html, className) {
1574
+ return html.replace(/<body\b([^>]*)>/i, (full, attrs) => {
1575
+ if (new RegExp(`\\b${className}\\b`).test(attrs)) return full;
1576
+ if (/\bclass\s*=\s*"/.test(attrs))
1577
+ return full.replace(/class="/, `class="${className} `);
1578
+ if (/\bclass\s*=\s*'/.test(attrs))
1579
+ return full.replace(/class='/, `class='${className} `);
1580
+ return `<body class="${className}"${attrs}>`;
1581
+ });
1582
+ }
1583
+ function activateAmpersandTarget(html, id) {
1584
+ var _a;
1585
+ const styles = (_a = html.match(/<style[^>]*>[\s\S]*?<\/style>/gi)) != null ? _a : [];
1586
+ if (!styles.some((block) => block.includes(".&"))) return html;
1587
+ return mapStyleBlocks(
1588
+ wrapBodyInner(html, `<div id="${id}">`, `</div>`),
1589
+ (css) => css.replace(/\.&/g, `#${id}`)
1590
+ );
1591
+ }
1592
+ function applyYahooCssQuirks(html) {
1593
+ return mapStyleBlocks(
1594
+ html,
1595
+ (css) => css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/!yahoo\b/gi, "").replace(/@media\s+screen\s+yahoo/gi, "@media screen")
1596
+ );
1597
+ }
1598
+ function prefixOutlookClasses(html) {
1599
+ const prefixed = html.replace(
1600
+ /\bclass\s*=\s*(["'])([^"']*)\1/gi,
1601
+ (_m, quote, classes) => {
1602
+ const next = classes.split(/\s+/).filter(Boolean).map(
1603
+ (name) => name === "emailens-shell" || name.startsWith("x_") ? name : `x_${name}`
1604
+ ).join(" ");
1605
+ return `class=${quote}${next}${quote}`;
1606
+ }
1607
+ );
1608
+ return mapStyleBlocks(
1609
+ prefixed,
1610
+ (css) => css.replace(
1611
+ /(^|[^.\w-])\.((?!x_)[A-Za-z_][\w-]*)/g,
1612
+ (whole, lead, name) => name === "emailens-shell" ? whole : `${lead}.x_${name}`
1613
+ )
1614
+ );
1615
+ }
1616
+ function applyClientTargeting(html, clientId) {
1617
+ let result = html;
1618
+ if (clientId === "apple-mail-macos" || clientId === "apple-mail-ios") {
1619
+ result = wrapBodyInner(
1620
+ addBodyClass(result, "Singleton"),
1621
+ `<div class="apple-mail">`,
1622
+ `</div>`
1623
+ );
1624
+ result = mapStyleBlocks(result, (css) => css.replace(WEBKIT_TARGET, ""));
1625
+ }
1626
+ if (clientId === "apple-mail-ios") {
1627
+ result = mapStyleBlocks(
1628
+ result,
1629
+ (css) => css.replace(
1630
+ /@supports\b[^{]*-webkit-overflow-scrolling\s*:\s*touch[^{]*/gi,
1631
+ "@media all "
1632
+ )
1633
+ );
1634
+ }
1635
+ if (clientId === "outlook-macos") {
1636
+ result = wrapBodyInner(result, `<div id="converted-body">`, `</div>`);
1637
+ result = mapStyleBlocks(result, (css) => css.replace(WEBKIT_TARGET, ""));
1638
+ }
1639
+ if (clientId === "thunderbird") {
1640
+ result = wrapBodyInner(result, `<div class="moz-text-html">`, `</div>`);
1641
+ result = mapStyleBlocks(
1642
+ result,
1643
+ (css) => css.replace(
1644
+ /@media\b[^{]*-moz-(?:device-pixel-ratio|windows-compositor)[^{]*/gi,
1645
+ "@media all "
1646
+ )
1647
+ );
1648
+ }
1649
+ if (clientId === "outlook-ios" || clientId === "outlook-android") {
1650
+ result = result.replace(
1651
+ /<body\b(?![^>]*\bdata-outlook-cycle\b)/i,
1652
+ `<body data-outlook-cycle=""`
1653
+ );
1654
+ }
1655
+ if (clientId === "outlook-ios") {
1656
+ result = wrapBodyInner(
1657
+ result,
1658
+ `<div class="olm-fragment-custom">`,
1659
+ `</div>`
1660
+ );
1661
+ }
1662
+ if (clientId === "outlook-windows") {
1663
+ result = mapStyleBlocks(result, (css) => css.replace(/\\0\/?/g, ""));
1664
+ result = retouchStyle(
1665
+ result,
1666
+ (style) => style.includes("\\0") ? style.replace(/\\0\/?/g, "") : null
1667
+ );
1668
+ }
1669
+ if (clientId === "outlook-web") result = prefixOutlookClasses(result);
1670
+ if (clientId === "aol") {
1671
+ result = applyYahooCssQuirks(result);
1672
+ result = activateAmpersandTarget(result, "aol-mail");
1673
+ }
1674
+ return result;
1675
+ }
1676
+ function getEffectiveWidth(clientId, html) {
1677
+ var _a;
1678
+ const vp = (_a = CLIENT_VIEWPORTS[clientId]) != null ? _a : DEFAULT_VIEWPORT;
1679
+ if (vp.isMobile && !isResponsiveEmail(html)) {
1680
+ return isMungeClient(clientId) ? vp.width : MOBILE_SHRINK_WIDTH;
1681
+ }
1682
+ return vp.width;
1683
+ }
1684
+ var OVERFLOW_TOLERANCE_PX = 2;
1685
+ var KEEPS_OVERFLOW = /* @__PURE__ */ new Set(["apple-mail-ios"]);
1686
+ var zoomsOutOverflow = (clientId) => {
1687
+ var _a;
1688
+ return ((_a = CLIENT_VIEWPORTS[clientId]) != null ? _a : DEFAULT_VIEWPORT).isMobile === true && !KEEPS_OVERFLOW.has(clientId);
1689
+ };
1690
+ function mobileShrink(clientId, layoutWidth, measuredWidth) {
1691
+ var _a;
1692
+ const vp = (_a = CLIENT_VIEWPORTS[clientId]) != null ? _a : DEFAULT_VIEWPORT;
1693
+ const measured = measuredWidth != null ? measuredWidth : 0;
1694
+ const overflows = measured > vp.width + OVERFLOW_TOLERANCE_PX;
1695
+ const shrinks = vp.isMobile && (layoutWidth > vp.width || overflows && zoomsOutOverflow(clientId));
1696
+ if (!shrinks) return { naturalWidth: vp.width, scale: 1 };
1697
+ const naturalWidth = Math.max(layoutWidth, measured);
1698
+ return { naturalWidth, scale: vp.width / naturalWidth };
1699
+ }
1700
+ function shrinkToFitStyle(naturalWidth, scale) {
1701
+ if (scale === 1) return "";
1702
+ return `<style>.emailens-shell{width:${naturalWidth}px!important;max-width:${naturalWidth}px!important;transform:scale(${scale});transform-origin:top left;}</style>`;
1703
+ }
1704
+ var SCROLLBAR_STYLE = `<style>*{scrollbar-width:thin;scrollbar-color:rgba(128,128,128,.25) transparent}::-webkit-scrollbar{width:5px;height:5px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:rgba(128,128,128,.25);border-radius:9999px}::-webkit-scrollbar-thumb:hover{background:rgba(128,128,128,.4)}</style>`;
1705
+ var FONT_FACES = [
1706
+ ["Roboto", "roboto"],
1707
+ ["Carlito", "carlito"],
1708
+ ["Arimo", "arimo"],
1709
+ ["Tinos", "tinos"],
1710
+ ["Selawik", "selawik"],
1711
+ ["Gelasio", "gelasio"],
1712
+ ["Cousine", "cousine"],
1713
+ ["Arial", "arimo"],
1714
+ ["Helvetica", "arimo"],
1715
+ ["Calibri", "carlito"],
1716
+ ["Times New Roman", "tinos"],
1717
+ ["Segoe UI", "selawik"],
1718
+ ["Segoe UI Web (West European)", "selawik"],
1719
+ ["Georgia", "gelasio"],
1720
+ ["Courier New", "cousine"],
1721
+ ["Source Serif 4", "source-serif-4"]
1722
+ ];
1723
+ var ITALIC_FILES = /* @__PURE__ */ new Set([
1724
+ "roboto",
1725
+ "carlito",
1726
+ "arimo",
1727
+ "tinos",
1728
+ "gelasio",
1729
+ "cousine",
1730
+ "source-serif-4"
1731
+ ]);
1732
+ function fontFace(family2, file, weight, italic) {
1733
+ const style = italic ? "italic" : "normal";
1734
+ const suffix = italic ? "italic" : "";
1735
+ return `@font-face{font-family:'${family2}';font-weight:${weight};font-style:${style};font-display:swap;src:url('/fonts/${file}-${weight}${suffix}.woff2') format('woff2')}`;
1736
+ }
1737
+ var faceRules = (faces) => faces.flatMap(([family2, file]) => {
1738
+ const rules = [400, 700].map((w) => fontFace(family2, file, w, false));
1739
+ if (ITALIC_FILES.has(file))
1740
+ rules.push(...[400, 700].map((w) => fontFace(family2, file, w, true)));
1741
+ return rules;
1742
+ }).join("");
1743
+ var FONT_FACE_STYLE = faceRules(FONT_FACES);
1744
+ var FONT_FACE_TAG = `<style>${FONT_FACE_STYLE}</style>`;
1745
+ var NO_SEGOE_FACE_TAG = `<style>${faceRules(
1746
+ FONT_FACES.filter(([family2]) => !family2.startsWith("Segoe UI"))
1747
+ )}</style>`;
1748
+ var hasSegoe = (clientId) => !/-(ios|android|macos)$/.test(clientId) && clientId !== "samsung-mail";
1749
+ var isApple = (clientId) => /-(ios|macos)$/.test(clientId);
1750
+ var APPLE_SYSTEM = "Apple System";
1751
+ var APPLE_SYSTEM_FILE = "selawik";
1752
+ var APPLE_SYSTEM_TAG = `<style>${[400, 700].map((w) => fontFace(APPLE_SYSTEM, APPLE_SYSTEM_FILE, w, false)).join("")}</style>`;
1753
+ var FONT_FAMILY = /(font-family\s*:\s*)((?:&quot;|'[^']*'|"[^"<>=]*"|[^;}"'<>!])+)/gi;
1754
+ var SYSTEM_NAMES = /^\s*(-apple-system|BlinkMacSystemFont|system-ui)\s*$/i;
1755
+ function platformFonts(html, clientId) {
1756
+ const apple = isApple(clientId);
1757
+ const segoe = hasSegoe(clientId);
1758
+ if (segoe && !apple) return html;
1759
+ return html.replace(FONT_FAMILY, (whole, prop, value) => {
1760
+ const families = value.split(",");
1761
+ const kept = families.filter((f) => segoe || !/^\s*(&quot;|["'])?Segoe UI/i.test(f)).map((f) => apple && SYSTEM_NAMES.test(f) ? `'${APPLE_SYSTEM}'` : f);
1762
+ if (kept.join(",") === value) return whole;
1763
+ return `${prop}${kept.join(",").trim() || "sans-serif"}`;
1764
+ });
1765
+ }
1766
+ var WORD_FONT_METRICS = [
1767
+ ["Segoe UI", "selawik", 106, 30, 100],
1768
+ ["Aptos", "selawik", 106, 32, 93.7],
1769
+ ["Arial", "arimo", 96, 23, 100],
1770
+ ["Helvetica", "arimo", 96, 23, 100],
1771
+ ["Georgia", "gelasio", 95, 24, 100],
1772
+ ["Calibri", "carlito", 98, 31, 100],
1773
+ ["Times New Roman", "tinos", 96, 23, 100],
1774
+ ["Courier New", "cousine", 90, 24, 100],
1775
+ ["Gill Sans MT", "arimo", 120.2, 33.4, 93.6, 99.1],
1776
+ ["Gill Sans MT Large", "arimo", 99.3, 24.6, 93.6, 99.1]
1777
+ ];
1778
+ var WORD_CLOUD_FONTS = [
1779
+ ["Work Sans", "work-sans", 98.2, 25.6],
1780
+ ["Lato", "lato", 104.2, 22.5],
1781
+ ["Montserrat", "montserrat", 101.9, 26.4],
1782
+ ["Nunito", "nunito", 106.2, 37.1],
1783
+ ["Nunito Sans", "nunito-sans", 106.2, 37.1],
1784
+ ["Open Sans", "open-sans", 112.2, 30.7],
1785
+ ["DM Sans", "dm-sans", 104.2, 32.5],
1786
+ ["IBM Plex Sans", "ibm-plex-sans", 107.8, 28.9],
1787
+ ["Ubuntu", "ubuntu", 98.8, 20],
1788
+ ["Source Code Pro", "source-code-pro", 103.6, 28.8],
1789
+ ["Raleway", "raleway", 99.4, 24.7],
1790
+ ["Playfair Display", "playfair-display", 113.6, 26.4],
1791
+ ["Poppins", "poppins", 117.5, 39.1]
1792
+ ];
1793
+ var WORD_SINGLE_SPACING = [
1794
+ ["Segoe UI", 1.4],
1795
+ ["Aptos", 1.29],
1796
+ ["Calibri", 1.29],
1797
+ ["Verdana", 1.27],
1798
+ ["Tahoma", 1.27],
1799
+ ["Courier", 1.14],
1800
+ ["Arial", 1.19],
1801
+ ["Helvetica", 1.19],
1802
+ ["Georgia", 1.19],
1803
+ ["Times", 1.19],
1804
+ ["Gill Sans MT Large", 1.2],
1805
+ ["Gill Sans", 1.45],
1806
+ ...WORD_CLOUD_FONTS.map(
1807
+ ([family2, , ascent, descent]) => [family2, (ascent + descent) / 100]
1808
+ )
1809
+ ];
1810
+ var WORD_CLOUD_FONTS_STYLE = WORD_CLOUD_FONTS.flatMap(
1811
+ ([family2, file, ascent, descent]) => {
1812
+ const spacing = `ascent-override:${ascent}%;descent-override:${descent}%;line-gap-override:0%`;
1813
+ return [
1814
+ `@font-face{font-family:'${family2}';font-weight:400;font-display:swap;src:url('/fonts/${file}-400.woff2') format('woff2');${spacing}}`,
1815
+ `@font-face{font-family:'${family2}';font-weight:700;font-display:swap;src:url('/fonts/${file}-700.woff2') format('woff2');${spacing}}`,
1816
+ `@font-face{font-family:'${family2}';font-weight:400;font-style:italic;font-display:swap;src:url('/fonts/${file}-400italic.woff2') format('woff2');${spacing}}`
1817
+ ];
1818
+ }
1819
+ ).join("");
1820
+ var WORD_FONT_METRICS_TAG = `<style>${WORD_CLOUD_FONTS_STYLE}${WORD_FONT_METRICS.flatMap(
1821
+ ([family2, file, ascent, descent, size, bold = size]) => [400, 700].map((weight) => {
1822
+ const adjust = weight === 700 ? bold : size;
1823
+ const scale = (v) => Math.round(v * size * 10 / adjust) / 10;
1824
+ return `@font-face{font-family:'${family2}';font-weight:${weight};font-display:swap;src:url('/fonts/${file}-${weight}.woff2') format('woff2');ascent-override:${scale(ascent)}%;descent-override:${scale(descent)}%;line-gap-override:0%;size-adjust:${adjust}%}`;
1825
+ })
1826
+ ).join("")}</style>`;
1827
+ var GMAIL_ANDROID_FONTS_TAG = `<style>${[
1828
+ "Arial",
1829
+ "Helvetica",
1830
+ "Helvetica Neue"
1831
+ ].flatMap(
1832
+ (family2) => [400, 700].flatMap(
1833
+ (weight) => [false, true].map((italic) => fontFace(family2, "roboto", weight, italic))
1834
+ )
1835
+ ).join("")}</style>`;
1836
+ var HTML_ESCAPES = {
1837
+ "&": "&amp;",
1838
+ "<": "&lt;",
1839
+ ">": "&gt;",
1840
+ '"': "&quot;"
1841
+ };
1842
+ var escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => HTML_ESCAPES[c]);
1843
+ function blockImagesInHtml(html) {
1844
+ return html.replace(/<img\b[^>]*>/gi, (tag) => {
1845
+ var _a, _b, _c, _d;
1846
+ const alt = (_b = (_a = /\balt\s*=\s*["']([^"']*)["']/i.exec(tag)) == null ? void 0 : _a[1]) != null ? _b : "";
1847
+ const width = (_c = /\bwidth\s*=\s*["']?(\d+)/i.exec(tag)) == null ? void 0 : _c[1];
1848
+ const height = (_d = /\bheight\s*=\s*["']?(\d+)/i.exec(tag)) == null ? void 0 : _d[1];
1849
+ const size = [
1850
+ width ? `width:${width}px` : "",
1851
+ height ? `height:${height}px` : "",
1852
+ "max-width:100%"
1853
+ ].filter(Boolean).join(";");
1854
+ return `<span role="img" aria-label="${escapeHtml(alt)}" style="display:inline-block;box-sizing:border-box;${size};min-width:28px;min-height:28px;border:1px solid #d0d0d0;background:#f4f4f4;color:#999;font:11px/1.3 -apple-system,sans-serif;padding:4px;vertical-align:top;overflow:hidden">&#128247; ${escapeHtml(alt)}</span>`;
1855
+ });
1856
+ }
1857
+ var NEVER_MATCHES = "(min-width:999999px)";
1858
+ var ALWAYS_MATCHES = "(min-width:0px)";
1859
+ var PREFERS_DARK_RE = /\(\s*prefers-color-scheme\s*:\s*dark\s*\)/gi;
1860
+ var PREFERS_LIGHT_RE = /\(\s*prefers-color-scheme\s*:\s*light\s*\)/gi;
1861
+ function pinPrefersColorScheme(html, darkActive) {
1862
+ return html.replace(PREFERS_DARK_RE, darkActive ? ALWAYS_MATCHES : NEVER_MATCHES).replace(PREFERS_LIGHT_RE, darkActive ? NEVER_MATCHES : ALWAYS_MATCHES);
1863
+ }
1864
+ var DECLARES_COLOR_SCHEME = new RegExp(`<meta\\b(?=[^>]*\\bname\\s*=\\s*["']?(?:color-scheme|supported-color-schemes)\\b)[^>]*\\bcontent\\s*=\\s*["'][^"']*\\bdark\\b|(?<!prefers-)color-scheme\\s*:[^;}"']*\\bdark\\b`, "i");
1865
+ function darkReachesContent(html, clientId) {
1866
+ if (!clientTriggersPrefersColorScheme(clientId)) return false;
1867
+ return clientId !== "apple-mail-macos" || DECLARES_COLOR_SCHEME.test(html);
1868
+ }
1869
+ var BODY_CANVAS_CLIENTS = /* @__PURE__ */ new Set([
1870
+ "outlook-windows-legacy",
1871
+ "apple-mail-macos",
1872
+ "outlook-macos",
1873
+ "gmail-web",
1874
+ "protonmail"
1875
+ ]);
1876
+ function bodyCanvas(html) {
1877
+ var _a, _b, _c, _d, _e, _f;
1878
+ const body = (_b = (_a = html.match(/<body[^>]*>/i)) == null ? void 0 : _a[0]) != null ? _b : "";
1879
+ return (_f = (_e = (_c = body.match(
1880
+ /style\s*=\s*"[^"]*background(?:-color)?\s*:\s*([^;"]+)/i
1881
+ )) == null ? void 0 : _c[1]) != null ? _e : (_d = body.match(/bgcolor\s*=\s*["']?([^"'\s>]+)/i)) == null ? void 0 : _d[1]) == null ? void 0 : _f.trim();
1882
+ }
1883
+ function bodyDeclaresFont(html) {
1884
+ const live = html.replace(/<!--[\s\S]*?-->/g, "");
1885
+ if (/<body\b[^>]*\bstyle\s*=\s*(["'])[^"']*font-family/i.test(live))
1886
+ return true;
1887
+ return /<style[^>]*>[\s\S]*?(?:^|[}\s,;])(?:html|body)\s*(?:,[^{]*)?\{[^}]*font-family[\s\S]*?<\/style>/i.test(
1888
+ live
1889
+ );
1890
+ }
1891
+ function prepareIframeHtml(html, clientId, isDarkMode, blockImages = false, options) {
1892
+ var _a;
1893
+ const mode = isDarkMode ? "dark" : "light";
1894
+ const vp = (_a = CLIENT_VIEWPORTS[clientId]) != null ? _a : DEFAULT_VIEWPORT;
1895
+ const contentDark = isDarkMode && darkReachesContent(html, clientId);
1896
+ const pinned = pinPrefersColorScheme(html, contentDark);
1897
+ const mutated = applyClientMutations(pinned, clientId);
1898
+ const imaged = blockImages ? blockImagesInHtml(mutated) : mutated;
1899
+ const shelled = wrapInShell(imaged);
1900
+ const shellStyle = buildShellStyle(
1901
+ clientId,
1902
+ mode,
1903
+ bodyDeclaresFont(mutated),
1904
+ BODY_CANVAS_CLIENTS.has(clientId) && !isDarkMode ? bodyCanvas(mutated) : void 0
1905
+ );
1906
+ const viewportMeta = vp.isMobile ? `<meta name="viewport" content="width=device-width, initial-scale=1">` : "";
1907
+ const colorSchemeMeta = contentDark ? `<meta name="color-scheme" content="dark light"><style>:root{color-scheme:dark}</style>` : "";
1908
+ let scaleStyle = "";
1909
+ if ((options == null ? void 0 : options.scaleToFit) && vp.isMobile && !isResponsiveEmail(html) && !isMungeClient(clientId)) {
1910
+ const fit = mobileShrink(clientId, getEffectiveWidth(clientId, html), null);
1911
+ scaleStyle = shrinkToFitStyle(fit.naturalWidth, fit.scale);
1912
+ }
1913
+ const doc = injectStyleIntoHtml(
1914
+ shelled,
1915
+ viewportMeta + colorSchemeMeta + (hasSegoe(clientId) ? FONT_FACE_TAG : NO_SEGOE_FACE_TAG) + (isApple(clientId) ? APPLE_SYSTEM_TAG : "") + (clientId === "outlook-windows-legacy" ? WORD_FONT_METRICS_TAG : "") + (clientId === "gmail-android" ? GMAIL_ANDROID_FONTS_TAG : "") + SCROLLBAR_STYLE + shellStyle + scaleStyle
1916
+ );
1917
+ return platformFonts(
1918
+ clientId === "protonmail" ? prependToHead(doc, PROTON_MESSAGE_CSS) : doc,
1919
+ clientId
1920
+ );
1921
+ }
1922
+ var PROTON_MESSAGE_CSS = "<style>body{font-size:14px}p,ul,ol,dl,blockquote,pre,menu,td,th{font-size:1em;margin-inline:0}blockquote,dl,ol,p,pre,td,th,ul{margin-block:0}p{margin-block:1em}table{margin-block-end:0;table-layout:auto}ul,ol,menu{padding-inline-start:2.5em}blockquote{margin:0;padding:0 0 0 16px;border-left:4px solid #e5e5e5}small{font-size:80%}a{color:#6d4aff;text-decoration:underline}body *{line-height:1.5}code{line-height:1}</style>";
1923
+ function prependToHead(html, tag) {
1924
+ return /<head[^>]*>/i.test(html) ? html.replace(/<head([^>]*)>/i, `<head$1>${tag}`) : tag + html;
1925
+ }
1926
+ var viewOf = (client) => {
1927
+ var _a;
1928
+ return (_a = CLIENT_VIEWPORTS[client]) != null ? _a : DEFAULT_VIEWPORT;
1929
+ };
1930
+ function designDoc(html, client, frameWidth) {
1931
+ var _a, _b, _c, _d;
1932
+ const shellStyle = buildShellStyle(client, "light", false);
1933
+ const shell = (_b = (_a = /\.emailens-shell\{([^}]*)\}/.exec(shellStyle)) == null ? void 0 : _a[1]) != null ? _b : "";
1934
+ const gutter = (_d = (_c = /padding:\s*\S+\s+(\d+px)/.exec(shell)) == null ? void 0 : _c[1]) != null ? _d : "0px";
1935
+ const fits = /\.emailens-shell img\{/.test(shellStyle);
1936
+ const doc = injectStyleIntoHtml(
1937
+ html,
1938
+ `<style>html,body{margin:0!important}:root{box-sizing:border-box!important;width:${frameWidth}px!important;padding:0 ${gutter}!important}${fits ? "img{max-width:100%;height:auto}" : ""}</style>`
1939
+ );
1940
+ return { doc, fits };
1941
+ }
1942
+ function releaseImages(doc, frame) {
1943
+ var _a;
1944
+ const root = doc.documentElement;
1945
+ for (const img of doc.images) {
1946
+ const own = Number.parseFloat((_a = img.getAttribute("width")) != null ? _a : "");
1947
+ if (!own || img.getBoundingClientRect().width >= own) continue;
1948
+ img.style.maxWidth = "none";
1949
+ if (root.scrollWidth > frame) img.style.maxWidth = "";
1950
+ }
1951
+ }
1952
+ function emailWidth(doc) {
1953
+ var _a;
1954
+ const shell = (_a = doc.querySelector(".emailens-shell")) != null ? _a : doc.body;
1955
+ const left2 = shell.getBoundingClientRect().left;
1956
+ const right = [...shell.querySelectorAll("*")].map((el) => el.getBoundingClientRect()).filter((r) => r.width > 0).reduce((m, r) => Math.max(m, r.right), left2);
1957
+ return Math.ceil(right - left2);
1958
+ }
1959
+ function frameOf(root) {
1960
+ const width = root.offsetWidth || 1;
1961
+ return { width, zoom: root.getBoundingClientRect().width / width };
1962
+ }
1963
+ var APP = "https://app.emailens.test";
1964
+ var FONTS_FROM = "https://app.emailens.dev/fonts/";
1965
+ var FONT_CACHE = join(homedir(), ".cache", "emailens", "fonts");
1966
+ var CONNECT_TIMEOUT_MS = 15e3;
1967
+ var VERDICT_LABEL = {
1968
+ kept: "Ready",
1969
+ changed: "Needs work",
1970
+ broken: "Broken"
1971
+ };
1972
+ var sharpP;
1973
+ var loadSharp = () => sharpP != null ? sharpP : sharpP = import("sharp").then(
1974
+ (m) => {
1975
+ var _a;
1976
+ return (_a = m.default) != null ? _a : m;
1977
+ },
1978
+ () => null
1979
+ );
1980
+ var MAX_HEIGHT = 5e3;
1981
+ var MAX_CSS_HEIGHT = 4e3;
1982
+ async function gray(sharp, png, cssPerPx) {
1983
+ const img = sharp(png);
1984
+ const { width = 1, height = 1 } = await img.metadata();
1985
+ const rows = Math.min(height, Math.ceil(MAX_CSS_HEIGHT / cssPerPx));
1986
+ const { data, info } = await img.extract({ left: 0, top: 0, width, height: rows }).resize({ width: Math.max(1, Math.round(width * cssPerPx)) }).greyscale().raw().toBuffer({ resolveWithObject: true });
1987
+ const out = new Uint8Array(info.width * info.height);
1988
+ for (let i = 0; i < out.length; i++) out[i] = data[i * info.channels];
1989
+ return { data: out, width: info.width, height: info.height };
1990
+ }
1991
+ async function shoot(page, minWidth) {
1992
+ const [width, height] = await page.evaluate(
1993
+ `[document.documentElement.scrollWidth, Math.ceil([...document.body.querySelectorAll("*")].map((e) => e.getBoundingClientRect()).filter((r) => r.height > 0).reduce((m, r) => Math.max(m, r.bottom), 0) || document.body.scrollHeight)]`
1994
+ );
1995
+ return page.screenshot({
1996
+ fullPage: true,
1997
+ clip: {
1998
+ x: 0,
1999
+ y: 0,
2000
+ width: Math.max(minWidth, width),
2001
+ height: Math.min(Math.max(height, 1), MAX_HEIGHT)
2002
+ }
2003
+ });
2004
+ }
2005
+ async function openBrowser() {
2006
+ let chromium;
2007
+ try {
2008
+ chromium = (await import("playwright-core")).chromium;
2009
+ } catch (e) {
2010
+ throw new Error(
2011
+ 'The design check needs "playwright-core" installed beside this package (npm install playwright-core), and a browser: a local Chromium (npx playwright-core install chromium) or BROWSERLESS_URL.'
2012
+ );
2013
+ }
2014
+ const url = process.env.BROWSERLESS_URL;
2015
+ if (!url) {
2016
+ return chromium.launch().catch((e) => {
2017
+ throw new Error(
2018
+ `No local Chromium (${e.message.split("\n")[0]}).
2019
+ Set BROWSERLESS_URL to a Browserless instance, or install one: npx playwright-core install chromium`
2020
+ );
2021
+ });
2022
+ }
2023
+ let timer;
2024
+ return Promise.race([
2025
+ chromium.connectOverCDP(url),
2026
+ new Promise((_, reject) => {
2027
+ timer = setTimeout(
2028
+ () => reject(new Error(`Browserless connection timed out after ${CONNECT_TIMEOUT_MS / 1e3}s. Check BROWSERLESS_URL.`)),
2029
+ CONNECT_TIMEOUT_MS
2030
+ );
2031
+ })
2032
+ ]).finally(() => clearTimeout(timer));
2033
+ }
2034
+ async function font(name) {
2035
+ const file = join(FONT_CACHE, name);
2036
+ if (existsSync(file)) return readFileSync(file);
2037
+ const res = await fetch(FONTS_FROM + name).catch(() => null);
2038
+ if (!(res == null ? void 0 : res.ok)) return null;
2039
+ const body = Buffer.from(await res.arrayBuffer());
2040
+ mkdirSync(FONT_CACHE, { recursive: true });
2041
+ writeFileSync(file, body);
2042
+ return body;
2043
+ }
2044
+ async function serve(route, doc) {
2045
+ const url = route.request().url();
2046
+ if (url === `${APP}/page`)
2047
+ return route.fulfill({ contentType: "text/html; charset=utf-8", body: doc });
2048
+ if (url.startsWith(`${APP}/fonts/`)) {
2049
+ const name = url.slice(`${APP}/fonts/`.length);
2050
+ const body = /^[a-z0-9-]+\.woff2$/.test(name) ? await font(name) : null;
2051
+ return body ? route.fulfill({ contentType: "font/woff2", body }) : route.fulfill({ status: 404, body: "" });
2052
+ }
2053
+ return /^https?:\/\//i.test(url) ? route.continue() : route.abort();
2054
+ }
2055
+ async function open(browser, doc, width, scale) {
2056
+ const context = await browser.newContext({
2057
+ viewport: { width, height: 900 },
2058
+ deviceScaleFactor: scale,
2059
+ javaScriptEnabled: false
2060
+ });
2061
+ const page = await context.newPage();
2062
+ await page.route("**/*", (route) => serve(route, doc).catch(() => {
2063
+ }));
2064
+ await page.goto(`${APP}/page`, { waitUntil: "load", timeout: 3e4 }).catch(() => {
2065
+ });
2066
+ await page.evaluate("document.fonts.ready");
2067
+ return { page, close: () => context.close() };
2068
+ }
2069
+ async function pixelGap(sharp, simPng, designPage, width, zoom) {
2070
+ return measureGap(
2071
+ await gray(sharp, simPng, 1 / 2),
2072
+ await gray(sharp, await shoot(designPage, width), zoom / 2)
2073
+ );
2074
+ }
2075
+ async function drawSim(browser, transformed, clientId, width, sharp) {
2076
+ const sim = await open(
2077
+ browser,
2078
+ prepareIframeHtml(transformed, clientId, false, false, { scaleToFit: true }),
2079
+ width,
2080
+ sharp ? 2 : 1
2081
+ );
2082
+ try {
2083
+ const drawn2 = await sim.page.evaluate(`(${emailWidth})(document)`);
2084
+ const fit = mobileShrink(clientId, width, drawn2);
2085
+ if (fit.scale !== 1)
2086
+ await sim.page.evaluate(
2087
+ `document.head.insertAdjacentHTML("beforeend", ${JSON.stringify(shrinkToFitStyle(fit.naturalWidth, fit.scale))})`
2088
+ );
2089
+ const root = `(document.querySelector(".emailens-shell") ?? document.body)`;
2090
+ const nodes = await sim.page.evaluate(`(${dumpDom})(${root})`);
2091
+ const frame = await sim.page.evaluate(`(${frameOf})(${root})`);
2092
+ const png = sharp ? await shoot(sim.page, width) : null;
2093
+ return { nodes, frame, png };
2094
+ } finally {
2095
+ await sim.close();
2096
+ }
2097
+ }
2098
+ function resultOf(clientId, name, kept, gap) {
2099
+ const verdict = verdictOf(kept, gap == null ? void 0 : gap.diff);
2100
+ return __spreadValues(__spreadValues({
2101
+ clientId,
2102
+ name,
2103
+ verdict,
2104
+ label: VERDICT_LABEL[verdict]
2105
+ }, explainDesign({ verdict, kept }, name)), gap ? { diff: +gap.diff.toFixed(4), aligned: aligned(gap) } : {});
2106
+ }
2107
+ async function checkDesign(browser, html, clientId, framework) {
2108
+ var _a, _b;
2109
+ if (!hasDesign(html)) return null;
2110
+ const name = (_b = (_a = EMAIL_CLIENTS.find((c) => c.id === clientId)) == null ? void 0 : _a.name) != null ? _b : clientId;
2111
+ const transformed = transformForClient(prepareWordSource(html), clientId, framework).html;
2112
+ const { width } = viewOf(clientId);
2113
+ const sharp = await loadSharp();
2114
+ const sim = await drawSim(browser, transformed, clientId, width, sharp);
2115
+ const { doc, fits } = designDoc(html, clientId, sim.frame.width);
2116
+ const design = await open(browser, doc, width, sharp ? 2 : 1);
2117
+ try {
2118
+ if (fits) await design.page.evaluate(`(${releaseImages})(document, ${sim.frame.width})`);
2119
+ const nodes = await design.page.evaluate(
2120
+ `(${markPictures})(document.body, (${dumpDom})(document.body))`
2121
+ );
2122
+ const zoom = sim.frame.zoom || 1;
2123
+ const gap = sharp && sim.png ? await pixelGap(sharp, sim.png, design.page, width, zoom) : null;
2124
+ return resultOf(clientId, name, keptOf(nodes, sim.nodes, zoom), gap);
2125
+ } finally {
2126
+ await design.close();
2127
+ }
2128
+ }
2129
+ async function checkDesignAcross(html, clientIds, opts = {}) {
2130
+ var _a;
2131
+ const browser = await openBrowser();
2132
+ try {
2133
+ const out = /* @__PURE__ */ new Map();
2134
+ const queue = [...clientIds];
2135
+ let done = 0;
2136
+ const work = async () => {
2137
+ var _a2;
2138
+ for (let id = queue.shift(); id; id = queue.shift()) {
2139
+ const r = await checkDesign(browser, html, id, opts.framework);
2140
+ if (r) out.set(id, r);
2141
+ (_a2 = opts.onProgress) == null ? void 0 : _a2.call(opts, ++done, clientIds.length);
2142
+ }
2143
+ };
2144
+ await Promise.all(Array.from({ length: (_a = opts.parallel) != null ? _a : 4 }, work));
2145
+ return clientIds.flatMap((id) => {
2146
+ var _a2;
2147
+ return (_a2 = out.get(id)) != null ? _a2 : [];
2148
+ });
2149
+ } finally {
2150
+ await browser.close();
2151
+ }
2152
+ }
2153
+ var PLACEHOLDER = /\{\{|\}\}|\*\||\|\*|%%|\$\{|\[\[/;
2154
+ var CSS_URL = /url\(\s*['"]?([^'")]+)['"]?\s*\)/g;
2155
+ var tiny = (v) => !!v && Number.parseFloat(v) <= 2;
2156
+ function imageUrls(html) {
2157
+ const $ = load(html);
2158
+ const found = [];
2159
+ $("img").each((_, el) => {
2160
+ var _a, _b, _c, _d;
2161
+ const img = $(el);
2162
+ const style = (_a = img.attr("style")) != null ? _a : "";
2163
+ if (tiny(img.attr("width")) || tiny(img.attr("height")) || tiny((_b = /(?:^|;)\s*width\s*:\s*([\d.]+)px/.exec(style)) == null ? void 0 : _b[1]) || tiny((_c = /(?:^|;)\s*height\s*:\s*([\d.]+)px/.exec(style)) == null ? void 0 : _c[1]))
2164
+ return;
2165
+ found.push((_d = img.attr("src")) != null ? _d : "");
2166
+ });
2167
+ $("[background]").each((_, el) => {
2168
+ var _a;
2169
+ found.push((_a = $(el).attr("background")) != null ? _a : "");
2170
+ });
2171
+ const css = [
2172
+ ...$("[style]").map((_, el) => {
2173
+ var _a;
2174
+ return (_a = $(el).attr("style")) != null ? _a : "";
2175
+ }).get(),
2176
+ ...$("style").map((_, el) => $(el).text()).get()
2177
+ ];
2178
+ for (const text of css)
2179
+ for (const m of text.matchAll(CSS_URL)) found.push(m[1]);
2180
+ const urls = found.map((u) => u.trim()).filter((u) => u && !/^(data|cid|about|blob):/i.test(u)).filter((u) => !PLACEHOLDER.test(u)).map((u) => u.startsWith("//") ? `https:${u}` : u);
2181
+ return [...new Set(urls)];
2182
+ }
2183
+ var DEAD_STATUS = /* @__PURE__ */ new Set([400, 404, 410]);
2184
+ function judge(r) {
2185
+ if (r.ok)
2186
+ return /^text\/html|^application\/(json|xml)/i.test(r.contentType) ? "dead" : "alive";
2187
+ if (r.kind === "bad_status" && r.status && DEAD_STATUS.has(r.status))
2188
+ return "dead";
2189
+ if (r.kind === "too_large") return "alive";
2190
+ return r.kind === "unreachable" ? "dead" : "unsure";
2191
+ }
2192
+ async function dead(url, fetcher) {
2193
+ if (!/^https?:\/\//i.test(url)) return true;
2194
+ if (url.startsWith("http://")) return false;
2195
+ const first = await fetcher(url);
2196
+ if (first.ok || first.kind !== "unreachable") return judge(first) === "dead";
2197
+ return judge(await fetcher(url)) === "dead";
2198
+ }
2199
+ async function deadImages(html, fetcher) {
2200
+ const urls = imageUrls(html);
2201
+ const out = [];
2202
+ for (let i = 0; i < urls.length; i += 6) {
2203
+ const batch = urls.slice(i, i + 6);
2204
+ const flags = await Promise.all(batch.map((u) => dead(u, fetcher)));
2205
+ out.push(...batch.filter((_, j) => flags[j]));
2206
+ }
2207
+ return out;
2208
+ }
2209
+ var PROVEN = /* @__PURE__ */ new Set([
2210
+ "gmail-web",
2211
+ "gmail-android",
2212
+ "yahoo-mail",
2213
+ "protonmail",
2214
+ "apple-mail-macos",
2215
+ "outlook-macos"
2216
+ ]);
2217
+ var PROVEN_CAP = 49;
2218
+ var UNPROVEN_CAP = 79;
2219
+ var DEAD_IMAGE = 10;
2220
+ function renderScores(engine, verdicts, deadImages2) {
2221
+ return Object.fromEntries(
2222
+ Object.entries(engine).map(([client, score]) => {
2223
+ const s = Math.max(0, score - DEAD_IMAGE * deadImages2);
2224
+ if (verdicts[client] !== "broken") return [client, s];
2225
+ return [
2226
+ client,
2227
+ Math.min(s, PROVEN.has(client) ? PROVEN_CAP : UNPROVEN_CAP)
2228
+ ];
2229
+ })
2230
+ );
2231
+ }
2232
+ export {
2233
+ CLIENT_VIEWPORTS,
2234
+ COLUMNS,
2235
+ CONTENT,
2236
+ DEAD_IMAGE,
2237
+ PROVEN,
2238
+ VERDICT_LABEL,
2239
+ WIDTH,
2240
+ checkDesign,
2241
+ checkDesignAcross,
2242
+ deadImages,
2243
+ designDoc,
2244
+ dumpDom,
2245
+ emailWidth,
2246
+ explainDesign,
2247
+ frameOf,
2248
+ hasDesign,
2249
+ imageUrls,
2250
+ isEmail,
2251
+ keptOf,
2252
+ markPictures,
2253
+ matchNodes,
2254
+ mobileShrink,
2255
+ openBrowser,
2256
+ prepareIframeHtml,
2257
+ prepareWordSource,
2258
+ releaseImages,
2259
+ renderScores,
2260
+ sameValue,
2261
+ shrinkToFitStyle,
2262
+ verdictOf,
2263
+ viewOf
2264
+ };