-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblog-heading-utils.mjs
More file actions
174 lines (147 loc) · 4.54 KB
/
blog-heading-utils.mjs
File metadata and controls
174 lines (147 loc) · 4.54 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import fs from 'node:fs';
import path from 'node:path';
export const blogContentDir = path.resolve(process.cwd(), 'src/content/docs/blog');
export const englishBlogContentDir = path.resolve(process.cwd(), 'src/content/docs/en/blog');
export const distDir = path.resolve(process.cwd(), 'dist');
export const blogLocaleDirs = {
zh: 'src/content/docs/blog',
en: 'src/content/docs/en/blog',
};
export function normalizeText(value) {
return decodeHtmlEntities(value)
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function decodeHtmlEntities(value) {
return value
.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
export function splitFrontmatter(source) {
if (!source.startsWith('---\n')) {
throw new Error('Expected MDX frontmatter to start with `---`.');
}
const end = source.indexOf('\n---\n', 4);
if (end === -1) {
throw new Error('Unable to locate the closing frontmatter fence.');
}
const frontmatter = source.slice(4, end);
const body = source.slice(end + 5);
const bodyStartLine = frontmatter.split('\n').length + 3;
return { frontmatter, body, bodyStartLine };
}
export function parseFrontmatterTitle(frontmatter) {
const match = frontmatter.match(/^title:\s*(.+)$/m);
if (!match) {
throw new Error('Missing `title` in frontmatter.');
}
let title = match[1].trim();
if (
(title.startsWith('"') && title.endsWith('"')) ||
(title.startsWith("'") && title.endsWith("'"))
) {
title = title.slice(1, -1);
}
return title;
}
export function scanMarkdownH1s(body, bodyStartLine = 1) {
const matches = [];
const lines = body.split('\n');
let activeFence = null;
for (const [index, line] of lines.entries()) {
const trimmed = line.trim();
const fenceMatch = trimmed.match(/^(```+|~~~+)/);
if (fenceMatch) {
const marker = fenceMatch[1][0];
if (activeFence === marker) {
activeFence = null;
} else if (activeFence === null) {
activeFence = marker;
}
continue;
}
if (activeFence !== null) {
continue;
}
const headingMatch = line.match(/^#\s+(.*)$/);
if (headingMatch) {
matches.push({
line: bodyStartLine + index,
text: headingMatch[1].trim(),
});
}
}
return matches;
}
export function extractH1Texts(html) {
return Array.from(html.matchAll(/<h1\b[^>]*>([\s\S]*?)<\/h1>/gi), (match) => normalizeText(match[1]));
}
export function hiddenFirstPanelRuleExists(html) {
return /content-panel:first-of-type[^}]*display\s*:\s*none/i.test(html);
}
export function readTextFile(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
export function requireFile(relativePath) {
const fullPath = path.join(distDir, relativePath);
if (!fs.existsSync(fullPath)) {
throw new Error(`Missing build artifact: ${relativePath}`);
}
return readTextFile(fullPath);
}
export function listRenderedHtmlFiles(relativeDir) {
const directory = path.join(distDir, relativeDir);
if (!fs.existsSync(directory)) {
return [];
}
const results = [];
const queue = [directory];
while (queue.length > 0) {
const current = queue.pop();
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
queue.push(fullPath);
continue;
}
if (entry.isFile() && entry.name === 'index.html') {
results.push(path.relative(distDir, fullPath));
}
}
}
return results.sort();
}
export function getBlogSourceEntries({ locale = 'zh', rootDir = process.cwd() } = {}) {
const relativeDir = blogLocaleDirs[locale];
if (!relativeDir) {
throw new Error(`Unsupported blog locale: ${locale}`);
}
const contentDir = path.resolve(rootDir, relativeDir);
if (!fs.existsSync(contentDir)) {
throw new Error(`Missing blog content directory: ${contentDir}`);
}
return fs
.readdirSync(contentDir)
.filter((name) => name.endsWith('.md') || name.endsWith('.mdx'))
.sort()
.map((name) => {
const relativePath = path.join(relativeDir, name);
const fullPath = path.join(contentDir, name);
const source = readTextFile(fullPath);
const { frontmatter, body, bodyStartLine } = splitFrontmatter(source);
const slug = name.replace(/\.(md|mdx)$/i, '');
return {
fullPath,
relativePath,
locale,
slug,
title: parseFrontmatterTitle(frontmatter),
body,
bodyStartLine,
};
});
}