|
| 1 | +import { createWriteStream } from 'node:fs' |
| 2 | +import { mkdtemp, rename, rm } from 'node:fs/promises' |
| 3 | +import path from 'node:path' |
| 4 | +import { Readable } from 'node:stream' |
| 5 | +import { pipeline } from 'node:stream/promises' |
| 6 | +import { createLogger } from '@sim/logger' |
| 7 | +import { compareStrings } from '@sim/utils/string' |
| 8 | +import { plugin } from 'bun' |
| 9 | +import { createMdxPlugin } from 'fumadocs-mdx/bun' |
| 10 | + |
| 11 | +const MAX_LLM_TEXT_BYTES = 64 * 1024 * 1024 |
| 12 | +const logger = createLogger('DocsLlmsFullAsset') |
| 13 | + |
| 14 | +await plugin(createMdxPlugin({ disableMetaFile: true })) |
| 15 | + |
| 16 | +const { source } = await import('@/lib/source') |
| 17 | +const { getLLMText } = await import('@/lib/llms') |
| 18 | +const publicDirectory = path.resolve('public') |
| 19 | +const temporaryDirectory = await mkdtemp(path.join(publicDirectory, '.llms-full-')) |
| 20 | +const temporaryFile = path.join(temporaryDirectory, 'llms-full.txt') |
| 21 | + |
| 22 | +async function* generateText(): AsyncGenerator<string> { |
| 23 | + let hasContent = false |
| 24 | + let bytes = 0 |
| 25 | + const pages = [...source.getPages()].sort((left, right) => compareStrings(left.url, right.url)) |
| 26 | + for (const page of pages) { |
| 27 | + if (!page?.data || !page.url) continue |
| 28 | + const text = await getLLMText(page) |
| 29 | + if (!text) continue |
| 30 | + const chunk = `${hasContent ? '\n\n---\n\n' : ''}${text}` |
| 31 | + bytes += Buffer.byteLength(chunk) |
| 32 | + if (bytes > MAX_LLM_TEXT_BYTES) { |
| 33 | + throw new Error('Full documentation text exceeds the static asset size budget') |
| 34 | + } |
| 35 | + yield chunk |
| 36 | + hasContent = true |
| 37 | + } |
| 38 | + if (!hasContent) throw new Error('No documentation text was generated') |
| 39 | +} |
| 40 | + |
| 41 | +try { |
| 42 | + await pipeline(Readable.from(generateText()), createWriteStream(temporaryFile)) |
| 43 | + await rename(temporaryFile, path.join(publicDirectory, 'llms-full.txt')) |
| 44 | + logger.info('Generated full documentation static asset') |
| 45 | +} finally { |
| 46 | + await rm(temporaryDirectory, { recursive: true, force: true }) |
| 47 | +} |
0 commit comments