// Email templates are Weft components: write one with the components in `components/`, render it with `render` from `std/app`, // and give the result to `document`. Everything shown in a component is escaped, so values from users are safe in it. /// An email rendered both ways: what `render` from `std/app` gives. export type Rendered = { html: string, text: string } fn escape(s: string): string { return s.replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll("\"", """) } /// Whether an address may go in a link or an image: `http`, `https`, `mailto`, `tel` or `cid`. export fn isSafeUrl(url: string): boolean { let lower = url.trim().toLowerCase() return lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("mailto:") || lower.startsWith("tel:") || lower.startsWith("cid:") } /// What surrounds an email's content. `preheader` is the line inboxes show beside the subject; `footer` is the small print; /// `lang` is the language of the text (`en`). export type DocumentOptions = { title?: string, preheader?: string, footer?: string, lang?: string } /// A rendered template as a whole email: its content in a centred column, with the preheader and footer. /// /// ```weft /// let mail = document(render(Receipt, { name: "Ana", total: "19,99 €" }), { title: "Your receipt", footer: "Example d.o.o." }) /// ``` export fn document(content: Rendered, options: DocumentOptions = {}): Rendered { let body = content.html let preheader = options.preheader ?? "" let hidden = preheader != "" ? `
${escape(preheader)}
` : "" let footer = options.footer ?? "" let small = footer != "" ? `

${escape(footer)}

` : "" let html = `${escape(options.title ?? "")}${hidden}
${body}${small}
` let plain = content.text return { html, text: footer != "" ? `${plain}\n\n--\n${footer}\n` : `${plain}\n` } }