|
| 1 | +import * as path from 'path'; |
| 2 | +import { exec as execCallback } from 'child_process'; |
| 3 | +import { promisify } from 'util'; |
| 4 | +import * as fs from 'fs/promises'; |
| 5 | +import { BookConfig, BookPageDto, ParsedSection } from '../utils/types'; |
| 6 | +import { MarkdownIngester } from './MarkdownIngester'; |
| 7 | +import { DocumentSource, logger } from '@cairo-coder/agents'; |
| 8 | +import { Document } from '@langchain/core/documents'; |
| 9 | +import { BookChunk } from '@cairo-coder/agents/types/index'; |
| 10 | +import { calculateHash } from '../utils/contentUtils'; |
| 11 | + |
| 12 | +export class StarknetJSIngester extends MarkdownIngester { |
| 13 | + private static readonly SKIPPED_DIRECTORIES = ['pictures', 'doc_scripts']; |
| 14 | + |
| 15 | + constructor() { |
| 16 | + const config: BookConfig = { |
| 17 | + repoOwner: 'starknet-io', |
| 18 | + repoName: 'starknet.js', |
| 19 | + fileExtension: '.md', |
| 20 | + chunkSize: 4096, |
| 21 | + chunkOverlap: 512, |
| 22 | + }; |
| 23 | + |
| 24 | + super(config, DocumentSource.STARKNET_JS); |
| 25 | + } |
| 26 | + |
| 27 | + protected getExtractDir(): string { |
| 28 | + return path.join(__dirname, '..', '..', 'temp', 'starknet-js-guides'); |
| 29 | + } |
| 30 | + |
| 31 | + protected async downloadAndExtractDocs(): Promise<BookPageDto[]> { |
| 32 | + const extractDir = this.getExtractDir(); |
| 33 | + const repoUrl = `https://github.com/${this.config.repoOwner}/${this.config.repoName}.git`; |
| 34 | + const exec = promisify(execCallback); |
| 35 | + |
| 36 | + try { |
| 37 | + // Clone the repository |
| 38 | + // TODO: Consider sparse clone optimization for efficiency: |
| 39 | + // git clone --depth 1 --filter=blob:none --sparse ${repoUrl} ${extractDir} |
| 40 | + // cd ${extractDir} && git sparse-checkout set www/docs/guides |
| 41 | + logger.info(`Cloning repository from ${repoUrl}...`); |
| 42 | + await exec(`git clone ${repoUrl} ${extractDir}`); |
| 43 | + logger.info('Repository cloned successfully'); |
| 44 | + |
| 45 | + // Navigate to the guides directory |
| 46 | + const docsDir = path.join(extractDir, 'www', 'docs', 'guides'); |
| 47 | + |
| 48 | + // Process markdown files from the guides directory |
| 49 | + const pages: BookPageDto[] = []; |
| 50 | + await this.processDirectory(docsDir, docsDir, pages); |
| 51 | + |
| 52 | + logger.info( |
| 53 | + `Processed ${pages.length} markdown files from StarknetJS guides`, |
| 54 | + ); |
| 55 | + return pages; |
| 56 | + } catch (error) { |
| 57 | + logger.error('Error downloading StarknetJS guides:', error); |
| 58 | + throw new Error('Failed to download and extract StarknetJS guides'); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private async processDirectory( |
| 63 | + dir: string, |
| 64 | + baseDir: string, |
| 65 | + pages: BookPageDto[], |
| 66 | + ): Promise<void> { |
| 67 | + const entries = await fs.readdir(dir, { withFileTypes: true }); |
| 68 | + |
| 69 | + for (const entry of entries) { |
| 70 | + const fullPath = path.join(dir, entry.name); |
| 71 | + |
| 72 | + if (entry.isDirectory()) { |
| 73 | + // Skip configured directories |
| 74 | + if (StarknetJSIngester.SKIPPED_DIRECTORIES.includes(entry.name)) { |
| 75 | + logger.debug(`Skipping directory: ${entry.name}`); |
| 76 | + continue; |
| 77 | + } |
| 78 | + // Recursively process subdirectories |
| 79 | + await this.processDirectory(fullPath, baseDir, pages); |
| 80 | + } else if (entry.isFile() && entry.name.endsWith('.md')) { |
| 81 | + // Read the markdown file |
| 82 | + const content = await fs.readFile(fullPath, 'utf-8'); |
| 83 | + |
| 84 | + // Create relative path without extension for the name |
| 85 | + const relativePath = path.relative(baseDir, fullPath); |
| 86 | + const name = relativePath.replace(/\.md$/, ''); |
| 87 | + |
| 88 | + pages.push({ |
| 89 | + name, |
| 90 | + content, |
| 91 | + }); |
| 92 | + |
| 93 | + logger.debug(`Processed file: ${name}`); |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + protected parsePage( |
| 99 | + content: string, |
| 100 | + split: boolean = false, |
| 101 | + ): ParsedSection[] { |
| 102 | + // Strip frontmatter before parsing |
| 103 | + const strippedContent = this.stripFrontmatter(content); |
| 104 | + return super.parsePage(strippedContent, split); |
| 105 | + } |
| 106 | + |
| 107 | + public stripFrontmatter(content: string): string { |
| 108 | + // Remove YAML frontmatter if present (delimited by --- at start and end) |
| 109 | + const frontmatterRegex = /^---\n[\s\S]*?\n---\n?/; |
| 110 | + return content.replace(frontmatterRegex, '').trimStart(); |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Create chunks from a single page with a proper source link to GitHub |
| 115 | + * This overrides the default to attach a meaningful URL for UI display. |
| 116 | + */ |
| 117 | + protected createChunkFromPage( |
| 118 | + page_name: string, |
| 119 | + page_content: string, |
| 120 | + ): Document<BookChunk>[] { |
| 121 | + const baseUrl = |
| 122 | + 'https://github.com/starknet-io/starknet.js/blob/main/www/docs/guides'; |
| 123 | + const pageUrl = `${baseUrl}/${page_name}.md`; |
| 124 | + |
| 125 | + const localChunks: Document<BookChunk>[] = []; |
| 126 | + const sanitizedContent = this.sanitizeCodeBlocks( |
| 127 | + this.stripFrontmatter(page_content), |
| 128 | + ); |
| 129 | + |
| 130 | + const sections = this.parsePage(sanitizedContent, true); |
| 131 | + |
| 132 | + sections.forEach((section: ParsedSection, index: number) => { |
| 133 | + // Reuse hashing and metadata shape from parent implementation by constructing Document directly |
| 134 | + // Importantly, attach a stable page-level sourceLink for the UI |
| 135 | + const content = section.content; |
| 136 | + const title = section.title; |
| 137 | + const uniqueId = `${page_name}-${index}`; |
| 138 | + |
| 139 | + // Lightweight hash to keep parity with other ingesters without duplicating util impl |
| 140 | + const contentHash = calculateHash(content); |
| 141 | + |
| 142 | + localChunks.push( |
| 143 | + new Document<BookChunk>({ |
| 144 | + pageContent: content, |
| 145 | + metadata: { |
| 146 | + name: page_name, |
| 147 | + title, |
| 148 | + chunkNumber: index, |
| 149 | + contentHash, |
| 150 | + uniqueId, |
| 151 | + sourceLink: pageUrl, |
| 152 | + source: this.source, |
| 153 | + }, |
| 154 | + }), |
| 155 | + ); |
| 156 | + }); |
| 157 | + |
| 158 | + return localChunks; |
| 159 | + } |
| 160 | +} |
0 commit comments