forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnippet-toc.ts
More file actions
67 lines (56 loc) · 1.95 KB
/
Copy pathsnippet-toc.ts
File metadata and controls
67 lines (56 loc) · 1.95 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
import { getTableOfContents } from "fumadocs-core/content/toc";
import fs from "fs";
import path from "path";
/**
* Extracts table of contents from snippet files referenced in page content
* Handles nested imports and excludes frontmatter
*/
async function extractSnippetTOC(
content: string,
processed = new Set<string>(),
): Promise<any[]> {
const toc: any[] = [];
const importPattern =
/import\s+\w+\s+from\s+["']@\/snippets\/([^"']+)\.mdx["']/g;
for (const match of content.matchAll(importPattern)) {
const snippetPath = path.join(process.cwd(), "snippets", `${match[1]}.mdx`);
if (processed.has(snippetPath)) continue;
processed.add(snippetPath);
try {
const snippetContent = fs.readFileSync(snippetPath, "utf-8");
const contentOnly = snippetContent.replace(/^---\n[\s\S]*?\n---\n/, "");
// Extract headers from this snippet
const snippetTOC = await getTableOfContents(contentOnly);
toc.push(...snippetTOC);
// Process nested imports
const nestedTOC = await extractSnippetTOC(snippetContent, processed);
toc.push(...nestedTOC);
} catch {
// Silently skip missing files
}
}
return toc;
}
/**
* Gets snippet TOC for a specific page by reading its source file
*/
export async function getSnippetTOCForPage(slug?: string[]): Promise<any[]> {
if (!slug) return [];
const possiblePaths = [
// Standard locations
path.join(process.cwd(), "content/docs", ...slug, "index.mdx"),
path.join(process.cwd(), "content/docs", ...slug) + ".mdx",
// Root-collection locations (e.g. content/docs/(root)/page.mdx)
path.join(process.cwd(), "content/docs", "(root)", ...slug, "index.mdx"),
path.join(process.cwd(), "content/docs", "(root)", ...slug) + ".mdx",
];
for (const filePath of possiblePaths) {
try {
const content = fs.readFileSync(filePath, "utf-8");
return await extractSnippetTOC(content);
} catch {
continue;
}
}
return [];
}