Files
copilotkit__copilotkit/docs/lib/snippet-toc.ts
John Rae-Grant e9e6fbdd85 Docs Rebranding with fixes (#2982)
Co-authored-by: Max Korp <maxkorp@8bytealchemy.com>
Co-authored-by: Santiago Cubino <scubino@litebox.ai>
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-08 14:28:26 -08:00

63 lines
2.0 KiB
TypeScript

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 [];
}