import { ParsedProject, FileInfo, ProjectStructure, ConversionOptions } from './types'; import { TokenCounter } from './tokenizer'; export class MarkdownConverter { private options: ConversionOptions; constructor(options: ConversionOptions = {}) { this.options = options; } convertToMarkdown(project: ParsedProject): string { // Apply token-aware file filtering const filteredProject = this.applyTokenAwareFiltering(project); const sections: string[] = []; // Header sections.push(this.generateHeader(filteredProject)); // Table of Contents sections.push(this.generateTableOfContents(filteredProject)); // Project Summary sections.push(this.generateProjectSummary(filteredProject)); // Project Structure sections.push(this.generateProjectStructure(filteredProject.structure)); // File Contents sections.push(this.generateFileContents(filteredProject.files)); // Footer sections.push(this.generateFooter()); return sections.join('\n\n'); } private generateHeader(project: ParsedProject): string { const projectName = project.structure.name; return `# ${projectName} - Codebase Documentation > Generated by autoMarkdown - Intelligent codebase to markdown converter ---`; } private generateTableOfContents(project: ParsedProject): string { const sections = [ '## Table of Contents', '', '- [Project Summary](#project-summary)', '- [Project Structure](#project-structure)', '- [File Contents](#file-contents)' ]; // Add file links project.files.forEach((file, index) => { const sanitizedPath = file.path.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase(); sections.push(` - [${file.path}](#file-${index + 1}-${sanitizedPath})`); }); return sections.join('\n'); } private generateProjectSummary(project: ParsedProject): string { const languages = [...new Set(project.files.map(f => f.language))]; const totalSize = project.files.reduce((sum, f) => sum + f.size, 0); return `## Project Summary ${project.summary} ### Key Statistics - **Total Files**: ${project.files.length} - **Languages**: ${languages.join(', ')} - **Total Size**: ${(totalSize / 1024).toFixed(2)} KB - **Most Important Files**: ${project.files.slice(0, 5).map(f => f.path).join(', ')}`; } private generateProjectStructure(structure: ProjectStructure, level: number = 0): string { if (level === 0) { return `## Project Structure \`\`\` ${this.renderStructureTree(structure, 0)} \`\`\``; } return this.renderStructureTree(structure, level); } private renderStructureTree(structure: ProjectStructure, level: number): string { const indent = ' '.repeat(level); const icon = structure.type === 'directory' ? '├──' : '├──'; let result = `${indent}${icon} ${structure.name}\n`; if (structure.children) { structure.children.forEach(child => { result += this.renderStructureTree(child, level + 1); }); } return result; } private generateFileContents(files: FileInfo[]): string { const sections = ['## File Contents']; files.forEach((file, index) => { const sanitizedPath = file.path.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase(); const fileSection = [ `### File ${index + 1}: \`${file.path}\``, ``, '', this.generateFileMetadata(file), '', '```' + file.language, file.content, '```' ]; sections.push(fileSection.join('\n')); }); return sections.join('\n\n'); } private generateFileMetadata(file: FileInfo): string { if (!this.options.includeMetadata) { return ''; } return `**Language**: ${file.language} | **Size**: ${file.size} bytes | **Importance**: ${file.importance.toFixed(1)}`; } private generateFooter(): string { const timestamp = new Date().toISOString(); return `--- *Documentation generated on ${timestamp} by [autoMarkdown](https://github.com/harshpreet931/autoMarkdown)* **Tips for LLM Processing:** - This markdown contains the complete codebase structure and content - Files are ordered by importance (most important first) - Use the table of contents for navigation - Each file includes metadata for context - The project structure shows the overall organization`; } convertToJson(project: ParsedProject): string { // Apply token-aware filtering for JSON too const filteredProject = this.applyTokenAwareFiltering(project); return JSON.stringify(filteredProject, null, 2); } private applyTokenAwareFiltering(project: ParsedProject): ParsedProject { const maxTokens = this.options.maxTokens ?? 1000000; // Configurable limit for different LLMs let currentTokens = 0; const includedFiles: FileInfo[] = []; // Estimate tokens for static content (headers, structure, etc.) const staticContent = this.estimateStaticTokens(project); currentTokens += staticContent; // Sort files by importance and include until we hit token limit const sortedFiles = [...project.files].sort((a, b) => b.importance - a.importance); for (const file of sortedFiles) { const fileTokens = this.estimateFileTokens(file); if (currentTokens + fileTokens <= maxTokens) { includedFiles.push(file); currentTokens += fileTokens; } else { // Stop including files to stay within token limit break; } } return { ...project, files: includedFiles, summary: this.updateSummaryWithFiltering(project.summary, includedFiles.length, project.files.length) }; } private estimateStaticTokens(project: ParsedProject): number { // Rough estimate for headers, structure, TOC, etc. const structureSize = JSON.stringify(project.structure).length; return Math.ceil((structureSize + 2000) / 4); // ~4 chars per token } private estimateFileTokens(file: FileInfo): number { // Estimate tokens for file content + metadata const contentTokens = Math.ceil(file.content.length / 4); const metadataTokens = 50; // File headers, language tags, etc. return contentTokens + metadataTokens; } private updateSummaryWithFiltering(originalSummary: string, includedFiles: number, totalFiles: number): string { if (includedFiles === totalFiles) { return originalSummary; } return `${originalSummary} Showing ${includedFiles} of ${totalFiles} files (optimized for token limits).`; } }