feat(markdown): add utility functions for parsing and stripping markdown

This commit is contained in:
Sam Chau
2025-11-05 07:28:52 +10:30
parent 58bd036a3a
commit 302a80d1cd

View File

@@ -0,0 +1,35 @@
/**
* Markdown utility for parsing markdown to HTML
*/
import { marked } from 'marked';
import sanitizeHtml from 'sanitize-html';
/**
* Parse markdown to sanitized HTML
*/
export function parseMarkdown(markdown: string | null | undefined): string {
if (!markdown) return '';
// Parse markdown to HTML
const html = marked.parse(markdown) as string;
// Sanitize HTML to prevent XSS
return sanitizeHtml(html, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']),
allowedAttributes: {
...sanitizeHtml.defaults.allowedAttributes,
img: ['src', 'alt', 'title']
}
});
}
/**
* Strip markdown formatting and return plain text
*/
export function stripMarkdown(markdown: string | null | undefined): string {
if (!markdown) return '';
const html = parseMarkdown(markdown);
return html.replace(/<[^>]*>/g, '').trim();
}