/** * Render-helper for sequence templates. * * Uses `react-dom/server.renderToStaticMarkup` (already a runtime dep of * the web app) to emit a self-contained HTML document plus a flat text * fallback for clients that prefer text/plain. We intentionally avoid the * full `react-email` package here — that migration is task #75 and * pulling it forward in V1 would force a 60+MB dep tree onto every worker * image. See docs/improvement-plan/05-business-features/marketing-funnel-phase-3.md. */ import type { ReactElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; export interface RenderedEmail { readonly html: string; readonly text: string; } /** * Convert HTML to a usable plain-text fallback. Strips tags and collapses * whitespace while preserving anchor URLs as `[text] (url)` for clients * that fall back to the text alternative. */ export function htmlToPlainText(html: string): string { // Preserve anchor URLs in the text fallback before stripping tags. const withAnchorUrls = html.replace( /]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/giu, (_, href: string, label: string) => `${label.replace(/<[^>]+>/gu, "").trim()} (${href})` ); return withAnchorUrls .replace(//giu, "") .replace(//giu, "") .replace(/(\r?\n)?/giu, "\n") .replace(/<\/(p|h1|h2|h3|li|div|tr)>/giu, "\n") .replace(/<[^>]+>/gu, "") .replace(/ /giu, " ") .replace(/&/giu, "&") .replace(/</giu, "<") .replace(/>/giu, ">") .replace(/'/giu, "'") .replace(/"/giu, '"') .replace(/[ \t]+\n/gu, "\n") .replace(/\n{3,}/gu, "\n\n") .trim(); } /** * Render a React element to `{ html, text }`. The HTML is prefixed with * a DOCTYPE so mail-clients render in standards mode. */ export function renderEmail(element: ReactElement): RenderedEmail { const body = renderToStaticMarkup(element); const html = `${body}`; const text = htmlToPlainText(body); return { html, text }; }