All files analyzer.ts

82.43% Statements 61/74
64.15% Branches 34/53
100% Functions 10/10
86.36% Lines 57/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182                                        2x           2x 2x     2x 23x 23x       2x 2x 23x 23x 2x             23x 23x 23x   23x 23x 402x   23x 23x 402x     402x   2x     2x 8x 8x             2x 2x 8x 8x                 400x 400x 4200x 4200x             402x 380x 380x               2x 23x 23x 23x     2x     2x 2x               2x     2x 20x 20x           2x 13x 13x 10x                     13x 10x                   2x     10x     10x         10x                    
import * as fs from 'fs';
import * as path from 'path';
import {
  scanFiles,
  calculateChangeAmplification,
  getParser,
  Severity,
  IssueType,
} from '@aiready/core';
import type {
  ChangeAmplificationOptions,
  ChangeAmplificationReport,
  FileChangeAmplificationResult,
  ChangeAmplificationIssue,
} from './types';
 
export async function analyzeChangeAmplification(
  options: ChangeAmplificationOptions
): Promise<ChangeAmplificationReport> {
  // Use core scanFiles which respects .gitignore recursively
  const files = await scanFiles({
    ...options,
    include: options.include || ['**/*.{ts,tsx,js,jsx,py,go}'],
  });
 
  // Compute graph metrics: fanIn and fanOut
  const dependencyGraph = new Map<string, string[]>(); // key: file, value: imported files
  const reverseGraph = new Map<string, string[]>(); // key: file, value: files that import it
 
  // Initialize graph
  for (const file of files) {
    dependencyGraph.set(file, []);
    reverseGraph.set(file, []);
  }
 
  // Parse files to build dependency graph
  let processed = 0;
  for (const file of files) {
    processed++;
    if (processed % 50 === 0 || processed === files.length) {
      options.onProgress?.(
        processed,
        files.length,
        `analyzing dependencies (${processed}/${files.length})`
      );
    }
 
    try {
      const parser = getParser(file);
      Iif (!parser) continue;
 
      const content = fs.readFileSync(file, 'utf8');
      const parseResult = parser.parse(content, file);
      const dependencies = parseResult.imports.map((i) => i.source);
 
      const extensions = ['.ts', '.tsx', '.js', '.jsx'];
      for (const dep of dependencies) {
        const depDir = path.dirname(file);
        let resolvedPath: string | undefined;
 
        if (dep.startsWith('.')) {
          // Relative import resolution
          const absoluteDepBase = path.resolve(depDir, dep);
 
          // Try extensions
          for (const ext of extensions) {
            const withExt = absoluteDepBase + ext;
            Iif (files.includes(withExt)) {
              resolvedPath = withExt;
              break;
            }
          }
 
          // Try /index variations
          Eif (!resolvedPath) {
            for (const ext of extensions) {
              const withIndex = path.join(absoluteDepBase, `index${ext}`);
              Iif (files.includes(withIndex)) {
                resolvedPath = withIndex;
                break;
              }
            }
          }
        } else {
          // Non-relative import (package or absolute)
          // Exact match or matches a file in our set (normalized)
          const depWithoutExt = dep.replace(/\.(ts|tsx|js|jsx)$/, '');
          resolvedPath = files.find((f) => {
            const fWithoutExt = f.replace(/\.(ts|tsx|js|jsx)$/, '');
            return (
              fWithoutExt === depWithoutExt ||
              fWithoutExt.endsWith(`/${depWithoutExt}`)
            );
          });
        }
 
        if (resolvedPath && resolvedPath !== file) {
          dependencyGraph.get(file)?.push(resolvedPath);
          reverseGraph.get(resolvedPath)?.push(file);
        }
      }
    } catch (err) {
      void err;
    }
  }
 
  const fileMetrics = files.map((file) => {
    const fanOut = dependencyGraph.get(file)?.length || 0;
    const fanIn = reverseGraph.get(file)?.length || 0;
    return { file, fanOut, fanIn };
  });
 
  const riskResult = calculateChangeAmplification({ files: fileMetrics });
 
  // Fallback: If score is 0 but we have files, ensure it's at least a baseline if not truly "explosive"
  let finalScore = riskResult.score;
  Iif (
    finalScore === 0 &&
    files.length > 0 &&
    riskResult.rating !== 'explosive'
  ) {
    finalScore = 10;
  }
 
  const results: FileChangeAmplificationResult[] = [];
 
  // Helper for severity mapping
  const getLevel = (s: any): number => {
    Iif (s === Severity.Critical || s === 'critical') return 4;
    Eif (s === Severity.Major || s === 'major') return 3;
    if (s === Severity.Minor || s === 'minor') return 2;
    if (s === Severity.Info || s === 'info') return 1;
    return 0;
  };
 
  for (const hotspot of riskResult.hotspots) {
    const issues: ChangeAmplificationIssue[] = [];
    if (hotspot.amplificationFactor > 20) {
      issues.push({
        type: IssueType.ChangeAmplification,
        severity:
          hotspot.amplificationFactor > 40 ? Severity.Critical : Severity.Major,
        message: `High change amplification detected (Factor: ${hotspot.amplificationFactor}). Changes here cascade heavily.`,
        location: { file: hotspot.file, line: 1 },
        suggestion: `Reduce coupling. Fan-out is ${hotspot.fanOut}, Fan-in is ${hotspot.fanIn}.`,
      });
    }
 
    // We only push results for files that have either high fan-in or fan-out
    if (hotspot.amplificationFactor > 5) {
      results.push({
        fileName: hotspot.file,
        issues,
        metrics: {
          aiSignalClarityScore: 100 - hotspot.amplificationFactor, // Just a rough score
        },
      });
    }
  }
 
  return {
    summary: {
      totalFiles: files.length,
      totalIssues: results.reduce((sum, r) => sum + r.issues.length, 0),
      criticalIssues: results.reduce(
        (sum, r) =>
          sum + r.issues.filter((i) => getLevel(i.severity) === 4).length,
        0
      ),
      majorIssues: results.reduce(
        (sum, r) =>
          sum + r.issues.filter((i) => getLevel(i.severity) === 3).length,
        0
      ),
      score: finalScore,
      rating: riskResult.rating,
      recommendations: riskResult.recommendations,
    },
    results,
  };
}