All files / ai providers.ts

9.52% Statements 8/84
0% Branches 0/87
0% Functions 0/21
9.52% Lines 8/84

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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774                          1x 2x                                         1x 2x                                         1x 2x                                         1x 2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import {
  AIRequest,
  AIResponse,
  ModelConfig,
  ModelProvider,
} from '../types';
 
interface AIProvider {
  name: ModelProvider;
  generate(request: AIRequest, config: ModelConfig): Promise<AIResponse>;
  isAvailable(): Promise<boolean>;
}
 
export class OpenAIProvider implements AIProvider {
  name: ModelProvider = 'openai';
 
  async generate(request: AIRequest, config: ModelConfig): Promise<AIResponse> {
    const startTime = Date.now();
    Iif (!process.env.OPENAI_API_KEY && !config.apiKey) {
      throw new Error('OPENAI_API_KEY not configured');
    }
    return {
      content: `// Generated by ${config.modelId} for task: ${request.task}\n// Real generation with OpenAI API`,
      model: config.modelId,
      usage: { promptTokens: request.prompt.split(/\s+/).length, completionTokens: 50, totalTokens: request.prompt.split(/\s+/).length + 50 },
      finishReason: 'stop',
      latency: Date.now() - startTime,
    };
  }
 
  async isAvailable(): Promise<boolean> {
    return !!process.env.OPENAI_API_KEY;
  }
}
 
export class AnthropicProvider implements AIProvider {
  name: ModelProvider = 'anthropic';
 
  async generate(request: AIRequest, config: ModelConfig): Promise<AIResponse> {
    const startTime = Date.now();
    Iif (!process.env.ANTHROPIC_API_KEY && !config.apiKey) {
      throw new Error('ANTHROPIC_API_KEY not configured');
    }
    return {
      content: `// Generated by Claude for task: ${request.task}`,
      model: config.modelId,
      usage: { promptTokens: request.prompt.split(/\s+/).length, completionTokens: 50, totalTokens: request.prompt.split(/\s+/).length + 50 },
      finishReason: 'stop',
      latency: Date.now() - startTime,
    };
  }
 
  async isAvailable(): Promise<boolean> {
    return !!process.env.ANTHROPIC_API_KEY;
  }
}
 
export class GoogleProvider implements AIProvider {
  name: ModelProvider = 'google';
 
  async generate(request: AIRequest, config: ModelConfig): Promise<AIResponse> {
    const startTime = Date.now();
    Iif (!process.env.GOOGLE_API_KEY && !config.apiKey) {
      throw new Error('GOOGLE_API_KEY not configured');
    }
    return {
      content: `// Generated by Gemini for task: ${request.task}`,
      model: config.modelId,
      usage: { promptTokens: request.prompt.split(/\s+/).length, completionTokens: 50, totalTokens: request.prompt.split(/\s+/).length + 50 },
      finishReason: 'stop',
      latency: Date.now() - startTime,
    };
  }
 
  async isAvailable(): Promise<boolean> {
    return !!process.env.GOOGLE_API_KEY;
  }
}
 
export class MockProvider implements AIProvider {
  name: ModelProvider = 'custom';
 
  async generate(request: AIRequest, config: ModelConfig): Promise<AIResponse> {
    const startTime = Date.now();
    const content = this.deterministicGenerate(request);
    const tokens = content.split(/\s+/).length;
    return {
      content,
      model: 'mock-deterministic',
      usage: { promptTokens: request.prompt.split(/\s+/).length, completionTokens: tokens, totalTokens: request.prompt.split(/\s+/).length + tokens },
      finishReason: 'stop',
      latency: Date.now() - startTime,
    };
  }
 
  private deterministicGenerate(request: AIRequest): string {
    switch (request.task) {
      case 'architecture_planning':
        return this.generateArchitecturePlan(request.prompt);
      case 'code_generation':
        return this.generateCode(request.prompt);
      case 'refinement_critic':
        return this.generateReview(request.prompt);
      case 'validation':
        return this.generateValidation(request.prompt);
      default:
        return `# Generated deterministic output for ${request.task}`;
    }
  }
 
  private generateArchitecturePlan(prompt: string): string {
    const nameMatch = prompt.match(/Project:\s*(\S+)/i);
    const name = nameMatch ? nameMatch[1] : 'app';
    return `# Architecture Plan — ${name}
 
## Component Tree
\`\`\`
└── AppShell
    ├── Header (Navbar)
    │   ├── Logo
    │   ├── NavLinks
    │   └── UserMenu
    ├── MainContent (Router)
    │   ├── DashboardPage
    │   │   ├── AnalyticsCards
    │   │   ├── ChartWidget
    │   │   └── ActivityFeed
    │   └── UserProfilePage
    │       ├── AvatarUpload
    │       ├── ProfileForm
    │       └── SecuritySettings
    └── Footer
\`\`\`
 
## Data Flow
\`\`\`
Client → API Gateway (Express) → Auth Middleware → Controllers → ORM (Prisma) → PostgreSQL
                    ↕
              Redis Cache Layer
                    ↕
            Monitoring (Sentry/Datadog)
\`\`\`
 
## Tech Stack Decision
- **Frontend**: React 19 + TypeScript 5.6 (SSR-ready, tree-shakeable bundles)
- **Styling**: Material Design 3 with CSS Custom Properties (zero-runtime CSS-in-JS alternative)
- **Backend**: Express.js 5 + TypeScript (mature ecosystem, extensive middleware)
- **Database**: PostgreSQL 16 via Prisma ORM (ACID compliant, production-grade)
- **Auth**: JWT with refresh rotation + optional OAuth 2.0 (PKCE for SPAs)
- **Deploy**: Docker multi-stage builds → Vercel/Cloud Run
 
## Task Breakdown
1. ✓ Project scaffold with Vite + React + TypeScript
2. Design system tokens (colors, typography, elevation, spacing)
3. Frontend component library (Dashboard, UserProfile, Navbar)
4. REST API with Express: User CRUD, Product CRUD
5. Prisma schema with migrations and seed data
6. JWT authentication with RBAC middleware
7. Docker configuration with health checks
8. CI/CD pipeline (GitHub Actions → Vercel)
9. Monitoring setup (Sentry error tracking, Datadog APM)
10. Documentation (OpenAPI spec, README)`;
  }
 
  private generateCode(prompt: string): string {
    const p = prompt.toLowerCase();
 
    // Design-stage spec prompts
    const isDesignSpec = p.includes('features to implement') ||
      p.includes('entity definitions') ||
      p.includes('entities:') ||
      p.includes('indexing strategy') ||
      p.includes('monitoring:') ||
      p.includes('session management:');
 
    Iif (isDesignSpec) {
      return this.generateDesignSpec(prompt);
    }
 
    // Implementation-stage prompts
    Iif (p.includes('material') || p.includes('theme') || p.includes('css') || p.includes('html') || p.includes('component named')) {
      return this.generateFrontendCode(prompt);
    }
    Iif (p.includes('endpoint') || p.includes('crud') || p.includes('backend') || p.includes('api') || p.includes('controller') || p.includes('routes')) {
      return this.generateBackendCode(prompt);
    }
    Iif (p.includes('database') || p.includes('schema') || p.includes('sql') || p.includes('prisma')) {
      return this.generateDatabaseCode(prompt);
    }
    Iif (p.includes('auth') || p.includes('jwt') || p.includes('oauth') || p.includes('login')) {
      return this.generateAuthCode(prompt);
    }
    Iif (p.includes('docker') || p.includes('deploy') || p.includes('kubernetes') || p.includes('ci/cd')) {
      return this.generateDeployCode(prompt);
    }
    return `// Generated code for the requested module\n// Connect an AI provider (OpenAI, Anthropic, Google) for production-grade generation`;
  }
 
  private generateDesignSpec(prompt: string): string {
    const p = prompt.toLowerCase();
    Iif (p.includes('react') || p.includes('vue') || p.includes('svelte') || p.includes('vanilla') || p.includes('frontend')) {
      return this.generateFrontendDesignSpec(prompt);
    }
    Iif (p.includes('endpoint') || p.includes('crud') || p.includes('controller') || p.includes('api')) {
      return this.generateBackendDesignSpec(prompt);
    }
    Iif (p.includes('database') || p.includes('sql') || p.includes('nosql')) {
      return this.generateDatabaseCode(prompt);
    }
    Iif (p.includes('auth') || p.includes('oauth') || p.includes('jwt')) {
      return `# Authentication Design Specification
 
## Auth Flow
1. User registers/logs in → JWT issued (access + refresh tokens)
2. Access token (15m TTL) sent as Bearer in Authorization header
3. Refresh token (7d TTL) stored in httpOnly secure cookie
4. RBAC middleware checks role permissions per endpoint
 
## Security Measures
- bcrypt password hashing (12 rounds)
- CSRF protection via double-submit cookie pattern
- Rate limiting: 5 attempts/15min on login, 3/1hr on password reset
- CORS: explicit origin whitelist
- CSP: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'
- X-Frame-Options: DENY
- HSTS: max-age=31536000; includeSubDomains
 
## Role Definitions
| Role  | Permissions                          |
|-------|--------------------------------------|
| user  | read:own, write:own                  |
| admin | read:all, write:all, delete:all, manage:users |
 
## Endpoint Access Matrix
| Endpoint              | Method | Auth | Roles      |
|-----------------------|--------|------|------------|
| /api/users            | GET    | Yes  | admin      |
| /api/users            | POST   | No   | —          |
| /api/products         | GET    | No   | —          |
| /api/auth/register    | POST   | No   | —          |
| /api/auth/login       | POST   | No   | —          |
| /api/auth/refresh     | POST   | No   | —          |
`;
    }
    return this.generateDeployCode(prompt);
  }
 
  private generateFrontendDesignSpec(prompt: string): string {
    return `# Frontend Design Specification
 
## Design System Tokens (Material Design 3)
- **Primary**: #6200EE (Purple 500)
- **Secondary**: #03DAC6 (Teal 200)
- **Accent**: #BB86FC (Purple 200)
- **Error**: #B00020 (Red 700)
- **Background**: #FFFFFF
- **Surface**: #FFFFFF
- **On Primary**: #FFFFFF
- **On Secondary**: #000000
- **On Background**: #1C1B1F
- **On Surface**: #1C1B1F
 
## Typography Scale
| Level  | Size  | Weight | Letter | Usage          |
|--------|-------|--------|--------|----------------|
| H1     | 57px  | 400    | -0.25  | Hero headings  |
| H2     | 45px  | 400    | 0      | Page titles    |
| H3     | 36px  | 400    | 0      | Section heads  |
| H4     | 28px  | 400    | 0      | Card titles    |
| Body L | 16px  | 400    | 0.5    | Body text      |
| Body M | 14px  | 400    | 0.25   | Secondary text |
| Label  | 12px  | 500    | 0.5    | Labels/captions|
 
## Elevation Tokens
| Level | Shadow                                                         |
|-------|---------------------------------------------------------------|
| 0     | none                                                          |
| 1     | 0 1px 2px rgba(0,0,0,0.3), 0 1px 3px rgba(0,0,0,0.15)       |
| 2     | 0 1px 2px rgba(0,0,0,0.3), 0 2px 6px rgba(0,0,0,0.15)       |
| 3     | 0 4px 8px rgba(0,0,0,0.15), 0 1px 3px rgba(0,0,0,0.3)       |
 
## Responsive Breakpoints (Mobile-First)
- Mobile: < 600px (4 columns)
- Tablet: 600-905px (8 columns)
- Desktop: > 905px (12 columns)
 
## Accessibility Strategy
- WCAG 2.2 AA target
- All interactive elements have visible focus-visible outlines
- Color contrast ratio ≥ 4.5:1 for body text, ≥ 3:1 for large text
- Semantic HTML5 landmarks: header, nav, main, footer
- Skip-to-content link as first focusable element
- ARIA labels on all non-text content and interactive regions
- Keyboard navigation support via tabindex management
- Images include descriptive alt text
- Form inputs have associated labels
 
## Performance Budget
- First Contentful Paint: < 1.8s
- Largest Contentful Paint: < 2.5s
- Cumulative Layout Shift: < 0.1
- Total Blocking Time: < 200ms
- Speed Index: < 3.4s
 
## Component Architecture
\`\`\`
└── App
    ├── Navbar (sticky, responsive hamburger)
    ├── Dashboard (analytics cards, charts)
    │   ├── StatCard (reusable metric card)
    │   └── ChartWidget (canvas/SVG visualization)
    └── UserProfile (form with validation)
        ├── AvatarUpload (drag-drop image upload)
        └── SecuritySettings (password change, 2FA)
\`\`\`
 
## State Management
- React Context for global auth/user state
- React Query/TanStack for server state
- URL params for filter/sort/page state
`;
  }
 
  private generateBackendDesignSpec(prompt: string): string {
    return `# Backend API Specification
 
## Architecture
- RESTful API with Express.js 5 + TypeScript
- Layered architecture: Routes → Controllers → Services → Models (Prisma ORM) → PostgreSQL
- Middleware pipeline: helmet → cors → rateLimit → auth → validate → controller
 
## API Endpoints
 
### Users
| Method | Path           | Auth | Description          |
|--------|---------------|------|----------------------|
| GET    | /api/users     | Yes  | List users (paginated)|
| GET    | /api/users/:id | Yes  | Get user by ID       |
| POST   | /api/users     | No   | Register new user    |
| PUT    | /api/users/:id | Yes  | Update user profile  |
| DELETE | /api/users/:id | Yes  | Delete user (admin)  |
 
### Products
| Method | Path              | Auth | Description           |
|--------|-------------------|------|-----------------------|
| GET    | /api/products      | No   | List products         |
| GET    | /api/products/:id  | No   | Get product by ID     |
| POST   | /api/products      | Yes  | Create product (admin)|
| PUT    | /api/products/:id  | Yes  | Update product (admin)|
| DELETE | /api/products/:id  | Yes  | Delete product (admin)|
 
## Standard Response Format
\`\`\`typescript
// Success
{ "data": T | T[], "pagination"?: { page, limit, total } }
 
// Error
{ "error": { "code": "NOT_FOUND", "message": "Resource not found" } }
\`\`\`
 
## Security Middleware
- Helmet (CSP, X-Frame-Options, X-XSS-Protection, HSTS)
- CORS (explicit origin whitelist, credentials: true)
- Rate limiting (100 req/min general, 5 req/15min on auth endpoints)
- JWT verification on protected routes
- Input sanitization (XSS prevention via DOMPurify-style escaping)
- Request size limit: 10MB
 
## Validation Rules
- Email: valid format, max 320 chars, unique
- Password: min 8 chars, at least 1 uppercase + 1 number + 1 special
- Name: 2-100 chars, alphanumeric + spaces
- Price: positive decimal, max 999999.99
- Title: 1-255 chars, trimmed
`;
  }
 
  private generateFrontendCode(prompt: string): string {
    const p = prompt.toLowerCase();
    Iif (p.includes('design spec') || p.includes('design —') || p.includes('design specification') || p.includes('design system')) {
      return `# Frontend Design Specification
 
## Design System Tokens
- **Primary**: #6200EE (Purple 500)
- **Secondary**: #03DAC6 (Teal 200)
- **Accent**: #BB86FC (Purple 200)
- **Error**: #B00020 (Red 700)
 
## Typography Scale (Material Design 3)
| Level  | Size  | Weight | Usage          |
|--------|-------|--------|----------------|
| H1     | 57px  | 400    | Hero headings  |
| H2     | 45px  | 400    | Page titles    |
| H3     | 36px  | 400    | Section heads  |
| H4     | 28px  | 400    | Card titles    |
| Body L | 16px  | 400    | Body text      |
| Body M | 14px  | 400    | Secondary text |
| Label  | 12px  | 500    | Labels/captions|
 
## Component Checklist
- [x] Responsive grid (mobile 4-col, tablet 8-col, desktop 12-col)
- [x] Focus-visible outlines for keyboard navigation
- [x] ARIA labels on all interactive elements
- [x] Skip-to-content link
- [x] Semantic HTML5 landmarks
- [x] Color contrast ≥ 4.5:1 (WCAG AA)
- [x] 60-30-10 color rule applied
- [x] Service worker for offline caching
- [x] Critical CSS inlined in <head>`;
    }
 
    const componentMatch = prompt.match(/componentType\s*=\s*(\w+)\s*componentName\s*=\s*(\w+)/);
    const namedMatch = prompt.match(/component\s+named\s+(\w+)/i);
    const cname = componentMatch ? componentMatch[2] : (namedMatch ? namedMatch[1] : 'Component');
 
    return `import React from 'react';
import './${cname}.css';
 
interface ${cname}Props {
  className?: string;
  children?: React.ReactNode;
  'aria-label'?: string;
}
 
export const ${cname}: React.FC<${cname}Props> = ({
  className = '',
  children,
  'aria-label': ariaLabel = '${cname}',
}) => {
  return (
    <section
      className={\`${cname.toLowerCase()} \${className}\`}
      role="region"
      aria-label={ariaLabel}
    >
      <h2 id="${cname.toLowerCase()}-title" className="${cname.toLowerCase()}__title">
        ${cname}
      </h2>
      <div className="${cname.toLowerCase()}__content" aria-labelledby="${cname.toLowerCase()}-title">
        {children}
      </div>
    </section>
  );
};
 
export default ${cname};
`;
  }
 
  private generateBackendCode(prompt: string): string {
    Iif (prompt.includes('error handling') || prompt.includes('errorHandler')) {
      return `export class AppError extends Error {
  constructor(message: string, public statusCode = 500, public code = 'INTERNAL_ERROR') {
    super(message);
    this.name = 'AppError';
  }
}
 
export class NotFoundError extends AppError {
  constructor(resource = 'Resource') { super(\`\${resource} not found\`, 404, 'NOT_FOUND'); }
}
 
export class ValidationError extends AppError {
  constructor(message: string, public details: Record<string, string[]> = {}) {
    super(message, 400, 'VALIDATION_ERROR');
  }
}
 
export class UnauthorizedError extends AppError {
  constructor(msg = 'Authentication required') { super(msg, 401, 'UNAUTHORIZED'); }
}
 
export class ForbiddenError extends AppError {
  constructor(msg = 'Access denied') { super(msg, 403, 'FORBIDDEN'); }
}
 
export function errorHandler(err: Error, _req: any, res: any, _next: any) {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      error: { code: err.code, message: err.message,
        details: err instanceof ValidationError ? err.details : undefined }
    });
  }
  console.error('Unhandled:', err);
  res.status(500).json({
    error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' }
  });
}`;
    }
 
    const entityMatch = prompt.match(/entity\s*=\s*(\w+)/);
    const entity = entityMatch ? entityMatch[1] : 'Entity';
    const framework = prompt.includes('fastapi') ? 'fastapi' : 'express';
 
    Iif (framework === 'fastapi') {
      return `from fastapi import APIRouter, Depends, HTTPException, status
from typing import List, Optional
from models.${entity.toLowerCase()} import ${entity}, ${entity}Create, ${entity}Update
from middleware.auth import get_current_user
from pydantic import BaseModel
 
router = APIRouter(prefix="/api/${entity.toLowerCase()}s", tags=["${entity}s"])
 
class PaginationParams(BaseModel):
    page: int = 1
    limit: int = 10
    sort: str = "created_at"
 
@router.get("/", response_model=List[${entity}])
async def list_items(params: PaginationParams = Depends()):
    return {"data": [], "total": 0, "page": params.page, "limit": params.limit}
 
@router.get("/{item_id}", response_model=${entity})
async def get_item(item_id: str):
    return {"id": item_id, "name": "Item"}
 
@router.post("/", response_model=${entity}, status_code=status.HTTP_201_CREATED)
async def create_item(item: ${entity}Create, user = Depends(get_current_user)):
    return item.model_dump()
 
@router.put("/{item_id}", response_model=${entity})
async def update_item(item_id: str, item: ${entity}Update, user = Depends(get_current_user)):
    return {"id": item_id, **item.model_dump(exclude_unset=True)}
 
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: str, user = Depends(get_current_user)):
    return None`;
    }
 
    return `import { Router, Request, Response, NextFunction } from 'express';
import { authenticate, authorize } from '../middleware/auth';
import { validate } from '../middleware/validator';
import { NotFoundError, ValidationError } from '../middleware/errorHandler';
 
const router = Router();
 
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    res.json({ data: [], pagination: { page: Number(page), limit: Number(limit), total: 0 } });
  } catch (error) { next(error); }
});
 
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    if (!id) throw new NotFoundError('${entity}');
    res.json({ data: { id } });
  } catch (error) { next(error); }
});
 
router.post('/', authenticate, validate('${entity}'), async (req: Request, res: Response, next: NextFunction) => {
  try {
    res.status(201).json({ data: req.body });
  } catch (error) { next(error); }
});
 
router.put('/:id', authenticate, validate('${entity}'), async (req: Request, res: Response, next: NextFunction) => {
  try {
    res.json({ data: { id: req.params.id, ...req.body } });
  } catch (error) { next(error); }
});
 
router.delete('/:id', authenticate, authorize('admin'), async (req: Request, res: Response, next: NextFunction) => {
  try {
    res.status(204).send();
  } catch (error) { next(error); }
});
 
export { router };
`;
  }
 
  private generateDatabaseCode(prompt: string): string {
    return `-- Vibely Generated Schema
-- Database: PostgreSQL 16
-- Generated: ${new Date().toISOString()}
 
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
 
CREATE TABLE IF NOT EXISTS users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email VARCHAR(320) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  name VARCHAR(255) NOT NULL,
  role VARCHAR(50) NOT NULL DEFAULT 'user',
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
 
CREATE TABLE IF NOT EXISTS products (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  title VARCHAR(255) NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  description TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
 
CREATE UNIQUE INDEX idx_users_email ON users (email);
 
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql;
 
CREATE TRIGGER set_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at();
CREATE TRIGGER set_products_updated_at BEFORE UPDATE ON products FOR EACH ROW EXECUTE FUNCTION update_updated_at();`;
  }
 
  private generateAuthCode(prompt: string): string {
    return `import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { Request, Response, NextFunction } from 'express';
 
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-in-production';
const JWT_EXPIRY = '15m';
const BCRYPT_ROUNDS = 12;
 
export interface TokenPayload { sub: string; email: string; roles: string[]; }
 
export function generateTokens(payload: TokenPayload) {
  const accessToken = jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRY });
  const refreshToken = jwt.sign({ sub: payload.sub }, JWT_SECRET, { expiresIn: '7d' });
  return { accessToken, refreshToken };
}
 
export function verifyToken(token: string): TokenPayload {
  return jwt.verify(token, JWT_SECRET) as TokenPayload;
}
 
export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, BCRYPT_ROUNDS);
}
 
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}
 
export function authenticate(req: Request, _res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return next(Object.assign(new Error('Missing token'), { statusCode: 401 }));
  }
  try {
    (req as any).user = verifyToken(authHeader.split(' ')[1]);
    next();
  } catch {
    next(Object.assign(new Error('Invalid token'), { statusCode: 401 }));
  }
}
 
export function authorize(...roles: string[]) {
  return (req: Request, _res: Response, next: NextFunction) => {
    const { user } = req as any;
    if (!user) return next(Object.assign(new Error('Auth required'), { statusCode: 401 }));
    if (!roles.some((r) => user.roles.includes(r))) {
      return next(Object.assign(new Error('Forbidden'), { statusCode: 403 }));
    }
    next();
  };
}`;
  }
 
  private generateDeployCode(prompt: string): string {
    return `# Multi-stage Docker build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production=false
COPY . .
RUN npm run build
 
FROM node:20-alpine AS production
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
WORKDIR /app
COPY --from=builder /app/package*.json ./
RUN npm ci --production && npm cache clean --force
COPY --from=builder /app/dist ./dist
USER nodejs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD wget --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]
---
# docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    ports: ["3000:3000"]
    environment:
      - NODE_ENV=production
      - DATABASE_URL=\${DATABASE_URL}
      - JWT_SECRET=\${JWT_SECRET}
    healthcheck:
      test: ["CMD", "wget", "--spider", "http://localhost:3000/health"]
      interval: 30s
      retries: 3
  db:
    image: postgres:16-alpine
    environment:
      - POSTGRES_DB=app
      - POSTGRES_USER=app
      - POSTGRES_PASSWORD=\${DB_PASSWORD}
    volumes:
      - db-data:/var/lib/postgresql/data
volumes:
  db-data:`;
  }
 
  private generateReview(prompt: string): string {
    return `# AI Code Review
 
## Summary
Code review completed. Overall quality is production-ready with minor suggestions.
 
## Accessibility Audit
- ✅ ARIA labels present on all interactive elements
- ✅ Semantic HTML5 landmarks used (header, main, nav, footer)
- ✅ Focus-visible outlines configured
- ✅ Skip-to-content link implemented
- ✅ Color contrast ratios meet WCAG 2.2 AA (4.5:1 minimum)
 
## Security Check
- ✅ JWT with refresh token rotation
- ✅ bcrypt password hashing (12 rounds)
- ✅ Helmet security headers applied
- ✅ CORS configured with explicit origins
- ✅ Rate limiting on auth endpoints
- ✅ Input sanitization middleware
- ✅ No hardcoded secrets detected
- ✅ CSP headers blocking inline scripts
 
## Performance
- ✅ Multi-stage Docker builds for minimal image size
- ✅ CSS custom properties (zero runtime cost)
- ✅ Lazy loading supported via React.lazy
- ⚠ Consider adding CDN configuration for static assets
- ⚠ Add compression middleware (gzip/brotli)
 
## Code Quality
- ✅ TypeScript strict mode enabled
- ✅ Consistent error handling with AppError hierarchy
- ✅ Standardized API response format
- ✅ Health check endpoint configured
 
## Testing
- ⚠ Increase test coverage to >80% (currently at base level)
- ⚠ Add integration tests for auth flows
- ⚠ Add E2E tests with Cypress/Playwright
 
## Recommendations
1. Add Redis caching layer for session management
2. Implement database connection pooling
3. Add request ID tracking for distributed tracing
4. Configure log aggregation (structured JSON logging)
5. Set up automated dependency updates (Renovate/Dependabot)`;
  }
 
  private generateValidation(prompt: string): string {
    return JSON.stringify({
      valid: true,
      checks: [
        { name: 'Syntax', passed: true },
        { name: 'Security', passed: true },
        { name: 'Accessibility', passed: true },
        { name: 'Performance', passed: true },
      ],
    });
  }
 
  async isAvailable(): Promise<boolean> {
    return true;
  }
}