import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import SiteDiskContentCache from "../files/SiteDiskContentCache.js"; import { JSDOM } from 'jsdom'; import { fetch, Agent } from "undici"; import { lookup } from "dns"; @RegisterScoped export default class HtmlForEmailService { @Inject diskCache: SiteDiskContentCache; async prepareHtml({ html, siteID, path, url }: { html: string, url :string, siteID, path: string[] }) { const browser = new JSDOM(html, { url}); await new Promise((resolve, reject) => { browser.window.addEventListener("load", () => { void inlineCSS(browser.window, browser.window.document).then(resolve); }); }); html = browser.window.document.documentElement.outerHTML; return html; } } async function inlineCSS(window, document: Document){ const dispatcher = new Agent({ connect: { lookup: (hostName, { all }, callback) => { const cb = (error, result) => { if (all) { callback(error, [{ address: result, family: 4 }]); } return callback(error, result, 4); }; if (hostName.endsWith(".localhost")) { // eslint-disable-next-line no-console console.log(`Resolving ${hostName} to 192.168.0.123`); cb(null, "192.168.0.123"); return; } lookup(hostName, 4, (error, result) => { // eslint-disable-next-line no-console console.log(`Resolving ${hostName} to ${result}`); cb(error, result); }); }, family: 4 } }); let id = Date.now(); window.CSS ??= {}; window.CSS.escape = function(value) { if (!value) { throw new TypeError('`CSS.escape` requires an argument.'); } const text = String(value); const length = text.length; let index = -1; let codeUnit; let result = ''; const firstCodeUnit = text.charCodeAt(0); if ( // If the character is the first character and is a `-` (U+002D), and // there is no second character, […] length === 1 && firstCodeUnit === 0x002D ) { return '\\' + text; } while (++index < length) { codeUnit = text.charCodeAt(index); // Note: there’s no need to special-case astral symbols, surrogate // pairs, or lone surrogates. // If the character is NULL (U+0000), then the REPLACEMENT CHARACTER // (U+FFFD). if (codeUnit === 0x0000) { result += '\uFFFD'; continue; } if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is // U+007F, […] (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit === 0x007F || // If the character is the first character and is in the range [0-9] // (U+0030 to U+0039), […] (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || // If the character is the second character and is in the range [0-9] // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] ( index === 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit === 0x002D ) ) { // https://drafts.csswg.org/cssom/#escape-a-character-as-code-point result += '\\' + codeUnit.toString(16) + ' '; continue; } // If the character is not handled by one of the above rules and is // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to // U+005A), or [a-z] (U+0061 to U+007A), […] if ( codeUnit >= 0x0080 || codeUnit === 0x002D || codeUnit === 0x005F || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005A || codeUnit >= 0x0061 && codeUnit <= 0x007A ) { // the character itself result += text.charAt(index); continue; } // Otherwise, the escaped character. // https://drafts.csswg.org/cssom/#escape-a-character result += '\\' + text.charAt(index); } return result; }; function changeImageType(e: Element, names = ["src", "large-src"]) { for(const name of names) { const value = e.getAttribute(name); if (!value) { continue; } const replaced = value.replace("/webp", "/png").replaceAll(".webp", ".png"); if (replaced !== value) { e.setAttribute(name, replaced); } } } async function flattenStyleSheets() { const includes = document.querySelectorAll(`link[rel="stylesheet"]`); const tasks = []; const remove = []; for(const styleSheet of includes.values()) { const href = new URL(styleSheet.getAttribute("href"), window.location.href); tasks.push(fetch(href.toString(), { dispatcher }) .then((x) => x.text()) .then((text) => ({ styleSheet, text })) ); remove.push(styleSheet); } const results = await Promise.all(tasks); for(const { styleSheet, text} of results) { const style = document.createElement("style"); style.textContent = text; document.head.appendChild(style); remove.push(styleSheet); remove.push(style); } const adoptedStyle = document.createElement("style"); const map = new Set(); const styles = []; for(const e of document.querySelectorAll(`body,body *`).values()) { for (const name of e.getAttributeNames()) { if (name.startsWith("styler-")) { const v = e.getAttribute(name); const key = `[${name}="${window.CSS.escape(v)}"]`; if(!map.has(key)) { map.add(key); styles.push(`${key} { --${name}: ${v}; }`); } } } changeImageType(e); } adoptedStyle.textContent = styles.join("\n"); document.head.appendChild(adoptedStyle); remove.push(adoptedStyle); return () => remove.forEach((x)=>x.remove()); } async function flattenStyler(rules) { const stylerPrefix = "styler-"; const root = window.getComputedStyle(window.document.documentElement); const all = document.querySelectorAll("body,body *"); for(const e of all.values()) { const cs = window.getComputedStyle(e); const remove: string[] = []; for(const name of e.getAttributeNames()) { if (!name.startsWith("styler-")) { continue; } remove.push(name); } if (!remove.length) { continue; } const className = "c-" + (id++).toString(36); e.classList.add(className); const styles = []; const style = (e as HTMLElement).style; for(const n of remove) { let value = e.getAttribute(n); if (value) { // we need to evaluate every var(--) value = value.replace(/(var\(([^\)]+)\))/gm, (m, p1, p2) => { const varName = p2.split(",")[0]; const cssValue = cs.getPropertyValue(varName) || root.getPropertyValue(varName); return p1 ? cssValue : m; }); } const cssName = n.substring(stylerPrefix.length); if (/padding|margin|border|font|width|height/i.test(cssName)) { style.setProperty(cssName, value); continue; } styles.push(`${cssName}: ${value}`); } rules.push(`.${className} { ${styles.join(";\n")}; }`); } } const defer = await flattenStyleSheets(); const newRules = []; await flattenStyler(newRules); const newStyle = document.createElement("style"); document.body.insertAdjacentElement("afterbegin", newStyle); newStyle.textContent = `* { box-sizing: border-box; }\n${newRules.join("\n")}`; defer(); // remove all scripts for(const s of Array.from(document.querySelectorAll("script").values())) { s.remove(); } }