/ opencodehub / src / lib / markdown.ts
Swadhin Biswas Feature/ai code reviewer (#73) · 8/2/2026
105a287
85 lines · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import rehypeStringify from "rehype-stringify";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";

import { visit } from "unist-util-visit";
import type { Text, Parent } from "mdast";

// Plugin to link owner/repo#123
function remarkCrossRepoLinks() {
  return (tree: any) => {
    visit(tree, "text", (node: Text, index, parent: Parent) => {
      const value = node.value;
      // Regex: owner/repo#123
      const regex = /\b([a-zA-Z0-9-]+)\/([a-zA-Z0-9-_\.]+)\#(\d+)\b/g;

      if (!regex.test(value)) return;

      const children = [];
      let lastIndex = 0;
      let match;

      regex.lastIndex = 0; // Reset
      while ((match = regex.exec(value)) !== null) {
        const start = match.index;
        const end = regex.lastIndex;
        const [fullMatch, owner, repo, number] = match;

        // Text before match
        if (start > lastIndex) {
          children.push({ type: "text", value: value.slice(lastIndex, start) });
        }

        // Link
        children.push({
          type: "link",
          url: `/${owner}/${repo}/issues/${number}`,
          title: null,
          children: [{ type: "text", value: fullMatch }],
          data: {
            hProperties: { className: ["issue-link"] }
          }
        });

        lastIndex = end;
      }

      // Text after last match
      if (lastIndex < value.length) {
        children.push({ type: "text", value: value.slice(lastIndex) });
      }

      // Replace node with children
      if (parent && typeof index === "number") {
        parent.children.splice(index, 1, ...(children as any));
        return index + children.length; // Skip over new nodes
      }
    });
  };
}

export async function renderMarkdown(content: string): Promise<string> {
  const file = await unified()
    .use(remarkParse)
    .use(remarkGfm)
    .use(remarkCrossRepoLinks) // Add custom plugin
    .use(remarkRehype)
    .use(rehypeHighlight) // Code highlighting
    .use(rehypeSanitize, {
      ...defaultSchema,
      attributes: {
        ...defaultSchema.attributes,
        code: [...(defaultSchema.attributes?.code || []), "className"],
        span: [...(defaultSchema.attributes?.span || []), "className"],
      },
    })
    .use(rehypeStringify)
    .process(content);

  return String(file);
}