-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdx.ts
76 lines (67 loc) · 2.01 KB
/
mdx.ts
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
import { join } from 'path';
import { readFileSync, readdirSync } from 'fs';
import { bundleMDX } from 'mdx-bundler';
import matter from 'gray-matter';
import readingTime from 'reading-time';
import remarkGfm from 'remark-gfm';
import rehypeSlug from 'rehype-slug';
import rehypeCodeTitles from 'rehype-code-titles';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypePrism from 'rehype-prism-plus';
export async function getFiles(type) {
return readdirSync(join(process.cwd(), 'data', type));
}
export async function getFileBySlug(type, slug?) {
const source = slug
? readFileSync(join(process.cwd(), 'data', type, `${slug}.mdx`), 'utf8')
: readFileSync(join(process.cwd(), 'data', `${type}.mdx`), 'utf8');
const { code, frontmatter } = await bundleMDX(source, {
xdmOptions(options) {
options.remarkPlugins = [...(options?.remarkPlugins ?? []), remarkGfm];
options.rehypePlugins = [
...(options?.rehypePlugins ?? []),
rehypeSlug,
rehypeCodeTitles,
rehypePrism,
[
rehypeAutolinkHeadings,
{
properties: {
className: ['anchor']
}
}
]
] as any;
return options;
}
});
const tweetMatches = source.match(/<StaticTweet\sid="[0-9]+"\s\/>/g);
const tweetIDs = tweetMatches?.map((tweet) => tweet.match(/[0-9]+/g)[0]);
return {
code,
tweetIDs: tweetIDs || [],
frontMatter: {
wordCount: source.split(/\s+/gu).length,
readingTime: readingTime(source),
slug: slug || null,
...frontmatter
}
};
}
export async function getAllFilesFrontMatter(type) {
const files = readdirSync(join(process.cwd(), 'data', type));
return files.reduce((allPosts, postSlug) => {
const source = readFileSync(
join(process.cwd(), 'data', type, postSlug),
'utf8'
);
const { data } = matter(source);
return [
{
...data,
slug: postSlug.replace('.mdx', '')
},
...allPosts
];
}, []);
}