JSPM

@yofix/analyzer

0.1.7
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 26
    • Score
      100M100P100Q82849F
    • License MIT

    LLM-powered library to analyze route impact from file changes in any frontend framework

    Package Exports

    • @yofix/analyzer
    • @yofix/analyzer/dist/index.js

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@yofix/analyzer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    Route Impact Analyzer

    ๐ŸŽฏ Intelligent route impact analysis powered by Claude AI

    A framework-agnostic library that analyzes code changes and determines which routes are impacted, using LLM intelligence for initial pattern detection and fast deterministic analysis for subsequent runs.

    โœจ Features

    • ๐ŸŽฏ 100% Accuracy - Verified against 20 real-world routes across 5 production PRs
    • ๐Ÿง  LLM-Powered Pattern Detection - Uses Claude AI to understand your routing structure automatically
    • ๐Ÿค– Hybrid Classification - Intelligent tracing for page-specific vs shared components
    • โšก Fast Cached Analysis - First run ~30s, subsequent runs < 100ms
    • ๐ŸŽฏ Smart Cache Invalidation - Auto mode only refreshes when route structure changes (85% cost reduction)
    • ๐ŸŽจ Framework-Agnostic - Supports React Router, Next.js, Vue Router, Angular, and more
    • ๐Ÿ” Deep Dependency Tracing - Handles 5-6 level import chains and nested route structures
    • ๐Ÿ”„ Bidirectional Analysis - Analyze Files โ†’ Routes OR Routes โ†’ Files
    • ๐Ÿš€ GitHub Actions Native - Built-in caching and PR comment generation
    • ๐Ÿ“Š Confidence Scoring - Know how reliable each impact prediction is
    • โœ… Production-Ready - Input validation, error handling, and TypeScript support
    • ๐Ÿ” Environment Variable Support - Secure API key management via .env files

    ๐Ÿ“ฆ Installation

    # Install globally for CLI usage
    npm install -g @yofix/analyzer
    # or
    yarn global add @yofix/analyzer
    
    # Install as a dependency in your project
    npm install @yofix/analyzer
    # or
    yarn add @yofix/analyzer

    ๐Ÿš€ Quick Start

    Note: After installing @yofix/analyzer, use the route-impact-analyzer CLI command.

    CLI Usage

    # Analyze changed files
    route-impact-analyzer analyze \
      --changed-files src/layout/Topbar.tsx src/pages/User/UserManagement.tsx \
      --base-url https://app.example.com \
      --llm-api-key $CLAUDE_API_KEY \
      --verbose
    
    # From a file list
    route-impact-analyzer analyze \
      --changed-files-file changed-files.txt \
      --base-url https://app.example.com \
      --output impact-report.json
    
    # Using environment variable (recommended)
    export CLAUDE_API_KEY=sk-ant-xxxx
    route-impact-analyzer analyze \
      --changed-files src/components/Button.tsx \
      --base-url https://app.example.com

    Programmatic Usage

    import { analyzeRouteImpact } from '@yofix/analyzer'
    
    const result = await analyzeRouteImpact({
      codebase: {
        path: './my-app'
      },
      changedFiles: [
        'src/layout/Topbar.tsx',
        'src/pages/User/UserManagement.tsx'
      ],
      options: {
        baseUrl: 'https://app.example.com',
        llm: {
          provider: 'anthropic',
          apiKey: process.env.CLAUDE_API_KEY,
          model: 'claude-sonnet-4-5-20250929'
        },
        cache: {
          enabled: true,
          forceRefresh: 'auto', // Smart invalidation
          provider: 'github-actions',
          ttl: 30 * 24 * 60 * 60 // 30 days
        },
        analysis: {
          includeLayouts: true,
          maxDepth: 10,
          verbose: true
        }
      }
    })
    
    console.log(result.impacts)

    Reverse Analysis (Routes โ†’ Files)

    import { analyzeFileImpact } from '@yofix/analyzer'
    
    const result = await analyzeFileImpact({
      codebase: {
        path: './my-app'
      },
      routes: [
        '/user/management',
        '/dashboard',
        '/settings'
      ],
      options: {
        baseUrl: 'https://app.example.com',
        llm: {
          provider: 'anthropic',
          apiKey: process.env.CLAUDE_API_KEY,
          model: 'claude-sonnet-4-5-20250929'
        },
        cache: {
          enabled: true,
          forceRefresh: false, // Use normal caching for route analysis
          provider: 'file-system'
        },
        analysis: {
          includeLayouts: true,
          maxDepth: 3, // Recommended: 3-5 for accurate results
          verbose: false
        }
      }
    })
    
    console.log(result.impacts)
    // Output: Array of files that impact each route
    import { analyzeRouteImpact } from '@yofix/analyzer'
    
    const result = await analyzeRouteImpact({
      codebase: { path: './my-app' },
      changedFiles: ['src/components/Button.tsx'],
      options: {
        cache: {
          enabled: true,
          forceRefresh: 'auto', // ๐ŸŽฏ Smart invalidation - only refresh when routes change
          provider: 'github-actions',
          ttl: 30 * 24 * 60 * 60,
        },
      },
    })

    Benefits of forceRefresh: 'auto' mode:

    • โœ… 85% cost reduction - Only calls LLM when route structure changes
    • โœ… Faster CI/CD - Most PRs complete in < 100ms (vs 2-5s)
    • โœ… High accuracy - Automatically detects new routes, layouts, or structural changes
    • โœ… Zero config - Works out of the box with all frameworks

    See COST_SAVINGS.md for detailed cost analysis.

    ๐ŸŽฏ Example Output

    Route Impact (Files โ†’ Routes)

    {
      "success": true,
      "metadata": {
        "timestamp": 1704067200000,
        "analysisType": "cached",
        "framework": "react-router",
        "totalFiles": 2,
        "cacheAge": 86400000
      },
      "impacts": [
        {
          "changedFile": "src/layout/Topbar.tsx",
          "impactedRoutes": [
            "https://app.example.com/home",
            "https://app.example.com/user/management",
            "https://app.example.com/dashboard",
            "https://app.example.com/settings"
          ],
          "reason": "layout",
          "confidence": "high"
        },
        {
          "changedFile": "src/pages/User/UserManagement.tsx",
          "impactedRoutes": [
            "https://app.example.com/user/management"
          ],
          "reason": "direct",
          "confidence": "high"
        }
      ]
    }

    File Impact (Routes โ†’ Files)

    {
      "success": true,
      "metadata": {
        "timestamp": 1704067200000,
        "analysisType": "cached",
        "framework": "react-router",
        "totalFiles": 3,
        "cacheAge": 86400000
      },
      "impacts": [
        {
          "route": "https://app.example.com/user/management",
          "impactingFiles": [
            "src/pages/User/UserManagement.tsx",
            "src/layout/PrivateLayout.tsx",
            "src/components/UserTable.tsx",
            "src/hooks/useUserData.ts",
            "src/contexts/AuthContext.tsx"
          ],
          "reason": "shared-component",
          "confidence": "medium"
        }
      ]
    }

    ๐Ÿ”ง GitHub Actions Integration

    name: Route Impact Analysis
    
    on:
      pull_request:
        types: [opened, synchronize]
    
    jobs:
      analyze-routes:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
            with:
              fetch-depth: 0
    
          - name: Get changed files
            id: changed-files
            run: |
              git diff --name-only ${{ github.event.pull_request.base.sha }} > changed-files.txt
    
          - name: Setup Node.js
            uses: actions/setup-node@v4
            with:
              node-version: '20'
    
          - name: Install analyzer
            run: npm install -g @yofix/analyzer
    
          - name: Run Analysis
            run: |
              route-impact-analyzer analyze \
                --changed-files-file changed-files.txt \
                --base-url https://app.example.com \
                --llm-api-key ${{ secrets.CLAUDE_API_KEY }} \
                --output impact-report.json \
                --verbose
    
          - name: Comment PR
            uses: actions/github-script@v7
            with:
              script: |
                const fs = require('fs')
                const report = JSON.parse(fs.readFileSync('impact-report.json'))
    
                if (!report.success || report.impacts.length === 0) {
                  return
                }
    
                let comment = `## ๐ŸŽฏ Route Impact Analysis\n\n`
                comment += `**Framework:** ${report.metadata.framework}\n`
                comment += `**Analysis Type:** ${report.metadata.analysisType}\n\n`
    
                for (const impact of report.impacts) {
                  comment += `### \`${impact.changedFile}\`\n`
                  comment += `**Impacted Routes (${impact.impactedRoutes.length}):**\n`
                  impact.impactedRoutes.slice(0, 10).forEach(route => {
                    comment += `- ${route}\n`
                  })
                  if (impact.impactedRoutes.length > 10) {
                    comment += `- ...and ${impact.impactedRoutes.length - 10} more\n`
                  }
                  comment += `**Reason:** ${impact.reason} (${impact.confidence} confidence)\n\n`
                }
    
                github.rest.issues.createComment({
                  issue_number: context.issue.number,
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  body: comment
                })

    ๐Ÿ—๏ธ How It Works

    Architecture Overview

    The analyzer combines LLM intelligence for pattern detection with deterministic static analysis for fast, accurate impact tracing. Here's the technical breakdown:

    ๐Ÿ” Core Components & File References

    1. Entry Points (src/index.ts, src/cli.ts)

    • analyzeRouteImpact() - Main API for Files โ†’ Routes analysis
    • analyzeFileImpact() - Reverse API for Routes โ†’ Files analysis
    • CLI powered by Commander.js with options for batch processing

    2. Framework Detection (src/core/FrameworkDetector.ts)

    • Analyzes package.json dependencies
    • Inspects directory structure (pages/, app/, routes/)
    • Identifies routing strategy (file-based vs centralized)
    • Supports: React Router, Next.js, Vue Router, Angular, Remix, Nuxt, SvelteKit

    3. LLM-Powered Pattern Analysis (src/core/PatternAnalyzer.ts + src/llm/ClaudeProvider.ts)

    • Gathers codebase context (file tree up to 200 files, sample routes, package.json)
    • Sends structured prompts to Claude AI via ClaudeProvider
    • Extracts routing patterns, layout components, and component mappings
    • NEW: Identifies sharedComponents array (globally used components like Button, Table)
    • NEW: Identifies pageSpecificDirectories array (page-local component directories)
    • Uses AST parsing to enrich patterns with actual route definitions
    • Resolves import aliases from tsconfig.json/jsconfig.json
    • Critical: Handles nested routes by recursively combining parent + child paths

    4. Static Analysis Engine (src/core/StaticAnalyzer.ts)

    • Builds dependency graph using Breadth-First Search (BFS)
    • Parses imports with Babel AST (src/utils/ASTParser.util.ts)
    • Resolves barrel exports (index.ts re-export patterns)
    • Creates forward/reverse dependency links
    • Complexity: O(n + m) where n = files, m = imports

    5. Route Impact Tracer (src/core/RouteTracer.ts)

    • Hybrid Classification System for intelligent dependency tracing:
      • page-specific: Components in /pages/*/components - traces FULL hierarchy
      • truly-shared: Global components (e.g., /components/Button) - only direct dependents
      • cross-page: Page importing from another page - traces through
      • layout: Layout/wrapper components - affects all routes using it
      • utility: Pure utility functions - only direct dependents
    • Classifies impact types:
      • Direct: Changed file IS the page component (high confidence)
      • Layout: Changed file IS a layout wrapper (high confidence)
      • Shared: Changed file used transitively (medium/low confidence based on classification)
    • Calculates confidence scores based on dependency depth and classification:
      • Depth 1 โ†’ High confidence
      • Depth 2-3 โ†’ Medium confidence
      • Depth > 3 โ†’ Low confidence
    • Critical Fix: Uses .filter() to find ALL routes per component (not just first route)
    • Deduplicates and merges results

    6. Cache Management (src/cache/CacheManager.ts)

    • Dual provider support: GitHub Actions + File System
    • 30-day TTL (configurable)
    • Cache key based on project root + SHA256 hash
    • Stores pattern cache (~50-500 KB typically)

    7. AST Parsing & Import Resolution

    • src/utils/ASTParser.util.ts - Babel parser for JS/TS/JSX/TSX
    • src/utils/PathResolver.util.ts - Resolves import aliases (@/* โ†’ src/*)
    • src/utils/FileSystem.util.ts - File I/O and glob operations

    ๐Ÿ“Š Execution Flow

    Phase 1: Input Validation & Setup

    User Input (changed files + options)
        โ†“
    Validation with Zod schemas (src/validation.ts)
        โ†“
    Normalize paths to project-relative
        โ†“
    Initialize CacheManager

    Phase 2: Pattern Detection (First Run Only)

    CacheManager.load()
        โ†“
    [Cache Hit] โ†’ Skip to Phase 3
    [Cache Miss] โ†“
    FrameworkDetector.detect()
        โ†“
    PatternAnalyzer.gatherCodebaseContext()
      - Read package.json
      - Scan file tree (max 100 files)
      - Find route files based on framework
      - Read sample routes (max 15 files)
        โ†“
    ClaudeProvider.detectPatterns() [LLM API Call ~2-5s]
      - Send context to Claude AI
      - Parse JSON response with patterns
        โ†“
    PatternAnalyzer.enrichPatternCache()
      - AST parsing of all route files
      - Extract actual route definitions
      - Resolve component paths through imports
      - Build comprehensive route mappings
        โ†“
    CacheManager.save(patternCache)

    Phase 3: Dependency Graph Building

    PatternCache
        โ†“
    StaticAnalyzer.buildDependencyGraph()
      - Start files: routes + layouts + page components
      - BFS traversal (max depth: 10)
      - For each file:
        โ”œโ”€ Parse AST to extract imports
        โ”œโ”€ Resolve import paths (handle aliases)
        โ”œโ”€ Resolve barrel exports (index.ts)
        โ”œโ”€ Create DependencyNode
        โ””โ”€ Link dependencies + dependents
        โ†“
    DependencyGraph {
      nodes: Map<filePath, DependencyNode>
      routes: Map<componentPath, RouteMapping>
    }

    Phase 4: Route Impact Tracing

    DependencyGraph + ChangedFiles
        โ†“
    RouteTracer.traceImpacts()
      - For each changed file:
        โ”œโ”€ Check: Is it a page component?
        โ”‚   Yes โ†’ Direct impact (high confidence)
        โ”œโ”€ Check: Is it a layout component?
        โ”‚   Yes โ†’ All routes using layout (high confidence)
        โ””โ”€ Otherwise: Find dependent routes
            โ”œโ”€ BFS to find files depending on this
            โ”œโ”€ Calculate dependency depth
            โ””โ”€ Assign confidence score
        โ†“
    Merge and deduplicate results
        โ†“
    AnalysisResult {
      success: true,
      metadata: { timestamp, framework, analysisType },
      impacts: RouteImpact[]
    }

    ๐Ÿงฎ Key Algorithms

    Dependency Finding (BFS)

    // Simplified algorithm from StaticAnalyzer.findDependents()
    function findDependents(graph, changedFile, maxDepth) {
      const queue = [{ file: changedFile, depth: 0 }]
      const visited = new Set()
      const dependents = []
    
      while (queue.length > 0) {
        const { file, depth } = queue.shift()
    
        if (depth > maxDepth || visited.has(file)) continue
        visited.add(file)
    
        const node = graph.nodes.get(file)
        for (const dependent of node.dependents) {
          queue.push({ file: dependent, depth: depth + 1 })
          dependents.push(dependent)
        }
      }
    
      return dependents
    }

    Confidence Scoring

    // From RouteTracer.calculateConfidence()
    function calculateConfidence(depth) {
      if (depth === 1) return 'high'
      if (depth <= 3) return 'medium'
      return 'low'
    }

    Barrel Export Resolution

    // From StaticAnalyzer.resolveBarrelExport()
    // Detects: export { Button } from './components/Button'
    // Resolves: 'src/pages' โ†’ ['src/pages/Home.tsx', 'src/pages/About.tsx']

    โšก Performance Characteristics

    Operation First Run Cached Run Complexity
    Pattern Detection 2-5 seconds < 100ms O(n) LLM call
    Graph Building 100-500ms 100-500ms O(n + m)
    Route Tracing 50-200ms 50-200ms O(k ร— d)
    Total ~3-6 seconds < 1 second -
    • n = number of files
    • m = number of imports
    • k = number of changed files
    • d = max traversal depth

    ๐ŸŽฏ Why This Approach?

    Hybrid Strategy Benefits:

    1. LLM for Pattern Detection - Handles any framework/structure automatically
    2. Static Analysis for Tracing - Fast, deterministic, and accurate
    3. Caching - Best of both worlds (smart + fast)

    Challenges Solved:

    • Nested Routes: AST parser recursively processes children arrays with proper path concatenation
    • Layout Components: Detected via usage patterns, not naming conventions
    • Import Aliases: Resolved from tsconfig.json dynamically
    • Barrel Exports: AST-based re-export resolution
    • Confidence Scoring: Prevents false positives from distant dependencies
    • Multiple Routes Per Component: Components mapping to multiple routes (e.g., /marketing/new AND /tru-roi/new)
    • Deep Import Chains: Page-specific components traced through 5-6 level hierarchies
    • False Positive Prevention: Truly-shared components limited to direct dependents only

    ๐Ÿ”ง Key Technical Improvements (v1.1.0)

    1. Hybrid Component Classification

    Problem: Original logic only counted direct dependents, missing deep import chains for page-specific components.

    Solution: Implemented intelligent classification system:

    switch (classification) {
      case 'page-specific':
        shouldInclude = true  // Trace through FULL hierarchy
        break
      case 'truly-shared':
        shouldInclude = directDependents.has(dependent)  // Only direct
        break
      // ... other classifications
    }

    Impact: CampaignDetailDrawer went from 2 routes โ†’ 7 routes (found all /tru-roi/* variants)

    2. Multiple Routes Per Component

    Problem: Used .find() which only returned first route when components mapped to multiple routes.

    Solution: Changed to .filter() to get ALL routes:

    // Before: const mapping = routeMappings.find(m => m.component === file)
    // After:  const mappings = routeMappings.filter(m => m.component === file)

    Impact: ConfigurationCenter went from 1 route โ†’ 5 routes (all variants found)

    3. Nested Route Extraction

    Problem: AST parser wasn't recursively processing children arrays in route objects.

    Solution: Rewrote extractReactRouterRoutes() to:

    • Recursively process nested structures
    • Concatenate parent + child paths (e.g., /tru-roi + /campaign-metrics)
    • Handle index routes that use parent path

    Impact: Cache now correctly extracts 254 routes vs 270 duplicates before

    4. Enhanced LLM Pattern Detection

    Problem: LLM didn't have enough context to identify page-specific vs shared components.

    Solution: Enhanced prompts with:

    • 200 files (up from 100)
    • sharedComponents array extraction (25 components)
    • pageSpecificDirectories array extraction (28 directories)

    Impact: 100% classification accuracy for page-specific components


    First Run (Pattern Detection with LLM)

    1. Framework Detection - Identifies your framework (React Router, Next.js, Vue, etc.)
    2. Pattern Analysis - Claude AI analyzes your codebase to understand:
      • Where routes are defined
      • How components map to routes
      • Which files are layouts/wrappers
      • Import alias patterns
    3. Cache Generation - Saves patterns for 30 days

    Subsequent Runs (Deterministic Analysis)

    1. Load Cached Patterns - Retrieves patterns from cache (< 100ms)
    2. Build Dependency Graph - Maps all file dependencies
    3. Trace Impacts - Determines which routes are affected by changes
    4. Output Results - Returns impacted routes with confidence scores

    ๐Ÿš€ Future Improvements & Roadmap

    ๐ŸŽฏ Planned Features

    1. Enhanced Analysis Capabilities

    • CSS/Style Impact Detection - Track which routes are affected by global CSS changes
    • State Management Tracing - Detect impacts through Redux/Zustand/Context providers
    • API Route Analysis - Map frontend routes to backend API endpoints
    • Performance Impact Scoring - Estimate bundle size changes per route
    • Dead Code Detection - Identify unused route components

    2. Smart Caching Enhancements

    • Incremental Cache Updates - Update only changed patterns instead of full refresh
    • Multi-Project Cache Sharing - Share patterns across monorepo packages
    • Redis/DynamoDB Support - Distributed caching for team environments
    • Cache Versioning - Support multiple pattern versions simultaneously
    • Partial Cache Invalidation - Invalidate only affected routes, not entire cache

    3. Advanced Dependency Analysis

    • Circular Dependency Detection - Warn about problematic import cycles
    • Dynamic Import Tracing - Better handling of React.lazy() and code splitting
    • Webpack/Vite Bundle Analysis - Integrate with build tools for accurate bundling
    • Cross-Package Dependencies - Support for monorepo/workspace analysis
    • CSS-in-JS Dependency Tracking - Trace styled-components/Emotion impacts

    4. Framework-Specific Optimizations

    • Next.js App Router Metadata - Track metadata file impacts (layout.tsx, page.tsx)
    • Next.js Server Actions - Trace server action dependencies
    • Remix Loader/Action Tracing - Detect impacts on data loaders
    • Vue 3 Composition API - Better support for composables and provide/inject
    • Angular Lazy Loading - Improved module boundary detection

    5. Developer Experience

    • VS Code Extension - Real-time route impact preview in editor
    • Git Hook Integration - Pre-commit route impact validation
    • Interactive CLI Mode - TUI for exploring impacts visually
    • Watch Mode - Continuous analysis during development
    • Diff Visualization - Visual graph of affected routes

    6. CI/CD & Collaboration

    • GitLab CI Integration - Native support for GitLab caching
    • Custom Webhook Support - Send impacts to Slack/Teams/Discord
    • PR Size Estimation - Predict review effort based on route impacts
    • Test Selection - Suggest which E2E tests to run based on impacts
    • Release Notes Generation - Auto-generate changelog by route

    7. Accuracy & Intelligence

    • Machine Learning Confidence - Train models on historical accuracy
    • User Feedback Loop - Learn from manual overrides
    • Multi-LLM Support - OpenAI GPT-4, Google Gemini as alternatives
    • Hybrid Analysis - Combine LLM + static analysis scores
    • Custom Pattern Training - Allow teams to define custom patterns

    8. Performance & Scalability

    • Parallel AST Parsing - Use worker threads for large codebases
    • Streaming Analysis - Process files incrementally for huge repos
    • Selective Indexing - Only analyze changed subtrees
    • Binary Cache Format - Faster serialization with Protocol Buffers
    • Graph Database Integration - Use Neo4j for complex dependency queries

    9. Testing & Validation

    • Impact Verification Mode - Run tests on affected routes to confirm
    • Historical Accuracy Tracking - Dashboard showing prediction success rate
    • A/B Testing Support - Track impacts across feature flags
    • Regression Testing - Ensure cache updates don't break existing patterns

    10. Enterprise Features

    • Team Collaboration - Share and merge pattern databases
    • Audit Logging - Track all analysis runs and cache modifications
    • Custom Rules Engine - Define organization-specific impact rules
    • Multi-Tenant Support - Isolate caches per team/project
    • SLA Monitoring - Track analysis performance and reliability

    ๐Ÿ’ก Implementation Suggestions

    Quick Wins (Low Effort, High Impact)

    1. Add --watch mode to CLI for continuous analysis
    2. Export GitHub Actions workflow as reusable action
    3. Add JSON schema validation for cache files
    4. Implement cache warmup CLI command
    5. Add support for .gitignore patterns in exclusions

    Medium Term (Moderate Effort)

    1. Build VS Code extension with real-time preview
    2. Add CSS/SCSS dependency tracking
    3. Implement incremental cache updates
    4. Add support for dynamic imports
    5. Create interactive TUI with blessed/ink

    Long Term (High Effort, High Value)

    1. Machine learning for confidence scoring
    2. Full monorepo/workspace support
    3. Graph database integration for complex queries
    4. Performance impact prediction
    5. Custom LLM fine-tuning for specific codebases

    ๐Ÿ› ๏ธ Contributing Ideas

    Want to contribute? Here are some areas where help is needed:

    • Framework Support - Add support for Qwik, Solid.js, Astro
    • Testing - Write E2E tests with real-world codebases
    • Documentation - Create video tutorials and blog posts
    • Benchmarking - Compare accuracy across different frameworks
    • Bug Fixes - Check Issues for open bugs

    ๐Ÿ“ˆ Metrics & Success Criteria

    Current Performance (Verified):

    • Pattern detection: ~30-35 seconds (first run with LLM)
    • Cached analysis: < 100ms (using existing patterns)
    • Accuracy: 100% โœ… (verified against 20 real-world routes across 5 PRs)
    • Direct impacts: 100% accuracy (high confidence)
    • Shared components: 100% accuracy (medium/low confidence based on depth)
    • False positives: 0
    • False negatives: 0

    Achievement Status:

    • โœ… Accuracy: 100% for all impact types (exceeded 95% goal)
    • โœ… First run: ~30s (LLM analysis + graph building)
    • โœ… Cached run: < 100ms (exceeded 500ms goal)
    • โœ… Support: 7+ frameworks
    • โœ… Cache hit rate: ~85% with auto mode

    See VERIFICATION_RESULTS.md and MANUAL_VERIFICATION.md for detailed accuracy validation.


    ๐Ÿ“š Supported Frameworks

    • โœ… React Router (v5, v6)
    • โœ… Next.js (Pages Router, App Router)
    • โœ… Vue Router
    • โœ… Angular Router
    • โœ… Remix
    • โœ… Nuxt
    • โœ… SvelteKit

    โš™๏ธ Configuration Options

    LLM Config

    llm: {
      provider: 'anthropic',
      apiKey: process.env.CLAUDE_API_KEY,
      model: 'claude-sonnet-4-5-20250929', // or 'claude-3-opus'
      maxTokens: 4096,
      temperature: 0.3
    }

    Cache Config

    cache: {
      enabled: true,                     // Enable/disable caching (default: true)
      forceRefresh: 'auto',              // false | true | 'auto' (default: false)
                                         // false = use cache (default behavior)
                                         // true = always refresh
                                         // 'auto' = smart invalidation (recommended for CI/CD)
      provider: 'github-actions',        // or 'file-system', 'redis'
      ttl: 30 * 24 * 60 * 60,           // 30 days in seconds (default)
      cacheKey: 'custom-key'             // Optional custom cache key
    }

    forceRefresh Modes Explained:

    Mode When to Use LLM Calls Cost Accuracy
    false (default) Local dev, stable codebases Only on first run Low High (until routes change)
    'auto' โญ CI/CD (recommended) Only when routes change (~15% of PRs) Lowest Highest
    true Testing, debugging Every run Highest Highest

    Note: If forceRefresh is not specified, it defaults to false (normal caching behavior).

    Analysis Options

    analysis: {
      includeLayouts: true,          // Include layout component impacts
      maxDepth: 10,                  // Max dependency traversal depth
      excludePatterns: [             // Patterns to exclude
        '**/*.test.tsx',
        '**/*.spec.ts'
      ],
      verbose: true                  // Verbose logging
    }

    ๐Ÿงช Testing

    # Run tests
    npm test
    
    # Run with coverage
    npm test -- --coverage
    
    # Run in watch mode
    npm test -- --watch

    ๐Ÿ“– API Reference

    See docs/API.md for detailed API documentation.

    ๐Ÿค Contributing

    Contributions are welcome! Please read CONTRIBUTING.md for details.

    ๐Ÿ“„ License

    MIT License - see LICENSE for details.

    ๐Ÿ™ Acknowledgments

    ๐Ÿ” Environment Variables

    The library supports loading API keys from environment variables. Create a .env file in your project root:

    CLAUDE_API_KEY=sk-ant-xxxx

    Or export it in your shell:

    export CLAUDE_API_KEY=sk-ant-xxxx

    The CLI will automatically read from process.env.CLAUDE_API_KEY if --llm-api-key is not provided.

    ๐Ÿ“ง Support


    Made with โค๏ธ for better CI/CD workflows