import { ELEMENT_NODE, TEXT_NODE, parse, transform, walk, walkSync } from "ultrahtml"; import sanitize, { type SanitizeOptions } from "ultrahtml/transformers/sanitize"; export type { SanitizeOptions }; const allowedElements = [ "p", "br", "strong", "b", "em", "i", "u", "s", "a", "ul", "ol", "li", "blockquote", "code", "pre", "h1", "h2", "h3", "h4", "h5", "h6", "span", ]; const allowedAttributesByElement: Record = { a: ["href", "title", "target", "rel"], span: ["class"], }; const defaultSanitizeOptions: SanitizeOptions = { allowElements: allowedElements, }; function enforceAttributeAllowlist(allowMap: Record) { // ultrahtml's sanitize transformer keeps unknown attributes by default // (its allowAttributes is keyed by attribute name, not element). This // transformer enforces a strict per-element attribute whitelist. return (node: Parameters[1]>[0]) => { walkSync(node, (n) => { if (n.type !== ELEMENT_NODE) return; const allowed = allowMap[n.name] ?? []; for (const attr of Object.keys(n.attributes)) { if (!allowed.includes(attr)) delete n.attributes[attr]; } }); return node; }; } export async function stripHTML(html: string): Promise { const ast = parse(html); let out = ""; await walk(ast, (node) => { if (node.type === TEXT_NODE) { out += node.value; } }); return out; } export async function sanitizeHTML( html: string, options: SanitizeOptions = defaultSanitizeOptions, allowAttributes: Record = allowedAttributesByElement, ): Promise { return await transform(html, [sanitize(options), enforceAttributeAllowlist(allowAttributes)]); }