All files / validation consistency.ts

1.53% Statements 2/130
0% Branches 0/62
0% Functions 0/40
1.9% Lines 2/105

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 3061x                 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
import { v4 as uuid } from 'uuid';
import {
  ConsistencyReport,
  ConsistencyCheck,
  ConsistencyViolation,
  ModuleOutput,
  ProjectManifest,
} from '../types';
 
export class ConsistencyChecker {
  async runFullCheck(
    manifest: ProjectManifest,
    outputs: ModuleOutput[]
  ): Promise<ConsistencyReport> {
    const checks: ConsistencyCheck[] = [];
    const violations: ConsistencyViolation[] = [];
 
    checks.push(this.checkApiContracts(outputs));
    checks.push(this.checkDataFlow(outputs));
    checks.push(this.checkSecurityCoherence(manifest, outputs));
    checks.push(this.checkAccessibility(outputs));
    checks.push(this.checkTestingCoverage(outputs));
 
    for (const check of checks) {
      Iif (check.status === 'fail') {
        violations.push({
          id: uuid(),
          category: check.category,
          severity: 'error',
          location: check.name,
          message: check.details,
          suggestion: 'Review generated code for the specified issue',
          autoFixable: false,
        });
      }
    }
 
    const passed = checks.every((c) => c.status !== 'fail');
    const overallScore =
      checks.reduce((sum, c) => sum + c.score, 0) / Math.max(checks.length, 1);
 
    return {
      id: uuid(),
      timestamp: new Date().toISOString(),
      overallScore: Math.round(overallScore * 100) / 100,
      checks,
      violations,
      passed,
    };
  }
 
  checkApiContracts(outputs: ModuleOutput[]): ConsistencyCheck {
    const frontendOutputs = outputs.filter((o) => o.module === 'frontend');
    const backendOutputs = outputs.filter((o) => o.module === 'backend');
 
    Iif (frontendOutputs.length === 0 || backendOutputs.length === 0) {
      return {
        category: 'api_contract',
        name: 'API Contract Validation',
        status: 'warn',
        details: 'Insufficient data to validate API contracts',
        score: 70,
      };
    }
 
    const frontendContent = frontendOutputs
      .flatMap((o) => o.files.map((f) => f.content))
      .join('\n');
    const backendContent = backendOutputs
      .flatMap((o) => o.files.map((f) => f.content))
      .join('\n');
 
    const fetchCalls = this.extractFetchCalls(frontendContent);
    const routeDefs = this.extractRouteDefinitions(backendContent);
 
    const unmatched = fetchCalls.filter((call) => {
      return !routeDefs.some((route) => call.includes(route));
    });
 
    const score = fetchCalls.length > 0
      ? Math.round(((fetchCalls.length - unmatched.length) / fetchCalls.length) * 100)
      : 100;
 
    return {
      category: 'api_contract',
      name: 'API Contract Validation',
      status: unmatched.length === 0 ? 'pass' : 'fail',
      details: unmatched.length > 0
        ? `Unmatched frontend API calls: ${unmatched.join(', ')}`
        : 'All frontend API calls match backend routes',
      score,
    };
  }
 
  private extractFetchCalls(content: string): string[] {
    const calls: string[] = [];
    const patterns = [
      /fetch\(['"]([^'"]+)['"]\)/g,
      /axios\.(?:get|post|put|delete|patch)\(['"]([^'"]+)['"]/g,
      /api\.(?:get|post|put|delete|patch)\(['"]([^'"]+)['"]/g,
    ];
    for (const pattern of patterns) {
      let match;
      while ((match = pattern.exec(content)) !== null) {
        calls.push(match[1]);
      }
    }
    return calls;
  }
 
  private extractRouteDefinitions(content: string): string[] {
    const routes: string[] = [];
    const patterns = [
      /app\.(?:get|post|put|delete|patch)\(['"]([^'"]+)['"]/g,
      /@(?:Get|Post|Put|Delete|Patch)\(['"]?([^'")\s]+)/g,
      /@app\.route\(['"]([^'"]+)['"]/g,
    ];
    for (const pattern of patterns) {
      let match;
      while ((match = pattern.exec(content)) !== null) {
        routes.push(match[1]);
      }
    }
    return routes;
  }
 
  checkDataFlow(outputs: ModuleOutput[]): ConsistencyCheck {
    const dbOutputs = outputs.filter((o) => o.module === 'database');
    const backendOutputs = outputs.filter((o) => o.module === 'backend');
    const frontendOutputs = outputs.filter((o) => o.module === 'frontend');
 
    Iif (dbOutputs.length === 0) {
      return {
        category: 'data_flow',
        name: 'Data Flow Alignment',
        status: 'warn',
        details: 'No database outputs to validate',
        score: 70,
      };
    }
 
    const dbFields = this.extractFields(dbOutputs);
    const backendRefs = this.extractBackendFieldReferences(backendOutputs);
 
    const dbFieldSet = new Set(dbFields);
    const missingInBackend = backendRefs.filter((ref) => !dbFieldSet.has(ref));
 
    return {
      category: 'data_flow',
      name: 'Data Flow Alignment',
      status: missingInBackend.length === 0 ? 'pass' : 'warn',
      details:
        missingInBackend.length > 0
          ? `Backend references fields not in schema: ${missingInBackend.join(', ')}`
          : 'Data flow is aligned across layers',
      score: missingInBackend.length === 0 ? 100 : 75,
    };
  }
 
  private extractFields(outputs: ModuleOutput[]): string[] {
    const fields = new Set<string>();
    for (const output of outputs) {
      for (const file of output.files) {
        Iif (file.type === 'model' || file.type === 'migration') {
          const fieldMatches = file.content.match(
            /(?:field|property|column)\s*[:(]\s*['"]?(\w+)['"]?/gi
          );
          Iif (fieldMatches) {
            fieldMatches.forEach((f) => fields.add(f.toLowerCase()));
          }
        }
      }
    }
    return Array.from(fields);
  }
 
  private extractBackendFieldReferences(outputs: ModuleOutput[]): string[] {
    const refs = new Set<string>();
    for (const output of outputs) {
      for (const file of output.files) {
        const refMatches = file.content.match(/\.(\w+)\s*[=:)]/g);
        Iif (refMatches) {
          refMatches.forEach((r) => refs.add(r.replace(/[^a-zA-Z]/g, '').toLowerCase()));
        }
      }
    }
    return Array.from(refs);
  }
 
  checkSecurityCoherence(
    manifest: ProjectManifest,
    outputs: ModuleOutput[]
  ): ConsistencyCheck {
    const issues: string[] = [];
 
    const allContent = outputs.flatMap((o) => o.files.map((f) => f.content)).join('\n');
    const allLower = allContent.toLowerCase();
 
    Iif (manifest.auth) {
      // Check for JWT/bearer token patterns realistically
      const hasTokenAuth = /\b(jwt|bearer|verifytoken|jsonwebtoken|createtoken)\b/i.test(allLower);
      const hasCorsCheck = /\b(cors|access-control-allow|cross-origin)\b/i.test(allLower);
      const hasCspCheck = /\b(content-security-policy|helmet\.contentsecuritypolicy|csp)\b/i.test(allLower);
      const hasSessionMgmt = /\b(bcrypt|hashpassword|argon2|pbkdf2)\b/i.test(allLower);
 
      Iif (!hasTokenAuth && !hasSessionMgmt) issues.push('No JWT/token or password hashing detected');
      Iif (!hasCorsCheck) issues.push('No CORS configuration detected');
      Iif (!hasCspCheck) issues.push('No CSP headers detected');
    }
 
    // Only flag hardcoded secrets if it looks like a production value (not env fallback)
    const envFallbackPattern = /process\.env\.\w+\s*\|\|\s*'[^']+'/g;
    const hasEnvFallback = envFallbackPattern.test(allContent);
    const hasRawSecret = /(?:api[_-]?key|secret|password)\s*[:=]\s*['"](?!change|your-|test|dev-|example)[^'"]{8,}['"]/i.test(allContent);
 
    Iif (hasRawSecret && !hasEnvFallback) {
      issues.push('Potential hardcoded secrets found');
    }
 
    const hasSanitization =
      /\b(sanitize|escapehtml|xss|dompurify|validat|input validator)\b/i.test(allLower);
    Iif (!hasSanitization) {
      issues.push('No input sanitization detected');
    }
 
    return {
      category: 'security',
      name: 'Security Coherence',
      status: issues.length === 0 ? 'pass' : 'fail',
      details: issues.length > 0 ? issues.join('; ') : 'All security checks passed',
      score: issues.length === 0 ? 100 : Math.max(0, 100 - issues.length * 20),
    };
  }
 
  checkAccessibility(outputs: ModuleOutput[]): ConsistencyCheck {
    const frontendOutputs = outputs.filter((o) => o.module === 'frontend');
    Iif (frontendOutputs.length === 0) {
      return {
        category: 'accessibility',
        name: 'Accessibility Audit',
        status: 'warn',
        details: 'No frontend outputs to audit',
        score: 70,
      };
    }
 
    const allHtml = frontendOutputs
      .flatMap((o) => o.files.filter((f) => f.type === 'component'))
      .map((f) => f.content)
      .join('\n');
 
    const hasImages = /<img\b|<Image\b|<picture\b/i.test(allHtml);
    const hasInteractive = /<(?:button|a\s|input|select|textarea|form)\b|onClick|onSubmit|type\s*=\s*["']submit/i.test(allHtml);
 
    const checks: Record<string, boolean> = {
      'ARIA labels': /aria-label|aria-labelledby|ariaLabel/i.test(allHtml),
      'Alt text for images': !hasImages || /alt\s*[=:]|altText|alt=/i.test(allHtml),
      'Semantic HTML': /<(?:nav|main|header|footer|article|section|aside|form)\b|role\s*=\s*["'](?:banner|navigation|main|contentinfo|region)/i.test(allHtml),
      'Focus management': !hasInteractive || /tabindex|focus|focus-visible|:focus/i.test(allHtml),
      'Color contrast': /#[0-9A-Fa-f]{3,6}|rgb\(|hsl\(|var\(--md-sys-color/i.test(allHtml),
      'Keyboard nav': !hasInteractive || /onKeyDown|onKeyPress|onkeydown|onkeypress|keydown|keypress|handleKeyDown|handleKeyPress/i.test(allHtml),
    };
 
    const failures = Object.entries(checks).filter(([, v]) => !v).map(([k]) => k);
    const score = Math.round(
      (Object.values(checks).filter(Boolean).length / Object.keys(checks).length) * 100
    );
 
    return {
      category: 'accessibility',
      name: 'Accessibility Audit',
      status: failures.length === 0 ? 'pass' : 'fail',
      details:
        failures.length > 0
          ? `Missing accessibility features: ${failures.join(', ')}`
          : 'Accessibility checks passed',
      score,
    };
  }
 
  checkTestingCoverage(outputs: ModuleOutput[]): ConsistencyCheck {
    const testFiles = outputs.flatMap((o) =>
      o.files.filter((f) => f.type === 'test')
    );
    const codeFiles = outputs.flatMap((o) =>
      o.files.filter((f) => f.type !== 'test' && f.type !== 'config' && f.type !== 'deployment')
    );
 
    const ratio = codeFiles.length > 0 ? testFiles.length / codeFiles.length : 0;
 
    return {
      category: 'testing',
      name: 'Testing Coverage',
      status: ratio >= 0.8 ? 'pass' : ratio > 0 ? 'warn' : 'warn',
      details: ratio > 0
        ? `Test-to-code file ratio: ${testFiles.length}/${codeFiles.length} (${Math.round(ratio * 100)}%)`
        : 'No test files generated — run `vibely stage implementation` with test templates to generate test suites',
      score: ratio >= 0.8 ? 100 : 50,
    };
  }
 
  checkResolvedViolations(report: ConsistencyReport): number {
    return report.violations.filter((v) => v.autoFixable).length;
  }
}