-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown-parser.ts
More file actions
87 lines (73 loc) · 2.24 KB
/
Copy pathmarkdown-parser.ts
File metadata and controls
87 lines (73 loc) · 2.24 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
import {
createHeadingIdGenerator,
normalizeHeadingText,
} from '@/blog/model/heading';
import { getFolderSlug, type TocItem } from '@/blog/services/post-repository';
import fs from 'fs';
import path from 'path';
// MDX 소스에서 헤딩 파싱 (렌더링된 HTML이 아닌 원본 MDX에서)
export function parseHeadingsFromMdx(mdxContent: string): TocItem[] {
try {
if (!mdxContent || typeof mdxContent !== 'string') {
console.warn('Invalid MDX content for TOC parsing');
return [];
}
const tocItems: TocItem[] = [];
const nextHeadingId = createHeadingIdGenerator();
const lines = mdxContent.split(/\r?\n/);
let activeFence: { marker: '`' | '~'; length: number } | null = null;
for (const line of lines) {
const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
if (fenceMatch) {
const fenceMarker = fenceMatch[1][0] as '`' | '~';
const fenceLength = fenceMatch[1].length;
if (!activeFence) {
activeFence = {
marker: fenceMarker,
length: fenceLength,
};
} else if (
activeFence.marker === fenceMarker &&
fenceLength >= activeFence.length
) {
activeFence = null;
}
continue;
}
if (activeFence) {
continue;
}
const headingMatch = /^(#{1,6})\s+(.+)$/.exec(line);
if (!headingMatch) {
continue;
}
const level = headingMatch[1].length;
const text = normalizeHeadingText(headingMatch[2]);
const id = nextHeadingId(text);
if (!text || !id) {
continue;
}
tocItems.push({
id,
text,
level,
});
}
return tocItems;
} catch (error) {
console.error('Error parsing MDX for TOC:', error);
return [];
}
}
// MDX 소스 파일 로드 (TOC 생성용)
export function getMdxSource(slug: string): string | null {
try {
const folderSlug = getFolderSlug(slug) || slug;
const postsDirectory = path.join(process.cwd(), 'posts');
const filePath = path.join(postsDirectory, folderSlug, 'index.mdx');
return fs.readFileSync(filePath, 'utf8');
} catch (error) {
console.error(`Failed to read MDX source for ${slug}:`, error);
return null;
}
}