web/src/utils/parse-markdown.ts

52 lines · 1774 bytes

 1import { marked } from 'marked';
 2
 3export const parseMarkdown = (text: string | undefined): string => {
 4  if (!text) return '';
 5
 6  // Custom renderer
 7  const renderer = new marked.Renderer();
 8
 9  // Override function to handle headings
10  renderer.heading = function ({ tokens, depth }) {
11    const text = this.parser.parseInline(tokens);
12    const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
13    return `<h${depth} id="${escapedText}">${text}</h${depth}>`;
14  };
15
16  // Override function to handle links
17  renderer.link = function ({ href, title, tokens }) {
18    const text = this.parser.parseInline(tokens);
19    if (href.startsWith('/')) {
20      href = `https://github.com/Lissy93/personal-security-checklist/blob/old-version/${href}`;
21    }
22    const titleAttr = title ? `title="${title}"` : '';
23    return `<a href="${href}" ${titleAttr} target="_blank" rel="noopener noreferrer">${text}</a>`;
24  };
25
26  // Sanitize the input to remove <script> tags
27  const sanitizeHtml = (html: string): string => {
28    return html.replace(
29      /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
30      '',
31    );
32  };
33
34  // Configure marked with the custom renderer
35  marked.use({ renderer });
36
37  // Parse the markdown, then sanitize the HTML to remove <script> tags
38  const rawHtml = marked.parse(text, { async: false }) as string;
39  const sanitizedHtml = sanitizeHtml(rawHtml);
40
41  return sanitizedHtml;
42};
43
44export const formatLink = (link: string) => {
45  return (link || '')
46    .replace(/^(https?:\/\/)?(www\.)?/, '')
47    .replace(/\/+$/, '');
48};
49
50// Resolve a `codeberg` field (either `owner/repo` shorthand or a full URL) to a full URL.
51export const codebergUrl = (codeberg: string) =>
52  /^https?:\/\//.test(codeberg) ? codeberg : `https://codeberg.org/${codeberg}`;