File size: 1,370 Bytes
4056320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//
// SPDX-FileCopyrightText: Hadad <hadad@linuxmail.org>
// SPDX-License-Identifier: Apache-2.0
//

import { Marked } from "marked";
import { markedHighlight } from "marked-highlight";
import hljs from "highlight.js";
import frontMatter from "front-matter";
import type { PostFrontMatter } from "../../shared/types.js";
import { siteConfig } from "../../shared/config.js";

const marked = new Marked(
  markedHighlight({
    langPrefix: "hljs language-",
    highlight(code: string, lang: string): string {
      const language = hljs.getLanguage(lang) ? lang : "plaintext";
      return hljs.highlight(code, { language }).value;
    },
  })
);

marked.setOptions({
  gfm: true,
  breaks: true,
});

export const parseMarkdown = (content: string): string => {
  const parsed = frontMatter<PostFrontMatter>(content);
  const htmlContent: string = marked.parse(parsed.body) as string;
  return htmlContent;
};

export const extractFrontMatter = (content: string): PostFrontMatter => {
  const parsed = frontMatter<PostFrontMatter>(content);

  const defaultFrontMatter: PostFrontMatter = {
    title: siteConfig.defaults.postTitle,
    date: new Date().toISOString().split("T")[0],
    description: siteConfig.defaults.postDescription,
    author: siteConfig.defaults.postAuthor,
    tags: [],
  };

  return {
    ...defaultFrontMatter,
    ...parsed.attributes,
  };
};