|
| 1 | +import { readFileSync, existsSync } from 'node:fs'; |
| 2 | +import { resolve, relative } from 'node:path'; |
| 3 | +import { parseArgs } from 'node:util'; |
| 4 | +import { glob } from 'glob'; |
| 5 | +import * as pagefind from 'pagefind'; |
| 6 | +import { extractComponentJSDoc, resolveComponentSource } from './extract-comp-description.ts'; |
| 7 | + |
| 8 | +interface StoryIndexEntry { |
| 9 | + id: string; |
| 10 | + type: string; |
| 11 | + name: string; |
| 12 | + title?: string; |
| 13 | + importPath?: string; |
| 14 | + tags?: string[]; |
| 15 | +} |
| 16 | + |
| 17 | +// --- CLI args --- |
| 18 | + |
| 19 | +const { values } = parseArgs({ |
| 20 | + options: { |
| 21 | + directory: { type: 'string', short: 'd' }, |
| 22 | + }, |
| 23 | +}); |
| 24 | + |
| 25 | +if (typeof values.directory !== 'string') { |
| 26 | + throw new Error('Expected --directory to be a string (e.g. --directory .out)'); |
| 27 | +} |
| 28 | + |
| 29 | +const outDir = resolve(process.cwd(), values.directory); |
| 30 | +const indexJsonPath = resolve(outDir, 'index.json'); |
| 31 | + |
| 32 | +if (!existsSync(indexJsonPath)) { |
| 33 | + throw new Error(`index.json not found at ${indexJsonPath}. Did you run "storybook build" first?`); |
| 34 | +} |
| 35 | + |
| 36 | +// --- Read Storybook index.json --- |
| 37 | + |
| 38 | +const storiesJson = JSON.parse(readFileSync(indexJsonPath, 'utf-8')); |
| 39 | +const entries: StoryIndexEntry[] = Object.values(storiesJson.entries); |
| 40 | + |
| 41 | +const importPathToEntry = new Map<string, StoryIndexEntry>(); |
| 42 | +for (const entry of entries) { |
| 43 | + if (entry.type === 'docs' && entry.importPath?.endsWith('.mdx')) { |
| 44 | + importPathToEntry.set(entry.importPath, entry); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +console.log(`Found ${importPathToEntry.size} docs entries in index.json`); |
| 49 | + |
| 50 | +const mdxFiles = await glob('**/*.mdx', { |
| 51 | + cwd: process.cwd(), |
| 52 | + ignore: ['node_modules/**', '.out/**', '**/node_modules/**'], |
| 53 | +}); |
| 54 | + |
| 55 | +console.log(`Found ${mdxFiles.length} MDX files on disk`); |
| 56 | + |
| 57 | +function extractTextFromMdx(source: string): string { |
| 58 | + const lines = source.split('\n'); |
| 59 | + const textParts: string[] = []; |
| 60 | + let inCodeBlock = false; |
| 61 | + |
| 62 | + for (const line of lines) { |
| 63 | + if (line.trimStart().startsWith('```')) { |
| 64 | + inCodeBlock = !inCodeBlock; |
| 65 | + continue; |
| 66 | + } |
| 67 | + |
| 68 | + if (inCodeBlock) continue; |
| 69 | + |
| 70 | + if (/^\s*import\s/.test(line)) continue; |
| 71 | + if (/^\s*export\s/.test(line)) continue; |
| 72 | + |
| 73 | + // Skip JSX-only lines (tags with no text content) |
| 74 | + if (/^\s*<[A-Z][\w.]*[\s/>]/.test(line) && !/>([^<]+)</.test(line)) continue; |
| 75 | + if (/^\s*<\/[A-Z]/.test(line)) continue; |
| 76 | + if (/^\s*<Meta\s/.test(line)) continue; |
| 77 | + |
| 78 | + const headingMatch = line.match(/^(#{1,6})\s+(.+)/); |
| 79 | + if (headingMatch) { |
| 80 | + textParts.push(headingMatch[2].trim()); |
| 81 | + continue; |
| 82 | + } |
| 83 | + |
| 84 | + const cleaned = line |
| 85 | + .replace(/<[^>]+>/g, '') |
| 86 | + .replace(/\{`([^`]*)`\}/g, '$1') |
| 87 | + .replace(/\{['"]([^'"]*)['"]\}/g, '$1') |
| 88 | + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') |
| 89 | + .replace(/`([^`]+)`/g, '$1') |
| 90 | + .replace(/\*{1,3}([^*]+)\*{1,3}/g, '$1') |
| 91 | + .replace(/[<>]/g, '') |
| 92 | + .trim(); |
| 93 | + |
| 94 | + if (cleaned.length > 0) { |
| 95 | + textParts.push(cleaned); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + return textParts.join(' '); |
| 100 | +} |
| 101 | + |
| 102 | +// --- Extract component descriptions from JSDoc --- |
| 103 | + |
| 104 | +const componentDescriptions = new Map<string, string>(); |
| 105 | +for (const entry of entries) { |
| 106 | + if (entry.type !== 'docs' || !entry.importPath?.endsWith('.mdx')) continue; |
| 107 | + if (!entry.tags?.includes('attached-mdx')) continue; |
| 108 | + |
| 109 | + const sourceFile = resolveComponentSource(entry.importPath); |
| 110 | + if (!sourceFile) continue; |
| 111 | + |
| 112 | + const description = extractComponentJSDoc(sourceFile); |
| 113 | + if (description) { |
| 114 | + componentDescriptions.set(entry.importPath, description); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +console.log(`Extracted ${componentDescriptions.size} component descriptions from JSDoc`); |
| 119 | + |
| 120 | +// --- Build Pagefind index --- |
| 121 | + |
| 122 | +const { index } = await pagefind.createIndex(); |
| 123 | +if (!index) { |
| 124 | + throw new Error('Failed to create Pagefind index'); |
| 125 | +} |
| 126 | + |
| 127 | +let indexed = 0; |
| 128 | +let skipped = 0; |
| 129 | + |
| 130 | +for (const mdxFile of mdxFiles) { |
| 131 | + const importPath = './' + mdxFile; |
| 132 | + const entry = importPathToEntry.get(importPath); |
| 133 | + |
| 134 | + if (!entry) { |
| 135 | + skipped++; |
| 136 | + continue; |
| 137 | + } |
| 138 | + |
| 139 | + const source = readFileSync(mdxFile, 'utf-8'); |
| 140 | + const mdxText = extractTextFromMdx(source); |
| 141 | + |
| 142 | + const description = componentDescriptions.get(importPath); |
| 143 | + const text = description ? `${description} ${mdxText}` : mdxText; |
| 144 | + |
| 145 | + if (text.length < 10) { |
| 146 | + skipped++; |
| 147 | + continue; |
| 148 | + } |
| 149 | + |
| 150 | + const url = `?path=/docs/${entry.id}`; |
| 151 | + |
| 152 | + const category = entry.title?.split(' / ')[0] || 'Docs'; |
| 153 | + const title = entry.title?.split(' / ').pop() || entry.name; |
| 154 | + |
| 155 | + const { errors } = await index.addCustomRecord({ |
| 156 | + url, |
| 157 | + content: text, |
| 158 | + language: 'en', |
| 159 | + meta: { |
| 160 | + title: entry.title || title, |
| 161 | + category, |
| 162 | + }, |
| 163 | + }); |
| 164 | + |
| 165 | + if (errors?.length) { |
| 166 | + console.warn(` Warning indexing ${mdxFile}:`, errors); |
| 167 | + } else { |
| 168 | + indexed++; |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +console.log(`Indexed ${indexed} docs, skipped ${skipped} files (no matching entry or too short)`); |
| 173 | + |
| 174 | +// --- Write index --- |
| 175 | + |
| 176 | +const pagefindDir = resolve(outDir, 'pagefind'); |
| 177 | +const { errors: writeErrors } = await index.writeFiles({ outputPath: pagefindDir }); |
| 178 | + |
| 179 | +if (writeErrors?.length) { |
| 180 | + console.error('Errors writing Pagefind index:', writeErrors); |
| 181 | + process.exit(1); |
| 182 | +} |
| 183 | + |
| 184 | +console.log(`Pagefind index written to ${relative(process.cwd(), pagefindDir)}/`); |
| 185 | + |
| 186 | +await pagefind.close(); |
0 commit comments