UNPKG

@paulohenriquevn/m2js

Version:

Transform TypeScript/JavaScript code into LLM-friendly Markdown summaries + Smart Dead Code Detection + Graph-Deep Diff Analysis. Extract exported functions, classes, and JSDoc comments for better AI context with 60%+ token reduction. Intelligent dead cod

335 lines 13.9 kB
"use strict"; /** * Enhanced Generator for M2JS * Generates AI-optimized documentation with business context and insights */ Object.defineProperty(exports, "__esModule", { value: true }); exports.generateEnhancedMarkdown = generateEnhancedMarkdown; exports.generateEnhancedDependencyAnalysis = generateEnhancedDependencyAnalysis; const generator_1 = require("./generator"); const business_context_analyzer_1 = require("./business-context-analyzer"); const usage_pattern_analyzer_1 = require("./usage-pattern-analyzer"); const architecture_analyzer_1 = require("./architecture-analyzer"); const semantic_analyzer_1 = require("./semantic-analyzer"); // import path from 'path'; // Currently unused /** * Generates enhanced documentation with AI-friendly analysis */ function generateEnhancedMarkdown(parsedFile, allParsedFiles, dependencyGraph, options, projectPath) { const sections = []; // Generate base markdown const baseMarkdown = (0, generator_1.generateMarkdown)(parsedFile, { includeComments: !options.noComments, businessContext: options.businessContext || options.aiEnhanced, usageExamples: options.usageExamples || options.aiEnhanced, architectureInsights: options.architectureInsights || options.aiEnhanced, semanticAnalysis: options.semanticAnalysis || options.aiEnhanced, }); sections.push(baseMarkdown); // Add enhanced sections if requested if (options.businessContext || options.aiEnhanced) { const businessContext = (0, business_context_analyzer_1.analyzeBusinessContext)(allParsedFiles, projectPath); sections.push(generateBusinessContextSection(businessContext)); } if (options.usageExamples || options.aiEnhanced) { const usageAnalysis = (0, usage_pattern_analyzer_1.analyzeUsagePatterns)(allParsedFiles, projectPath); sections.push(generateUsageExamplesSection(usageAnalysis, parsedFile)); } if (options.architectureInsights || options.aiEnhanced) { const architectureInsights = (0, architecture_analyzer_1.analyzeArchitecture)(allParsedFiles, dependencyGraph); sections.push(generateArchitectureSection(architectureInsights, parsedFile)); } if (options.semanticAnalysis || options.aiEnhanced) { const semanticAnalysis = (0, semantic_analyzer_1.analyzeSemanticRelationships)(allParsedFiles, dependencyGraph); sections.push(generateSemanticSection(semanticAnalysis, parsedFile)); } return sections.filter(section => section.trim()).join('\n\n'); } /** * Generates business context section */ function generateBusinessContextSection(context) { const sections = []; const ctx = context; sections.push('## 🎯 Business Context'); sections.push(`**Domain**: ${ctx.domain} (${ctx.confidence}% confidence)`); if (ctx.description) { sections.push(`**Description**: ${ctx.description}`); } if (ctx.frameworks && ctx.frameworks.length > 0) { sections.push(`**Tech Stack**: ${ctx.frameworks.join(', ')}`); } if (ctx.patterns && ctx.patterns.length > 0) { sections.push(`**Architecture**: ${ctx.patterns.join(', ')}`); } if (ctx.entities && ctx.entities.length > 0) { sections.push(''); sections.push('**Business Entities**:'); ctx.entities.forEach((entity) => { sections.push(`- ${entity}`); }); } if (ctx.businessRules && ctx.businessRules.length > 0) { sections.push(''); sections.push('**Business Rules**:'); ctx.businessRules.forEach((rule) => { sections.push(`- ${rule}`); }); } return sections.join('\n'); } /** * Generates usage examples section */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function generateUsageExamplesSection(usage, parsedFile) { const sections = []; const usageData = usage; if (!usageData.examples) return ''; // Filter examples relevant to this file const relevantExamples = usageData.examples.filter((example) => parsedFile.functions.some(func => func.name === example.function) || parsedFile.classes.some(cls => cls.methods.some(method => example.function?.includes(method.name)))); if (relevantExamples.length === 0) { return ''; } sections.push('## 📖 Usage Examples'); // Group by category const categories = [ 'creation', 'validation', 'transformation', 'query', 'business-logic', ]; categories.forEach(category => { const categoryExamples = relevantExamples.filter((ex) => ex.category === category); if (categoryExamples.length > 0) { sections.push(`### ${category.charAt(0).toUpperCase() + category.slice(1).replace('-', ' ')}`); categoryExamples.slice(0, 2).forEach((example) => { sections.push(`**${example.function}**`); sections.push('```typescript'); sections.push(example.code || ''); sections.push('```'); sections.push(`*${example.description}*`); sections.push(''); }); } }); // Add common patterns if (usageData.patterns && usageData.patterns.length > 0) { sections.push('### Common Patterns'); usageData.patterns.slice(0, 3).forEach((pattern) => { sections.push(`**${pattern.pattern}**: ${pattern.description}`); }); } return sections.join('\n'); } /** * Generates architecture insights section */ function generateArchitectureSection(insights, parsedFile) { const sections = []; sections.push('## 🏗️ Architecture Insights'); // Layer information if (insights.layerArchitecture) { sections.push(`**Pattern**: ${insights.layerArchitecture.pattern}`); sections.push(`**Rationale**: ${insights.layerArchitecture.rationale}`); // Find which layer this file belongs to const currentLayer = insights.layerArchitecture.layers.find((layer) => layer.files.includes(parsedFile.fileName)); if (currentLayer) { sections.push(''); sections.push(`**This File's Role**: ${currentLayer.name}`); sections.push(`**Responsibility**: ${currentLayer.responsibility}`); } } // Data flow patterns if (insights.dataFlow.length > 0) { sections.push(''); sections.push('**Data Flow Patterns**:'); insights.dataFlow.slice(0, 2).forEach((flow) => { sections.push(`- **${flow.name}**: ${flow.description}`); }); } // Error handling strategy if (insights.errorStrategy) { sections.push(''); sections.push(`**Error Handling**: ${insights.errorStrategy.strategy}`); if (insights.errorStrategy.patterns.length > 0) { sections.push(`**Patterns**: ${insights.errorStrategy.patterns.join(', ')}`); } } return sections.join('\n'); } /** * Generates semantic analysis section */ function generateSemanticSection(semantic, parsedFile) { const sections = []; // Find entities in this file const fileEntities = semantic.entities.filter((entity) => parsedFile.classes.some(cls => cls.name === entity.name)); if (fileEntities.length === 0) { return ''; } sections.push('## 🔗 Domain Analysis'); fileEntities.forEach((entity) => { sections.push(`### ${entity.name} Entity`); sections.push(`**Type**: ${entity.type}`); sections.push(`**Description**: ${entity.description}`); // Relationships const entityRelationships = semantic.relationships.filter((rel) => rel.from === entity.name || rel.to === entity.name); if (entityRelationships.length > 0) { sections.push(''); sections.push('**Relationships**:'); entityRelationships.forEach((rel) => { sections.push(`- ${rel.from} ${rel.type} ${rel.to} (${rel.cardinality})`); }); } // State transitions const stateTransition = semantic.stateTransitions.find((st) => st.entity === entity.name); if (stateTransition) { sections.push(''); sections.push(`**States**: ${stateTransition.states.join(' → ')}`); } // Business rules const entityInvariants = semantic.invariants.filter((inv) => inv.entity === entity.name); if (entityInvariants.length > 0) { sections.push(''); sections.push('**Business Rules**:'); entityInvariants.forEach((inv) => { sections.push(`- ${inv.rule}`); }); } }); // Workflows involving this file const relevantWorkflows = semantic.workflows.filter((workflow) => workflow.name.includes(parsedFile.fileName.replace('.ts', ''))); if (relevantWorkflows.length > 0) { sections.push(''); sections.push('**Business Workflows**:'); relevantWorkflows.slice(0, 2).forEach((workflow) => { sections.push(`- **${workflow.name}**: ${workflow.description}`); }); } return sections.join('\n'); } /** * Generates enhanced dependency analysis with all insights */ function generateEnhancedDependencyAnalysis(allParsedFiles, dependencyGraph, options, projectPath) { const sections = []; // Start with base dependency analysis const baseDependencyMarkdown = generateDependencyMarkdown(dependencyGraph, { includeMermaid: options.mermaid, }); sections.push(baseDependencyMarkdown); // Add enhanced sections if (options.businessContext || options.aiEnhanced) { const businessContext = (0, business_context_analyzer_1.analyzeBusinessContext)(allParsedFiles, projectPath); sections.push(generateBusinessContextSection(businessContext)); } if (options.architectureInsights || options.aiEnhanced) { const architectureInsights = (0, architecture_analyzer_1.analyzeArchitecture)(allParsedFiles, dependencyGraph); sections.push(generateFullArchitectureSection(architectureInsights)); } if (options.semanticAnalysis || options.aiEnhanced) { const semanticAnalysis = (0, semantic_analyzer_1.analyzeSemanticRelationships)(allParsedFiles, dependencyGraph); sections.push(generateFullSemanticSection(semanticAnalysis)); } return sections.filter(section => section.trim()).join('\n\n'); } /** * Generates full architecture section for dependency analysis */ function generateFullArchitectureSection(insights) { const sections = []; sections.push('## 🏗️ Complete Architecture Analysis'); // Layer architecture sections.push(`### ${insights.layerArchitecture.pattern}`); sections.push(insights.layerArchitecture.rationale); sections.push(''); insights.layerArchitecture.layers.forEach((layer) => { sections.push(`**${layer.name}**`); sections.push(`- Responsibility: ${layer.responsibility}`); sections.push(`- Files: ${layer.files.join(', ')}`); sections.push(''); }); // Design principles analysis if (insights.designPrinciples.length > 0) { sections.push('### Design Principles Analysis'); insights.designPrinciples.forEach((principle) => { sections.push(`**${principle.principle}**`); if (principle.evidence.length > 0) { sections.push('✅ Evidence:'); principle.evidence.forEach((evidence) => { sections.push(`- ${evidence}`); }); } if (principle.violations.length > 0) { sections.push('⚠️ Potential Issues:'); principle.violations.forEach((violation) => { sections.push(`- ${violation}`); }); } sections.push(''); }); } return sections.join('\n'); } /** * Generates full semantic analysis section */ function generateFullSemanticSection(semantic) { const sections = []; sections.push('## 🔗 Complete Domain Model'); // Entity relationship diagram if (semantic.entities.length > 0 && semantic.relationships.length > 0) { sections.push('### Entity Relationships'); sections.push('```mermaid'); sections.push('erDiagram'); semantic.relationships.forEach((rel) => { const mermaidRel = convertToMermaidRelationship(rel.type); sections.push(` ${rel.from} ${mermaidRel} ${rel.to} : "${rel.description}"`); }); sections.push('```'); sections.push(''); } // Business workflows if (semantic.workflows.length > 0) { sections.push('### Business Workflows'); semantic.workflows.forEach((workflow) => { sections.push(`**${workflow.name}**`); sections.push(workflow.description); sections.push(''); sections.push('Steps:'); workflow.steps.forEach((step) => { sections.push(`${step.order}. ${step.action} (${step.actor})`); }); sections.push(''); }); } return sections.join('\n'); } /** * Converts relationship type to Mermaid syntax */ function convertToMermaidRelationship(type) { switch (type) { case 'has-one': return '||--||'; case 'has-many': return '||--o{'; case 'belongs-to': return '}o--||'; case 'uses': return '..>'; default: return '--'; } } // Import the base function (this would need to be implemented) function generateDependencyMarkdown(_graph, _options) { // This would call the existing generateDependencyMarkdown function // For now, return a placeholder return '# Dependency Analysis\n\n(Base dependency analysis would go here)'; } //# sourceMappingURL=enhanced-generator.js.map