diff --git a/.github/copilot/instructions/angular.instructions.md b/.github/copilot/instructions/angular.instructions.md new file mode 100644 index 0000000..12b7355 --- /dev/null +++ b/.github/copilot/instructions/angular.instructions.md @@ -0,0 +1,104 @@ +--- +description: 'Angular-specific coding standards and best practices' +applyTo: '**/*.ts, **/*.html, **/*.scss, **/*.css' +--- + +# Angular Development Instructions + +Instructions for generating high-quality Angular applications with TypeScript, using Angular Signals for state management, adhering to Angular best practices as outlined at https://angular.dev. + +## Project Context +- Latest Angular version (use standalone components by default) +- TypeScript for type safety +- Angular CLI for project setup and scaffolding +- Follow Angular Style Guide (https://angular.dev/style-guide) +- Use Angular Material or other modern UI libraries for consistent styling (if specified) + +## Development Standards + +### Architecture +- Use standalone components unless modules are explicitly required +- Organize code by standalone feature modules or domains for scalability +- Implement lazy loading for feature modules to optimize performance +- Use Angular's built-in dependency injection system effectively +- Structure components with a clear separation of concerns (smart vs. presentational components) + +### TypeScript +- Enable strict mode in `tsconfig.json` for type safety +- Define clear interfaces and types for components, services, and models +- Use type guards and union types for robust type checking +- Implement proper error handling with RxJS operators (e.g., `catchError`) +- Use typed forms (e.g., `FormGroup`, `FormControl`) for reactive forms + +### Component Design +- Follow Angular's component lifecycle hooks best practices +- When using Angular >= 19, Use `input()` `output()`, `viewChild()`, `viewChildren()`, `contentChild()` and `contentChildren()` functions instead of decorators; otherwise use decorators +- Leverage Angular's change detection strategy (default or `OnPush` for performance) +- Keep templates clean and logic in component classes or services +- Use Angular directives and pipes for reusable functionality + +### Styling +- Use Angular's component-level CSS encapsulation (default: ViewEncapsulation.Emulated) +- Prefer SCSS for styling with consistent theming +- Implement responsive design using CSS Grid, Flexbox, or Angular CDK Layout utilities +- Follow Angular Material's theming guidelines if used +- Maintain accessibility (a11y) with ARIA attributes and semantic HTML + +### State Management +- Use Angular Signals for reactive state management in components and services +- Leverage `signal()`, `computed()`, and `effect()` for reactive state updates +- Use writable signals for mutable state and computed signals for derived state +- Handle loading and error states with signals and proper UI feedback +- Use Angular's `AsyncPipe` to handle observables in templates when combining signals with RxJS + +### Data Fetching +- Use Angular's `HttpClient` for API calls with proper typing +- Implement RxJS operators for data transformation and error handling +- Use Angular's `inject()` function for dependency injection in standalone components +- Implement caching strategies (e.g., `shareReplay` for observables) +- Store API response data in signals for reactive updates +- Handle API errors with global interceptors for consistent error handling + +### Security +- Sanitize user inputs using Angular's built-in sanitization +- Implement route guards for authentication and authorization +- Use Angular's `HttpInterceptor` for CSRF protection and API authentication headers +- Validate form inputs with Angular's reactive forms and custom validators +- Follow Angular's security best practices (e.g., avoid direct DOM manipulation) + +### Performance +- Enable production builds with `ng build --prod` for optimization +- Use lazy loading for routes to reduce initial bundle size +- Optimize change detection with `OnPush` strategy and signals for fine-grained reactivity +- Use trackBy in `ngFor` loops to improve rendering performance +- Implement server-side rendering (SSR) or static site generation (SSG) with Angular Universal (if specified) + +### Testing +- Write unit tests for components, services, and pipes using Jasmine and Karma +- Use Angular's `TestBed` for component testing with mocked dependencies +- Test signal-based state updates using Angular's testing utilities +- Write end-to-end tests with Cypress or Playwright (if specified) +- Mock HTTP requests using `provideHttpClientTesting` +- Ensure high test coverage for critical functionality + +## Implementation Process +1. Plan project structure and feature modules +2. Define TypeScript interfaces and models +3. Scaffold components, services, and pipes using Angular CLI +4. Implement data services and API integrations with signal-based state +5. Build reusable components with clear inputs and outputs +6. Add reactive forms and validation +7. Apply styling with SCSS and responsive design +8. Implement lazy-loaded routes and guards +9. Add error handling and loading states using signals +10. Write unit and end-to-end tests +11. Optimize performance and bundle size + +## Additional Guidelines +- Follow the Angular Style Guide for file naming conventions (see https://angular.dev/style-guide), e.g., use `feature.ts` for components and `feature-service.ts` for services. For legacy codebases, maintain consistency with existing pattern. +- Use Angular CLI commands for generating boilerplate code +- Document components and services with clear JSDoc comments +- Ensure accessibility compliance (WCAG 2.1) where applicable +- Use Angular's built-in i18n for internationalization (if specified) +- Keep code DRY by creating reusable utilities and shared modules +- Use signals consistently for state management to ensure reactive updates diff --git a/.github/copilot/instructions/nestjs.instructions.md b/.github/copilot/instructions/nestjs.instructions.md new file mode 100644 index 0000000..f9ef64f --- /dev/null +++ b/.github/copilot/instructions/nestjs.instructions.md @@ -0,0 +1,406 @@ +--- +applyTo: '**/*.ts, **/*.js, **/*.json, **/*.spec.ts, **/*.e2e-spec.ts' +description: 'NestJS development standards and best practices for building scalable Node.js server-side applications' +--- + +# NestJS Development Best Practices + +## Your Mission + +As GitHub Copilot, you are an expert in NestJS development with deep knowledge of TypeScript, decorators, dependency injection, and modern Node.js patterns. Your goal is to guide developers in building scalable, maintainable, and well-architected server-side applications using NestJS framework principles and best practices. + +## Core NestJS Principles + +### **1. Dependency Injection (DI)** +- **Principle:** NestJS uses a powerful DI container that manages the instantiation and lifetime of providers. +- **Guidance for Copilot:** + - Use `@Injectable()` decorator for services, repositories, and other providers + - Inject dependencies through constructor parameters with proper typing + - Prefer interface-based dependency injection for better testability + - Use custom providers when you need specific instantiation logic + +### **2. Modular Architecture** +- **Principle:** Organize code into feature modules that encapsulate related functionality. +- **Guidance for Copilot:** + - Create feature modules with `@Module()` decorator + - Import only necessary modules and avoid circular dependencies + - Use `forRoot()` and `forFeature()` patterns for configurable modules + - Implement shared modules for common functionality + +### **3. Decorators and Metadata** +- **Principle:** Leverage decorators to define routes, middleware, guards, and other framework features. +- **Guidance for Copilot:** + - Use appropriate decorators: `@Controller()`, `@Get()`, `@Post()`, `@Injectable()` + - Apply validation decorators from `class-validator` library + - Use custom decorators for cross-cutting concerns + - Implement metadata reflection for advanced scenarios + +## Project Structure Best Practices + +### **Recommended Directory Structure** +``` +src/ +├── app.module.ts +├── main.ts +├── common/ +│ ├── decorators/ +│ ├── filters/ +│ ├── guards/ +│ ├── interceptors/ +│ ├── pipes/ +│ └── interfaces/ +├── config/ +├── modules/ +│ ├── auth/ +│ ├── users/ +│ └── products/ +└── shared/ + ├── services/ + └── constants/ +``` + +### **File Naming Conventions** +- **Controllers:** `*.controller.ts` (e.g., `users.controller.ts`) +- **Services:** `*.service.ts` (e.g., `users.service.ts`) +- **Modules:** `*.module.ts` (e.g., `users.module.ts`) +- **DTOs:** `*.dto.ts` (e.g., `create-user.dto.ts`) +- **Entities:** `*.entity.ts` (e.g., `user.entity.ts`) +- **Guards:** `*.guard.ts` (e.g., `auth.guard.ts`) +- **Interceptors:** `*.interceptor.ts` (e.g., `logging.interceptor.ts`) +- **Pipes:** `*.pipe.ts` (e.g., `validation.pipe.ts`) +- **Filters:** `*.filter.ts` (e.g., `http-exception.filter.ts`) + +## API Development Patterns + +### **1. Controllers** +- Keep controllers thin - delegate business logic to services +- Use proper HTTP methods and status codes +- Implement comprehensive input validation with DTOs +- Apply guards and interceptors at the appropriate level + +```typescript +@Controller('users') +@UseGuards(AuthGuard) +export class UsersController { + constructor(private readonly usersService: UsersService) {} + + @Get() + @UseInterceptors(TransformInterceptor) + async findAll(@Query() query: GetUsersDto): Promise { + return this.usersService.findAll(query); + } + + @Post() + @UsePipes(ValidationPipe) + async create(@Body() createUserDto: CreateUserDto): Promise { + return this.usersService.create(createUserDto); + } +} +``` + +### **2. Services** +- Implement business logic in services, not controllers +- Use constructor-based dependency injection +- Create focused, single-responsibility services +- Handle errors appropriately and let filters catch them + +```typescript +@Injectable() +export class UsersService { + constructor( + @InjectRepository(User) + private readonly userRepository: Repository, + private readonly emailService: EmailService, + ) {} + + async create(createUserDto: CreateUserDto): Promise { + const user = this.userRepository.create(createUserDto); + const savedUser = await this.userRepository.save(user); + await this.emailService.sendWelcomeEmail(savedUser.email); + return savedUser; + } +} +``` + +### **3. DTOs and Validation** +- Use class-validator decorators for input validation +- Create separate DTOs for different operations (create, update, query) +- Implement proper transformation with class-transformer + +```typescript +export class CreateUserDto { + @IsString() + @IsNotEmpty() + @Length(2, 50) + name: string; + + @IsEmail() + email: string; + + @IsString() + @MinLength(8) + @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, { + message: 'Password must contain uppercase, lowercase and number', + }) + password: string; +} +``` + +## Database Integration + +### **TypeORM Integration** +- Use TypeORM as the primary ORM for database operations +- Define entities with proper decorators and relationships +- Implement repository pattern for data access +- Use migrations for database schema changes + +```typescript +@Entity('users') +export class User { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ unique: true }) + email: string; + + @Column() + name: string; + + @Column({ select: false }) + password: string; + + @OneToMany(() => Post, post => post.author) + posts: Post[]; + + @CreateDateColumn() + createdAt: Date; + + @UpdateDateColumn() + updatedAt: Date; +} +``` + +### **Custom Repositories** +- Extend base repository functionality when needed +- Implement complex queries in repository methods +- Use query builders for dynamic queries + +## Authentication and Authorization + +### **JWT Authentication** +- Implement JWT-based authentication with Passport +- Use guards to protect routes +- Create custom decorators for user context + +```typescript +@Injectable() +export class JwtAuthGuard extends AuthGuard('jwt') { + canActivate(context: ExecutionContext): boolean | Promise { + return super.canActivate(context); + } + + handleRequest(err: any, user: any, info: any) { + if (err || !user) { + throw err || new UnauthorizedException(); + } + return user; + } +} +``` + +### **Role-Based Access Control** +- Implement RBAC using custom guards and decorators +- Use metadata to define required roles +- Create flexible permission systems + +```typescript +@SetMetadata('roles', ['admin']) +@UseGuards(JwtAuthGuard, RolesGuard) +@Delete(':id') +async remove(@Param('id') id: string): Promise { + return this.usersService.remove(id); +} +``` + +## Error Handling and Logging + +### **Exception Filters** +- Create global exception filters for consistent error responses +- Handle different types of exceptions appropriately +- Log errors with proper context + +```typescript +@Catch() +export class AllExceptionsFilter implements ExceptionFilter { + private readonly logger = new Logger(AllExceptionsFilter.name); + + catch(exception: unknown, host: ArgumentsHost): void { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + const status = exception instanceof HttpException + ? exception.getStatus() + : HttpStatus.INTERNAL_SERVER_ERROR; + + this.logger.error(`${request.method} ${request.url}`, exception); + + response.status(status).json({ + statusCode: status, + timestamp: new Date().toISOString(), + path: request.url, + message: exception instanceof HttpException + ? exception.message + : 'Internal server error', + }); + } +} +``` + +### **Logging** +- Use built-in Logger class for consistent logging +- Implement proper log levels (error, warn, log, debug, verbose) +- Add contextual information to logs + +## Testing Strategies + +### **Unit Testing** +- Test services independently using mocks +- Use Jest as the testing framework +- Create comprehensive test suites for business logic + +```typescript +describe('UsersService', () => { + let service: UsersService; + let repository: Repository; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + UsersService, + { + provide: getRepositoryToken(User), + useValue: { + create: jest.fn(), + save: jest.fn(), + find: jest.fn(), + }, + }, + ], + }).compile(); + + service = module.get(UsersService); + repository = module.get>(getRepositoryToken(User)); + }); + + it('should create a user', async () => { + const createUserDto = { name: 'John', email: 'john@example.com' }; + const user = { id: '1', ...createUserDto }; + + jest.spyOn(repository, 'create').mockReturnValue(user as User); + jest.spyOn(repository, 'save').mockResolvedValue(user as User); + + expect(await service.create(createUserDto)).toEqual(user); + }); +}); +``` + +### **Integration Testing** +- Use TestingModule for integration tests +- Test complete request/response cycles +- Mock external dependencies appropriately + +### **E2E Testing** +- Test complete application flows +- Use supertest for HTTP testing +- Test authentication and authorization flows + +## Performance and Security + +### **Performance Optimization** +- Implement caching strategies with Redis +- Use interceptors for response transformation +- Optimize database queries with proper indexing +- Implement pagination for large datasets + +### **Security Best Practices** +- Validate all inputs using class-validator +- Implement rate limiting to prevent abuse +- Use CORS appropriately for cross-origin requests +- Sanitize outputs to prevent XSS attacks +- Use environment variables for sensitive configuration + +```typescript +// Rate limiting example +@Controller('auth') +@UseGuards(ThrottlerGuard) +export class AuthController { + @Post('login') + @Throttle(5, 60) // 5 requests per minute + async login(@Body() loginDto: LoginDto) { + return this.authService.login(loginDto); + } +} +``` + +## Configuration Management + +### **Environment Configuration** +- Use @nestjs/config for configuration management +- Validate configuration at startup +- Use different configs for different environments + +```typescript +@Injectable() +export class ConfigService { + constructor( + @Inject(CONFIGURATION_TOKEN) + private readonly config: Configuration, + ) {} + + get databaseUrl(): string { + return this.config.database.url; + } + + get jwtSecret(): string { + return this.config.jwt.secret; + } +} +``` + +## Common Pitfalls to Avoid + +- **Circular Dependencies:** Avoid importing modules that create circular references +- **Heavy Controllers:** Don't put business logic in controllers +- **Missing Error Handling:** Always handle errors appropriately +- **Improper DI Usage:** Don't create instances manually when DI can handle it +- **Missing Validation:** Always validate input data +- **Synchronous Operations:** Use async/await for database and external API calls +- **Memory Leaks:** Properly dispose of subscriptions and event listeners + +## Development Workflow + +### **Development Setup** +1. Use NestJS CLI for scaffolding: `nest generate module users` +2. Follow consistent file organization +3. Use TypeScript strict mode +4. Implement comprehensive linting with ESLint +5. Use Prettier for code formatting + +### **Code Review Checklist** +- [ ] Proper use of decorators and dependency injection +- [ ] Input validation with DTOs and class-validator +- [ ] Appropriate error handling and exception filters +- [ ] Consistent naming conventions +- [ ] Proper module organization and imports +- [ ] Security considerations (authentication, authorization, input sanitization) +- [ ] Performance considerations (caching, database optimization) +- [ ] Comprehensive testing coverage + +## Conclusion + +NestJS provides a powerful, opinionated framework for building scalable Node.js applications. By following these best practices, you can create maintainable, testable, and efficient server-side applications that leverage the full power of TypeScript and modern development patterns. + +--- + + diff --git a/.github/copilot/instructions/nextjs-tailwind.instructions.md b/.github/copilot/instructions/nextjs-tailwind.instructions.md new file mode 100644 index 0000000..ffc4378 --- /dev/null +++ b/.github/copilot/instructions/nextjs-tailwind.instructions.md @@ -0,0 +1,72 @@ +--- +description: 'Next.js + Tailwind development standards and instructions' +applyTo: '**/*.tsx, **/*.ts, **/*.jsx, **/*.js, **/*.css' +--- + +# Next.js + Tailwind Development Instructions + +Instructions for high-quality Next.js applications with Tailwind CSS styling and TypeScript. + +## Project Context + +- Latest Next.js (App Router) +- TypeScript for type safety +- Tailwind CSS for styling + +## Development Standards + +### Architecture +- App Router with server and client components +- Group routes by feature/domain +- Implement proper error boundaries +- Use React Server Components by default +- Leverage static optimization where possible + +### TypeScript +- Strict mode enabled +- Clear type definitions +- Proper error handling with type guards +- Zod for runtime type validation + +### Styling +- Tailwind CSS with consistent color palette +- Responsive design patterns +- Dark mode support +- Follow container queries best practices +- Maintain semantic HTML structure + +### State Management +- React Server Components for server state +- React hooks for client state +- Proper loading and error states +- Optimistic updates where appropriate + +### Data Fetching +- Server Components for direct database queries +- React Suspense for loading states +- Proper error handling and retry logic +- Cache invalidation strategies + +### Security +- Input validation and sanitization +- Proper authentication checks +- CSRF protection +- Rate limiting implementation +- Secure API route handling + +### Performance +- Image optimization with next/image +- Font optimization with next/font +- Route prefetching +- Proper code splitting +- Bundle size optimization + +## Implementation Process +1. Plan component hierarchy +2. Define types and interfaces +3. Implement server-side logic +4. Build client components +5. Add proper error handling +6. Implement responsive styling +7. Add loading states +8. Write tests diff --git a/.github/copilot/instructions/nextjs.instructions.md b/.github/copilot/instructions/nextjs.instructions.md new file mode 100644 index 0000000..d28d5e5 --- /dev/null +++ b/.github/copilot/instructions/nextjs.instructions.md @@ -0,0 +1,143 @@ +--- +applyTo: '**' +--- + +# Next.js Best Practices for LLMs (2025) + +_Last updated: July 2025_ + +This document summarizes the latest, authoritative best practices for building, structuring, and maintaining Next.js applications. It is intended for use by LLMs and developers to ensure code quality, maintainability, and scalability. + +--- + +## 1. Project Structure & Organization + +- **Use the `app/` directory** (App Router) for all new projects. Prefer it over the legacy `pages/` directory. +- **Top-level folders:** + - `app/` — Routing, layouts, pages, and route handlers + - `public/` — Static assets (images, fonts, etc.) + - `lib/` — Shared utilities, API clients, and logic + - `components/` — Reusable UI components + - `contexts/` — React context providers + - `styles/` — Global and modular stylesheets + - `hooks/` — Custom React hooks + - `types/` — TypeScript type definitions +- **Colocation:** Place files (components, styles, tests) near where they are used, but avoid deeply nested structures. +- **Route Groups:** Use parentheses (e.g., `(admin)`) to group routes without affecting the URL path. +- **Private Folders:** Prefix with `_` (e.g., `_internal`) to opt out of routing and signal implementation details. + +- **Feature Folders:** For large apps, group by feature (e.g., `app/dashboard/`, `app/auth/`). +- **Use `src/`** (optional): Place all source code in `src/` to separate from config files. + +## 2.1. Server and Client Component Integration (App Router) + +**Never use `next/dynamic` with `{ ssr: false }` inside a Server Component.** This is not supported and will cause a build/runtime error. + +**Correct Approach:** +- If you need to use a Client Component (e.g., a component that uses hooks, browser APIs, or client-only libraries) inside a Server Component, you must: + 1. Move all client-only logic/UI into a dedicated Client Component (with `'use client'` at the top). + 2. Import and use that Client Component directly in the Server Component (no need for `next/dynamic`). + 3. If you need to compose multiple client-only elements (e.g., a navbar with a profile dropdown), create a single Client Component that contains all of them. + +**Example:** + +```tsx +// Server Component +import DashboardNavbar from '@/components/DashboardNavbar'; + +export default async function DashboardPage() { + // ...server logic... + return ( + <> + {/* This is a Client Component */} + {/* ...rest of server-rendered page... */} + + ); +} +``` + +**Why:** +- Server Components cannot use client-only features or dynamic imports with SSR disabled. +- Client Components can be rendered inside Server Components, but not the other way around. + +**Summary:** +Always move client-only UI into a Client Component and import it directly in your Server Component. Never use `next/dynamic` with `{ ssr: false }` in a Server Component. + +--- + +## 2. Component Best Practices + +- **Component Types:** + - **Server Components** (default): For data fetching, heavy logic, and non-interactive UI. + - **Client Components:** Add `'use client'` at the top. Use for interactivity, state, or browser APIs. +- **When to Create a Component:** + - If a UI pattern is reused more than once. + - If a section of a page is complex or self-contained. + - If it improves readability or testability. +- **Naming Conventions:** + - Use `PascalCase` for component files and exports (e.g., `UserCard.tsx`). + - Use `camelCase` for hooks (e.g., `useUser.ts`). + - Use `snake_case` or `kebab-case` for static assets (e.g., `logo_dark.svg`). + - Name context providers as `XyzProvider` (e.g., `ThemeProvider`). +- **File Naming:** + - Match the component name to the file name. + - For single-export files, default export the component. + - For multiple related components, use an `index.ts` barrel file. +- **Component Location:** + - Place shared components in `components/`. + - Place route-specific components inside the relevant route folder. +- **Props:** + - Use TypeScript interfaces for props. + - Prefer explicit prop types and default values. +- **Testing:** + - Co-locate tests with components (e.g., `UserCard.test.tsx`). + +## 3. Naming Conventions (General) + +- **Folders:** `kebab-case` (e.g., `user-profile/`) +- **Files:** `PascalCase` for components, `camelCase` for utilities/hooks, `kebab-case` for static assets +- **Variables/Functions:** `camelCase` +- **Types/Interfaces:** `PascalCase` +- **Constants:** `UPPER_SNAKE_CASE` + +## 4. API Routes (Route Handlers) + +- **Prefer API Routes over Edge Functions** unless you need ultra-low latency or geographic distribution. +- **Location:** Place API routes in `app/api/` (e.g., `app/api/users/route.ts`). +- **HTTP Methods:** Export async functions named after HTTP verbs (`GET`, `POST`, etc.). +- **Request/Response:** Use the Web `Request` and `Response` APIs. Use `NextRequest`/`NextResponse` for advanced features. +- **Dynamic Segments:** Use `[param]` for dynamic API routes (e.g., `app/api/users/[id]/route.ts`). +- **Validation:** Always validate and sanitize input. Use libraries like `zod` or `yup`. +- **Error Handling:** Return appropriate HTTP status codes and error messages. +- **Authentication:** Protect sensitive routes using middleware or server-side session checks. + +## 5. General Best Practices + +- **TypeScript:** Use TypeScript for all code. Enable `strict` mode in `tsconfig.json`. +- **ESLint & Prettier:** Enforce code style and linting. Use the official Next.js ESLint config. +- **Environment Variables:** Store secrets in `.env.local`. Never commit secrets to version control. +- **Testing:** Use Jest, React Testing Library, or Playwright. Write tests for all critical logic and components. +- **Accessibility:** Use semantic HTML and ARIA attributes. Test with screen readers. +- **Performance:** + - Use built-in Image and Font optimization. + - Use Suspense and loading states for async data. + - Avoid large client bundles; keep most logic in Server Components. +- **Security:** + - Sanitize all user input. + - Use HTTPS in production. + - Set secure HTTP headers. +- **Documentation:** + - Write clear README and code comments. + - Document public APIs and components. + +# Avoid Unnecessary Example Files + +Do not create example/demo files (like ModalExample.tsx) in the main codebase unless the user specifically requests a live example, Storybook story, or explicit documentation component. Keep the repository clean and production-focused by default. + +# Always use the latest documentation and guides +- For every nextjs related request, begin by searching for the most current nextjs documentation, guides, and examples. +- Use the following tools to fetch and search documentation if they are available: + - `resolve_library_id` to resolve the package/library name in the docs. + - `get_library_docs` for up to date documentation. + + diff --git a/.github/copilot/instructions/nodejs-javascript-vitest.instructions.md b/.github/copilot/instructions/nodejs-javascript-vitest.instructions.md new file mode 100644 index 0000000..6a38953 --- /dev/null +++ b/.github/copilot/instructions/nodejs-javascript-vitest.instructions.md @@ -0,0 +1,30 @@ +--- +description: "Guidelines for writing Node.js and JavaScript code with Vitest testing" +applyTo: '**/*.js, **/*.mjs, **/*.cjs' +--- + +# Code Generation Guidelines + +## Coding standards +- Use JavaScript with ES2022 features and Node.js (20+) ESM modules +- Use Node.js built-in modules and avoid external dependencies where possible +- Ask the user if you require any additional dependencies before adding them +- Always use async/await for asynchronous code, and use 'node:util' promisify function to avoid callbacks +- Keep the code simple and maintainable +- Use descriptive variable and function names +- Do not add comments unless absolutely necessary, the code should be self-explanatory +- Never use `null`, always use `undefined` for optional values +- Prefer functions over classes + +## Testing +- Use Vitest for testing +- Write tests for all new features and bug fixes +- Ensure tests cover edge cases and error handling +- NEVER change the original code to make it easier to test, instead, write tests that cover the original code as it is + +## Documentation +- When adding new features or making significant changes, update the README.md file where necessary + +## User interactions +- Ask questions if you are unsure about the implementation details, design choices, or need clarification on the requirements +- Always answer in the same language as the question, but use english for the generated content like code, comments or docs diff --git a/.github/copilot/instructions/reactjs.instructions.md b/.github/copilot/instructions/reactjs.instructions.md new file mode 100644 index 0000000..79bd275 --- /dev/null +++ b/.github/copilot/instructions/reactjs.instructions.md @@ -0,0 +1,162 @@ +--- +description: 'ReactJS development standards and best practices' +applyTo: '**/*.jsx, **/*.tsx, **/*.js, **/*.ts, **/*.css, **/*.scss' +--- + +# ReactJS Development Instructions + +Instructions for building high-quality ReactJS applications with modern patterns, hooks, and best practices following the official React documentation at https://react.dev. + +## Project Context +- Latest React version (React 19+) +- TypeScript for type safety (when applicable) +- Functional components with hooks as default +- Follow React's official style guide and best practices +- Use modern build tools (Vite, Create React App, or custom Webpack setup) +- Implement proper component composition and reusability patterns + +## Development Standards + +### Architecture +- Use functional components with hooks as the primary pattern +- Implement component composition over inheritance +- Organize components by feature or domain for scalability +- Separate presentational and container components clearly +- Use custom hooks for reusable stateful logic +- Implement proper component hierarchies with clear data flow + +### TypeScript Integration +- Use TypeScript interfaces for props, state, and component definitions +- Define proper types for event handlers and refs +- Implement generic components where appropriate +- Use strict mode in `tsconfig.json` for type safety +- Leverage React's built-in types (`React.FC`, `React.ComponentProps`, etc.) +- Create union types for component variants and states + +### Component Design +- Follow the single responsibility principle for components +- Use descriptive and consistent naming conventions +- Implement proper prop validation with TypeScript or PropTypes +- Design components to be testable and reusable +- Keep components small and focused on a single concern +- Use composition patterns (render props, children as functions) + +### State Management +- Use `useState` for local component state +- Implement `useReducer` for complex state logic +- Leverage `useContext` for sharing state across component trees +- Consider external state management (Redux Toolkit, Zustand) for complex applications +- Implement proper state normalization and data structures +- Use React Query or SWR for server state management + +### Hooks and Effects +- Use `useEffect` with proper dependency arrays to avoid infinite loops +- Implement cleanup functions in effects to prevent memory leaks +- Use `useMemo` and `useCallback` for performance optimization when needed +- Create custom hooks for reusable stateful logic +- Follow the rules of hooks (only call at the top level) +- Use `useRef` for accessing DOM elements and storing mutable values + +### Styling +- Use CSS Modules, Styled Components, or modern CSS-in-JS solutions +- Implement responsive design with mobile-first approach +- Follow BEM methodology or similar naming conventions for CSS classes +- Use CSS custom properties (variables) for theming +- Implement consistent spacing, typography, and color systems +- Ensure accessibility with proper ARIA attributes and semantic HTML + +### Performance Optimization +- Use `React.memo` for component memoization when appropriate +- Implement code splitting with `React.lazy` and `Suspense` +- Optimize bundle size with tree shaking and dynamic imports +- Use `useMemo` and `useCallback` judiciously to prevent unnecessary re-renders +- Implement virtual scrolling for large lists +- Profile components with React DevTools to identify performance bottlenecks + +### Data Fetching +- Use modern data fetching libraries (React Query, SWR, Apollo Client) +- Implement proper loading, error, and success states +- Handle race conditions and request cancellation +- Use optimistic updates for better user experience +- Implement proper caching strategies +- Handle offline scenarios and network errors gracefully + +### Error Handling +- Implement Error Boundaries for component-level error handling +- Use proper error states in data fetching +- Implement fallback UI for error scenarios +- Log errors appropriately for debugging +- Handle async errors in effects and event handlers +- Provide meaningful error messages to users + +### Forms and Validation +- Use controlled components for form inputs +- Implement proper form validation with libraries like Formik, React Hook Form +- Handle form submission and error states appropriately +- Implement accessibility features for forms (labels, ARIA attributes) +- Use debounced validation for better user experience +- Handle file uploads and complex form scenarios + +### Routing +- Use React Router for client-side routing +- Implement nested routes and route protection +- Handle route parameters and query strings properly +- Implement lazy loading for route-based code splitting +- Use proper navigation patterns and back button handling +- Implement breadcrumbs and navigation state management + +### Testing +- Write unit tests for components using React Testing Library +- Test component behavior, not implementation details +- Use Jest for test runner and assertion library +- Implement integration tests for complex component interactions +- Mock external dependencies and API calls appropriately +- Test accessibility features and keyboard navigation + +### Security +- Sanitize user inputs to prevent XSS attacks +- Validate and escape data before rendering +- Use HTTPS for all external API calls +- Implement proper authentication and authorization patterns +- Avoid storing sensitive data in localStorage or sessionStorage +- Use Content Security Policy (CSP) headers + +### Accessibility +- Use semantic HTML elements appropriately +- Implement proper ARIA attributes and roles +- Ensure keyboard navigation works for all interactive elements +- Provide alt text for images and descriptive text for icons +- Implement proper color contrast ratios +- Test with screen readers and accessibility tools + +## Implementation Process +1. Plan component architecture and data flow +2. Set up project structure with proper folder organization +3. Define TypeScript interfaces and types +4. Implement core components with proper styling +5. Add state management and data fetching logic +6. Implement routing and navigation +7. Add form handling and validation +8. Implement error handling and loading states +9. Add testing coverage for components and functionality +10. Optimize performance and bundle size +11. Ensure accessibility compliance +12. Add documentation and code comments + +## Additional Guidelines +- Follow React's naming conventions (PascalCase for components, camelCase for functions) +- Use meaningful commit messages and maintain clean git history +- Implement proper code splitting and lazy loading strategies +- Document complex components and custom hooks with JSDoc +- Use ESLint and Prettier for consistent code formatting +- Keep dependencies up to date and audit for security vulnerabilities +- Implement proper environment configuration for different deployment stages +- Use React Developer Tools for debugging and performance analysis + +## Common Patterns +- Higher-Order Components (HOCs) for cross-cutting concerns +- Render props pattern for component composition +- Compound components for related functionality +- Provider pattern for context-based state sharing +- Container/Presentational component separation +- Custom hooks for reusable logic extraction diff --git a/.github/copilot/instructions/typescript-5-es2022.instructions.md b/.github/copilot/instructions/typescript-5-es2022.instructions.md new file mode 100644 index 0000000..1b53035 --- /dev/null +++ b/.github/copilot/instructions/typescript-5-es2022.instructions.md @@ -0,0 +1,114 @@ +--- +description: 'Guidelines for TypeScript Development targeting TypeScript 5.x and ES2022 output' +applyTo: '**/*.ts' +--- + +# TypeScript Development + +> These instructions assume projects are built with TypeScript 5.x (or newer) compiling to an ES2022 JavaScript baseline. Adjust guidance if your runtime requires older language targets or down-level transpilation. + +## Core Intent + +- Respect the existing architecture and coding standards. +- Prefer readable, explicit solutions over clever shortcuts. +- Extend current abstractions before inventing new ones. +- Prioritize maintainability and clarity, short methods and classes, clean code. + +## General Guardrails + +- Target TypeScript 5.x / ES2022 and prefer native features over polyfills. +- Use pure ES modules; never emit `require`, `module.exports`, or CommonJS helpers. +- Rely on the project's build, lint, and test scripts unless asked otherwise. +- Note design trade-offs when intent is not obvious. + +## Project Organization + +- Follow the repository's folder and responsibility layout for new code. +- Use kebab-case filenames (e.g., `user-session.ts`, `data-service.ts`) unless told otherwise. +- Keep tests, types, and helpers near their implementation when it aids discovery. +- Reuse or extend shared utilities before adding new ones. + +## Naming & Style + +- Use PascalCase for classes, interfaces, enums, and type aliases; camelCase for everything else. +- Skip interface prefixes like `I`; rely on descriptive names. +- Name things for their behavior or domain meaning, not implementation. + +## Formatting & Style + +- Run the repository's lint/format scripts (e.g., `npm run lint`) before submitting. +- Match the project's indentation, quote style, and trailing comma rules. +- Keep functions focused; extract helpers when logic branches grow. +- Favor immutable data and pure functions when practical. + +## Type System Expectations + +- Avoid `any` (implicit or explicit); prefer `unknown` plus narrowing. +- Use discriminated unions for realtime events and state machines. +- Centralize shared contracts instead of duplicating shapes. +- Express intent with TypeScript utility types (e.g., `Readonly`, `Partial`, `Record`). + +## Async, Events & Error Handling + +- Use `async/await`; wrap awaits in try/catch with structured errors. +- Guard edge cases early to avoid deep nesting. +- Send errors through the project's logging/telemetry utilities. +- Surface user-facing errors via the repository's notification pattern. +- Debounce configuration-driven updates and dispose resources deterministically. + +## Architecture & Patterns + +- Follow the repository's dependency injection or composition pattern; keep modules single-purpose. +- Observe existing initialization and disposal sequences when wiring into lifecycles. +- Keep transport, domain, and presentation layers decoupled with clear interfaces. +- Supply lifecycle hooks (e.g., `initialize`, `dispose`) and targeted tests when adding services. + +## External Integrations + +- Instantiate clients outside hot paths and inject them for testability. +- Never hardcode secrets; load them from secure sources. +- Apply retries, backoff, and cancellation to network or IO calls. +- Normalize external responses and map errors to domain shapes. + +## Security Practices + +- Validate and sanitize external input with schema validators or type guards. +- Avoid dynamic code execution and untrusted template rendering. +- Encode untrusted content before rendering HTML; use framework escaping or trusted types. +- Use parameterized queries or prepared statements to block injection. +- Keep secrets in secure storage, rotate them regularly, and request least-privilege scopes. +- Favor immutable flows and defensive copies for sensitive data. +- Use vetted crypto libraries only. +- Patch dependencies promptly and monitor advisories. + +## Configuration & Secrets + +- Reach configuration through shared helpers and validate with schemas or dedicated validators. +- Handle secrets via the project's secure storage; guard `undefined` and error states. +- Document new configuration keys and update related tests. + +## UI & UX Components + +- Sanitize user or external content before rendering. +- Keep UI layers thin; push heavy logic to services or state managers. +- Use messaging or events to decouple UI from business logic. + +## Testing Expectations + +- Add or update unit tests with the project's framework and naming style. +- Expand integration or end-to-end suites when behavior crosses modules or platform APIs. +- Run targeted test scripts for quick feedback before submitting. +- Avoid brittle timing assertions; prefer fake timers or injected clocks. + +## Performance & Reliability + +- Lazy-load heavy dependencies and dispose them when done. +- Defer expensive work until users need it. +- Batch or debounce high-frequency events to reduce thrash. +- Track resource lifetimes to prevent leaks. + +## Documentation & Comments + +- Add JSDoc to public APIs; include `@remarks` or `@example` when helpful. +- Write comments that capture intent, and remove stale notes during refactors. +- Update architecture or design docs when introducing significant patterns. diff --git a/.github/copilot/instructions/typescript-mcp-server.instructions.md b/.github/copilot/instructions/typescript-mcp-server.instructions.md new file mode 100644 index 0000000..97185e6 --- /dev/null +++ b/.github/copilot/instructions/typescript-mcp-server.instructions.md @@ -0,0 +1,228 @@ +--- +description: 'Instructions for building Model Context Protocol (MCP) servers using the TypeScript SDK' +applyTo: '**/*.ts, **/*.js, **/package.json' +--- + +# TypeScript MCP Server Development + +## Instructions + +- Use the **@modelcontextprotocol/sdk** npm package: `npm install @modelcontextprotocol/sdk` +- Import from specific paths: `@modelcontextprotocol/sdk/server/mcp.js`, `@modelcontextprotocol/sdk/server/stdio.js`, etc. +- Use `McpServer` class for high-level server implementation with automatic protocol handling +- Use `Server` class for low-level control with manual request handlers +- Use **zod** for input/output schema validation: `npm install zod@3` +- Always provide `title` field for tools, resources, and prompts for better UI display +- Use `registerTool()`, `registerResource()`, and `registerPrompt()` methods (recommended over older APIs) +- Define schemas using zod: `{ inputSchema: { param: z.string() }, outputSchema: { result: z.string() } }` +- Return both `content` (for display) and `structuredContent` (for structured data) from tools +- For HTTP servers, use `StreamableHTTPServerTransport` with Express or similar frameworks +- For local integrations, use `StdioServerTransport` for stdio-based communication +- Create new transport instances per request to prevent request ID collisions (stateless mode) +- Use session management with `sessionIdGenerator` for stateful servers +- Enable DNS rebinding protection for local servers: `enableDnsRebindingProtection: true` +- Configure CORS headers and expose `Mcp-Session-Id` for browser-based clients +- Use `ResourceTemplate` for dynamic resources with URI parameters: `new ResourceTemplate('resource://{param}', { list: undefined })` +- Support completions for better UX using `completable()` wrapper from `@modelcontextprotocol/sdk/server/completable.js` +- Implement sampling with `server.server.createMessage()` to request LLM completions from clients +- Use `server.server.elicitInput()` to request additional user input during tool execution +- Enable notification debouncing for bulk updates: `debouncedNotificationMethods: ['notifications/tools/list_changed']` +- Dynamic updates: call `.enable()`, `.disable()`, `.update()`, or `.remove()` on registered items to emit `listChanged` notifications +- Use `getDisplayName()` from `@modelcontextprotocol/sdk/shared/metadataUtils.js` for UI display names +- Test servers with MCP Inspector: `npx @modelcontextprotocol/inspector` + +## Best Practices + +- Keep tool implementations focused on single responsibilities +- Provide clear, descriptive titles and descriptions for LLM understanding +- Use proper TypeScript types for all parameters and return values +- Implement comprehensive error handling with try-catch blocks +- Return `isError: true` in tool results for error conditions +- Use async/await for all asynchronous operations +- Close database connections and clean up resources properly +- Validate input parameters before processing +- Use structured logging for debugging without polluting stdout/stderr +- Consider security implications when exposing file system or network access +- Implement proper resource cleanup on transport close events +- Use environment variables for configuration (ports, API keys, etc.) +- Document tool capabilities and limitations clearly +- Test with multiple clients to ensure compatibility + +## Common Patterns + +### Basic Server Setup (HTTP) +```typescript +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import express from 'express'; + +const server = new McpServer({ + name: 'my-server', + version: '1.0.0' +}); + +const app = express(); +app.use(express.json()); + +app.post('/mcp', async (req, res) => { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true + }); + + res.on('close', () => transport.close()); + + await server.connect(transport); + await transport.handleRequest(req, res, req.body); +}); + +app.listen(3000); +``` + +### Basic Server Setup (stdio) +```typescript +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; + +const server = new McpServer({ + name: 'my-server', + version: '1.0.0' +}); + +// ... register tools, resources, prompts ... + +const transport = new StdioServerTransport(); +await server.connect(transport); +``` + +### Simple Tool +```typescript +import { z } from 'zod'; + +server.registerTool( + 'calculate', + { + title: 'Calculator', + description: 'Perform basic calculations', + inputSchema: { a: z.number(), b: z.number(), op: z.enum(['+', '-', '*', '/']) }, + outputSchema: { result: z.number() } + }, + async ({ a, b, op }) => { + const result = op === '+' ? a + b : op === '-' ? a - b : + op === '*' ? a * b : a / b; + const output = { result }; + return { + content: [{ type: 'text', text: JSON.stringify(output) }], + structuredContent: output + }; + } +); +``` + +### Dynamic Resource +```typescript +import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; + +server.registerResource( + 'user', + new ResourceTemplate('users://{userId}', { list: undefined }), + { + title: 'User Profile', + description: 'Fetch user profile data' + }, + async (uri, { userId }) => ({ + contents: [{ + uri: uri.href, + text: `User ${userId} data here` + }] + }) +); +``` + +### Tool with Sampling +```typescript +server.registerTool( + 'summarize', + { + title: 'Text Summarizer', + description: 'Summarize text using LLM', + inputSchema: { text: z.string() }, + outputSchema: { summary: z.string() } + }, + async ({ text }) => { + const response = await server.server.createMessage({ + messages: [{ + role: 'user', + content: { type: 'text', text: `Summarize: ${text}` } + }], + maxTokens: 500 + }); + + const summary = response.content.type === 'text' ? + response.content.text : 'Unable to summarize'; + const output = { summary }; + return { + content: [{ type: 'text', text: JSON.stringify(output) }], + structuredContent: output + }; + } +); +``` + +### Prompt with Completion +```typescript +import { completable } from '@modelcontextprotocol/sdk/server/completable.js'; + +server.registerPrompt( + 'review', + { + title: 'Code Review', + description: 'Review code with specific focus', + argsSchema: { + language: completable(z.string(), value => + ['typescript', 'python', 'javascript', 'java'] + .filter(l => l.startsWith(value)) + ), + code: z.string() + } + }, + ({ language, code }) => ({ + messages: [{ + role: 'user', + content: { + type: 'text', + text: `Review this ${language} code:\n\n${code}` + } + }] + }) +); +``` + +### Error Handling +```typescript +server.registerTool( + 'risky-operation', + { + title: 'Risky Operation', + description: 'An operation that might fail', + inputSchema: { input: z.string() }, + outputSchema: { result: z.string() } + }, + async ({ input }) => { + try { + const result = await performRiskyOperation(input); + const output = { result }; + return { + content: [{ type: 'text', text: JSON.stringify(output) }], + structuredContent: output + }; + } catch (err: unknown) { + const error = err as Error; + return { + content: [{ type: 'text', text: `Error: ${error.message}` }], + isError: true + }; + } + } +); +``` diff --git a/.github/copilot/instructions/vuejs3.instructions.md b/.github/copilot/instructions/vuejs3.instructions.md new file mode 100644 index 0000000..7c3f74f --- /dev/null +++ b/.github/copilot/instructions/vuejs3.instructions.md @@ -0,0 +1,153 @@ +--- +description: 'VueJS 3 development standards and best practices with Composition API and TypeScript' +applyTo: '**/*.vue, **/*.ts, **/*.js, **/*.scss' +--- + +# VueJS 3 Development Instructions + +Instructions for building high-quality VueJS 3 applications with the Composition API, TypeScript, and modern best practices. + +## Project Context +- Vue 3.x with Composition API as default +- TypeScript for type safety +- Single File Components (`.vue`) with `