diff --git a/Bolt.new/Backend-Architecture-Guidelines.txt b/Bolt.new/Backend-Architecture-Guidelines.txt new file mode 100644 index 00000000..410adf97 --- /dev/null +++ b/Bolt.new/Backend-Architecture-Guidelines.txt @@ -0,0 +1,1745 @@ +# Backend Architecture Guidelines + +This document contains comprehensive guidelines for creating robust, scalable, and maintainable backend systems. + +## Architecture Philosophy + +Build backend systems that are: + +- **Scalable and Resilient** - Able to handle growing loads and recover from failures +- **Secure by Design** - Security integrated at every level, not added as an afterthought +- **Maintainable** - Clean architecture that's easy to understand and extend +- **Performance Optimized** - Efficient resource utilization and response times +- **Observable** - Comprehensive logging, monitoring, and debugging capabilities + +## Core Architecture Principles + +### Clean Architecture + +- **Layer Separation** + - Controllers/Routes (API endpoints) + - Services (business logic) + - Data Access (repository pattern) + - Domain Models (entities) + - Infrastructure (external services, databases) + +- **Dependency Inversion** + - High-level modules don't depend on low-level modules + - Both depend on abstractions + - Abstractions don't depend on details + - Details depend upon abstractions + +- **Single Responsibility** + - Each module has one reason to change + - Functions do one thing well + - Classes encapsulate cohesive functionality + - Services manage specific domains + +- **Domain-Driven Design** + - Business logic in the domain layer + - Ubiquitous language shared with stakeholders + - Bounded contexts to isolate domains + - Aggregates to enforce invariants + +### API Design + +- **RESTful Principles** + - Resource-oriented endpoints + - Appropriate HTTP methods + - Proper status codes + - Hypermedia links where appropriate + - Version management + +- **GraphQL Considerations** + - Schema-first development + - Resolver optimization + - Query complexity analysis + - Batching and caching + - Authorization directives + +- **API Versioning** + - URL path versioning (`/v1/resources`) + - Accept header versioning + - Content negotiation + - Deprecation strategy + - Documentation of changes + +- **Contract First** + - OpenAPI/Swagger documentation + - Schema validation + - Consumer-driven contracts + - Integration tests against spec + - Automated documentation + +### Statelessness and Scaling + +- **Horizontal Scaling** + - Stateless services + - Load balancing + - Session management via tokens + - No server affinity + - Container orchestration + +- **Vertical Scaling** + - Resource allocation + - Performance profiling + - Memory optimization + - CPU utilization + - I/O efficiency + +- **Microservices Considerations** + - Service boundaries + - Inter-service communication + - API gateways + - Service discovery + - Circuit breaking + +- **Monolith Optimization** + - Modular architecture + - Clear boundaries + - Resource isolation + - Deployment strategies + - Scaling bottleneck identification + +## Database and Data Management + +### Schema Design + +- **Relational Database** + - Normalization (3NF baseline) + - Foreign key constraints + - Indexing strategy + - Query optimization + - Transaction boundaries + +- **NoSQL Database** + - Data access patterns + - Denormalization strategy + - Eventual consistency + - Partition keys + - Compound indexes + +- **Migration Strategy** + - Version control for schema + - Forward-only migrations + - Rollback planning + - Zero-downtime updates + - Data validation + +- **Entity Relationships** + - One-to-one + - One-to-many + - Many-to-many + - Polymorphic relationships + - Self-referential relationships + +### Data Access Patterns + +- **Repository Pattern** + - Entity-specific repositories + - Query abstraction + - Transaction support + - Caching integration + - Error handling + +- **Object-Relational Mapping** + - Entity mapping + - Lazy/eager loading + - Change tracking + - Query generation + - Performance considerations + +- **Query Optimization** + - Execution plans + - Index utilization + - N+1 query prevention + - Batch operations + - Connection pooling + +- **Data Caching** + - Cache invalidation + - TTL strategies + - Distributed caching + - Cache warming + - Stale-while-revalidate + +### Data Integrity and Validation + +- **Input Validation** + - Request schema validation + - Type checking + - Business rule enforcement + - Cross-field validation + - Sanitization + +- **Output Validation** + - Response schema conformance + - Content security + - Sensitive data redaction + - Consistent formatting + - Pagination metadata + +- **Data Constraints** + - Database constraints + - Application-level validation + - Cross-service consistency + - Idempotency guarantees + - State transition rules + +- **Error Cases** + - Input validation errors + - Business rule violations + - Resource not found + - Conflict resolution + - Server capability limits + +## Security Implementation + +### Authentication + +- **User Identity** + - Credential storage + - Password policies + - Multi-factor authentication + - Account lockout + - Password reset + +- **JWT Implementation** + - Token structure + - Signing algorithms + - Expiration strategy + - Refresh mechanism + - Revocation strategy + +- **OAuth/OIDC** + - Authorization flows + - Provider integration + - Scope management + - Token validation + - User info endpoints + +- **API Authentication** + - API keys + - Client credentials + - Certificate-based + - IP whitelisting + - Rate limiting + +### Authorization + +- **Role-Based Access** + - Role definition + - Permission mapping + - Role hierarchy + - Default deny + - Least privilege + +- **Attribute-Based Access** + - Policy evaluation + - Context awareness + - Dynamic permissions + - Environmental conditions + - Temporal constraints + +- **Resource Ownership** + - Multi-tenancy + - User-based isolation + - Team/organization access + - Delegation model + - Ownership transfer + +- **Permission Enforcement** + - Controller/middleware level + - Service layer enforcement + - Data access filtering + - Object-level security + - Field-level security + +### Data Protection + +- **Encryption** + - Data at rest + - Data in transit + - Key management + - Rotation policies + - Algorithm selection + +- **PII Handling** + - Classification + - Minimization + - Anonymization + - Pseudonymization + - Retention policies + +- **Secrets Management** + - Environment variables + - Vault services + - Access control + - Audit logging + - Rotation strategy + +- **Database Security** + - Network isolation + - Access controls + - Query parameterization + - Connection security + - Auditing + +### Security Posture + +- **Vulnerability Management** + - Dependency scanning + - Static analysis + - Dynamic testing + - Penetration testing + - Responsible disclosure + +- **Security Headers** + - Content Security Policy + - CORS configuration + - XSS protection + - CSRF prevention + - Clickjacking protection + +- **Rate Limiting** + - Request throttling + - Account limits + - IP-based limiting + - Graduated response + - Breach detection + +- **Audit Logging** + - Security events + - Access attempts + - Administrative actions + - Data modifications + - System changes + +## Error Handling and Resilience + +### Error Management + +- **Standardized Errors** + - Error classification + - Status code mapping + - Error codes + - User messages + - Developer details + +- **Exception Handling** + - Try-catch patterns + - Async error handling + - Middleware interception + - Global error handlers + - Service-specific handling + +- **Graceful Degradation** + - Fallback strategies + - Default behaviors + - Partial content responses + - Circuit breakers + - Bulkhead pattern + +- **Retry Logic** + - Exponential backoff + - Jitter implementation + - Maximum attempts + - Idempotency guarantees + - Failure reporting + +### Resilience Patterns + +- **Circuit Breaker** + - Failure threshold + - Recovery timeout + - Half-open state + - Health monitoring + - Circuit isolation + +- **Bulkhead Pattern** + - Resource isolation + - Thread pools + - Connection limitations + - Request prioritization + - Failure containment + +- **Timeouts** + - Connection timeouts + - Read timeouts + - Write timeouts + - Service timeouts + - Cascade prevention + +- **Rate Limiters** + - Request throttling + - Token bucket algorithm + - Leaky bucket algorithm + - Fixed/sliding window + - Adaptive strategies + +### Recovery Strategies + +- **Disaster Recovery** + - Backup strategy + - Restore procedures + - Recovery time objectives + - Recovery point objectives + - Failover systems + +- **Data Consistency** + - Outbox pattern + - Saga pattern + - Eventual consistency + - Two-phase commit + - Compensating transactions + +- **Self-Healing** + - Health checks + - Automatic restarts + - Replication + - State reconciliation + - Data repair + +- **Chaos Engineering** + - Failure injection + - Load testing + - Network degradation + - Resource exhaustion + - Recovery validation + +## Performance Optimization + +### Response Time + +- **Caching Strategy** + - Response caching + - Object caching + - Computation caching + - Cache hierarchy + - Invalidation triggers + +- **Query Optimization** + - Indexing strategy + - Query planning + - Result limiting + - Join optimization + - Execution analysis + +- **Async Processing** + - Background jobs + - Message queues + - Scheduled tasks + - Event-driven architecture + - Long-running processes + +- **I/O Management** + - Connection pooling + - Batch operations + - Stream processing + - File I/O optimization + - Network I/O efficiency + +### Resource Utilization + +- **Memory Management** + - Memory profiling + - Leak detection + - Object pooling + - Garbage collection tuning + - Buffer management + +- **CPU Optimization** + - Thread allocation + - Worker processes + - Computation distribution + - Algorithm efficiency + - Hot path optimization + +- **Database Efficiency** + - Connection pooling + - Query optimization + - Read/write splitting + - Sharding + - Replication strategy + +- **Network Efficiency** + - Payload compression + - Request batching + - Keep-alive connections + - Response streaming + - Protocol selection + +### Scaling Strategies + +- **Horizontal Scaling** + - Stateless design + - Load balancing + - Session management + - Data partitioning + - Service discovery + +- **Vertical Scaling** + - Resource allocation + - Hardware optimization + - Application tuning + - Server configuration + - Database sizing + +- **Caching Layers** + - Client-side cache + - CDN integration + - API gateway cache + - Application cache + - Database cache + +- **Read/Write Splitting** + - Command Query Responsibility Segregation + - Read replicas + - Write sharding + - Cache read optimization + - Eventual consistency model + +## Observability and Monitoring + +### Logging + +- **Log Levels** + - Error: System failures + - Warn: Potential issues + - Info: System events + - Debug: Development details + - Trace: Detailed execution flow + +- **Log Structure** + - Timestamp + - Severity + - Service/component + - Correlation ID + - Context information + +- **Log Storage** + - Centralized collection + - Retention policies + - Access controls + - Search capabilities + - Archival strategy + +- **Log Analysis** + - Pattern detection + - Anomaly identification + - Performance insights + - Error investigation + - Audit capabilities + +### Metrics + +- **System Metrics** + - CPU utilization + - Memory usage + - Disk I/O + - Network throughput + - Connection count + +- **Application Metrics** + - Request rate + - Response time + - Error rate + - Concurrent users + - Business transactions + +- **Database Metrics** + - Query performance + - Connection utilization + - Index efficiency + - Lock contention + - Storage growth + +- **Custom Business Metrics** + - Conversion rates + - User engagement + - Feature usage + - Business KPIs + - Revenue indicators + +### Tracing + +- **Distributed Tracing** + - Trace context propagation + - Span collection + - Service mapping + - Latency analysis + - Dependency visualization + +- **Transaction Tracking** + - Request lifecycle + - Service boundaries + - Error propagation + - Resource utilization + - External calls + +- **Performance Profiling** + - Hotspot identification + - Method-level timing + - Resource consumption + - Lock contention + - I/O blocking + +- **User Journey Tracking** + - Session correlation + - Flow visualization + - Conversion funnels + - Abandonment points + - Experience metrics + +### Alerting + +- **Alert Configuration** + - Threshold definition + - Duration conditions + - Composite alerts + - Priority levels + - Notification channels + +- **Alert Management** + - Escalation policies + - On-call rotations + - Alert grouping + - Suppression rules + - Maintenance windows + +- **Alert Response** + - Playbooks + - Automated remediation + - Incident classification + - Resolution tracking + - Post-mortem analysis + +- **Business Alerting** + - KPI thresholds + - Trend deviations + - Conversion drops + - Revenue impacts + - Customer experience degradation + +## Testing Strategy + +### Test Types + +- **Unit Testing** + - Function/method testing + - Component isolation + - Mock dependencies + - State verification + - Edge case coverage + +- **Integration Testing** + - Service interaction + - API contracts + - Database integration + - External service mocking + - Environment setup + +- **System Testing** + - End-to-end workflows + - Real environment + - Data flow validation + - UI integration + - Cross-service functionality + +- **Performance Testing** + - Load testing + - Stress testing + - Endurance testing + - Spike testing + - Scalability testing + +### Test Implementation + +- **Test-Driven Development** + - Write tests first + - Red-green-refactor cycle + - Continuous test execution + - Test coverage goals + - Regression prevention + +- **Behavior-Driven Development** + - Specification by example + - Shared understanding + - Business-centric language + - Acceptance criteria + - Feature validation + +- **Test Organization** + - Test hierarchy + - Descriptive naming + - Setup and teardown + - Shared fixtures + - Test isolation + +- **Test Automation** + - CI/CD integration + - Parallel execution + - Selective testing + - Test reporting + - Failure analysis + +### Test Data Management + +- **Test Data Creation** + - Factories/builders + - Realistic data + - Randomization + - Edge cases + - Invalid data + +- **Database Fixtures** + - Known state setup + - Test isolation + - Transactional tests + - Cleanup procedures + - Data versioning + +- **Mocking and Stubbing** + - External dependencies + - Service virtualization + - Response simulation + - Behavior verification + - State verification + +- **Property-Based Testing** + - Generative testing + - Invariant checking + - Random inputs + - Edge case discovery + - Shrinking to minimal examples + +## Deployment and Operations + +### CI/CD Pipeline + +- **Continuous Integration** + - Automated builds + - Test execution + - Static analysis + - Security scanning + - Artifact generation + +- **Continuous Delivery** + - Environment promotion + - Configuration management + - Deployment approval + - Release notes + - Rollback capability + +- **Automated Testing** + - Unit test suite + - Integration tests + - E2E testing + - Performance verification + - Security validation + +- **Code Quality Gates** + - Test coverage + - Static analysis + - Duplicate detection + - Complexity metrics + - Vulnerability scanning + +### Infrastructure as Code + +- **Environment Definition** + - Infrastructure templates + - Configuration scripts + - Network setup + - Resource allocation + - Security groups + +- **Configuration Management** + - Environment variables + - Feature flags + - Secrets handling + - Parameter stores + - Configuration versioning + +- **Deployment Strategies** + - Blue/green deployment + - Canary releases + - Feature flagging + - A/B testing + - Rolling updates + +- **Containerization** + - Image building + - Registry management + - Orchestration + - Scaling policies + - Service discovery + +### Operation Management + +- **Incident Response** + - Alert triage + - Escalation procedures + - Communication channels + - Resolution tracking + - Post-incident review + +- **Runbooks** + - Common operations + - Troubleshooting guides + - Recovery procedures + - Maintenance tasks + - Emergency protocols + +- **Capacity Planning** + - Resource monitoring + - Growth forecasting + - Scaling thresholds + - Cost optimization + - Performance benchmarks + +- **Change Management** + - Change requests + - Risk assessment + - Approval workflow + - Implementation plans + - Verification procedures + +## Code Organization + +### Project Structure + +- **Directory Organization** + - Feature-based grouping + - Layer-based separation + - Config isolation + - Test proximity + - Documentation location + +- **Module System** + - Clear dependencies + - Interface definitions + - Circular dependency prevention + - Encapsulation + - Public APIs + +- **Naming Conventions** + - Consistent patterns + - Descriptive names + - Purpose indication + - Abbreviation avoidance + - Version indicators + +- **Configuration Management** + - Environment separation + - Defaults and overrides + - Validation + - Documentation + - Secret handling + +### Coding Standards + +- **Style Guidelines** + - Formatting rules + - Naming conventions + - Comment practices + - Module organization + - Code documentation + +- **Code Quality** + - Complexity limits + - Function size + - Class responsibility + - Coupling metrics + - Duplication prevention + +- **Documentation** + - API documentation + - Implementation notes + - Architecture documentation + - Decision records + - Operation guides + +- **Version Control** + - Commit messages + - Branch strategy + - Pull request process + - Code review standards + - Merge requirements + +## Implementation Examples + +### Express.js API Implementation + +```typescript +// src/controllers/userController.ts +import { Request, Response, NextFunction } from 'express'; +import { UserService } from '../services/userService'; +import { CreateUserDto, UpdateUserDto } from '../dtos/userDtos'; + +export class UserController { + constructor(private userService: UserService) {} + + async getUsers(req: Request, res: Response, next: NextFunction): Promise { + try { + const users = await this.userService.findAll(); + res.status(200).json(users); + } catch (error) { + next(error); + } + } + + async getUserById(req: Request, res: Response, next: NextFunction): Promise { + try { + const id = parseInt(req.params.id); + const user = await this.userService.findById(id); + + if (!user) { + res.status(404).json({ message: 'User not found' }); + return; + } + + res.status(200).json(user); + } catch (error) { + next(error); + } + } + + async createUser(req: Request, res: Response, next: NextFunction): Promise { + try { + const userData: CreateUserDto = req.body; + const newUser = await this.userService.create(userData); + res.status(201).json(newUser); + } catch (error) { + next(error); + } + } + + async updateUser(req: Request, res: Response, next: NextFunction): Promise { + try { + const id = parseInt(req.params.id); + const userData: UpdateUserDto = req.body; + const updatedUser = await this.userService.update(id, userData); + + if (!updatedUser) { + res.status(404).json({ message: 'User not found' }); + return; + } + + res.status(200).json(updatedUser); + } catch (error) { + next(error); + } + } + + async deleteUser(req: Request, res: Response, next: NextFunction): Promise { + try { + const id = parseInt(req.params.id); + const deleted = await this.userService.delete(id); + + if (!deleted) { + res.status(404).json({ message: 'User not found' }); + return; + } + + res.status(204).send(); + } catch (error) { + next(error); + } + } +} +``` + +### Service Layer Implementation + +```typescript +// src/services/userService.ts +import { User } from '../models/user'; +import { UserRepository } from '../repositories/userRepository'; +import { CreateUserDto, UpdateUserDto } from '../dtos/userDtos'; +import { NotFoundError, ValidationError } from '../utils/errors'; + +export class UserService { + constructor(private userRepository: UserRepository) {} + + async findAll(): Promise { + return this.userRepository.findAll(); + } + + async findById(id: number): Promise { + return this.userRepository.findById(id); + } + + async create(userData: CreateUserDto): Promise { + // Validate data + this.validateUserData(userData); + + // Check if email already exists + const existingUser = await this.userRepository.findByEmail(userData.email); + if (existingUser) { + throw new ValidationError('Email already registered'); + } + + // Create new user + return this.userRepository.create(userData); + } + + async update(id: number, userData: UpdateUserDto): Promise { + // Validate data + this.validateUserData(userData, false); + + // Check if user exists + const user = await this.userRepository.findById(id); + if (!user) { + throw new NotFoundError('User not found'); + } + + // Check email uniqueness if changing email + if (userData.email && userData.email !== user.email) { + const existingUser = await this.userRepository.findByEmail(userData.email); + if (existingUser) { + throw new ValidationError('Email already registered'); + } + } + + // Update user + return this.userRepository.update(id, userData); + } + + async delete(id: number): Promise { + return this.userRepository.delete(id); + } + + private validateUserData(data: CreateUserDto | UpdateUserDto, isCreating = true): void { + const errors: string[] = []; + + if (isCreating && !data.email) { + errors.push('Email is required'); + } + + if (data.email && !this.isValidEmail(data.email)) { + errors.push('Invalid email format'); + } + + if (isCreating && !data.password) { + errors.push('Password is required'); + } + + if (data.password && data.password.length < 8) { + errors.push('Password must be at least 8 characters long'); + } + + if (errors.length > 0) { + throw new ValidationError(errors.join(', ')); + } + } + + private isValidEmail(email: string): boolean { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); + } +} +``` + +### Repository Pattern Implementation + +```typescript +// src/repositories/userRepository.ts +import { db } from '../config/database'; +import { User } from '../models/user'; +import { CreateUserDto, UpdateUserDto } from '../dtos/userDtos'; +import { hashPassword } from '../utils/auth'; + +export class UserRepository { + async findAll(): Promise { + return db.users.findMany({ + select: { + id: true, + name: true, + email: true, + role: true, + createdAt: true, + updatedAt: true, + }, + }); + } + + async findById(id: number): Promise { + return db.users.findUnique({ + where: { id }, + select: { + id: true, + name: true, + email: true, + role: true, + createdAt: true, + updatedAt: true, + }, + }); + } + + async findByEmail(email: string): Promise { + return db.users.findUnique({ + where: { email }, + select: { + id: true, + name: true, + email: true, + role: true, + createdAt: true, + updatedAt: true, + }, + }); + } + + async create(userData: CreateUserDto): Promise { + const hashedPassword = await hashPassword(userData.password); + + return db.users.create({ + data: { + name: userData.name, + email: userData.email, + password: hashedPassword, + role: userData.role || 'USER', + }, + select: { + id: true, + name: true, + email: true, + role: true, + createdAt: true, + updatedAt: true, + }, + }); + } + + async update(id: number, userData: UpdateUserDto): Promise { + const data: any = { + name: userData.name, + email: userData.email, + role: userData.role, + }; + + // Only hash password if it's included in the update + if (userData.password) { + data.password = await hashPassword(userData.password); + } + + // Remove undefined values + Object.keys(data).forEach(key => data[key] === undefined && delete data[key]); + + return db.users.update({ + where: { id }, + data, + select: { + id: true, + name: true, + email: true, + role: true, + createdAt: true, + updatedAt: true, + }, + }); + } + + async delete(id: number): Promise { + try { + await db.users.delete({ + where: { id }, + }); + return true; + } catch (error) { + // If no rows were affected, user didn't exist + if (error.code === 'P2025') { + return false; + } + throw error; + } + } +} +``` + +### Error Handling Middleware + +```typescript +// src/middleware/errorHandler.ts +import { Request, Response, NextFunction } from 'express'; +import { ValidationError, NotFoundError, AuthorizationError } from '../utils/errors'; +import logger from '../utils/logger'; + +export function errorHandler( + err: Error, + req: Request, + res: Response, + next: NextFunction +) { + // Log all errors + logger.error({ + message: err.message, + stack: err.stack, + method: req.method, + path: req.path, + ip: req.ip, + userId: req.user?.id, + }); + + // Handle specific error types + if (err instanceof ValidationError) { + return res.status(400).json({ + status: 'error', + message: err.message, + code: 'VALIDATION_ERROR', + }); + } + + if (err instanceof NotFoundError) { + return res.status(404).json({ + status: 'error', + message: err.message, + code: 'NOT_FOUND', + }); + } + + if (err instanceof AuthorizationError) { + return res.status(403).json({ + status: 'error', + message: err.message, + code: 'FORBIDDEN', + }); + } + + // Handle unexpected errors + const isDevelopment = process.env.NODE_ENV === 'development'; + + return res.status(500).json({ + status: 'error', + message: 'Internal server error', + code: 'SERVER_ERROR', + ...(isDevelopment && { + detail: err.message, + stack: err.stack, + }), + }); +} +``` + +### Authentication Implementation + +```typescript +// src/middleware/authenticate.ts +import { Request, Response, NextFunction } from 'express'; +import jwt from 'jsonwebtoken'; +import { UserService } from '../services/userService'; +import { AuthorizationError } from '../utils/errors'; + +interface TokenPayload { + userId: number; + role: string; + iat: number; + exp: number; +} + +export function authenticate( + requiredRoles: string[] = [] +) { + return async (req: Request, res: Response, next: NextFunction) => { + try { + // Get token from authorization header + const authHeader = req.headers.authorization; + if (!authHeader || !authHeader.startsWith('Bearer ')) { + throw new AuthorizationError('Authentication required'); + } + + const token = authHeader.split(' ')[1]; + + // Verify token + let payload: TokenPayload; + try { + payload = jwt.verify( + token, + process.env.JWT_SECRET! + ) as TokenPayload; + } catch (err) { + throw new AuthorizationError('Invalid token'); + } + + // Check token expiration + const now = Math.floor(Date.now() / 1000); + if (payload.exp < now) { + throw new AuthorizationError('Token expired'); + } + + // Check role if required + if (requiredRoles.length > 0 && !requiredRoles.includes(payload.role)) { + throw new AuthorizationError('Insufficient permissions'); + } + + // Get user and attach to request + const userService = new UserService(); + const user = await userService.findById(payload.userId); + + if (!user) { + throw new AuthorizationError('User not found'); + } + + // Attach user to request object + req.user = user; + + next(); + } catch (error) { + next(error); + } + }; +} +``` + +### Custom Error Classes + +```typescript +// src/utils/errors.ts +export class ValidationError extends Error { + constructor(message: string) { + super(message); + this.name = 'ValidationError'; + Object.setPrototypeOf(this, ValidationError.prototype); + } +} + +export class NotFoundError extends Error { + constructor(message: string) { + super(message); + this.name = 'NotFoundError'; + Object.setPrototypeOf(this, NotFoundError.prototype); + } +} + +export class AuthorizationError extends Error { + constructor(message: string) { + super(message); + this.name = 'AuthorizationError'; + Object.setPrototypeOf(this, AuthorizationError.prototype); + } +} + +export class DatabaseError extends Error { + constructor(message: string) { + super(message); + this.name = 'DatabaseError'; + Object.setPrototypeOf(this, DatabaseError.prototype); + } +} + +export class ServiceError extends Error { + constructor(message: string) { + super(message); + this.name = 'ServiceError'; + Object.setPrototypeOf(this, ServiceError.prototype); + } +} +``` + +## Libraries and Tools + +### Core Dependencies + +- **Web Framework** + - Express.js + - Fastify + - NestJS + - Koa + +- **Database Access** + - Prisma + - TypeORM + - Sequelize + - Knex + +- **Validation** + - Joi + - Zod + - class-validator + - Yup + +- **Authentication** + - Passport.js + - jsonwebtoken + - bcrypt + - OAuth libraries + +### Development Tools + +- **Testing** + - Jest + - Mocha/Chai + - SuperTest + - Cypress + - k6 + +- **Linting & Formatting** + - ESLint + - Prettier + - TypeScript + - Husky (pre-commit hooks) + - lint-staged + +- **Documentation** + - Swagger/OpenAPI + - JSDoc + - Postman collections + - Markdown documentation + - Architecture Decision Records (ADRs) + +- **Monitoring** + - Prometheus + - Grafana + - Datadog + - New Relic + - Sentry + +## Best Practices Checklist + +### Development Checklist + +- [ ] Use TypeScript with strict mode +- [ ] Document all APIs with OpenAPI/Swagger +- [ ] Write comprehensive tests (unit, integration, E2E) +- [ ] Automate CI/CD pipeline +- [ ] Implement request validation +- [ ] Set up logging and monitoring +- [ ] Use consistent error handling +- [ ] Configure linting and code formatting +- [ ] Implement authentication and authorization +- [ ] Set up database migrations + +### Security Checklist + +- [ ] Use HTTPS for all communications +- [ ] Implement proper authentication +- [ ] Apply authorization on all endpoints +- [ ] Validate all input data +- [ ] Use parameterized queries +- [ ] Sanitize output to prevent XSS +- [ ] Apply rate limiting +- [ ] Set security headers +- [ ] Handle secrets securely +- [ ] Scan dependencies for vulnerabilities + +### Production Readiness + +- [ ] Configure proper logging +- [ ] Set up monitoring and alerts +- [ ] Implement health checks +- [ ] Configure CI/CD pipeline +- [ ] Document deployment procedures +- [ ] Create runbooks for common operations +- [ ] Set up backup and restore procedures +- [ ] Plan for scaling +- [ ] Document API contracts +- [ ] Create incident response plan + +## Code Examples + +### Express.js Application Setup + +```typescript +// src/app.ts +import express from 'express'; +import cors from 'cors'; +import helmet from 'helmet'; +import compression from 'compression'; +import rateLimit from 'express-rate-limit'; +import { errorHandler } from './middleware/errorHandler'; +import { notFoundHandler } from './middleware/notFoundHandler'; +import { requestLogger } from './middleware/requestLogger'; +import routes from './routes'; + +const app = express(); + +// Middleware +app.use(helmet()); // Security headers +app.use(cors()); // CORS handling +app.use(compression()); // Response compression +app.use(express.json()); // Parse JSON bodies +app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies +app.use(requestLogger); // Log all requests + +// Rate limiting +const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per IP + standardHeaders: true, + legacyHeaders: false, + message: 'Too many requests from this IP, please try again later', +}); +app.use(limiter); + +// Routes +app.use('/api', routes); + +// Error handling +app.use(notFoundHandler); +app.use(errorHandler); + +export default app; +``` + +### API Route Definition + +```typescript +// src/routes/userRoutes.ts +import { Router } from 'express'; +import { UserController } from '../controllers/userController'; +import { UserService } from '../services/userService'; +import { UserRepository } from '../repositories/userRepository'; +import { authenticate } from '../middleware/authenticate'; +import { validateRequest } from '../middleware/validateRequest'; +import { createUserSchema, updateUserSchema } from '../validation/userSchemas'; + +const router = Router(); +const userRepository = new UserRepository(); +const userService = new UserService(userRepository); +const userController = new UserController(userService); + +router.get('/', + authenticate(['ADMIN']), + (req, res, next) => userController.getUsers(req, res, next) +); + +router.get('/:id', + authenticate(), + (req, res, next) => userController.getUserById(req, res, next) +); + +router.post('/', + validateRequest(createUserSchema), + (req, res, next) => userController.createUser(req, res, next) +); + +router.put('/:id', + authenticate(), + validateRequest(updateUserSchema), + (req, res, next) => userController.updateUser(req, res, next) +); + +router.delete('/:id', + authenticate(['ADMIN']), + (req, res, next) => userController.deleteUser(req, res, next) +); + +export default router; +``` + +### Dependency Injection Setup + +```typescript +// src/config/container.ts +import { Container } from 'inversify'; +import { TYPES } from './types'; +import { UserController } from '../controllers/userController'; +import { UserService } from '../services/userService'; +import { UserRepository } from '../repositories/userRepository'; +import { DatabaseConnection } from '../config/database'; +import { Logger } from '../utils/logger'; + +const container = new Container(); + +// Infrastructure +container.bind(TYPES.DatabaseConnection).to(DatabaseConnection).inSingletonScope(); +container.bind(TYPES.Logger).to(Logger).inSingletonScope(); + +// Repositories +container.bind(TYPES.UserRepository).to(UserRepository).inSingletonScope(); + +// Services +container.bind(TYPES.UserService).to(UserService).inSingletonScope(); + +// Controllers +container.bind(TYPES.UserController).to(UserController).inSingletonScope(); + +export { container }; +``` + +### Testing Example + +```typescript +// src/services/__tests__/userService.test.ts +import { UserService } from '../userService'; +import { UserRepository } from '../../repositories/userRepository'; +import { ValidationError, NotFoundError } from '../../utils/errors'; + +// Mock the repository +jest.mock('../../repositories/userRepository'); + +describe('UserService', () => { + let userService: UserService; + let userRepository: jest.Mocked; + + beforeEach(() => { + userRepository = new UserRepository() as jest.Mocked; + userService = new UserService(userRepository); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe('create', () => { + it('should create a user with valid data', async () => { + // Arrange + const userData = { + name: 'John Doe', + email: 'john@example.com', + password: 'password123', + }; + + userRepository.findByEmail.mockResolvedValue(null); + userRepository.create.mockResolvedValue({ + id: 1, + ...userData, + role: 'USER', + createdAt: new Date(), + updatedAt: new Date(), + }); + + // Act + const result = await userService.create(userData); + + // Assert + expect(userRepository.findByEmail).toHaveBeenCalledWith(userData.email); + expect(userRepository.create).toHaveBeenCalledWith(userData); + expect(result).toHaveProperty('id', 1); + expect(result).toHaveProperty('name', userData.name); + expect(result).toHaveProperty('email', userData.email); + }); + + it('should throw ValidationError if email already exists', async () => { + // Arrange + const userData = { + name: 'John Doe', + email: 'john@example.com', + password: 'password123', + }; + + userRepository.findByEmail.mockResolvedValue({ + id: 1, + name: 'Existing User', + email: userData.email, + role: 'USER', + createdAt: new Date(), + updatedAt: new Date(), + }); + + // Act & Assert + await expect(userService.create(userData)).rejects.toThrow(ValidationError); + expect(userRepository.create).not.toHaveBeenCalled(); + }); + + it('should throw ValidationError if email is invalid', async () => { + // Arrange + const userData = { + name: 'John Doe', + email: 'invalid-email', + password: 'password123', + }; + + // Act & Assert + await expect(userService.create(userData)).rejects.toThrow(ValidationError); + expect(userRepository.findByEmail).not.toHaveBeenCalled(); + expect(userRepository.create).not.toHaveBeenCalled(); + }); + }); + + describe('update', () => { + it('should update a user with valid data', async () => { + // Arrange + const userId = 1; + const userData = { + name: 'Updated Name', + }; + + userRepository.findById.mockResolvedValue({ + id: userId, + name: 'Original Name', + email: 'user@example.com', + role: 'USER', + createdAt: new Date(), + updatedAt: new Date(), + }); + + userRepository.update.mockResolvedValue({ + id: userId, + name: 'Updated Name', + email: 'user@example.com', + role: 'USER', + createdAt: new Date(), + updatedAt: new Date(), + }); + + // Act + const result = await userService.update(userId, userData); + + // Assert + expect(userRepository.findById).toHaveBeenCalledWith(userId); + expect(userRepository.update).toHaveBeenCalledWith(userId, userData); + expect(result).toHaveProperty('id', userId); + expect(result).toHaveProperty('name', 'Updated Name'); + }); + + it('should throw NotFoundError if user does not exist', async () => { + // Arrange + const userId = 999; + const userData = { + name: 'Updated Name', + }; + + userRepository.findById.mockResolvedValue(null); + + // Act & Assert + await expect(userService.update(userId, userData)).rejects.toThrow(NotFoundError); + expect(userRepository.update).not.toHaveBeenCalled(); + }); + }); +}); +``` + +## Best Practices + +### Code Structure Best Practices + +- Keep files small and focused on a single responsibility +- Use consistent naming conventions across the codebase +- Group related functionality together +- Separate business logic from infrastructure concerns +- Maintain clear dependency boundaries + +### API Design Best Practices + +- Use nouns for resource endpoints +- Keep URLs clean and simple +- Use HTTP methods appropriately +- Return appropriate status codes +- Document all endpoints + +### Security Best Practices + +- Never trust client input +- Implement proper authentication and authorization +- Follow the principle of least privilege +- Keep dependencies up to date +- Run regular security scans + +### Performance Best Practices + +- Implement appropriate caching +- Optimize database queries +- Use async/await for I/O operations +- Monitor and optimize bottlenecks +- Consider pagination for large data sets + +### Testing Best Practices + +- Write tests at multiple levels (unit, integration, system) +- Use test doubles (mocks, stubs, spies) appropriately +- Aim for high code coverage +- Test happy paths and edge cases +- Incorporate testing into the development workflow \ No newline at end of file diff --git a/Bolt.new/Bolt-Design-System.txt b/Bolt.new/Bolt-Design-System.txt new file mode 100644 index 00000000..94022065 --- /dev/null +++ b/Bolt.new/Bolt-Design-System.txt @@ -0,0 +1,1029 @@ +# Bolt Design System + +This document contains comprehensive design guidelines for creating beautiful, consistent, and production-ready user interfaces. + +## Design Philosophy + +Create interfaces that are: + +- **Professional and Beautiful** - Clean, modern aesthetics with attention to detail +- **Production-Ready** - Fully featured and implementation-ready for real-world use +- **Unique** - Distinctive visual style that avoids generic or cookie-cutter designs +- **Consistent** - Cohesive visual language across all components and screens +- **Accessible** - Usable by everyone, regardless of abilities or circumstances + +## Core Principles + +### Human-Centered Design +- Intuitive interfaces that minimize cognitive load +- Progressive disclosure of complex functionality +- Contextual assistance when and where needed +- Meaningful feedback throughout user journeys +- Focus on user goals rather than system capabilities + +### Content-First Approach +- Content determines layout structure +- Strong information hierarchy guides attention +- Intentional whitespace improves readability +- Visual rhythm creates natural flow +- Respect natural reading patterns + +### Adaptive Consistency +- Platform-appropriate patterns for native feel +- Responsive adaptation across device sizes +- Context-aware behavior that anticipates needs +- Common interaction models for learnability +- Familiar conventions balanced with innovation + +## Visual Language + +### Modern Minimalism +- Include only essential elements +- Use purposeful negative space +- Create focused interactions +- Apply deliberate contrast +- Maintain visual clarity + +### Foundational Harmony +- Balance compositions with visual weight +- Establish rhythm through spacing and repetition +- Create proportional relationships between elements +- Align to grid for structural consistency +- Maintain spatial relationships across contexts + +### Subtle Sophistication +- Add refined details that reward attention +- Implement elegant transitions between states +- Design thoughtful animations that guide users +- Polish micro-interactions for delight +- Ensure quality craftsmanship in every element + +## Color System + +### Primary Palette + +- **Azure Blue** (#0066FF) + - Primary actions and buttons + - Key interactive elements + - Focus states and selections + - Brand identity elements + - Progress indicators + +- **Charcoal** (#242933) + - Primary backgrounds (dark mode) + - Container elements + - Base typography in dark mode + - UI frameworks and structure + - Navigation elements + +- **Platinum** (#F4F5F7) + - Light backgrounds (light mode) + - Content areas + - Card elements + - Form field backgrounds + - Subtle dividers + +### Secondary Palette + +- **Mint Green** (#00CC99) + - Success states + - Completion indicators + - Positive metrics + - Growth elements + - Approval indicators + +- **Coral** (#FF6B6B) + - Error states + - Alerts and warnings + - Destructive actions + - Critical information + - Attention elements + +- **Amber** (#FFAB49) + - Warning states + - Notification badges + - Attention indicators + - Pending status + - Moderate alerts + +- **Lavender** (#8B5CF6) + - Accent elements + - Premium features + - Highlighted content + - Special states + - Interactive tutorials + +### Neutral Shades + +- **Dark** + - #242933 (Darkest - text, backgrounds) + - #373F4D (Dark - secondary UI) + - #4A5468 (Medium-dark - borders) + +- **Mid** + - #6B7A99 (Primary mid-tone - secondary text) + - #8A94A6 (Light mid-tone - disabled elements) + - #B0B7C3 (Lightest mid-tone - subtle elements) + +- **Light** + - #D9E0E8 (Dark light - borders) + - #E5E9F0 (Medium light - backgrounds) + - #F4F5F7 (Lightest - page backgrounds) + +### Accessibility Guidelines + +- Maintain minimum contrast ratios: + - 4.5:1 for normal text + - 3:1 for large text + - 3:1 for UI components and graphics + - 4.5:1 for focus indicators + - 7:1 for enhanced accessibility + +- Never use color alone to convey meaning +- Include additional indicators for important states +- Support system color schemes and high contrast modes +- Design for color blindness with multiple visual cues +- Test with accessibility tools during development + +## Typography + +### Font System + +- **Primary Font: Inter** + - UI elements + - Content text + - Navigation + - Forms and inputs + - Labels and buttons + +- **Secondary Font: Roboto Mono** + - Code examples + - Technical data + - Console output + - Terminal commands + - Numerical data and metrics + +- **Display Font: Montserrat** + - Headlines + - Marketing elements + - Feature introductions + - Welcome screens + - Statement elements + +### Type Scale + +#### Mobile +- Display: 32px/40px +- Heading 1: 24px/32px +- Heading 2: 20px/28px +- Heading 3: 18px/24px +- Subtitle: 16px/24px +- Body: 14px/20px +- Caption: 12px/16px +- Small: 10px/14px + +#### Tablet +- Display: 40px/48px +- Heading 1: 32px/40px +- Heading 2: 24px/32px +- Heading 3: 20px/28px +- Subtitle: 18px/26px +- Body: 16px/24px +- Caption: 14px/20px +- Small: 12px/16px + +#### Desktop +- Display: 48px/56px +- Heading 1: 40px/48px +- Heading 2: 32px/40px +- Heading 3: 24px/32px +- Subtitle: 20px/28px +- Body: 16px/24px +- Caption: 14px/20px +- Small: 12px/16px + +### Text Styles + +- **Weight Application** + - Regular (400): Body text, captions + - Medium (500): Subtitles, emphasis + - Bold (700): Headlines, buttons + - Extra Bold (800): Key features, CTAs + - Light (300): Large display text + +- **Line Height** + - Headlines: 1.2 × font size + - Body text: 1.5 × font size + - Buttons: 1.25 × font size + - Captions: 1.33 × font size + - Code blocks: 1.6 × font size + +## Component Design + +### Interactive Elements + +#### Buttons + +- **Primary Button** + - Background: Azure Blue (#0066FF) + - Text: White + - Border radius: 8px + - Height: 44px (mobile), 48px (desktop) + - Padding: 12px 20px + - States: Hover/focus darkens by 10% + +- **Secondary Button** + - Background: Transparent + - Text: Azure Blue (#0066FF) + - Border: 1.5px Azure Blue + - Border radius: 8px + - Height: 44px (mobile), 48px (desktop) + - States: Hover adds light background + +- **Tertiary Button** + - Background: Transparent + - Text: Current text color + - Underline on hover + - Padding: 8px 12px + - Height: 44px (mobile), 48px (desktop) + - States: Hover adds underline + +- **Danger Button** + - Background: Coral (#FF6B6B) + - Text: White + - Border radius: 8px + - Height: 44px (mobile), 48px (desktop) + - States: Hover/focus darkens by 10% + +- **Disabled Button** + - Background: Mid Gray + - Text: Dark Gray + - Opacity: 60% + - No hover effects + - Cursor: not-allowed + +#### Input Fields + +- **Text Input** + - Background: Light neutral + - Border: 1px Mid neutral + - Border radius: 8px + - Height: 44px (mobile), 48px (desktop) + - Inner padding: 12px 16px + - Focus: Azure Blue border/ring + +- **Dropdown** + - Styling matches text input + - Icon: Chevron down + - Dropdown menu: Card styling + - Option height: 44px + - Option padding: 16px + - Selected: Accent background + +- **Checkbox** + - Size: 20px × 20px + - Border radius: 4px + - Border: 1.5px Mid neutral + - Checked: Azure Blue fill, white checkmark + - Focus: 2px outline, 2px offset + +- **Radio Button** + - Size: 20px × 20px + - Border radius: 50% + - Border: 1.5px Mid neutral + - Selected: 8px Azure Blue dot + - Focus: 2px outline, 2px offset + +- **Toggle** + - Height: 24px + - Width: 44px + - Border radius: 12px + - Thumb: 20px circle + - Off state: Mid Gray + - On state: Azure Blue + +### Content Containers + +#### Cards +- Background: White (light mode), Dark charcoal (dark mode) +- Border radius: 12px +- Shadow: 0 2px 8px rgba(0,0,0,0.1) +- Padding: 20px +- Dividers: 1px Light neutral +- Header: 16px bottom spacing +- Footer: 16px top spacing +- Interactions: Subtle hover effect + +#### Lists +- Item height: 56px (with icon), 44px (text only) +- Padding: 16px horizontal +- Dividers: 1px Light neutral +- Selected: Light Azure background +- Hover: 5% darken/lighten +- Icon spacing: 16px from text + +#### Tables +- Header: Medium weight, Light neutral background +- Rows: Alternating background optional +- Cell padding: 12px 16px +- Border: 1px Light neutral +- Hover: 5% darken/lighten +- Sorting indicators: 16px icons + +#### Dialogs +- Background: White (light mode), Dark charcoal (dark mode) +- Border radius: 16px +- Shadow: 0 4px 24px rgba(0,0,0,0.15) +- Width: 90% (mobile), 480px (desktop) +- Title: 24px/32px +- Content padding: 24px +- Button container: 24px padding, top border + +### Navigation Components + +#### Tab Bar +- Height: 56px +- Icon size: 24px +- Label: 12px, Medium weight +- Active indicator: Accent color +- Background: White (light mode), Dark charcoal (dark mode) +- Shadow: 0 -2px 8px rgba(0,0,0,0.1) + +#### Navigation Bar +- Height: 56px +- Title: 18px, Medium weight +- Back button: Chevron left + optional text +- Action buttons: 44px touch target +- Background: White (light mode), Dark charcoal (dark mode) +- Shadow: 0 2px 8px rgba(0,0,0,0.1) + +#### Sidebar +- Width: 280px +- Item height: 44px +- Icon size: 20px +- Section headers: 14px, Medium weight +- Active indicator: 4px accent border +- Background: Light neutral (light mode), Dark charcoal (dark mode) + +#### Bottom Sheet +- Border top-radius: 16px +- Handle indicator: 32px × 4px pill +- Maximum height: 90% of screen +- Drag threshold: 20% of height +- Background: White (light mode), Dark charcoal (dark mode) +- Shadow: 0 -4px 24px rgba(0,0,0,0.15) + +## Layout Guidelines + +### Spacing System +- Base Unit: 4px +- Spacing Scale: + - 2xs: 4px (1× base) + - xs: 8px (2× base) + - sm: 12px (3× base) + - md: 16px (4× base) + - lg: 24px (6× base) + - xl: 32px (8× base) + - 2xl: 48px (12× base) + - 3xl: 64px (16× base) + - 4xl: 96px (24× base) + +- Application: + - Inline elements: xs (8px) + - Related items: md (16px) + - Component groups: lg (24px) + - Section separation: xl-2xl (32-48px) + - Page margins: lg-xl (24-32px) + +### Grid System +- **Mobile (320-599px)** + - Columns: 4 + - Margin: 16px + - Gutter: 16px + - Column width: Fluid + +- **Tablet (600-1023px)** + - Columns: 8 + - Margin: 32px + - Gutter: 24px + - Column width: Fluid + +- **Desktop (1024px+)** + - Columns: 12 + - Margin: 32px + - Gutter: 32px + - Column width: Fluid + - Max width: 1440px + +- Common layouts: + - Full-width: 4/4, 8/8, or 12/12 columns + - Content area: 4/4, 6/8, or 8/12 columns + - Half-width: 2/4, 4/8, or 6/12 columns + - Third-width: n/a, n/a, or 4/12 columns + +### Responsive Patterns + +#### Stacking +- Desktop: Side-by-side elements +- Mobile: Vertical stacking +- Preserve primary content first +- Maintain spacing proportions +- Reconsider element hierarchy for smaller screens + +#### Column Reduction +- Desktop: Multi-column layout +- Mobile: Fewer columns +- Reflow content to maintain relationships +- Preserve content priority +- Adjust spacing proportionally + +#### Container Adaptation +- Desktop: Fixed-width containers +- Mobile: Fluid-width containers +- Maintain relative proportions +- Adjust padding for smaller screens +- Optimize touch targets for mobile + +#### UI Transformation +- Desktop: Extended navigation +- Mobile: Condensed navigation +- Reposition actions for thumb reach +- Prioritize content on small screens +- Hide secondary information until needed + +## Iconography + +### Icon System +- **Icon Library: Lucide** + - Stroke-based icons + - 24×24px default size + - 2px stroke width + - Rounded line caps + - Consistent padding + +- **Size Framework** + - Small: 16px (touch targets: 32px) + - Medium: 24px (touch targets: 44px) + - Large: 32px (touch targets: 56px) + - Feature: 48px (touch targets: 64px) + +- **Alignment** + - Center in touch target + - Align with text baseline when inline + - Use with consistent margins + - Balance visual weight + - Ensure proper spacing + +### Interactive States +- **Default** + - Color: Current text color + - Background: Transparent + - Opacity: 100% + - No decorations + - Normal scale + +- **Hover** + - Color: Current text color + - Background: 5% fill + - Opacity: 100% + - No decorations + - Normal scale + +- **Active** + - Color: Current text color + - Background: 10% fill + - Opacity: 100% + - No decorations + - 98% scale (slight press effect) + +- **Disabled** + - Color: Current text color + - Background: Transparent + - Opacity: 40% + - No decorations + - Normal scale + +- **Selected** + - Color: Accent color + - Background: Transparent + - Opacity: 100% + - No decorations + - Normal scale + +## Motion Design + +### Animation Principles +- **Purposeful** + - Always serves user goals + - Communicates state changes + - Provides clear feedback + - Guides attention + - Establishes relationships + +- **Efficient** + - Quick and responsive + - No unnecessary delays + - Complements interaction + - Minimizes distraction + - Enhances productivity + +- **Cohesive** + - Consistent timing + - Unified easing + - Thematic relations + - Predictable behaviors + - Systematic application + +### Timing System +- **Duration Scale** + - Extra fast: 100ms + - Fast: 200ms + - Normal: 300ms + - Slow: 400ms + - Extra slow: 500ms + +- **Usage Guidelines** + - Interface feedback: Extra fast + - Micro-interactions: Fast + - Component transitions: Normal + - View transitions: Slow + - Onboarding animations: Extra slow + +- **Easing Curves** + - Standard: cubic-bezier(0.2, 0.0, 0.2, 1.0) + - Accelerate: cubic-bezier(0.3, 0.0, 1.0, 1.0) + - Decelerate: cubic-bezier(0.0, 0.0, 0.2, 1.0) + - Sharp: cubic-bezier(0.4, 0.0, 0.6, 1.0) + - Bounce: spring(mass: 1, stiffness: 80, damping: 10) + +### Animation Patterns + +#### Transitions +- **Fade** + - Opacity: 0 → 1 + - Duration: Fast (200ms) + - Easing: Standard + - Usage: Element appearance/disappearance + - Implementation: CSS transitions or animation libraries + +- **Slide** + - Transform: translateY/X + - Duration: Normal (300ms) + - Easing: Decelerate + - Usage: Lists, panels, sheets + - Implementation: CSS transitions or animation libraries + +- **Scale** + - Transform: scale + - Duration: Fast (200ms) + - Easing: Standard + - Usage: Buttons, interactive elements + - Implementation: CSS transitions or animation libraries + +- **Crossfade** + - Combined opacity transitions + - Duration: Normal (300ms) + - Easing: Standard + - Usage: Content replacement + - Implementation: CSS transitions or animation libraries + +#### Micro-interactions +- **Button Press** + - Scale: 1.0 → 0.98 → 1.0 + - Duration: Extra fast (100ms) + - Easing: Sharp + - Usage: All buttons + - Implementation: CSS or JS animation + +- **Toggle Switch** + - Thumb translation + background color + - Duration: Fast (200ms) + - Easing: Standard + - Usage: Boolean settings + - Implementation: CSS transitions + +- **Input Focus** + - Border/shadow transition + - Duration: Fast (200ms) + - Easing: Decelerate + - Usage: Form fields + - Implementation: CSS transitions + +## Mobile-Specific Guidelines + +### Touch Interaction +- **Minimum Target Size** + - Primary targets: 48px + - Secondary targets: 44px + - Minimum spacing: 8px + - Hit slop extension: 8-12px + - Form controls: 44px height + +- **Touch Feedback** + - Visual: Opacity/scale change + - Haptic: Light impact (iOS) + - Audio: None by default + - Duration: 100ms maximum + - Consistency across similar elements + +### Gesture Patterns + +#### Common Gestures +- **Tap** + - Action: Select, activate + - Feedback: Visual highlight + - Duration: Instant + - Components: Buttons, list items + - Implementation: TouchableOpacity, Pressable + +- **Long Press** + - Action: Context menu, selection mode + - Feedback: Visual + haptic + - Duration: 500ms + - Components: List items, cards + - Implementation: Custom gesture handlers + +- **Swipe** + - Action: Dismiss, reveal actions + - Feedback: Content follows finger + - Threshold: 30% of width + - Components: List items, cards + - Implementation: Custom gesture handlers + +- **Drag** + - Action: Reorder, resize + - Feedback: Element follows finger + - Constraint: Within container + - Components: List items, sliders + - Implementation: Custom gesture handlers + +- **Pinch** + - Action: Zoom, scale + - Feedback: Content scales with fingers + - Limits: Min/max scale (0.5-3.0) + - Components: Images, maps + - Implementation: Custom gesture handlers + +#### Custom Patterns +- **Pull to Refresh** + - Activation threshold: 25% of header height + - Visual indicator: Spinner, custom animation + - Haptic: Success (iOS) + - Components: Lists, content screens + - Implementation: RefreshControl + +- **Swipe to Delete** + - Reveal threshold: 30% of width + - Confirm threshold: 60% of width + - Visual cue: Red background, delete icon + - Haptic: None until commit + - Implementation: Custom swipeable component + +### Platform Adaptations +- **iOS Specifics** + - Navigation: Back swipe gesture + - Tab bar: Bottom placement + - Action sheets: Slide up + - Typography: San Francisco + - Components: Follow iOS design patterns + +- **Android Specifics** + - Navigation: Hardware back support + - Tab bar: Material design patterns + - Dialogs: Material design + - Typography: Roboto + - Components: Follow Material design patterns + +- **Web Specifics** + - Navigation: Browser history integration + - Input: Keyboard navigation support + - Hover states: Implemented + - Typography: System fonts + - Components: Web-appropriate patterns + +## Accessibility Guidelines + +### Visual Accessibility +- **Color Contrast** + - Text: 4.5:1 against background + - Large text: 3:1 against background + - UI components: 3:1 against adjacent colors + - Focus indicators: 3:1 against background + - Icons: 3:1 against background + +- **Text Sizing** + - Support dynamic type (iOS) + - Support font scaling (Android) + - Minimum 14sp base size + - Test with larger text settings + - Maintain layout with larger text + +- **Focus States** + - Visible focus indicators + - High contrast focus styles + - Logical focus order + - Keyboard navigation support + - Touch target highlighting + +### Screen Reader Support +- **Labeling** + - Meaningful accessibilityLabel + - Descriptive accessibilityHint + - Appropriate accessibilityRole + - Group related elements + - Context-aware descriptions + +- **Interactive Elements** + - Clear touch targets + - Appropriate accessibilityTraits + - State descriptions (selected, disabled) + - Error messaging + - Success confirmation + +- **Navigation** + - Logical reading order + - Screen reader focus control + - Landmark regions + - Skip navigation options + - Consistent patterns + +### Inclusive Design +- **Multiple Interaction Methods** + - Touch support + - Keyboard navigation + - Voice control compatibility + - Switch control support + - Gesture alternatives + +- **Reduced Motion** + - Respect prefers-reduced-motion + - Essential animation only + - No auto-playing content + - Static alternatives + - No parallax effects + +- **Cognitive Considerations** + - Clear, simple language + - Consistent patterns + - Error prevention + - Undo capability + - Progress indicators + +## Implementation Patterns + +### Web Applications +- Use semantic HTML elements for proper structure +- Implement responsive breakpoints based on layout guidelines +- Apply fluid typography and spacing +- Use CSS variables for theming and consistency +- Implement keyboard navigation and focus management + +### React/React Native +- Structure components following atomic design +- Use styled components or stylesheet patterns consistently +- Implement motion with appropriate libraries (Framer Motion, Reanimated) +- Handle platform-specific adaptation with custom hooks +- Build accessible components with proper ARIA roles + +### Mobile Native +- Implement platform-specific UI adaptations +- Use native navigation patterns +- Handle gestures with appropriate libraries +- Optimize for touch interaction +- Implement proper permission handling + +## Image Guidelines + +### Photography +- Use high-quality, professionally shot images +- Maintain consistent style across all imagery +- Prefer images with natural lighting +- Avoid overly staged or artificial-looking photos +- Use diverse and inclusive representation + +### Illustrations +- Maintain consistent style with brand identity +- Use illustrations to simplify complex concepts +- Scale appropriately across device sizes +- Ensure accessibility with proper alt text +- Consider animation for key illustrations + +### Icons +- Use consistent icon set (Lucide) +- Maintain uniform weight and style +- Size appropriately for context +- Provide text labels where possible +- Ensure sufficient contrast + +## Branding Integration + +### Logo Usage +- Maintain clear space around logo +- Use appropriate size for context +- Avoid stretching or distorting +- Use approved color variations +- Apply consistently across platforms + +### Brand Colors +- Use primary brand colors for key elements +- Apply secondary palette for supporting elements +- Maintain consistent color application +- Follow accessibility guidelines +- Consider color meaning and psychology + +### Voice and Tone +- Professional but approachable +- Clear and concise +- Consistent terminology +- Inclusive and respectful language +- Helpful and solution-oriented + +## Implementation Examples + +### Component Examples + +```jsx +// Button Component +const Button = ({ + children, + variant = "primary", + size = "medium", + disabled = false, + ...props +}) => { + return ( + + ); +}; + +// Card Component +const Card = ({ children, padding = true }) => { + return ( +
+ {children} +
+ ); +}; +``` + +### Style Implementation + +```css +:root { + /* Color variables */ + --color-primary: #0066FF; + --color-secondary: #6B7A99; + --color-success: #00CC99; + --color-warning: #FFAB49; + --color-danger: #FF6B6B; + --color-accent: #8B5CF6; + + /* Dark neutrals */ + --color-dark-1: #242933; + --color-dark-2: #373F4D; + --color-dark-3: #4A5468; + + /* Mid neutrals */ + --color-mid-1: #6B7A99; + --color-mid-2: #8A94A6; + --color-mid-3: #B0B7C3; + + /* Light neutrals */ + --color-light-1: #D9E0E8; + --color-light-2: #E5E9F0; + --color-light-3: #F4F5F7; + + /* Spacing scale */ + --space-2xs: 4px; + --space-xs: 8px; + --space-sm: 12px; + --space-md: 16px; + --space-lg: 24px; + --space-xl: 32px; + --space-2xl: 48px; + --space-3xl: 64px; + --space-4xl: 96px; + + /* Font families */ + --font-primary: 'Inter', sans-serif; + --font-secondary: 'Roboto Mono', monospace; + --font-display: 'Montserrat', sans-serif; + + /* Font sizes */ + --text-xs: 12px; + --text-sm: 14px; + --text-md: 16px; + --text-lg: 18px; + --text-xl: 20px; + --text-2xl: 24px; + --text-3xl: 32px; + --text-4xl: 40px; + --text-5xl: 48px; +} + +/* Button styles */ +.button { + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + font-family: var(--font-primary); + font-weight: 500; + transition: all 0.2s ease; +} + +.button.primary { + background-color: var(--color-primary); + color: white; +} + +.button.primary:hover { + background-color: #0052CC; +} + +/* Card styles */ +.card { + background-color: white; + border-radius: 12px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); +} + +.card.card-padded { + padding: 20px; +} +``` + +## Platform-Specific Guidelines + +### Web Applications +- Test across modern browsers +- Implement responsive breakpoints +- Support keyboard navigation +- Optimize for various screen sizes +- Consider print stylesheets for relevant content + +### iOS Applications +- Follow Apple Human Interface Guidelines +- Use native components when possible +- Support Dynamic Type +- Implement proper safe area handling +- Test on multiple iOS devices + +### Android Applications +- Follow Material Design guidelines +- Support different screen sizes and densities +- Implement proper permission handling +- Test on various Android versions +- Consider manufacturer customizations + +### Cross-Platform Applications +- Maintain consistent branding +- Adapt UI for platform conventions +- Optimize performance for each platform +- Use platform-specific features when appropriate +- Test thoroughly on all target platforms + +## Quality Assurance + +### Design QA Checklist +- Typography follows type scale +- Colors match defined palette +- Spacing adheres to spacing scale +- Components use defined patterns +- Icons follow icon system +- Interactive states are properly defined +- Animation follows motion guidelines +- Layout responds appropriately +- Accessibility requirements met +- Platform adaptations implemented + +### Implementation QA Checklist +- Visual fidelity matches design +- Responsive behavior works correctly +- Interactions function as expected +- Animations are smooth and purposeful +- Accessibility features implemented +- Edge cases handled gracefully +- Performance meets targets +- Cross-browser/device compatibility +- Error states display correctly +- Focus management functions properly + +## Best Practices + +1. Start with content and user needs +2. Design for flexibility across screen sizes +3. Consider all interactive states +4. Test with actual users when possible +5. Document patterns for consistency +6. Build components for reusability +7. Consider localization and internationalization +8. Optimize performance from the start +9. Design with accessibility in mind +10. Regularly review and refine the system \ No newline at end of file