|
| 1 | +import * as crypto from 'crypto'; |
| 2 | +import * as fs from 'fs'; |
| 3 | +import * as path from 'path'; |
| 4 | + |
| 5 | +import type {MdastNode} from './types'; |
| 6 | + |
| 7 | +export const CAPTURE_TREE_VERSION = 1; |
| 8 | + |
| 9 | +function hashString(value: string): string { |
| 10 | + return crypto.createHash('sha1').update(value).digest('hex'); |
| 11 | +} |
| 12 | + |
| 13 | +export function captureDirForSite(siteDir: string): string { |
| 14 | + return path.join(siteDir, '.docusaurus', 'llms-export', 'trees'); |
| 15 | +} |
| 16 | + |
| 17 | +export function capturedTreePathForSource( |
| 18 | + sourceAbsPath: string, |
| 19 | + siteDir: string, |
| 20 | +): string { |
| 21 | + let absolutePath: string; |
| 22 | + try { |
| 23 | + absolutePath = fs.realpathSync(sourceAbsPath); |
| 24 | + } catch { |
| 25 | + absolutePath = path.resolve(sourceAbsPath); |
| 26 | + } |
| 27 | + return path.join( |
| 28 | + captureDirForSite(siteDir), |
| 29 | + `${hashString(absolutePath)}.json`, |
| 30 | + ); |
| 31 | +} |
| 32 | + |
| 33 | +export function wrapCapturedTree(tree: unknown): { |
| 34 | + version: number; |
| 35 | + tree: unknown; |
| 36 | +} { |
| 37 | + return {version: CAPTURE_TREE_VERSION, tree}; |
| 38 | +} |
| 39 | + |
| 40 | +export function unwrapCapturedTree(payload: unknown): MdastNode | null { |
| 41 | + if (!payload || typeof payload !== 'object') return null; |
| 42 | + |
| 43 | + const record = payload as Record<string, unknown>; |
| 44 | + |
| 45 | + // Handle versioned format |
| 46 | + if ('version' in record && 'tree' in record) { |
| 47 | + const version = Number(record.version); |
| 48 | + if (version !== CAPTURE_TREE_VERSION) return null; |
| 49 | + return (record.tree as MdastNode) ?? null; |
| 50 | + } |
| 51 | + |
| 52 | + // Legacy format support (version 1 only) |
| 53 | + if (CAPTURE_TREE_VERSION === 1) { |
| 54 | + return payload as MdastNode; |
| 55 | + } |
| 56 | + |
| 57 | + return null; |
| 58 | +} |
0 commit comments