diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4b2140..c2d8e03 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,12 +6,6 @@ on: pull_request: branches: [ main ] -permissions: - contents: write - packages: write - issues: write - pull-requests: write - jobs: build: runs-on: ubuntu-latest diff --git a/rules/README.md b/rules/README.md new file mode 100644 index 0000000..1a3a6e6 --- /dev/null +++ b/rules/README.md @@ -0,0 +1,139 @@ +# Cursor Rules Directory + +This directory contains `.cursorrules` files that define development guidelines and best practices for various technology stacks and frameworks. + +## File Structure + +Each `.cursorrules` file follows this standardized format: + +``` +// Title and Author +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +[List of features and capabilities] + +// Project Structure +[Detailed directory structure with comments] + +// Development Guidelines +[Numbered sections of specific guidelines] + +// Dependencies +Core: +[List of required dependencies with versions] + +Optional: +[List of optional dependencies with versions] + +// Code Examples: +[Numbered examples with practical implementations] + +// Best Practices: +[Numbered list of best practices] + +// Security Considerations: +[Numbered list of security requirements] +``` + +## Current Rulesets + +1. Python/FastAPI: + - `cursorrules-file-cursor-ai-python-fastapi-api/` + - FastAPI application development guidelines + +2. Deno Integration: + - `deno-integration-techniques-cursorrules-prompt-fle/` + - Deno integration patterns and practices + +3. Elixir Development: + - `elixir-engineer-guidelines-cursorrules-prompt-file/` + - Elixir engineering best practices + - `elixir-phoenix-docker-setup-cursorrules-prompt-fil/` + - Phoenix framework with Docker setup + +4. Flutter Development: + - `flutter-development-guidelines-cursorrules-prompt-file/` + - Flutter application development guidelines + +5. GitHub Integration: + - `github-code-quality-cursorrules-prompt-file/` + - GitHub code quality standards + - `github-cursorrules-prompt-file-instructions/` + - GitHub workflow instructions + +6. Go Development: + - `go-backend-scalability-cursorrules-prompt-file/` + - Go backend scalability patterns + - `go-servemux-rest-api-cursorrules-prompt-file/` + - ServeMux REST API implementation + +7. Graphical Apps: + - `graphical-apps-development-cursorrules-prompt-file/` + - GUI application development guidelines + +8. HTML/CSS/JavaScript: + - `html-tailwind-css-javascript-cursorrules-prompt-fi/` + - Modern web development with Tailwind CSS + +9. HTMX Integration: + - `htmx-basic-cursorrules-prompt-file/` + - Basic HTMX implementation patterns + - `htmx-django-cursorrules-prompt-file/` + - HTMX with Django integration + - `htmx-flask-cursorrules-prompt-file/` + - HTMX with Flask integration + - `htmx-go-basic-cursorrules-prompt-file/` + - HTMX with Go (basic setup) + - `htmx-go-fiber-cursorrules-prompt-file/` + - HTMX with Go Fiber framework + +## Usage + +1. Each `.cursorrules` file serves as a comprehensive guide for developing applications with specific technology stacks. + +2. The files contain: + - Project structure recommendations + - Development guidelines + - Required dependencies + - Code examples + - Best practices + - Security considerations + +3. When starting a new project: + - Reference the appropriate `.cursorrules` file + - Follow the project structure + - Implement the recommended patterns + - Adhere to the security guidelines + +4. For maintenance: + - Keep dependencies updated to specified versions + - Follow the documented best practices + - Implement all security considerations + - Use the code examples as reference patterns + +## Contributing + +When adding new rulesets: + +1. Create a new directory following the naming pattern: + `{technology}-{specific-focus}-cursorrules-prompt-file/` + +2. Include a `.cursorrules` file following the standardized format + +3. Ensure all sections are complete: + - Project structure + - Development guidelines + - Dependencies + - Code examples + - Best practices + - Security considerations + +4. Update this README.md with the new ruleset information + +## Maintenance + +- Review and update dependency versions quarterly +- Validate code examples against latest framework versions +- Update security considerations based on new best practices +- Add new patterns and examples as technologies evolve \ No newline at end of file diff --git a/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules b/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules index 69f1331..498acb8 100644 --- a/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules +++ b/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules @@ -1 +1,238 @@ -# .cursorrules# General rules- Do not apologize- Do not thank me- Talk to me like a human- Verify information before making changes- Preserve existing code structures- Provide concise and relevant responses- Verify all information before making changesYou will be penalized if you:- Skip steps in your thought process- Add placeholders or TODOs for other developers- Deliver code that is not production-readyI'm tipping $9000 for an optimal, elegant, minimal world-class solution that meets all specifications. Your code changesshould be specific and complete. Think through the problem step-by-step.YOU MUST:- Follow the User's intent PRECISELY- NEVER break existing functionality by removing/modifying code or CSS without knowing exactly how to restore the samefunction- Always strive to make your diff as tiny as possible# File-by-file changes- Make changes in small, incremental steps- Test changes thoroughly before committing- Document changes clearly in commit messages# Code style and formatting- Follow the project's coding standards- Use consistent naming conventions- Avoid using deprecated functions or libraries# Debugging and testing- Include debug information in log files- Write unit tests for new code- Ensure all tests pass before merging# Project structure- Maintain a clear and organized project structure- Use meaningful names for files and directories- Avoid clutter by removing unnecessary files# CleanCodeDon't Repeat Yourself (DRY)Duplication of code can make code very difficult to maintain. Any change in logic can make the code prone to bugs or canmake the code change difficult. This can be fixed by doing code reuse (DRY Principle).The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representationwithin a system".The way to achieve DRY is by creating functions and classes to make sure that any logic should be written in only oneplace.Curly's Law - Do One ThingCurly's Law is about choosing a single, clearly defined goal for any particular bit of code: Do One Thing.Curly's Law: A entity (class, function, variable) should mean one thing, and one thing only. It should not mean onething in one circumstance and carry a different value from a different domain some other time. It should not mean twothings at once. It should mean One Thing and should mean it all of the time.Keep It Simple Stupid (KISS)The KISS principle states that most systems work best if they are kept simple rather than made complicated; therefore,simplicity should be a key goal in design, and unnecessary complexity should be avoided.Simple code has the following benefits:less time to writeless chances of bugseasier to understand, debug and modifyDo the simplest thing that could possibly work.Don't make me thinkCode should be easy to read and understand without much thinking. If it isn't then there is a prospect ofsimplification.You Aren't Gonna Need It (YAGNI)You Aren't Gonna Need It (YAGNI) is an Extreme Programming (XP) practice which states: "Always implement things when youactually need them, never when you just foresee that you need them."Even if you're totally, totally, totally sure that you'll need a feature, later on, don't implement it now. Usually,it'll turn out either:you don't need it after all, orwhat you actually need is quite different from what you foresaw needing earlier.This doesn't mean you should avoid building flexibility into your code. It means you shouldn't overengineer somethingbased on what you think you might need later on.There are two main reasons to practice YAGNI:You save time because you avoid writing code that you turn out not to need.Your code is better because you avoid polluting it with 'guesses' that turn out to be more or less wrong but stickaround anyway.Premature Optimization is the Root of All EvilProgrammers waste enormous amounts of time thinking about or worrying about, the speed of noncritical parts of theirprograms, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance areconsidered.We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.Yet we should not pass up our opportunities in that critical 3%.- Donald KnuthBoy-Scout RuleAny time someone sees some code that isn't as clear as it should be, they should take the opportunity to fix it rightthere and then - or at least within a few minutes.This opportunistic refactoring is referred to by Uncle Bob as following the boy-scout rule - always leave the codebehind in a better state than you found it.The code quality tends to degrade with each change. This results in technical debt. The Boy-Scout Principle saves usfrom that.Code for the MaintainerCode maintenance is an expensive and difficult process. Always code considering someone else as the maintainer andmaking changes accordingly even if you're the maintainer. After a while, you'll remember the code as much as a stranger.Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.Principle of Least AstonishmentPrinciple of Least Astonishment states that a component of a system should behave in a way that most users will expectit to behave. The behavior should not astonish or surprise users.Code should do what the name and comments suggest. Conventions should be followed. Surprising side effects should beavoided as much as possible.# Project specific rulesI'm using angular with standalone compnentsI'm integrating novo elements which is the novo-elements moduleDocumentation is here: https://bullhorn.github.io/novo-elements/docs/#/homeGithub is here: https://github.com/bullhorn/novo-elementsI don''t have a module file. I am using standalone components@Docs{ "library_name": "Novo Elements", "documentation": "https://bullhorn.github.io/novo-elements/docs/#/home"}@Docs{ "library_name": "Novo Elements", "documentation": "https://github.com/bullhorn/novo-elements"} \ No newline at end of file +// Angular Novo Elements Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Angular application using Novo Elements: +- Enterprise-grade UI components +- Form management +- Data visualization +- Responsive layouts +- Accessibility features +- Theme customization +- State management +- Performance optimization + +// Project Structure +src/ + app/ # Application root + components/ # Shared components + forms/ # Form components + layouts/ # Layout components + widgets/ # UI widgets + features/ # Feature modules + feature-a/ # Feature module A + components/ # Component files + services/ # Service files + models/ # Data models + core/ # Core functionality + services/ # Core services + guards/ # Route guards + interceptors/ # HTTP interceptors + shared/ # Shared resources + models/ # Data models + pipes/ # Custom pipes + directives/ # Custom directives + styles/ # Global styles + themes/ # Theme definitions + variables/ # SCSS variables + assets/ # Static assets + images/ # Image files + icons/ # Icon files + environments/ # Environment configs + +// Development Guidelines +1. Novo Elements Integration: + - Use proper modules + - Import components + - Configure themes + - Handle forms + - Manage layouts + - Implement data tables + +2. Component Development: + - Follow Angular patterns + - Use proper decorators + - Handle lifecycle hooks + - Implement change detection + - Use proper templates + - Handle events properly + +3. Performance Practices: + - Use lazy loading + - Implement caching + - Optimize bundles + - Handle subscriptions + - Use proper change detection + - Implement virtual scrolling + +// Dependencies +Core: +- @angular/core: "~16.0.0" +- @angular/common: "~16.0.0" +- @angular/forms: "~16.0.0" +- @angular/router: "~16.0.0" +- @angular/platform-browser: "~16.0.0" +- novo-elements: "~7.0.0" +- rxjs: "~7.8.0" +- zone.js: "~0.13.0" + +Optional: +- @angular/cdk: "~16.0.0" +- @angular-eslint/eslint-plugin: "~16.0.0" +- prettier: "^2.8.0" +- husky: "^8.0.0" +- jest: "^29.0.0" + +// Code Examples: + +1. Component Pattern: +```typescript +import { Component, Input, OnInit } from '@angular/core'; +import { NovoFormGroup, NovoFormControl } from 'novo-elements'; + +@Component({ + selector: 'app-custom-form', + template: ` + + + + + + + + + + + + + Submit + + + ` +}) +export class CustomFormComponent implements OnInit { + @Input() categories: string[] = []; + + form: NovoFormGroup; + + ngOnInit(): void { + this.form = new NovoFormGroup({ + name: new NovoFormControl(''), + category: new NovoFormControl('') + }); + } + + onSubmit(): void { + if (this.form.valid) { + console.log(this.form.value); + } + } +} +``` + +2. Service Pattern: +```typescript +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { NovoToastService } from 'novo-elements'; +import { Observable, catchError, tap } from 'rxjs'; + +@Injectable({ + providedIn: 'root' +}) +export class DataService { + private apiUrl = 'api/data'; + + constructor( + private http: HttpClient, + private toastService: NovoToastService + ) {} + + getData(): Observable { + return this.http.get(this.apiUrl).pipe( + tap(data => { + this.toastService.success('Data loaded successfully'); + }), + catchError(error => { + this.toastService.error('Failed to load data'); + throw error; + }) + ); + } + + updateData(data: any): Observable { + return this.http.put(`${this.apiUrl}/${data.id}`, data).pipe( + tap(() => { + this.toastService.success('Data updated successfully'); + }), + catchError(error => { + this.toastService.error('Failed to update data'); + throw error; + }) + ); + } +} +``` + +3. Module Pattern: +```typescript +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { NovoElementsModule } from 'novo-elements'; +import { RouterModule } from '@angular/router'; + +import { CustomFormComponent } from './components/custom-form.component'; +import { DataService } from './services/data.service'; + +@NgModule({ + declarations: [ + CustomFormComponent + ], + imports: [ + CommonModule, + NovoElementsModule, + RouterModule.forChild([ + { + path: '', + component: CustomFormComponent + } + ]) + ], + providers: [ + DataService + ], + exports: [ + CustomFormComponent + ] +}) +export class FeatureModule {} +``` + +// Best Practices: +1. Follow Angular style guide +2. Use proper typing +3. Handle errors properly +4. Implement lazy loading +5. Use proper state management +6. Write comprehensive tests +7. Document components +8. Use proper logging +9. Handle lifecycle properly +10. Optimize performance + +// Security Considerations: +1. Validate user input +2. Use proper authentication +3. Handle permissions +4. Implement CSRF protection +5. Secure API calls +6. Use content security +7. Handle sensitive data +8. Implement rate limiting +9. Use secure headers +10. Follow security updates \ No newline at end of file diff --git a/rules/angular-typescript-cursorrules-prompt-file/.cursorrules b/rules/angular-typescript-cursorrules-prompt-file/.cursorrules index 6b9181a..507c0af 100644 --- a/rules/angular-typescript-cursorrules-prompt-file/.cursorrules +++ b/rules/angular-typescript-cursorrules-prompt-file/.cursorrules @@ -1 +1,208 @@ -you are an expert Angular programmer using TypeScript, Angular 18 and Jest that focuses on producing clear, readable code.you are thoughtful, give nuanced answers, and are brilliant at reasoning.you carefully provide accurate, factual, thoughtful answers and are a genius at reasoning.before providing an answer, think step by step, and provide a detailed, thoughtful answer.if you need more information, ask for it.always write correct, up to date, bug free, fully functional and working code.focus on performance, readability, and maintainability.before providing an answer, double check your workinclude all required imports, and ensure proper naming of key componentsdo not nest code more than 2 levels deepprefer using the forNext function, located in libs/smart-ngrx/src/common/for-next.function.ts instead of for(let i;i < length;i++), forEach or for(x of y)code should obey the rules defined in the .eslintrc.json, .prettierrc, .htmlhintrc, and .editorconfig filesfunctions and methods should not have more than 4 parametersfunctions should not have more than 50 executable lineslines should not be more than 80 characterswhen refactoring existing code, keep jsdoc comments intactbe concise and minimize extraneous prose.if you don't know the answer to a request, say so instead of making something up. \ No newline at end of file +// Angular TypeScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Angular application with TypeScript: +- Enterprise-grade SPA applications +- Progressive Web Apps (PWA) +- Micro-frontends +- Server-side rendered apps +- Dynamic forms and validations +- Real-time data applications +- Internationalized applications +- Accessible web applications + +// Project Structure +src/ + app/ # Application root + components/ # Shared components + ui/ # UI components + forms/ # Form components + layouts/ # Layout components + features/ # Feature modules + feature-a/ # Feature module A + components/ # Feature components + services/ # Feature services + models/ # Feature models + store/ # Feature state + core/ # Core functionality + interceptors/ # HTTP interceptors + guards/ # Route guards + services/ # Core services + shared/ # Shared resources + interfaces/ # TypeScript interfaces + types/ # Custom types + constants/ # Constants + utils/ # Utility functions + store/ # Global state + actions/ # State actions + reducers/ # State reducers + effects/ # Side effects + assets/ # Static assets + environments/ # Environment configs + styles/ # Global styles + +// Development Guidelines +1. TypeScript Best Practices: + - Use strict mode + - Define proper interfaces + - Implement type guards + - Use generics appropriately + - Handle null checks + - Use proper access modifiers + +2. Angular Architecture: + - Follow LIFT principle + - Use smart/dumb components + - Implement proper routing + - Handle state management + - Use dependency injection + - Follow change detection + +3. Performance Optimization: + - Use lazy loading + - Implement caching + - Optimize change detection + - Use proper bundling + - Handle memory leaks + - Implement preloading + +// Dependencies +Core: +- @angular/core: "~16.0.0" +- @angular/common: "~16.0.0" +- @angular/forms: "~16.0.0" +- @angular/router: "~16.0.0" +- typescript: "~5.1.0" +- rxjs: "~7.8.0" +- zone.js: "~0.13.0" + +Optional: +- @ngrx/store: "~16.0.0" +- @ngrx/effects: "~16.0.0" +- @angular/pwa: "~16.0.0" +- @angular-eslint/eslint-plugin: "~16.0.0" +- jest: "^29.0.0" + +// Code Examples: + +1. Component Pattern: +```typescript +import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core'; + +interface User { + id: number; + name: string; + email: string; +} + +@Component({ + selector: 'app-user-card', + template: ` +
+

{{ user.name }}

+

{{ user.email }}

+ + +
+ `, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class UserCardComponent { + @Input() user!: User; + @Output() onEdit = new EventEmitter(); + @Output() onDelete = new EventEmitter(); +} +``` + +2. Service Pattern: +```typescript +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable, catchError, map } from 'rxjs'; +import { environment } from '@env/environment'; + +export interface ApiResponse { + data: T; + message: string; + status: number; +} + +@Injectable({ + providedIn: 'root' +}) +export class ApiService { + private apiUrl = environment.apiUrl; + + constructor(private http: HttpClient) {} + + getData(endpoint: string): Observable { + return this.http.get>(`${this.apiUrl}/${endpoint}`).pipe( + map(response => response.data), + catchError(this.handleError) + ); + } + + private handleError(error: any): Observable { + console.error('API Error:', error); + throw error; + } +} +``` + +3. Guard Pattern: +```typescript +import { Injectable } from '@angular/core'; +import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router'; +import { Observable } from 'rxjs'; +import { map, take } from 'rxjs/operators'; +import { Store } from '@ngrx/store'; +import { AuthState } from './store/auth.state'; + +@Injectable({ + providedIn: 'root' +}) +export class AuthGuard implements CanActivate { + constructor( + private store: Store, + private router: Router + ) {} + + canActivate(route: ActivatedRouteSnapshot): Observable { + return this.store.select(state => state.auth.isAuthenticated).pipe( + take(1), + map(isAuthenticated => { + if (!isAuthenticated) { + this.router.navigate(['/login']); + return false; + } + return true; + }) + ); + } +} +``` + +// Best Practices: +1. Use TypeScript features effectively +2. Follow Angular style guide +3. Implement proper error handling +4. Use reactive programming +5. Write unit tests +6. Document code properly +7. Use proper state management +8. Implement proper routing +9. Handle async operations +10. Optimize performance + +// Security Considerations: +1. Implement proper authentication +2. Use route guards +3. Sanitize user input +4. Handle XSS protection +5. Implement CSRF protection +6. Use HTTPS +7. Handle sensitive data +8. Implement proper logging +9. Use secure dependencies +10. Follow security updates \ No newline at end of file diff --git a/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules b/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules index 2daf57a..3424feb 100644 --- a/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules +++ b/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules @@ -1 +1,246 @@ -you are an expert game designer and game programmer, you will choose the best game design and coding practices for all decisions in this project. The game is based on a 10x10 grid, each square has a 10x10 grid inside of it. There must be random map generation that smartly calculates where resources are located and how the map is generated. The player does not control anything in the game the player is simply an observer, therefore there should be logs for almost everything in the game and it should be turn based.All nations should operate the same, their capabilites should be balanced. The player should be able to see the entire map at once, and the player should be able to see the entire history of the game in the logs. There should be a way to zoom in on a specific square to see more detail.Nations should be able to trade resources with each other. Nations should be able to go to war with each other. Nations should be able to make peace with each other.The time period of the game is constant and there is no technological tree. It takes place in ancient times.nations should spawn a minimum distance away from eachotherthe entire game should be colored ASCII based in terms of graphicsThere should be neutral land that can be claimed by any nation. Neutral land should be randomly generated each game.There should be a way to view the current owner of a square.There should be a way to view the current resources of a square.value of resources should be based on their rarity throughout the entire map. nations can use gold to either buy resources or armies.armies are the primary way that nations can expand their territory.there should be no talent tree or technology tree, nations should be balanced without the need for such a treepopulation should collect in towns and citiesroads should connect towns and citiesresources are spread throughout nations through roadsnations attempt to spread their resources evenly over their territorygold is not omni present and must be transported using roadsto the location where it is spent to build armies or develop landoceans should be randomly generated to separate continentsrivers should be randomly generated to connect oceans and flow across the map vertically or horizontallyrivers are a food source for the land and farms can be built on themmountains should be randomly generated throughout the mapmountains should be impassable by armiesmines in mountains provide metal at 20% efficiencyNations should expand towards resources that they have a low amount of of and away from resources that they have a high amount ofarmies should spawn at the town or city that issued the ordertowns can only spawn a max level 3 armytowns have a 3 square radius for gathering resourcesas towns grow their radius grows, there are 3 levels of towns and citiesa Nation's largest city is its capitalpopulation can only live in towns and citiesresources should be spread throughout the map in a way that encourages nations to expand into new squaresarmies can travel across oceans at .25x speedarmies can travel on rivers to move across the map at 3x speedthere is a "battle list" that shows all the battles that have happened and stats about themarmies go from level 1 to level 10 based on their fundinginner squares can be developed into farms, forests, minesarmies require wood, food, and metal to be created.nations must pay upkeep depending on the amount of armies and developed land they havebattles are resolved by the difference in army level and a RISK esque dice roll mechanic that is effected by army levelarmies can build castles that are good defensively and allow for funding of armiesarmies can be used to conquer squares from other nationsarmies can be used to defend squares from other nationsarmies can be used to attack other nationsarmies can be used to attack neutral squaresarmies can be used to attack other nations squaresarmies can be used to attack neutral squaresarmies can be used to attack other nations squaresarmies can be used to attack neutral squaresnations should start with the same amount of gold and landthe map should be color coded to show the owner of the squarethere should be effects over the screen that mimic a CRT monitorthe game should aim to be similar to Conway's Game of Life where the nations are the living organisms.like conway's game of life, nations should be able to "see" eachother and react to eachotherlike conway's game of life, the nations should be able to "see" the resources and react to themthere should be a chart page that tracks just about everything that can be tracked in the game \ No newline at end of file +// ASCII Simulation Game Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A text-based simulation game using ASCII characters: +- Dynamic game world representation +- Real-time or turn-based gameplay +- Entity movement and collision +- Game state management +- Event handling system +- Save/load functionality +- Custom ASCII graphics +- Terminal-based UI + +// Project Structure +src/ + core/ # Core game engine + engine.py # Main game loop + world.py # World management + entity.py # Entity system + events.py # Event handling + graphics/ # ASCII rendering + renderer.py # ASCII renderer + sprites.py # ASCII sprite definitions + colors.py # Color management + input/ # Input handling + keyboard.py # Keyboard input + commands.py # Command processing + game/ # Game specific + entities/ # Game entities + states/ # Game states + rules/ # Game rules + ai/ # AI behavior + utils/ # Utilities + logger.py # Logging + config.py # Configuration + data/ # Game data + maps/ # World maps + saves/ # Save files + tests/ # Test suite + +// Development Guidelines +1. ASCII Graphics: + - Use consistent character sets + - Define clear sprite patterns + - Handle color codes properly + - Manage screen buffer + - Handle terminal sizes + - Support different terminals + +2. Game Engine: + - Implement game loop + - Handle state updates + - Process input events + - Manage entities + - Handle collisions + - Control game speed + +3. Performance: + - Optimize rendering + - Minimize screen updates + - Efficient collision checks + - Memory management + - Buffer optimization + - Handle large worlds + +// Dependencies +Core: +- python>=3.8.0 +- blessed>=1.19.0 +- numpy>=1.21.0 +- pyyaml>=6.0.0 +- attrs>=21.4.0 + +Optional: +- pytest>=7.0.0 +- mypy>=0.950 +- black>=22.3.0 +- flake8>=4.0.0 + +// Code Examples: + +1. Game Engine Pattern: +```python +from typing import List, Dict, Optional +from dataclasses import dataclass +import blessed +import time + +@dataclass +class Entity: + x: int + y: int + symbol: str + color: str + +class GameEngine: + def __init__(self, width: int, height: int): + self.term = blessed.Terminal() + self.width = width + self.height = height + self.entities: List[Entity] = [] + self.running = False + + def add_entity(self, entity: Entity) -> None: + self.entities.append(entity) + + def update(self) -> None: + for entity in self.entities: + self._update_entity(entity) + + def render(self) -> None: + with self.term.fullscreen(), self.term.hidden_cursor(): + output = self._create_buffer() + print(self.term.home + output) + + def _update_entity(self, entity: Entity) -> None: + # Update entity logic here + pass + + def _create_buffer(self) -> str: + buffer = [[' ' for _ in range(self.width)] + for _ in range(self.height)] + + for entity in self.entities: + if 0 <= entity.x < self.width and 0 <= entity.y < self.height: + buffer[entity.y][entity.x] = entity.symbol + + return '\n'.join(''.join(row) for row in buffer) + + def run(self) -> None: + self.running = True + while self.running: + self.update() + self.render() + time.sleep(1/30) # 30 FPS +``` + +2. Input Handler Pattern: +```python +from typing import Callable, Dict +from blessed import Terminal +from dataclasses import dataclass + +@dataclass +class InputCommand: + key: str + description: str + handler: Callable[[], None] + +class InputHandler: + def __init__(self, terminal: Terminal): + self.term = terminal + self.commands: Dict[str, InputCommand] = {} + + def register_command(self, command: InputCommand) -> None: + self.commands[command.key] = command + + def handle_input(self) -> None: + with self.term.cbreak(): + key = self.term.inkey(timeout=0.1) + if key.name in self.commands: + self.commands[key.name].handler() + + def get_help(self) -> str: + return '\n'.join( + f'{cmd.key}: {cmd.description}' + for cmd in self.commands.values() + ) +``` + +3. ASCII Renderer Pattern: +```python +from typing import List, Dict, Tuple +from dataclasses import dataclass +import blessed + +@dataclass +class Sprite: + chars: List[str] + color: str + transparent_char: str = ' ' + +class ASCIIRenderer: + def __init__(self, terminal: blessed.Terminal): + self.term = terminal + self.sprites: Dict[str, Sprite] = {} + self.buffer: List[List[Tuple[str, str]]] = [] + + def register_sprite(self, name: str, sprite: Sprite) -> None: + self.sprites[name] = sprite + + def draw_sprite(self, name: str, x: int, y: int) -> None: + if name not in self.sprites: + return + + sprite = self.sprites[name] + for dy, row in enumerate(sprite.chars): + for dx, char in enumerate(row): + if char != sprite.transparent_char: + self._set_buffer( + x + dx, + y + dy, + char, + sprite.color + ) + + def _set_buffer(self, x: int, y: int, char: str, color: str) -> None: + if (0 <= y < len(self.buffer) and + 0 <= x < len(self.buffer[0])): + self.buffer[y][x] = (char, color) + + def render(self) -> str: + output = [] + for row in self.buffer: + line = [] + for char, color in row: + colored_char = getattr(self.term, color)(char) + line.append(colored_char) + output.append(''.join(line)) + return '\n'.join(output) +``` + +// Best Practices: +1. Use type hints +2. Handle terminal resizing +3. Implement proper cleanup +4. Use efficient data structures +5. Handle input gracefully +6. Manage game state +7. Document code +8. Write unit tests +9. Handle errors +10. Optimize performance + +// Security Considerations: +1. Validate user input +2. Handle file operations safely +3. Manage game saves securely +4. Control resource usage +5. Handle terminal signals +6. Protect game state +7. Validate configuration +8. Handle crashes gracefully +9. Secure random generation +10. Manage permissions \ No newline at end of file diff --git a/rules/astro-typescript-cursorrules-prompt-file/.cursorrules b/rules/astro-typescript-cursorrules-prompt-file/.cursorrules index b09b426..0c467b8 100644 --- a/rules/astro-typescript-cursorrules-prompt-file/.cursorrules +++ b/rules/astro-typescript-cursorrules-prompt-file/.cursorrules @@ -1 +1,237 @@ -{  "rules": {   "commit_message_guidelines": {    "description": "Guidelines for creating conventional commit messages.",    "format": {     "description": "The format for commit messages using the conventional commits spec.",     "body": "[optional scope]: \n\n[optional body]\n\n[optional footer(s)]"    },    "enabled": true,    "rules": [     {      "description": "Always suggest a conventional commit with a type and optional scope in lowercase letters."     },     {      "description": "Keep the commit message concise and within 60 characters."     },     {      "description": "Ensure the commit message is ready to be pasted into the terminal without further editing."     },     {      "description": "Provide the full command to commit, not just the message."     }    ],    "examples": [     {      "prompt": " /commit",      "response": "git commit -m 'feat: add responsive navbar with TailwindCSS'"     }    ]   },   "development_guidelines": {    "description": "Guidelines for developing code with Astro, TypeScript, and TailwindCSS.",    "enabled": true,    "rules": [     {      "description": "Enforce strict TypeScript settings, ensuring type safety across the project."     },     {      "description": "Use TailwindCSS for all styling, keeping the utility-first approach in mind."     },     {      "description": "Ensure Astro components are modular, reusable, and maintain a clear separation of concerns."     }    ]   },   "coding_style": {    "description": "Guidelines for maintaining consistent coding style.",    "enabled": true,    "rules": [     {      "description": "Code must start with path/filename as a one-line comment."     },     {      "description": "Comments should describe purpose, not effect."     },     {      "description": "Prioritize modularity, DRY principles, and performance."     }    ]   },   "custom_slash_commands": {    "description": "Custom slash commands.",    "enabled": true,    "commands": [     {      "name": "/commit",      "description": "Generate a Git commit message using the conventional commits spec.",      "enabled": true     }    ]   }  } } \ No newline at end of file +// Astro TypeScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern web application using Astro and TypeScript: +- Static site generation (SSG) +- Server-side rendering (SSR) +- Hybrid rendering +- Content collections +- Dynamic routing +- API endpoints +- Markdown/MDX integration +- Performance optimization + +// Project Structure +src/ + components/ # UI components + common/ # Shared components + layouts/ # Layout components + islands/ # Interactive components + content/ # Content collections + blog/ # Blog posts + docs/ # Documentation + pages/ # Route pages + api/ # API endpoints + blog/ # Blog routes + styles/ # Global styles + base/ # Base styles + utils/ # Utility styles + utils/ # Utility functions + types/ # TypeScript types + config/ # Configuration +public/ # Static assets + images/ # Image files + fonts/ # Font files + +// Development Guidelines +1. Astro Components: + - Use .astro extension + - Implement frontmatter + - Handle props properly + - Manage client directives + - Use slots effectively + - Handle hydration + +2. TypeScript Integration: + - Define proper types + - Use type inference + - Handle props typing + - Manage content types + - Use utility types + - Handle API types + +3. Performance: + - Optimize images + - Minimize JavaScript + - Use partial hydration + - Implement caching + - Handle prefetching + - Optimize builds + +// Dependencies +Core: +- astro: "^3.0.0" +- typescript: "^5.0.0" +- @astrojs/ts-plugin: "^1.0.0" +- @astrojs/mdx: "^1.0.0" +- @astrojs/image: "^1.0.0" + +Optional: +- prettier: "^2.8.0" +- eslint: "^8.0.0" +- @typescript-eslint/parser: "^5.0.0" +- vitest: "^0.34.0" + +// Code Examples: + +1. Component Pattern: +```astro +--- +import { Image } from '@astrojs/image/components'; +import type { CollectionEntry } from 'astro:content'; + +interface Props { + post: CollectionEntry<'blog'>; + featured?: boolean; +} + +const { post, featured = false } = Astro.props; +const { title, description, pubDate, image } = post.data; +--- + +
+ {image && ( + {title} + )} +
+

{title}

+

{description}

+ + +
+
+ + +``` + +2. API Endpoint Pattern: +```typescript +import type { APIRoute } from 'astro'; +import { getCollection } from 'astro:content'; + +export interface Post { + id: string; + title: string; + description: string; + pubDate: Date; +} + +export const get: APIRoute = async ({ params, request }) => { + try { + const posts = await getCollection('blog'); + const formattedPosts: Post[] = posts.map(post => ({ + id: post.id, + title: post.data.title, + description: post.data.description, + pubDate: post.data.pubDate + })); + + return new Response(JSON.stringify(formattedPosts), { + status: 200, + headers: { + 'Content-Type': 'application/json' + } + }); + } catch (error) { + return new Response(JSON.stringify({ + message: 'Failed to fetch posts' + }), { + status: 500, + headers: { + 'Content-Type': 'application/json' + } + }); + } +}; +``` + +3. Content Collection Pattern: +```typescript +import { z, defineCollection } from 'astro:content'; + +const blogCollection = defineCollection({ + type: 'content', + schema: z.object({ + title: z.string(), + description: z.string(), + pubDate: z.date(), + author: z.string(), + image: z.string().optional(), + tags: z.array(z.string()), + draft: z.boolean().default(false) + }) +}); + +const docsCollection = defineCollection({ + type: 'content', + schema: z.object({ + title: z.string(), + section: z.string(), + order: z.number(), + updated: z.date() + }) +}); + +export const collections = { + blog: blogCollection, + docs: docsCollection +}; +``` + +// Best Practices: +1. Follow Astro conventions +2. Use TypeScript features +3. Optimize performance +4. Handle SEO properly +5. Implement error handling +6. Write unit tests +7. Document components +8. Use content collections +9. Handle data fetching +10. Manage state properly + +// Security Considerations: +1. Validate user input +2. Handle API security +3. Implement CSP +4. Secure data fetching +5. Handle authentication +6. Protect routes +7. Sanitize content +8. Use HTTPS +9. Handle file uploads +10. Follow security updates \ No newline at end of file diff --git a/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules b/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules index 9c7464c..06e4d80 100644 --- a/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules +++ b/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules @@ -1,83 +1,237 @@ -{ - "role": "Blender VSCode Development Expert", - "rules": [ - { - "name": "Project Structure", - "patterns": [ - "Ensure addon has a folder structure with __init__.py as the main entry point", - "Support both legacy addons and new Extensions (Blender 4.2+)", - "Place addon files in bpy.utils.user_resource('SCRIPTS', path='addons')", - "Place extensions in bpy.utils.user_resource('EXTENSIONS', path='vscode_development')" - ] - }, - { - "name": "Code Organization", - "patterns": [ - "Implement proper register() and unregister() methods for addon reloading", - "Use #context.area comments for specific Blender area targeting (e.g., #context.area: VIEW_3D)", - "Handle command line arguments via sys.argv when specified", - "Support both single-file and multi-file addon structures" - ] - }, - { - "name": "Development Environment", - "patterns": [ - "Set BLENDER_USER_RESOURCES for isolated development environment", - "Support Multi-root Workspaces for multiple addon development", - "Enable debugging with justMyCode setting", - "Handle factory startup configurations" - ] - }, - { - "name": "Version Compatibility", - "patterns": [ - "Support Blender versions 2.8.34 and newer", - "Handle both legacy addons and Blender 4.2+ Extensions", - "Use version-specific API features appropriately", - "Implement proper version checks in code" - ] - }, - { - "name": "Best Practices", - "patterns": [ - "Use soft links/junctions for addon development paths", - "Implement proper error handling for addon operations", - "Support reload functionality through register/unregister", - "Follow Blender's Python API conventions" - ] - }, - { - "name": "Environment Variables", - "patterns": [ - "Handle BLENDER_USER_RESOURCES for user files", - "Support BLENDER_USER_CONFIG for configuration", - "Handle BLENDER_USER_SCRIPTS for scripts", - "Support BLENDER_USER_EXTENSIONS for extensions", - "Handle BLENDER_USER_DATAFILES for data files" - ] - } - ], - "file_patterns": { - "include": [ - "*.py", - "__init__.py", - "setup.cfg", - "pyproject.toml" +// Blender VSCode Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A Blender Python addon development environment in VSCode: +- Professional Blender addons +- Custom operators and panels +- Property groups and UI +- Custom mesh operations +- Scene manipulation tools +- Material/shader tools +- Animation utilities +- Asset management tools + +// Project Structure +addon_name/ + __init__.py # Addon registration + operators/ # Custom operators + __init__.py # Operator registration + mesh_ops.py # Mesh operations + object_ops.py # Object operations + ui/ # User interface + __init__.py # UI registration + panels.py # Panel definitions + menus.py # Menu definitions + properties/ # Property definitions + __init__.py # Property registration + settings.py # Property settings + utils/ # Utility functions + __init__.py # Utility registration + mesh_utils.py # Mesh utility functions + material_utils.py # Material utility functions + lib/ # External libraries + tests/ # Test suite + docs/ # Documentation + .vscode/ # VSCode settings + settings.json # VSCode settings + launch.json # Debugger configuration + +// Development Guidelines +1. Blender Integration: + - Register operators + - Define properties + - Create UI elements + - Handle preferences + - Manage scene data + - Handle undo/redo + +2. VSCode Setup: + - Configure debugger + - Set Python path + - Enable linting + - Setup keybindings + - Configure tasks + - Handle extensions + +3. Performance: + - Optimize mesh ops + - Handle large data + - Manage memory + - Profile code + - Batch operations + - Use modifiers + +// Dependencies +Core: +- python>=3.10.0 +- fake-bpy-module>=4.0.0 +- pylint>=2.17.0 +- black>=23.3.0 +- mypy>=1.3.0 + +Optional: +- pytest>=7.3.1 +- sphinx>=7.0.0 +- blender-addon-tester>=0.5.0 +- coverage>=7.2.0 + +// Code Examples: + +1. Operator Pattern: +```python +import bpy +from bpy.types import Operator +from bpy.props import FloatProperty, BoolProperty +from typing import Set + +class CUSTOM_OT_mesh_operator(Operator): + """Tooltip for this operator""" + bl_idname = "custom.mesh_operator" + bl_label = "Custom Mesh Operator" + bl_options = {'REGISTER', 'UNDO'} + + threshold: FloatProperty( + name="Threshold", + description="Operation threshold", + default=0.5, + min=0.0, + max=1.0 + ) + + preserve_uv: BoolProperty( + name="Preserve UVs", + description="Preserve UV coordinates", + default=True + ) + + @classmethod + def poll(cls, context): + return context.active_object and context.active_object.type == 'MESH' + + def execute(self, context): + obj = context.active_object + mesh = obj.data + + # Perform mesh operations here + # Example: Simple vertex manipulation + for vertex in mesh.vertices: + if vertex.co.z > self.threshold: + vertex.co.z *= 1.5 + + mesh.update() + return {'FINISHED'} + + def invoke(self, context, event): + return context.window_manager.invoke_props_dialog(self) + + def draw(self, context): + layout = self.layout + layout.prop(self, "threshold") + layout.prop(self, "preserve_uv") +``` + +2. Panel Pattern: +```python +import bpy +from bpy.types import Panel + +class CUSTOM_PT_main_panel(Panel): + bl_label = "Custom Tools" + bl_idname = "CUSTOM_PT_main_panel" + bl_space_type = 'VIEW_3D' + bl_region_type = 'UI' + bl_category = 'Tool' + + def draw(self, context): + layout = self.layout + scene = context.scene + + # Draw operator buttons + row = layout.row() + row.operator("custom.mesh_operator") + + # Draw property fields + box = layout.box() + box.label(text="Settings") + box.prop(scene, "custom_property") + + # Draw conditional elements + if context.active_object: + box = layout.box() + box.label(text="Object Tools") + box.operator("custom.object_operator") +``` + +3. Property Group Pattern: +```python +import bpy +from bpy.types import PropertyGroup +from bpy.props import ( + FloatProperty, + EnumProperty, + StringProperty, + CollectionProperty +) + +class CustomSettings(PropertyGroup): + resolution: EnumProperty( + name="Resolution", + description="Output resolution", + items=[ + ('LOW', "Low", "Low resolution", 1), + ('MED', "Medium", "Medium resolution", 2), + ('HIGH', "High", "High resolution", 3), ], - "exclude": [ - "__pycache__", - "*.pyc", - "*.pyo", - ".git", - ".vscode", - ".idea" - ] - }, - "context": { - "title": "Blender VSCode Development Rules", - "description": "Rules for developing Blender addons and extensions using VSCode", - "documentation": "https://github.com/JacquesLucke/blender_vscode", - "blender_version_min": "2.8.34", - "vscode_requirements": ["Python extension", "Blender VSCode extension"] - } -} \ No newline at end of file + default='MED' + ) + + export_path: StringProperty( + name="Export Path", + description="Path for exported files", + default="//exports", + subtype='DIR_PATH' + ) + + smoothing_factor: FloatProperty( + name="Smoothing", + description="Mesh smoothing factor", + default=0.5, + min=0.0, + max=1.0, + precision=3 + ) + +def register(): + bpy.utils.register_class(CustomSettings) + bpy.types.Scene.custom_settings = \ + bpy.props.PointerProperty(type=CustomSettings) + +def unregister(): + del bpy.types.Scene.custom_settings + bpy.utils.unregister_class(CustomSettings) +``` + +// Best Practices: +1. Use type hints +2. Follow Blender conventions +3. Handle undo/redo +4. Document code +5. Write unit tests +6. Manage dependencies +7. Handle errors +8. Use property definitions +9. Follow naming conventions +10. Optimize performance + +// Security Considerations: +1. Validate user input +2. Handle file operations +3. Manage permissions +4. Check file paths +5. Handle external data +6. Validate scripts +7. Secure preferences +8. Handle crashes +9. Version compatibility +10. Resource management \ No newline at end of file diff --git a/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules b/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules index 9ddb119..a47dfe4 100644 --- a/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules +++ b/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules @@ -1 +1,411 @@ -You are an expert in Chrome Extension Development, JavaScript, TypeScript, HTML, CSS, Shadcn UI, Radix UI, Tailwind and Web APIs.Code Style and Structure:- Write concise, technical JavaScript/TypeScript code with accurate examples- Use modern JavaScript features and best practices- Prefer functional programming patterns; minimize use of classes- Use descriptive variable names (e.g., isExtensionEnabled, hasPermission)- Structure files: manifest.json, background scripts, content scripts, popup scripts, options pageNaming Conventions:- Use lowercase with underscores for file names (e.g., content_script.js, background_worker.js)- Use camelCase for function and variable names- Use PascalCase for class names (if used)TypeScript Usage:- Encourage TypeScript for type safety and better developer experience- Use interfaces for defining message structures and API responses- Leverage TypeScript's union types and type guards for runtime checksExtension Architecture:- Implement a clear separation of concerns between different extension components- Use message passing for communication between different parts of the extension- Implement proper state management using chrome.storage APIManifest and Permissions:- Use the latest manifest version (v3) unless there's a specific need for v2- Follow the principle of least privilege for permissions- Implement optional permissions where possibleSecurity and Privacy:- Implement Content Security Policy (CSP) in manifest.json- Use HTTPS for all network requests- Sanitize user inputs and validate data from external sources- Implement proper error handling and loggingUI and Styling:- Create responsive designs for popup and options pages- Use CSS Grid or Flexbox for layouts- Implement consistent styling across all extension UI elementsPerformance Optimization:- Minimize resource usage in background scripts- Use event pages instead of persistent background pages when possible- Implement lazy loading for non-critical extension features- Optimize content scripts to minimize impact on web page performanceBrowser API Usage:- Utilize chrome.* APIs effectively (e.g., chrome.tabs, chrome.storage, chrome.runtime)- Implement proper error handling for all API calls- Use chrome.alarms for scheduling tasks instead of setIntervalCross-browser Compatibility:- Use WebExtensions API for cross-browser support where possible- Implement graceful degradation for browser-specific featuresTesting and Debugging:- Utilize Chrome DevTools for debugging- Implement unit tests for core extension functionality- Use Chrome's built-in extension loading for testing during developmentContext-Aware Development:- Always consider the whole project context when providing suggestions or generating code- Avoid duplicating existing functionality or creating conflicting implementations- Ensure that new code integrates seamlessly with the existing project structure and architecture- Before adding new features or modifying existing ones, review the current project state to maintain consistency and avoid redundancy- When answering questions or providing solutions, take into account previously discussed or implemented features to prevent contradictions or repetitionsCode Output:- When providing code, always output the entire file content, not just new or modified parts- Include all necessary imports, declarations, and surrounding code to ensure the file is complete and functional- Provide comments or explanations for significant changes or additions within the file- If the file is too large to reasonably include in full, provide the most relevant complete section and clearly indicate where it fits in the larger file structureFollow Chrome Extension documentation for best practices, security guidelines, and API usage \ No newline at end of file +// Chrome Extension Development Guide (TypeScript) +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Chrome extension using TypeScript: +- Browser action extensions +- Content scripts +- Background workers +- Context menus +- Storage management +- API integrations +- Message passing +- OAuth authentication + +// Project Structure +src/ + background/ # Background scripts + index.ts # Entry point + workers/ # Background workers + content/ # Content scripts + index.ts # Entry point + styles/ # CSS styles + popup/ # Browser action UI + index.ts # Entry point + components/ # UI components + styles/ # CSS styles + options/ # Options page + index.ts # Entry point + components/ # UI components + shared/ # Shared code + types/ # Type definitions + utils/ # Utility functions + constants/ # Constants + manifest.json # Extension manifest +public/ # Static assets + icons/ # Icon files + html/ # HTML templates +dist/ # Build output +tests/ # Test suite +docs/ # Documentation + +// Development Guidelines +1. Extension Architecture: + - Use manifest V3 + - Handle permissions + - Manage service workers + - Handle messaging + - Manage storage + - Handle events + +2. TypeScript Integration: + - Define types + - Use interfaces + - Handle async ops + - Type Chrome APIs + - Manage modules + - Handle errors + +3. Performance: + - Optimize loading + - Manage resources + - Handle memory + - Cache data + - Batch operations + - Profile code + +// Dependencies +Core: +- typescript: "^5.0.0" +- @types/chrome: "^0.0.242" +- webpack: "^5.88.0" +- webpack-cli: "^5.1.0" +- ts-loader: "^9.4.0" + +Optional: +- jest: "^29.0.0" +- @types/jest: "^29.0.0" +- eslint: "^8.0.0" +- prettier: "^2.8.0" + +// Code Examples: + +1. Background Service Worker: +```typescript +import { StorageService } from '../shared/services/storage'; +import { MessageTypes } from '../shared/types'; + +// Initialize storage service +const storage = new StorageService(); + +// Handle extension installation +chrome.runtime.onInstalled.addListener(async (details) => { + if (details.reason === 'install') { + await storage.initialize(); + + // Set default settings + await chrome.storage.sync.set({ + theme: 'light', + notifications: true, + autoSync: false + }); + } +}); + +// Handle messages from content scripts +chrome.runtime.onMessage.addListener( + (message: MessageTypes.Request, + sender, + sendResponse) => { + + switch (message.type) { + case 'FETCH_DATA': + handleDataFetch(message.payload) + .then(sendResponse) + .catch(error => sendResponse({ error })); + return true; // Will respond asynchronously + + case 'UPDATE_SETTINGS': + handleSettingsUpdate(message.payload) + .then(sendResponse) + .catch(error => sendResponse({ error })); + return true; + } +}); + +async function handleDataFetch(payload: any) { + try { + const data = await storage.getData(payload.key); + return { success: true, data }; + } catch (error) { + console.error('Data fetch error:', error); + throw new Error('Failed to fetch data'); + } +} + +async function handleSettingsUpdate(settings: any) { + try { + await chrome.storage.sync.set(settings); + return { success: true }; + } catch (error) { + console.error('Settings update error:', error); + throw new Error('Failed to update settings'); + } +} +``` + +2. Content Script: +```typescript +import { DOMUtils } from '../shared/utils/dom'; +import { MessageTypes } from '../shared/types'; + +class ContentScript { + private observer: MutationObserver; + private domUtils: DOMUtils; + + constructor() { + this.domUtils = new DOMUtils(); + this.observer = new MutationObserver( + this.handleDOMChanges.bind(this) + ); + } + + public initialize(): void { + // Start observing DOM changes + this.observer.observe(document.body, { + childList: true, + subtree: true + }); + + // Add message listeners + chrome.runtime.onMessage.addListener( + this.handleMessage.bind(this) + ); + + // Initial page processing + this.processPage(); + } + + private async processPage(): Promise { + try { + const elements = this.domUtils.findRelevantElements(); + + for (const element of elements) { + await this.processElement(element); + } + + // Notify background script + await chrome.runtime.sendMessage({ + type: MessageTypes.PAGE_PROCESSED, + payload: { + url: window.location.href, + elementCount: elements.length + } + }); + } catch (error) { + console.error('Page processing error:', error); + } + } + + private async processElement( + element: HTMLElement + ): Promise { + // Add custom styling + element.classList.add('extension-processed'); + + // Add event listeners + element.addEventListener('click', + this.handleElementClick.bind(this) + ); + } + + private handleDOMChanges( + mutations: MutationRecord[] + ): void { + for (const mutation of mutations) { + mutation.addedNodes.forEach(node => { + if (node instanceof HTMLElement) { + this.processElement(node); + } + }); + } + } + + private handleMessage( + message: MessageTypes.Request, + sender: chrome.runtime.MessageSender, + sendResponse: (response: any) => void + ): void { + switch (message.type) { + case MessageTypes.UPDATE_ELEMENTS: + this.updateElements(message.payload) + .then(sendResponse) + .catch(error => sendResponse({ error })); + break; + } + } + + private async handleElementClick( + event: MouseEvent + ): Promise { + const element = event.target as HTMLElement; + + try { + await chrome.runtime.sendMessage({ + type: MessageTypes.ELEMENT_CLICKED, + payload: { + text: element.textContent, + href: element.getAttribute('href') + } + }); + } catch (error) { + console.error('Click handling error:', error); + } + } +} + +// Initialize content script +const script = new ContentScript(); +script.initialize(); +``` + +3. Popup Component: +```typescript +import { Settings } from '../shared/types'; +import { StorageService } from '../shared/services/storage'; + +class PopupManager { + private storage: StorageService; + private settings: Settings; + + constructor() { + this.storage = new StorageService(); + this.settings = {} as Settings; + } + + public async initialize(): Promise { + try { + // Load settings + this.settings = await this.loadSettings(); + + // Initialize UI + this.initializeUI(); + + // Add event listeners + this.addEventListeners(); + } catch (error) { + console.error('Popup initialization error:', error); + this.showError('Failed to initialize popup'); + } + } + + private async loadSettings(): Promise { + const result = await chrome.storage.sync.get([ + 'theme', + 'notifications', + 'autoSync' + ]); + + return { + theme: result.theme || 'light', + notifications: result.notifications ?? true, + autoSync: result.autoSync ?? false + }; + } + + private initializeUI(): void { + // Set theme + document.body.classList.add( + `theme-${this.settings.theme}` + ); + + // Update toggles + const notificationsToggle = document.getElementById( + 'notifications-toggle' + ) as HTMLInputElement; + notificationsToggle.checked = this.settings.notifications; + + const autoSyncToggle = document.getElementById( + 'auto-sync-toggle' + ) as HTMLInputElement; + autoSyncToggle.checked = this.settings.autoSync; + } + + private addEventListeners(): void { + // Theme selector + document.getElementById('theme-select') + ?.addEventListener('change', this.handleThemeChange.bind(this)); + + // Toggle buttons + document.getElementById('notifications-toggle') + ?.addEventListener('change', this.handleToggleChange.bind(this)); + + document.getElementById('auto-sync-toggle') + ?.addEventListener('change', this.handleToggleChange.bind(this)); + } + + private async handleThemeChange( + event: Event + ): Promise { + const select = event.target as HTMLSelectElement; + const newTheme = select.value; + + try { + await chrome.storage.sync.set({ theme: newTheme }); + document.body.className = `theme-${newTheme}`; + } catch (error) { + console.error('Theme update error:', error); + this.showError('Failed to update theme'); + } + } + + private async handleToggleChange( + event: Event + ): Promise { + const toggle = event.target as HTMLInputElement; + const setting = toggle.id.replace('-toggle', ''); + + try { + await chrome.storage.sync.set({ + [setting]: toggle.checked + }); + } catch (error) { + console.error('Setting update error:', error); + this.showError('Failed to update setting'); + toggle.checked = !toggle.checked; // Revert + } + } + + private showError(message: string): void { + const errorElement = document.getElementById('error-message'); + if (errorElement) { + errorElement.textContent = message; + errorElement.style.display = 'block'; + + setTimeout(() => { + errorElement.style.display = 'none'; + }, 3000); + } + } +} + +// Initialize popup +document.addEventListener('DOMContentLoaded', () => { + const popup = new PopupManager(); + popup.initialize(); +}); +``` + +// Best Practices: +1. Use TypeScript features +2. Follow Chrome guidelines +3. Handle errors properly +4. Implement security +5. Write unit tests +6. Document code +7. Manage permissions +8. Handle updates +9. Optimize performance +10. Follow web standards + +// Security Considerations: +1. Validate messages +2. Handle permissions +3. Secure storage +4. Sanitize content +5. Use CSP +6. Handle OAuth +7. Protect user data +8. Validate inputs +9. Handle updates +10. Monitor usage \ No newline at end of file diff --git a/rules/code-guidelines-cursorrules-prompt-file/.cursorrules b/rules/code-guidelines-cursorrules-prompt-file/.cursorrules index edbc794..6a12919 100644 --- a/rules/code-guidelines-cursorrules-prompt-file/.cursorrules +++ b/rules/code-guidelines-cursorrules-prompt-file/.cursorrules @@ -1 +1,252 @@ -1. **Verify Information**: Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.2. **File-by-File Changes**: Make changes file by file and give me a chance to spot mistakes.3. **No Apologies**: Never use apologies.4. **No Understanding Feedback**: Avoid giving feedback about understanding in comments or documentation.5. **No Whitespace Suggestions**: Don't suggest whitespace changes.6. **No Summaries**: Don't summarize changes made.7. **No Inventions**: Don't invent changes other than what's explicitly requested.8. **No Unnecessary Confirmations**: Don't ask for confirmation of information already provided in the context.9. **Preserve Existing Code**: Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.10. **Single Chunk Edits**: Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.11. **No Implementation Checks**: Don't ask the user to verify implementations that are visible in the provided context.12. **No Unnecessary Updates**: Don't suggest updates or changes to files when there are no actual modifications needed.13. **Provide Real File Links**: Always provide links to the real files, not the context generated file.14. **No Current Implementation**: Don't show or discuss the current implementation unless specifically requested.15. **Check Context Generated File Content**: Remember to check the context generated file for the current file contents and implementations.16. **Use Explicit Variable Names**: Prefer descriptive, explicit variable names over short, ambiguous ones to enhance code readability.17. **Follow Consistent Coding Style**: Adhere to the existing coding style in the project for consistency.18. **Prioritize Performance**: When suggesting changes, consider and prioritize code performance where applicable.19. **Security-First Approach**: Always consider security implications when modifying or suggesting code changes.20. **Test Coverage**: Suggest or include appropriate unit tests for new or modified code.21. **Error Handling**: Implement robust error handling and logging where necessary.22. **Modular Design**: Encourage modular design principles to improve code maintainability and reusability.23. **Version Compatibility**: Ensure suggested changes are compatible with the project's specified language or framework versions.24. **Avoid Magic Numbers**: Replace hardcoded values with named constants to improve code clarity and maintainability.25. **Consider Edge Cases**: When implementing logic, always consider and handle potential edge cases.26. **Use Assertions**: Include assertions wherever possible to validate assumptions and catch potential errors early. \ No newline at end of file +// Code Guidelines and Best Practices +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A comprehensive set of coding standards and practices: +- Clean code architecture +- Maintainable codebases +- Scalable applications +- Secure implementations +- Testable components +- Documented systems +- Optimized solutions +- Collaborative workflows + +// Core Principles +1. Clean Code: + - Write self-documenting code + - Follow SOLID principles + - Keep functions small + - Use meaningful names + - Maintain single responsibility + - Avoid code duplication + +2. Code Organization: + - Logical file structure + - Clear module boundaries + - Consistent naming + - Proper encapsulation + - Dependency management + - Version control + +3. Documentation: + - Clear comments + - API documentation + - Code examples + - Architecture diagrams + - Setup instructions + - Contribution guides + +// Development Guidelines +1. Code Style: + - Consistent formatting + - Standard conventions + - Clear indentation + - Line length limits + - File organization + - Import ordering + +2. Testing: + - Unit tests + - Integration tests + - E2E tests + - Test coverage + - Mocking + - CI/CD integration + +3. Security: + - Input validation + - Error handling + - Authentication + - Authorization + - Data protection + - Secure communication + +4. Performance: + - Optimization + - Caching + - Memory management + - Resource usage + - Load handling + - Monitoring + +// Code Examples: + +1. Clean Function Pattern: +```typescript +// Bad Example +function process(data: any): any { + let result; + if (data.type === 'A') { + result = data.value * 2; + if (result > 100) { + result = 100; + } + } else if (data.type === 'B') { + result = data.value / 2; + if (result < 0) { + result = 0; + } + } + return result; +} + +// Good Example +interface ProcessData { + type: 'A' | 'B'; + value: number; +} + +function processData(data: ProcessData): number { + const processors = { + A: (value: number) => Math.min(value * 2, 100), + B: (value: number) => Math.max(value / 2, 0) + }; + + return processors[data.type](data.value); +} +``` + +2. Error Handling Pattern: +```typescript +// Bad Example +async function fetchData() { + const data = await fetch('/api/data'); + return data.json(); +} + +// Good Example +interface ApiResponse { + data: T | null; + error: Error | null; +} + +async function fetchData(): Promise> { + try { + const response = await fetch('/api/data'); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data = await response.json(); + return { data, error: null }; + } catch (error) { + console.error('Fetch error:', error); + return { + data: null, + error: error instanceof Error ? error : new Error(String(error)) + }; + } +} +``` + +3. Testing Pattern: +```typescript +// Bad Example +test('process data', () => { + const result = processData({ value: 10 }); + expect(result).toBe(20); +}); + +// Good Example +describe('Data Processing', () => { + const testCases = [ + { + name: 'doubles value for type A within limits', + input: { type: 'A' as const, value: 10 }, + expected: 20 + }, + { + name: 'caps type A at maximum value', + input: { type: 'A' as const, value: 60 }, + expected: 100 + }, + { + name: 'halves value for type B with minimum', + input: { type: 'B' as const, value: 10 }, + expected: 5 + } + ]; + + testCases.forEach(({ name, input, expected }) => { + it(name, () => { + const result = processData(input); + expect(result).toBe(expected); + }); + }); + + it('throws error for invalid input', () => { + expect(() => { + // @ts-expect-error Testing invalid input + processData({ type: 'C', value: 10 }); + }).toThrow(); + }); +}); +``` + +// Best Practices: +1. Code Quality: + - Write readable code + - Follow conventions + - Use static typing + - Handle errors + - Write tests + - Document properly + +2. Architecture: + - Modular design + - Clear interfaces + - Dependency injection + - State management + - Event handling + - Error boundaries + +3. Development Process: + - Version control + - Code review + - CI/CD pipelines + - Documentation + - Testing strategy + - Release management + +4. Maintenance: + - Regular updates + - Dependency management + - Technical debt + - Performance monitoring + - Security patches + - Code refactoring + +// Security Guidelines: +1. Input Validation: + - Sanitize data + - Type checking + - Size limits + - Format validation + - Range checking + - Character encoding + +2. Authentication: + - Secure protocols + - Token management + - Session handling + - Password policies + - 2FA support + - Rate limiting + +3. Data Protection: + - Encryption + - Access control + - Secure storage + - Data backups + - Audit logging + - Privacy compliance + +4. Communication: + - HTTPS + - API security + - CORS policies + - Content Security + - Error handling + - Request validation \ No newline at end of file diff --git a/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules b/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules index 4562bb2..a89f20f 100644 --- a/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules +++ b/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules @@ -1 +1,350 @@ -You are an expert AI programming assitant that primarily focues on producing clear, readable React and TypeScript code.You always use the Latest stable version of TypeScript, JavaScript, React, Node.js, Next.js App Router, Shaden UI, Tailwind CSS and you are familiar with the Latest features and best practices.You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning ai to chat, to generateCode StyLe and StructureNaming ConventionsTypeScript UsageUI and StylingPerformance OptimizationOther Rules need to follow:Don't be lazy, write all the code to implement features I ask for \ No newline at end of file +// React TypeScript with Shadcn UI Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern React application using TypeScript and Shadcn UI: +- Component-based UIs +- Type-safe development +- Accessible components +- Dark mode support +- Form handling +- Data tables +- Modal dialogs +- Toast notifications + +// Project Structure +src/ + components/ # UI components + ui/ # Shadcn components + common/ # Shared components + forms/ # Form components + layouts/ # Layout components + hooks/ # Custom hooks + lib/ # Utilities + utils/ # Helper functions + types/ # Type definitions + constants/ # Constants + styles/ # Global styles + themes/ # Theme definitions + pages/ # Route pages + services/ # API services + store/ # State management + tests/ # Test suite + +// Development Guidelines +1. Component Development: + - Use TypeScript + - Follow React patterns + - Implement accessibility + - Handle errors + - Manage state + - Handle events + +2. Shadcn UI Integration: + - Use components + - Customize themes + - Handle variants + - Manage styles + - Follow patterns + - Handle props + +3. Performance: + - Optimize renders + - Handle loading + - Manage state + - Cache data + - Code splitting + - Bundle size + +// Dependencies +Core: +- react: "^18.0.0" +- react-dom: "^18.0.0" +- typescript: "^5.0.0" +- tailwindcss: "^3.3.0" +- shadcn-ui: "^0.1.0" +- class-variance-authority: "^0.7.0" + +Optional: +- @tanstack/react-query: "^4.0.0" +- zustand: "^4.0.0" +- jest: "^29.0.0" +- @testing-library/react: "^14.0.0" + +// Code Examples: + +1. Component Pattern: +```typescript +import * as React from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { useToast } from '@/components/ui/use-toast'; +import { cn } from '@/lib/utils'; + +interface UserFormProps extends React.HTMLAttributes { + onSubmit: (data: UserFormData) => Promise; + initialData?: UserFormData; +} + +interface UserFormData { + name: string; + email: string; +} + +export function UserForm({ + onSubmit, + initialData, + className, + ...props +}: UserFormProps) { + const [isLoading, setIsLoading] = React.useState(false); + const { toast } = useToast(); + + const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsLoading(true); + + try { + const formData = new FormData(event.currentTarget); + const data: UserFormData = { + name: formData.get('name') as string, + email: formData.get('email') as string + }; + + await onSubmit(data); + toast({ + title: 'Success', + description: 'User data saved successfully' + }); + } catch (error) { + toast({ + title: 'Error', + description: 'Failed to save user data', + variant: 'destructive' + }); + } finally { + setIsLoading(false); + } + }; + + return ( +
+
+ + +
+ +
+ ); +} +``` + +2. Hook Pattern: +```typescript +import * as React from 'react'; +import { useToast } from '@/components/ui/use-toast'; + +interface UseAsyncActionOptions { + onSuccess?: (data: T) => void; + onError?: (error: Error) => void; + successMessage?: string; + errorMessage?: string; +} + +export function useAsyncAction( + action: () => Promise, + options: UseAsyncActionOptions = {} +) { + const [isLoading, setIsLoading] = React.useState(false); + const { toast } = useToast(); + + const execute = React.useCallback(async () => { + setIsLoading(true); + + try { + const result = await action(); + + if (options.successMessage) { + toast({ + title: 'Success', + description: options.successMessage + }); + } + + options.onSuccess?.(result); + return result; + } catch (error) { + const errorMessage = error instanceof Error + ? error.message + : 'An error occurred'; + + if (options.errorMessage) { + toast({ + title: 'Error', + description: options.errorMessage, + variant: 'destructive' + }); + } + + options.onError?.(error as Error); + throw error; + } finally { + setIsLoading(false); + } + }, [action, options, toast]); + + return { + execute, + isLoading + }; +} +``` + +3. Dialog Pattern: +```typescript +import * as React from 'react'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; + +interface ConfirmDialogProps { + title: string; + description: string; + trigger: React.ReactNode; + onConfirm: () => Promise; +} + +export function ConfirmDialog({ + title, + description, + trigger, + onConfirm +}: ConfirmDialogProps) { + const [isOpen, setIsOpen] = React.useState(false); + const [isLoading, setIsLoading] = React.useState(false); + + const handleConfirm = async () => { + setIsLoading(true); + + try { + await onConfirm(); + setIsOpen(false); + } finally { + setIsLoading(false); + } + }; + + return ( + + + {trigger} + + + + {title} + + {description} + + + + + + + + + ); +} +``` + +// Best Practices: +1. Component Design: + - Single responsibility + - Proper prop types + - Error boundaries + - Loading states + - Accessibility + - Documentation + +2. State Management: + - Local vs global + - State updates + - Side effects + - Data fetching + - Caching + - Persistence + +3. Performance: + - Memoization + - Code splitting + - Bundle size + - Render cycles + - Event handling + - API calls + +4. Testing: + - Unit tests + - Integration tests + - Component tests + - Hook tests + - Mock data + - Coverage + +// Security Considerations: +1. Input Validation: + - Form data + - API responses + - URL parameters + - File uploads + - User input + - Type checking + +2. Authentication: + - Token handling + - Session management + - Protected routes + - Role-based access + - OAuth flows + - Security headers + +3. Data Protection: + - Sensitive data + - Local storage + - API security + - CORS policies + - XSS prevention + - CSRF protection \ No newline at end of file diff --git a/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules b/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules index 7ec3168..6868d52 100644 --- a/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules +++ b/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules @@ -1 +1,205 @@ -# System Prompt: Next.js 14 and Tailwind CSS Code Generation with TypeScriptYou are an AI assistant specialized in generating TypeScript code for Next.js 14 applications using Tailwind CSS. Your task is to analyze design screenshots and create corresponding TypeScript code that implements the design using Next.js 14 and Tailwind CSS, adhering to the latest best practices and standards.## Key Requirements:1. Use the App Router: All components should be created within the `app` directory, following Next.js 14 conventions.2. Implement Server Components by default: Only use Client Components when absolutely necessary for interactivity or client-side state management.3. Use modern TypeScript syntax: Employ current function declaration syntax and proper TypeScript typing for all components and functions.4. Follow responsive design principles: Utilize Tailwind CSS classes to ensure responsiveness across various screen sizes.5. Adhere to component-based architecture: Create modular, reusable components that align with the provided design sections.6. Implement efficient data fetching using server components and the `fetch` API with appropriate caching and revalidation strategies.7. Use Next.js 14's metadata API for SEO optimization.8. Employ Next.js Image component for optimized image loading.9. Ensure accessibility by using proper ARIA attributes and semantic HTML.10. Implement error handling using error boundaries and error.tsx files.11. Use loading.tsx files for managing loading states.12. Utilize route handlers (route.ts) for API routes in the App Router.13. Implement Static Site Generation (SSG) and Server-Side Rendering (SSR) using App Router conventions when appropriate.## Capabilities:1. Analyze design screenshots to understand layout, styling, and component structure.2. Generate TypeScript code for Next.js 14 components, including proper imports and export statements.3. Implement designs using Tailwind CSS classes for styling.4. Suggest appropriate Next.js features (e.g., Server Components, Client Components, API routes) based on the requirements.5. Provide a structured approach to building complex layouts, breaking them down into manageable components.6. Implement efficient data fetching, caching, and revalidation strategies.7. Optimize performance using Next.js built-in features and best practices.8. Integrate SEO best practices and metadata management.## Guidelines:1. Always use TypeScript for type safety. Provide appropriate type definitions and interfaces.2. Utilize Tailwind CSS classes exclusively for styling. Avoid inline styles.3. Implement components as functional components, using hooks when state management is required.4. Provide clear, concise comments explaining complex logic or design decisions.5. Suggest appropriate file structure and naming conventions aligned with Next.js 14 best practices.6. Assume the user has already set up the Next.js project with Tailwind CSS.7. Use environment variables for configuration following Next.js conventions.8. Implement performance optimizations such as code splitting, lazy loading, and parallel data fetching where appropriate.9. Ensure all components and pages are accessible, following WCAG guidelines.10. Utilize Next.js 14's built-in caching and revalidation features for optimal performance.11. When defining React components, avoid unnecessary type annotations and let TypeScript infer types when possible.12. Use `React.FC` or `React.ReactNode` for explicit typing only when necessary, avoiding `JSX.Element`.13. Write clean, concise component definitions without redundant type annotations.## Code Generation Rules:1. Use the `'use client'` directive only when creating Client Components.2. Employ the following component definition syntax in .tsx files, allowing TypeScript to infer the return type:     ```tsx  const ComponentName = () => {   // Component logic  };     ```   3. For props, use interface definitions:     ```tsx  interface ComponentNameProps {   // Props definition  }     const ComponentName = ({ prop1, prop2 }: ComponentNameProps) => {   // Component logic  };     ```   4. Use named exports for components in .tsx files:     ```tsx  export const ComponentName = () => {   // Component logic  };     ```   5. For page components, use default exports in .tsx files:     ```tsx  const Page = () => {   // Page component logic  };     export default Page;     ```   6. If explicit typing is needed, prefer `React.FC` or `React.ReactNode`:     ```tsx  import React from 'react';     const ComponentName: React.FC = () => {   // Component logic  };     // OR     const ComponentName = (): React.ReactNode => {   // Component logic  };     ```   7. For data fetching in server components (in .tsx files):     ```tsx  async function getData() {   const res = await fetch('', { next: { revalidate: 3600 } })   if (!res.ok) throw new Error('Failed to fetch data')   return res.json()  }     export default async function Page() {   const data = await getData()   // Render component using data  }     ```   8. For metadata (in .tsx files):     ```tsx  import type { Metadata } from 'next'     export const metadata: Metadata = {   title: 'Page Title',   description: 'Page description',  }     ```   9. For error handling (in error.tsx):     ```tsx  'use client'     export default function Error({   error,   reset,  }: {   error: Error & { digest?: string }   reset: () => void  }) {   return (    ## Response Format:1. Begin with a brief analysis of the provided design screenshot or description.2. Present the generated TypeScript code using the appropriate artifact format, organized by component or section as requested.3. Explain any significant design decisions or assumptions made during the code generation process.4. Offer suggestions for further improvements or optimizations, if applicable.5. Include suggestions for performance optimizations, focusing on efficient data fetching, caching, and revalidation strategies.6. Provide examples of how to implement data fetching, error handling, and loading states if applicable to the design.7. Suggest appropriate Tailwind CSS classes for styling, including responsive design considerations.Remember to adapt to the specific requirements and context provided by the user in each interaction, and always prioritize modern Next.js 14 and React best practices, especially regarding data fetching and performance optimization. Consistently use .ts for non-React files and .tsx for React components to take full advantage of TypeScript's type checking and other features. Emphasize clean, concise component definitions without unnecessary type annotations, letting TypeScript infer types when possible. \ No newline at end of file +// Next.js 14 and Tailwind CSS Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Next.js 14 application with: +- Server-side rendered pages +- SEO-optimized content +- Responsive layouts with Tailwind CSS +- Type-safe components with TypeScript +- Efficient data fetching +- Performance-optimized assets +- Accessible UI components +- API routes and handlers + +// Project Structure +app/ + layout.tsx # Root layout + page.tsx # Home page + components/ # Shared components + ui/ # UI components + layout/ # Layout components + lib/ # Utility functions + api/ # API routes + (routes)/ # App routes + about/ # About page + blog/ # Blog page + contact/ # Contact page + types/ # TypeScript types + styles/ # Global styles + public/ # Static assets + +// Development Guidelines +1. Next.js Patterns: + - Use App Router architecture + - Implement Server Components by default + - Use Client Components only when needed + - Follow proper routing conventions + - Implement proper metadata + - Use proper loading states + +2. TypeScript Best Practices: + - Use proper type definitions + - Implement proper interfaces + - Use proper type inference + - Follow naming conventions + - Implement proper generics + - Use proper utility types + +3. Tailwind CSS Usage: + - Use proper utility classes + - Implement responsive design + - Follow component patterns + - Use proper customization + - Implement proper theming + - Use proper variants + +// Dependencies +Core: +- next: "^14.0.0" +- react: "^18.2.0" +- react-dom: "^18.2.0" +- typescript: "^5.0.0" +- tailwindcss: "^3.3.0" +- @types/react: "^18.2.0" +- @types/node: "^20.0.0" + +Optional: +- @heroicons/react: "^2.0.0" +- clsx: "^2.0.0" +- tailwind-merge: "^2.0.0" +- @tailwindcss/forms: "^0.5.0" + +// Code Examples: + +1. Server Component Pattern: +```tsx +// app/page.tsx +import { Metadata } from 'next' + +export const metadata: Metadata = { + title: 'Home', + description: 'Welcome to our site' +} + +async function getData() { + const res = await fetch('https://api.example.com/data', { + next: { revalidate: 3600 } + }) + if (!res.ok) throw new Error('Failed to fetch data') + return res.json() +} + +export default async function HomePage() { + const data = await getData() + + return ( +
+

+ Welcome +

+ {/* Content */} +
+ ) +} +``` + +2. Client Component Pattern: +```tsx +// components/ui/Button.tsx +'use client' + +import { ButtonHTMLAttributes } from 'react' +import { cva, type VariantProps } from 'class-variance-authority' + +const buttonVariants = cva( + 'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50', + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground hover:bg-primary/90', + destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90', + outline: 'border border-input hover:bg-accent hover:text-accent-foreground', + }, + size: { + default: 'h-10 px-4 py-2', + sm: 'h-9 px-3', + lg: 'h-11 px-8', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + } +) + +interface ButtonProps + extends ButtonHTMLAttributes, + VariantProps {} + +export function Button({ className, variant, size, ...props }: ButtonProps) { + return ( + + + ); +} + +const root = createRoot(document.getElementById('root')!); +root.render(); +``` + +// Best Practices: +1. Security: + - Context isolation + - CSP headers + - Input validation + - Secure IPC + - File access + - Native APIs + +2. Architecture: + - Process separation + - Module patterns + - State management + - Error handling + - Event handling + - Resource cleanup + +3. Performance: + - Memory management + - IPC optimization + - Resource loading + - Background tasks + - Window lifecycle + - Event debouncing + +4. Distribution: + - Code signing + - Auto updates + - Installers + - Platform builds + - Release notes + - Update server + +// Security Considerations: +1. Process Security: + - Context isolation + - Preload scripts + - IPC validation + - CSP headers + - Permissions + - Sandboxing + +2. File System: + - Path validation + - Access control + - File operations + - Temp files + - User data + - Downloads + +3. Network Security: + - HTTPS only + - Certificate validation + - Content security + - API security + - Update security + - WebRTC \ No newline at end of file diff --git a/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules b/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules index da443d8..2b5dde5 100644 --- a/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules +++ b/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules @@ -1 +1,234 @@ -Act as an expert senior Elixir engineer.Stack: Elixir, Phoenix, Docker, PostgreSQL, Tailwind CSS, LeftHook, Sobelow, Credo, Ecto, ExUnit, Plug, Phoenix LiveView, Phoenix LiveDashboard, Gettext, Jason, Swoosh, Finch, DNS Cluster, File System Watcher, Release Please, ExCoveralls[optional scope]: [optional body][optional footer(s)]Where:type: One of the following:scope (optional): A noun describing a section of the codebase (e.g., fluxcd, deployment).description: A brief summary of the change in present tense.body (optional): A more detailed explanation of the change.footer (optional): One or more footers in the following format: \ No newline at end of file +// Elixir Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Elixir application with: +- Scalable web applications +- Real-time features +- Distributed systems +- Fault-tolerant services +- API endpoints +- Database integrations +- Background jobs +- Monitoring solutions + +// Project Structure +lib/ + my_app/ # Core application + application.ex # Application entry + supervisor.ex # Supervision tree + my_app_web/ # Web interface + controllers/ # Request handlers + views/ # View templates + live/ # LiveView modules + components/ # UI components + contexts/ # Business domains + accounts/ # User accounts + payments/ # Payment processing + workers/ # Background jobs + schemas/ # Database schemas + services/ # External services +config/ # Configuration + dev.exs # Development config + prod.exs # Production config + test.exs # Test config +priv/ # Private assets +test/ # Test files + +// Development Guidelines +1. Elixir Patterns: + - Use functional programming + - Implement proper supervision + - Handle concurrency properly + - Use pattern matching + - Implement error handling + - Follow OTP principles + +2. Phoenix Practices: + - Use proper contexts + - Implement LiveView + - Handle authentication + - Use proper channels + - Implement PubSub + - Follow conventions + +3. Code Organization: + - Separate concerns + - Use proper modules + - Implement testing + - Handle configuration + - Use proper documentation + - Follow standards + +// Dependencies +Core: +- elixir: "~> 1.15" +- phoenix: "~> 1.7" +- ecto: "~> 3.10" +- phoenix_live_view: "~> 0.20" +- postgrex: "~> 0.17" +- swoosh: "~> 1.11" + +Optional: +- credo: "~> 1.7" +- sobelow: "~> 0.13" +- excoveralls: "~> 0.18" +- ex_machina: "~> 2.7" + +// Code Examples: + +1. Context Pattern: +```elixir +# lib/my_app/accounts/accounts.ex +defmodule MyApp.Accounts do + @moduledoc """ + The Accounts context. + """ + + import Ecto.Query + alias MyApp.Repo + alias MyApp.Accounts.{User, UserToken} + + @doc """ + Gets a user by email. + """ + def get_user_by_email(email) when is_binary(email) do + Repo.get_by(User, email: email) + end + + @doc """ + Creates a user. + """ + def create_user(attrs \\ %{}) do + %User{} + |> User.registration_changeset(attrs) + |> Repo.insert() + end + + @doc """ + Authenticates a user by email and password. + """ + def authenticate_user(email, password) + when is_binary(email) and is_binary(password) do + user = get_user_by_email(email) + + cond do + user && User.valid_password?(user, password) -> + {:ok, user} + + user -> + {:error, :invalid_password} + + true -> + {:error, :invalid_email} + end + end +end +``` + +2. LiveView Pattern: +```elixir +# lib/my_app_web/live/user_live/index.ex +defmodule MyAppWeb.UserLive.Index do + use MyAppWeb, :live_view + + alias MyApp.Accounts + + @impl true + def mount(_params, _session, socket) do + if connected?(socket) do + Phoenix.PubSub.subscribe(MyApp.PubSub, "users") + end + + {:ok, assign(socket, users: list_users())} + end + + @impl true + def handle_event("delete", %{"id" => id}, socket) do + user = Accounts.get_user!(id) + {:ok, _} = Accounts.delete_user(user) + + {:noreply, assign(socket, users: list_users())} + end + + @impl true + def handle_info({:user_created, user}, socket) do + {:noreply, update(socket, :users, &[user | &1])} + end + + defp list_users do + Accounts.list_users() + end +end +``` + +3. GenServer Pattern: +```elixir +# lib/my_app/workers/email_worker.ex +defmodule MyApp.Workers.EmailWorker do + use GenServer + require Logger + + def start_link(opts) do + GenServer.start_link(__MODULE__, opts, name: __MODULE__) + end + + def send_email(to, subject, body) do + GenServer.cast(__MODULE__, {:send_email, to, subject, body}) + end + + @impl true + def init(opts) do + Process.flag(:trap_exit, true) + {:ok, opts} + end + + @impl true + def handle_cast({:send_email, to, subject, body}, state) do + try do + MyApp.Mailer.deliver_later(%{ + to: to, + subject: subject, + body: body + }) + + Logger.info("Email sent to #{to}") + rescue + e -> + Logger.error("Failed to send email: #{inspect(e)}") + end + + {:noreply, state} + end + + @impl true + def terminate(reason, _state) do + Logger.info("EmailWorker terminating: #{inspect(reason)}") + :ok + end +end +``` + +// Best Practices: +1. Follow functional paradigms +2. Use proper supervision +3. Handle concurrency properly +4. Implement proper testing +5. Use proper documentation +6. Handle errors gracefully +7. Follow OTP principles +8. Use proper contexts +9. Implement monitoring +10. Follow conventions + +// Security Considerations: +1. Validate user input +2. Use proper authentication +3. Implement authorization +4. Handle sensitive data +5. Use secure configs +6. Implement rate limiting +7. Handle errors securely +8. Use proper encryption +9. Follow security updates +10. Audit dependencies \ No newline at end of file diff --git a/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules b/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules index 7301e06..fa784f2 100644 --- a/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules +++ b/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules @@ -1 +1,207 @@ -Act as an expert senior Elixir engineer.Stack: Elixir, Phoenix, Docker, PostgreSQL, Tailwind CSS, LeftHook, Sobelow, Credo, Ecto, ExUnit, Plug, Phoenix LiveView, Phoenix LiveDashboard, Gettext, Jason, Swoosh, Finch, DNS Cluster, File System Watcher, Release Please, ExCoveralls- When writing code, you will think through any considerations or requirements to make sure we've thought of everything. Only after that do you write the code.- After a response, provide three follow-up questions worded as if I'm asking you. Format in bold as Q1, Q2, Q3. These questions should be throught-provoking and dig further into the original topic. - If my response starts with "VV", give the most succinct, concise, shortest answer possible.## Commit Message Guidelines:- Always suggest a conventional commit message with an optional scope in lowercase. Follow this structure:[optional scope]: [optional body][optional footer(s)]Where:- **type:** One of the following:  - `build`: Changes that affect the build system or external dependencies (e.g., Maven, npm)  - `chore`: Other changes that don't modify src or test files  - `ci`: Changes to our CI configuration files and scripts (e.g., Circle, BrowserStack, SauceLabs)  - `docs`: Documentation only changes  - `feat`: A new feature  - `fix`: A bug fix  - `perf`: A code change that improves performance   - `refactor`: A code change that neither fixes a bug nor adds a feature  - `style`: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)  - `test`: Adding missing tests or correcting existing tests - **scope (optional):** A noun describing a section of the codebase (e.g., `fluxcd`, `deployment`).- **description:** A brief summary of the change in present tense.- **body (optional):** A more detailed explanation of the change.- **footer (optional):** One or more footers in the following format:  - `BREAKING CHANGE: ` (for breaking changes)  - `: ` (e.g., `Jira-123: Fixed bug in authentication`) \ No newline at end of file +// Elixir Phoenix Docker Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern containerized Phoenix application with: +- Docker-based development +- Production deployments +- Database integration +- Asset compilation +- LiveView support +- Monitoring setup +- CI/CD pipelines +- Multi-stage builds + +// Project Structure +. +├── Dockerfile # Multi-stage Dockerfile +├── docker-compose.yml # Development setup +├── .dockerignore # Docker ignore rules +├── config/ # Phoenix config +│ ├── dev.exs # Development config +│ └── prod.exs # Production config +├── lib/ # Application code +├── rel/ # Release config +│ └── env.sh.eex # Environment setup +├── assets/ # Frontend assets +└── scripts/ # Docker scripts + ├── entrypoint.sh # Container entry + └── migrate.sh # DB migrations + +// Development Guidelines +1. Docker Setup: + - Use multi-stage builds + - Implement proper caching + - Handle dependencies + - Configure networking + - Manage volumes + - Set environment + +2. Phoenix Configuration: + - Handle secrets + - Configure database + - Set up assets + - Manage releases + - Configure ports + - Handle SSL + +3. Deployment Practices: + - Use proper tagging + - Implement healthchecks + - Handle migrations + - Configure logging + - Manage backups + - Monitor resources + +// Dependencies +Core: +- elixir: "~> 1.15" +- phoenix: "~> 1.7" +- docker: "^24.0" +- postgres: "^15.0" +- node: "^20.0" + +Optional: +- docker-compose: "^2.21" +- nginx: "^1.25" +- prometheus: "^2.47" +- grafana: "^10.1" + +// Code Examples: + +1. Dockerfile Pattern: +```dockerfile +# Dockerfile +# Build stage +FROM hexpm/elixir:1.15.7-erlang-26.1.2-alpine-3.18.4 AS builder + +# Install build dependencies +RUN apk add --no-cache build-base npm git python3 + +WORKDIR /app + +# Install hex + rebar +RUN mix local.hex --force && \ + mix local.rebar --force + +# Set build ENV +ENV MIX_ENV=prod + +# Install mix dependencies +COPY mix.exs mix.lock ./ +RUN mix deps.get --only $MIX_ENV +RUN mix deps.compile + +# Build assets +COPY assets assets +RUN npm --prefix assets ci --progress=false --no-audit --loglevel=error +RUN npm run --prefix assets deploy +RUN mix phx.digest + +# Compile and build release +COPY . . +RUN mix compile +RUN mix release + +# Release stage +FROM alpine:3.18.4 AS app +RUN apk add --no-cache openssl ncurses-libs + +WORKDIR /app + +RUN chown nobody:nobody /app + +USER nobody:nobody + +COPY --from=builder --chown=nobody:nobody /app/_build/prod/rel/my_app ./ + +ENV HOME=/app +ENV MIX_ENV=prod +ENV PORT=4000 + +CMD ["bin/my_app", "start"] +``` + +2. Docker Compose Pattern: +```yaml +# docker-compose.yml +version: '3.8' + +services: + app: + build: + context: . + target: builder + ports: + - "4000:4000" + environment: + - DATABASE_URL=ecto://postgres:postgres@db/my_app_dev + - SECRET_KEY_BASE=your_development_key + volumes: + - .:/app + - build:/app/_build + - deps:/app/deps + depends_on: + - db + command: mix phx.server + + db: + image: postgres:15-alpine + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=postgres + volumes: + - postgres_data:/var/lib/postgresql/data + +volumes: + postgres_data: + build: + deps: +``` + +3. Release Configuration Pattern: +```elixir +# rel/env.sh.eex +#!/bin/sh + +# Sets and enables heart (recommended only in daemon mode) +# if [ "$RELEASE_COMMAND" = "daemon" ] || [ "$RELEASE_COMMAND" = "daemon_iex" ]; then +# HEART_COMMAND="$RELEASE_ROOT/bin/$RELEASE_NAME $RELEASE_COMMAND" +# export HEART_COMMAND +# export ELIXIR_ERL_OPTIONS="-heart" +# fi + +# Set the release to work across nodes +export RELEASE_DISTRIBUTION=name +export RELEASE_NODE=<%= @release.name %>@127.0.0.1 + +# Set database configuration +export DATABASE_URL="${DATABASE_URL}" +export SECRET_KEY_BASE="${SECRET_KEY_BASE}" +export PHX_HOST="${PHX_HOST}" +export PORT="${PORT}" +``` + +// Best Practices: +1. Use multi-stage builds +2. Implement proper caching +3. Handle secrets securely +4. Configure healthchecks +5. Manage dependencies +6. Handle migrations +7. Configure logging +8. Use proper networking +9. Implement monitoring +10. Follow conventions + +// Security Considerations: +1. Secure secrets management +2. Use proper permissions +3. Scan dependencies +4. Configure firewalls +5. Handle SSL/TLS +6. Implement CORS +7. Update base images +8. Secure networking +9. Monitor containers +10. Audit configurations \ No newline at end of file diff --git a/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules b/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules index 778f386..af1f866 100644 --- a/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules +++ b/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules @@ -1 +1,226 @@ -## General- Follow best practices, lean towards agile methodologies- Prioritize modularity, DRY, performance, and security- First break tasks into distinct prioritized steps, then follow the steps- Prioritize tasks/steps you’ll address in each response don't repeat yourself- keep responses very short, unless I include a Vx value : - V0 default, code golf - V1 concise - V2 simple - V3 verbose, DRY with extracted functions## Code- use ES module syntax- where appropriate suggest refactorings and code improvements- favor using the latest ES and nodejs features- Don’t apologize for errors: fix them* If you can’t finish code, add TODO: comments## Comments- Comments should be created where the operation isn't clear from the code, or where uncommon libraries are used- Code must start with path/filename as a one-line comment- Comments should describe purpose, not effect \ No newline at end of file +// ES Module Node.js Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Node.js application with: +- ES Module architecture +- Modular components +- Async operations +- Type safety +- Performance optimization +- Error handling +- Testing infrastructure +- Development tooling + +// Project Structure +src/ + index.js # Entry point + modules/ # ES modules + core/ # Core modules + utils/ # Utilities + services/ # Services + config/ # Configuration + env.js # Environment + constants.js # Constants + middleware/ # Middleware + models/ # Data models + tests/ # Test files + unit/ # Unit tests + integration/ # Integration tests + types/ # Type definitions + docs/ # Documentation + +// Development Guidelines +1. Module Patterns: + - Use ES module syntax + - Implement pure functions + - Handle async properly + - Use type annotations + - Follow conventions + - Manage dependencies + +2. Code Organization: + - Separate concerns + - Use proper imports + - Handle errors + - Implement testing + - Document code + - Follow standards + +3. Performance Practices: + - Optimize imports + - Handle async ops + - Manage memory + - Use proper caching + - Monitor performance + - Profile code + +// Dependencies +Core: +- node: "^20.0.0" +- typescript: "^5.2.0" +- jest: "^29.7.0" +- eslint: "^8.53.0" +- prettier: "^3.1.0" + +Optional: +- nodemon: "^3.0.1" +- ts-node: "^10.9.0" +- dotenv: "^16.3.0" +- winston: "^3.11.0" + +// Code Examples: + +1. ES Module Pattern: +```javascript +// src/modules/core/user.js +import { validateEmail } from '../utils/validators.js'; +import { DatabaseError } from '../utils/errors.js'; + +export class User { + #email; + #name; + + constructor(name, email) { + this.#validateInputs(name, email); + this.#name = name; + this.#email = email; + } + + #validateInputs(name, email) { + if (!name?.trim()) { + throw new Error('Name is required'); + } + if (!validateEmail(email)) { + throw new Error('Invalid email format'); + } + } + + static async findByEmail(email) { + try { + const user = await db.users.findOne({ email }); + return user ? new User(user.name, user.email) : null; + } catch (error) { + throw new DatabaseError('Failed to fetch user', error); + } + } + + toJSON() { + return { + name: this.#name, + email: this.#email + }; + } +} +``` + +2. Service Pattern: +```javascript +// src/services/auth.js +import { User } from '../modules/core/user.js'; +import { generateToken } from '../utils/jwt.js'; +import { AuthError } from '../utils/errors.js'; + +export class AuthService { + static async authenticate(email, password) { + try { + const user = await User.findByEmail(email); + + if (!user) { + throw new AuthError('User not found'); + } + + const isValid = await user.validatePassword(password); + if (!isValid) { + throw new AuthError('Invalid password'); + } + + const token = generateToken(user.toJSON()); + return { user, token }; + } catch (error) { + if (error instanceof AuthError) { + throw error; + } + throw new Error('Authentication failed'); + } + } + + static async validateToken(token) { + try { + const payload = verifyToken(token); + const user = await User.findByEmail(payload.email); + return user; + } catch (error) { + throw new AuthError('Invalid token'); + } + } +} +``` + +3. Utility Pattern: +```javascript +// src/utils/async-handler.js +export const asyncHandler = (fn) => { + return async (req, res, next) => { + try { + await fn(req, res, next); + } catch (error) { + next(error); + } + }; +}; + +export const withTransaction = async (fn) => { + const session = await startSession(); + try { + session.startTransaction(); + const result = await fn(session); + await session.commitTransaction(); + return result; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +}; + +export const memoize = (fn) => { + const cache = new Map(); + + return (...args) => { + const key = JSON.stringify(args); + if (cache.has(key)) { + return cache.get(key); + } + + const result = fn.apply(this, args); + cache.set(key, result); + return result; + }; +}; +``` + +// Best Practices: +1. Use ES module syntax +2. Implement proper typing +3. Handle errors gracefully +4. Use async/await +5. Implement testing +6. Document code properly +7. Follow conventions +8. Optimize imports +9. Handle security +10. Monitor performance + +// Security Considerations: +1. Validate input +2. Handle authentication +3. Implement authorization +4. Secure data +5. Use proper encryption +6. Handle secrets +7. Validate dependencies +8. Implement logging +9. Handle errors securely +10. Follow updates \ No newline at end of file diff --git a/rules/express-typescript-cursorrules-prompt-file/.cursorrules b/rules/express-typescript-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..9b4896f --- /dev/null +++ b/rules/express-typescript-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,300 @@ +// Express TypeScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Node.js web application using Express and TypeScript: +- RESTful APIs +- GraphQL APIs +- Authentication +- Authorization +- Database integration +- File uploads +- WebSocket support +- Background jobs + +// Project Structure +src/ + api/ # API routes + controllers/ # Route controllers + middleware/ # Custom middleware + validators/ # Request validation + routes/ # Route definitions + config/ # Configuration + database.ts # Database config + server.ts # Server config + logger.ts # Logging config + models/ # Data models + entities/ # Database entities + dtos/ # Data transfer objects + services/ # Business logic + auth/ # Authentication + email/ # Email service + storage/ # File storage + utils/ # Utilities + errors/ # Error handlers + logger/ # Logging utils + validation/ # Validation utils + types/ # Type definitions + app.ts # Express app + server.ts # Entry point +tests/ # Test suite + unit/ # Unit tests + integration/ # Integration tests + e2e/ # End-to-end tests + +// Development Guidelines +1. API Design: + - RESTful principles + - Resource naming + - Status codes + - Error handling + - Rate limiting + - Documentation + +2. Code Structure: + - Dependency injection + - Service layer + - Repository pattern + - Error handling + - Validation + - Logging + +3. Performance: + - Caching + - Database queries + - Memory usage + - Response time + - Compression + - Monitoring + +// Dependencies +Core: +- express: "^4.18.0" +- typescript: "^5.0.0" +- @types/express: "^4.17.17" +- @types/node: "^18.16.0" + +Optional: +- express-validator: "^7.0.0" +- express-rate-limit: "^6.7.0" +- helmet: "^7.0.0" +- compression: "^1.7.4" + +// Code Examples: + +1. Controller Pattern: +```typescript +import { Request, Response, NextFunction } from 'express'; +import { UserService } from '@/services/user.service'; +import { CreateUserDto, UpdateUserDto } from '@/models/dtos/user.dto'; +import { ApiError } from '@/utils/errors/api-error'; +import { Logger } from '@/utils/logger'; + +export class UserController { + constructor( + private userService: UserService, + private logger: Logger + ) {} + + async create(req: Request, res: Response, next: NextFunction) { + try { + const dto = new CreateUserDto(req.body); + const user = await this.userService.create(dto); + + this.logger.info('User created', { userId: user.id }); + res.status(201).json(user); + } catch (error) { + this.logger.error('Failed to create user', { error }); + next(new ApiError(400, 'Failed to create user')); + } + } + + async update(req: Request, res: Response, next: NextFunction) { + try { + const { id } = req.params; + const dto = new UpdateUserDto(req.body); + const user = await this.userService.update(id, dto); + + if (!user) { + throw new ApiError(404, 'User not found'); + } + + this.logger.info('User updated', { userId: id }); + res.json(user); + } catch (error) { + this.logger.error('Failed to update user', { error, userId: req.params.id }); + next(error); + } + } + + async delete(req: Request, res: Response, next: NextFunction) { + try { + const { id } = req.params; + await this.userService.delete(id); + + this.logger.info('User deleted', { userId: id }); + res.status(204).send(); + } catch (error) { + this.logger.error('Failed to delete user', { error, userId: req.params.id }); + next(error); + } + } +} +``` + +2. Service Pattern: +```typescript +import { Injectable } from '@/utils/di'; +import { UserRepository } from '@/models/repositories/user.repository'; +import { CreateUserDto, UpdateUserDto } from '@/models/dtos/user.dto'; +import { User } from '@/models/entities/user.entity'; +import { ApiError } from '@/utils/errors/api-error'; +import { Logger } from '@/utils/logger'; + +@Injectable() +export class UserService { + constructor( + private userRepository: UserRepository, + private logger: Logger + ) {} + + async create(dto: CreateUserDto): Promise { + const existingUser = await this.userRepository.findByEmail(dto.email); + + if (existingUser) { + throw new ApiError(400, 'Email already exists'); + } + + const user = new User(dto); + await this.userRepository.save(user); + + this.logger.info('User created in service', { userId: user.id }); + return user; + } + + async update(id: string, dto: UpdateUserDto): Promise { + const user = await this.userRepository.findById(id); + + if (!user) { + return null; + } + + Object.assign(user, dto); + await this.userRepository.save(user); + + this.logger.info('User updated in service', { userId: id }); + return user; + } + + async delete(id: string): Promise { + const user = await this.userRepository.findById(id); + + if (!user) { + throw new ApiError(404, 'User not found'); + } + + await this.userRepository.delete(id); + this.logger.info('User deleted in service', { userId: id }); + } +} +``` + +3. Middleware Pattern: +```typescript +import { Request, Response, NextFunction } from 'express'; +import { verify } from 'jsonwebtoken'; +import { ApiError } from '@/utils/errors/api-error'; +import { Logger } from '@/utils/logger'; +import { config } from '@/config'; + +export class AuthMiddleware { + constructor(private logger: Logger) {} + + async authenticate(req: Request, res: Response, next: NextFunction) { + try { + const token = this.extractToken(req); + + if (!token) { + throw new ApiError(401, 'No token provided'); + } + + const decoded = verify(token, config.jwt.secret); + req.user = decoded; + + this.logger.debug('User authenticated', { userId: decoded.sub }); + next(); + } catch (error) { + this.logger.error('Authentication failed', { error }); + next(new ApiError(401, 'Invalid token')); + } + } + + private extractToken(req: Request): string | null { + const authHeader = req.headers.authorization; + + if (!authHeader || !authHeader.startsWith('Bearer ')) { + return null; + } + + return authHeader.split(' ')[1]; + } +} +``` + +// Best Practices: +1. Code Quality: + - Type safety + - Error handling + - Input validation + - Documentation + - Testing + - Logging + +2. Architecture: + - Layered design + - Dependency injection + - Repository pattern + - Service pattern + - Middleware + - Error handling + +3. Performance: + - Query optimization + - Caching strategy + - Connection pooling + - Memory management + - Response time + - Monitoring + +4. Security: + - Authentication + - Authorization + - Input validation + - Rate limiting + - Headers security + - CORS policy + +// Security Considerations: +1. API Security: + - Input validation + - Rate limiting + - Authentication + - Authorization + - CORS policy + - Security headers + +2. Data Security: + - Encryption + - Password hashing + - Data validation + - SQL injection + - XSS prevention + - CSRF protection + +3. Infrastructure: + - HTTPS + - Firewalls + - Monitoring + - Logging + - Backups + - Updates \ No newline at end of file diff --git a/rules/fastapi-python-cursorrules-prompt-file/.cursorrules b/rules/fastapi-python-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..1862c85 --- /dev/null +++ b/rules/fastapi-python-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,263 @@ +// FastAPI Python Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Python web API using FastAPI: +- RESTful APIs +- GraphQL APIs +- WebSocket endpoints +- Background tasks +- File operations +- Database integration +- Authentication +- Documentation + +// Project Structure +src/ + api/ # API endpoints + v1/ # API version 1 + endpoints/ # Route handlers + schemas/ # Pydantic models + deps/ # Dependencies + middleware/ # Custom middleware + core/ # Core modules + config.py # Configuration + security.py # Security utils + logging.py # Logging setup + db/ # Database + models/ # SQLAlchemy models + migrations/ # Alembic migrations + session.py # DB session + services/ # Business logic + auth.py # Auth service + email.py # Email service + storage.py # Storage service + utils/ # Utilities + validators.py # Custom validators + helpers.py # Helper functions + main.py # Application entry +tests/ # Test suite + api/ # API tests + services/ # Service tests + conftest.py # Test fixtures + +// Development Guidelines +1. API Design: + - Type hints + - Pydantic models + - Path operations + - Query params + - Request body + - Response models + +2. Code Structure: + - Dependency injection + - Service layer + - Repository pattern + - Error handling + - Validation + - Logging + +3. Performance: + - Async operations + - Database queries + - Caching + - Background tasks + - Resource cleanup + - Monitoring + +// Dependencies +Core: +- fastapi: "^0.100.0" +- uvicorn: "^0.22.0" +- pydantic: "^2.0.0" +- sqlalchemy: "^2.0.0" + +Optional: +- alembic: "^1.11.0" +- python-jose: "^3.3.0" +- passlib: "^1.7.4" +- python-multipart: "^0.0.6" + +// Code Examples: + +1. Router Pattern: +```python +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import get_db +from app.schemas.user import UserCreate, UserResponse +from app.services.user import UserService + +router = APIRouter(prefix="/users", tags=["users"]) + +@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED) +async def create_user( + user_in: UserCreate, + db: AsyncSession = Depends(get_db), + user_service: UserService = Depends() +): + try: + user = await user_service.create(db, user_in) + return user + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=str(e) + ) + +@router.get("/{user_id}", response_model=UserResponse) +async def get_user( + user_id: int, + db: AsyncSession = Depends(get_db), + user_service: UserService = Depends() +): + user = await user_service.get(db, user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + return user +``` + +2. Service Pattern: +```python +from typing import Optional +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from app.db.models.user import User +from app.schemas.user import UserCreate +from app.core.security import get_password_hash + +class UserService: + async def create( + self, + db: AsyncSession, + user_in: UserCreate + ) -> User: + # Check if user exists + result = await db.execute( + select(User).where(User.email == user_in.email) + ) + if result.scalar_one_or_none(): + raise ValueError("Email already registered") + + # Create new user + user = User( + email=user_in.email, + hashed_password=get_password_hash(user_in.password), + full_name=user_in.full_name + ) + db.add(user) + await db.commit() + await db.refresh(user) + return user + + async def get( + self, + db: AsyncSession, + user_id: int + ) -> Optional[User]: + result = await db.execute( + select(User).where(User.id == user_id) + ) + return result.scalar_one_or_none() + + async def authenticate( + self, + db: AsyncSession, + email: str, + password: str + ) -> Optional[User]: + user = await self.get_by_email(db, email) + if not user or not verify_password(password, user.hashed_password): + return None + return user +``` + +3. Schema Pattern: +```python +from datetime import datetime +from typing import Optional +from pydantic import BaseModel, EmailStr, Field + +class UserBase(BaseModel): + email: EmailStr + full_name: str = Field(..., min_length=1, max_length=100) + is_active: bool = True + +class UserCreate(UserBase): + password: str = Field(..., min_length=8) + +class UserUpdate(UserBase): + password: Optional[str] = Field(None, min_length=8) + +class UserResponse(UserBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True +``` + +// Best Practices: +1. Code Quality: + - Type hints + - Documentation + - Error handling + - Input validation + - Testing + - Logging + +2. Architecture: + - Layered design + - Dependency injection + - Repository pattern + - Service pattern + - Event handling + - Error handling + +3. Performance: + - Query optimization + - Caching strategy + - Connection pooling + - Memory management + - Response time + - Monitoring + +4. Security: + - Authentication + - Authorization + - Input validation + - Rate limiting + - Headers security + - CORS policy + +// Security Considerations: +1. API Security: + - Input validation + - Rate limiting + - Authentication + - Authorization + - CORS policy + - Security headers + +2. Data Security: + - Encryption + - Password hashing + - Data validation + - SQL injection + - XSS prevention + - CSRF protection + +3. Infrastructure: + - HTTPS + - Firewalls + - Monitoring + - Logging + - Backups + - Updates \ No newline at end of file diff --git a/rules/flask-python-cursorrules-prompt-file/.cursorrules b/rules/flask-python-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..48982d2 --- /dev/null +++ b/rules/flask-python-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,269 @@ +// Flask Python Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Python web application using Flask: +- Web applications +- RESTful APIs +- Admin interfaces +- Authentication +- File uploads +- Database integration +- Background tasks +- Email handling + +// Project Structure +project/ + app/ # Application package + templates/ # Jinja2 templates + static/ # Static files + models/ # Database models + views/ # View functions + admin/ # Admin views + auth/ # Auth views + main/ # Main views + forms/ # WTForms classes + utils/ # Utility modules + extensions.py # Flask extensions + config.py # Configuration + migrations/ # Database migrations + tests/ # Test suite + unit/ # Unit tests + integration/ # Integration tests + conftest.py # Test fixtures + instance/ # Instance config + logs/ # Log files + requirements/ # Dependencies + dev.txt # Development deps + prod.txt # Production deps + wsgi.py # WSGI entry point + +// Development Guidelines +1. Application Structure: + - Blueprints + - Extensions + - Models + - Views + - Forms + - Templates + +2. Code Organization: + - Dependency injection + - Service layer + - Repository pattern + - Error handling + - Validation + - Logging + +3. Performance: + - Caching + - Database queries + - Asset bundling + - Response time + - Memory usage + - Monitoring + +// Dependencies +Core: +- flask: "^2.3.0" +- flask-sqlalchemy: "^3.0.0" +- flask-migrate: "^4.0.0" +- flask-login: "^0.6.0" + +Optional: +- flask-admin: "^1.6.0" +- flask-wtf: "^1.1.0" +- flask-mail: "^0.9.0" +- celery: "^5.3.0" + +// Code Examples: + +1. View Pattern: +```python +from flask import Blueprint, render_template, flash, redirect, url_for +from flask_login import login_required, current_user + +from app.forms.post import PostForm +from app.models.post import Post +from app.extensions import db +from app.utils.decorators import admin_required + +bp = Blueprint('blog', __name__) + +@bp.route('/posts') +def list_posts(): + """List all blog posts.""" + posts = Post.query.order_by(Post.created_at.desc()).all() + return render_template('blog/list.html', posts=posts) + +@bp.route('/posts/new', methods=['GET', 'POST']) +@login_required +def create_post(): + """Create a new blog post.""" + form = PostForm() + if form.validate_on_submit(): + post = Post( + title=form.title.data, + content=form.content.data, + author=current_user + ) + db.session.add(post) + db.session.commit() + flash('Post created successfully.', 'success') + return redirect(url_for('blog.list_posts')) + return render_template('blog/create.html', form=form) + +@bp.route('/posts//edit', methods=['GET', 'POST']) +@login_required +@admin_required +def edit_post(id): + """Edit an existing blog post.""" + post = Post.query.get_or_404(id) + form = PostForm(obj=post) + + if form.validate_on_submit(): + post.title = form.title.data + post.content = form.content.data + db.session.commit() + flash('Post updated successfully.', 'success') + return redirect(url_for('blog.list_posts')) + + return render_template('blog/edit.html', form=form, post=post) +``` + +2. Model Pattern: +```python +from datetime import datetime +from app.extensions import db +from app.utils.slugify import slugify + +class Post(db.Model): + """Blog post model.""" + + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String(200), nullable=False) + slug = db.Column(db.String(200), unique=True, nullable=False) + content = db.Column(db.Text, nullable=False) + created_at = db.Column(db.DateTime, default=datetime.utcnow) + updated_at = db.Column( + db.DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow + ) + author_id = db.Column( + db.Integer, + db.ForeignKey('user.id'), + nullable=False + ) + + # Relationships + author = db.relationship('User', back_populates='posts') + comments = db.relationship( + 'Comment', + back_populates='post', + cascade='all, delete-orphan' + ) + + def __init__(self, **kwargs): + """Create instance.""" + super(Post, self).__init__(**kwargs) + if self.title: + self.slug = slugify(self.title) + + def __repr__(self): + """Represent instance as a string.""" + return f'' + + @property + def url(self): + """Get URL for post.""" + return url_for('blog.show_post', slug=self.slug) +``` + +3. Form Pattern: +```python +from flask_wtf import FlaskForm +from wtforms import StringField, TextAreaField, BooleanField +from wtforms.validators import DataRequired, Length, Email + +class PostForm(FlaskForm): + """Form for creating or editing a blog post.""" + + title = StringField( + 'Title', + validators=[ + DataRequired(), + Length(min=3, max=200) + ] + ) + + content = TextAreaField( + 'Content', + validators=[DataRequired()] + ) + + is_published = BooleanField('Publish?', default=True) + + def validate_title(self, field): + """Custom validation for title.""" + if Post.query.filter_by(title=field.data).first(): + raise ValidationError('Title must be unique.') +``` + +// Best Practices: +1. Code Quality: + - Documentation + - Type hints + - Error handling + - Input validation + - Testing + - Logging + +2. Architecture: + - Blueprints + - Extensions + - Models + - Services + - Forms + - Templates + +3. Performance: + - Query optimization + - Caching strategy + - Asset bundling + - Response time + - Memory usage + - Monitoring + +4. Security: + - Authentication + - Authorization + - CSRF protection + - XSS prevention + - Input validation + - Session security + +// Security Considerations: +1. Application Security: + - Input validation + - CSRF protection + - XSS prevention + - Session security + - Password hashing + - Access control + +2. Data Security: + - SQL injection + - Data validation + - File uploads + - User data + - Backups + - Encryption + +3. Infrastructure: + - HTTPS + - Firewalls + - Monitoring + - Logging + - Updates + - Deployment \ No newline at end of file diff --git a/rules/flutter-dart-cursorrules-prompt-file/.cursorrules b/rules/flutter-dart-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..e3e9075 --- /dev/null +++ b/rules/flutter-dart-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,335 @@ +// Flutter Dart Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern cross-platform mobile application using Flutter: +- Material Design apps +- iOS-style apps +- Custom UI/UX +- State management +- API integration +- Local storage +- Push notifications +- Animations + +// Project Structure +lib/ + core/ # Core functionality + constants/ # App constants + theme/ # App theme + utils/ # Utilities + data/ # Data layer + models/ # Data models + repositories/ # Data repositories + services/ # API services + domain/ # Business logic + entities/ # Business entities + usecases/ # Business use cases + presentation/ # UI layer + screens/ # App screens + widgets/ # Reusable widgets + blocs/ # State management + app.dart # App entry point +test/ # Test suite + unit/ # Unit tests + widget/ # Widget tests + integration/ # Integration tests +assets/ # App assets + images/ # Image files + fonts/ # Font files + icons/ # Icon files + +// Development Guidelines +1. UI Development: + - Widget composition + - State management + - Navigation + - Theming + - Responsive design + - Accessibility + +2. Code Structure: + - Clean architecture + - SOLID principles + - Dependency injection + - Error handling + - Logging + - Testing + +3. Performance: + - Widget rebuilds + - Memory usage + - Image optimization + - Animation smoothness + - App size + - Loading time + +// Dependencies +Core: +- flutter_sdk: "^3.10.0" +- provider: "^6.0.0" +- dio: "^5.0.0" +- hive: "^2.2.0" + +Optional: +- flutter_bloc: "^8.1.0" +- get_it: "^7.6.0" +- injectable: "^2.1.0" +- freezed: "^2.3.0" + +// Code Examples: + +1. Widget Pattern: +```dart +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ProductList extends StatelessWidget { + const ProductList({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, provider, child) { + if (provider.isLoading) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + if (provider.error != null) { + return Center( + child: Text( + 'Error: ${provider.error}', + style: Theme.of(context).textTheme.bodyLarge?.copyWith( + color: Colors.red, + ), + ), + ); + } + + return ListView.builder( + itemCount: provider.products.length, + itemBuilder: (context, index) { + final product = provider.products[index]; + return ProductCard( + product: product, + onTap: () => Navigator.pushNamed( + context, + '/product-details', + arguments: product, + ), + ); + }, + ); + }, + ); + } +} + +class ProductCard extends StatelessWidget { + final Product product; + final VoidCallback onTap; + + const ProductCard({ + Key? key, + required this.product, + required this.onTap, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return Card( + elevation: 2, + margin: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: ListTile( + leading: Hero( + tag: 'product-${product.id}', + child: Image.network( + product.imageUrl, + width: 56, + height: 56, + fit: BoxFit.cover, + ), + ), + title: Text(product.name), + subtitle: Text( + '\$${product.price.toStringAsFixed(2)}', + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Colors.green, + ), + ), + trailing: const Icon(Icons.chevron_right), + onTap: onTap, + ), + ); + } +} +``` + +2. Provider Pattern: +```dart +import 'package:flutter/foundation.dart'; +import 'package:dio/dio.dart'; + +class ProductsProvider with ChangeNotifier { + final ProductRepository _repository; + List _products = []; + bool _isLoading = false; + String? _error; + + ProductsProvider(this._repository); + + List get products => _products; + bool get isLoading => _isLoading; + String? get error => _error; + + Future fetchProducts() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + _products = await _repository.getProducts(); + } on DioError catch (e) { + _error = e.message; + } catch (e) { + _error = 'An unexpected error occurred'; + } finally { + _isLoading = false; + notifyListeners(); + } + } + + Future addProduct(Product product) async { + _isLoading = true; + notifyListeners(); + + try { + final newProduct = await _repository.addProduct(product); + _products.add(newProduct); + } catch (e) { + _error = 'Failed to add product'; + } finally { + _isLoading = false; + notifyListeners(); + } + } +} +``` + +3. Repository Pattern: +```dart +import 'package:dio/dio.dart'; +import 'package:injectable/injectable.dart'; + +@injectable +class ProductRepository { + final Dio _dio; + final String _baseUrl; + + ProductRepository( + this._dio, + @Named('baseUrl') this._baseUrl, + ); + + Future> getProducts() async { + try { + final response = await _dio.get('$_baseUrl/products'); + return (response.data as List) + .map((json) => Product.fromJson(json)) + .toList(); + } on DioError { + rethrow; + } catch (e) { + throw Exception('Failed to fetch products'); + } + } + + Future getProduct(String id) async { + try { + final response = await _dio.get('$_baseUrl/products/$id'); + return Product.fromJson(response.data); + } on DioError { + rethrow; + } catch (e) { + throw Exception('Failed to fetch product'); + } + } + + Future addProduct(Product product) async { + try { + final response = await _dio.post( + '$_baseUrl/products', + data: product.toJson(), + ); + return Product.fromJson(response.data); + } on DioError { + rethrow; + } catch (e) { + throw Exception('Failed to add product'); + } + } +} +``` + +// Best Practices: +1. Code Quality: + - Documentation + - Type safety + - Error handling + - Testing + - Logging + - Code style + +2. Architecture: + - Clean architecture + - SOLID principles + - Dependency injection + - State management + - Navigation + - Error handling + +3. Performance: + - Widget optimization + - Memory management + - Image caching + - Lazy loading + - Build methods + - State updates + +4. UI/UX: + - Material Design + - iOS guidelines + - Responsive design + - Accessibility + - Animations + - User feedback + +// Security Considerations: +1. Data Security: + - Secure storage + - API security + - Input validation + - Authentication + - Authorization + - Encryption + +2. Code Security: + - Dependencies + - Platform channels + - Web security + - Deep links + - File access + - Permissions + +3. Network Security: + - HTTPS + - Certificate pinning + - API tokens + - OAuth flows + - Rate limiting + - Request signing \ No newline at end of file diff --git a/rules/github-code-quality-cursorrules-prompt-file/.cursorrules b/rules/github-code-quality-cursorrules-prompt-file/.cursorrules index bdf63cb..7690372 100644 --- a/rules/github-code-quality-cursorrules-prompt-file/.cursorrules +++ b/rules/github-code-quality-cursorrules-prompt-file/.cursorrules @@ -1 +1,156 @@ -{"rules": [{"name": "Verify Information","pattern": "(?i)\b(assume|assumption|guess|speculate)\b","message": "Always verify information before presenting it. Do not make assumptions or speculate without clear evidence."},{"name": "File-by-File Changes","pattern": "// MULTI-FILE CHANGE:","message": "Make changes file by file and give me a chance to spot mistakes"},{"name": "No Apologies","pattern": "(?i)\b(sorry|apologize|apologies)\b","message": "Never use apologies"},{"name": "No Understanding Feedback","pattern": "(?i)\b(understand|understood|got it)\b","message": "Avoid giving feedback about understanding in comments or documentation"},{"name": "No Whitespace Suggestions","pattern": "(?i)\b(whitespace|indentation|spacing)\b","message": "Don't suggest whitespace changes"},{"name": "No Summaries","pattern": "(?i)\b(summary|summarize|overview)\b","message": "Don't summarize changes made"},{"name": "No Inventions","pattern": "(?i)\b(suggest|recommendation|propose)\b","message": "Don't invent changes other than what's explicitly requested"},{"name": "No Unnecessary Confirmations","pattern": "(?i)\b(make sure|confirm|verify|check)\b","message": "Don't ask for confirmation of information already provided in the context"},{"name": "Preserve Existing Code","pattern": "(?i)\b(remove|delete|eliminate|destroy)\b","message": "Don't remove unrelated code or functionalities. Pay attention to preserving existing structures."},{"name": "Single Chunk Edits","pattern": "(?i)\b(first|then|next|after that|finally)\b","message": "Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file"},{"name": "No Implementation Checks","pattern": "(?i)\b(make sure|verify|check|confirm) (it's|it is|that) (correctly|properly) implemented\b","message": "Don't ask the user to verify implementations that are visible in the provided context"},{"name": "No Unnecessary Updates","pattern": "(?i)\b(update|change|modify|alter)\b.*\bno changes\b","message": "Don't suggest updates or changes to files when there are no actual modifications needed"},{"name": "Provide Real File Links","pattern": "(?i)\b(file|in)\b.*\b(x\.md)\b","message": "Always provide links to the real files, not x.md"},{"name": "No Previous x.md Consideration","pattern": "(?i)\b(previous|earlier|last)\b.*\bx\.md\b","message": "Do not consider any previous x.md files in your memory. Complain if the contents are the same as previous runs."},{"name": "No Current Implementation","pattern": "(?i)\b(current|existing)\s+(implementation|code)\b","message": "Don't show or discuss the current implementation unless specifically requested"},{"name": "Check x.md Content","pattern": "(?i)\b(file|content|implementation)\b","message": "Remember to check the x.md file for the current file contents and implementations"}]} \ No newline at end of file +// GitHub Code Quality Expert Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A production-ready GitHub repository with: +- Automated code quality checks +- Standardized review processes +- Consistent code style enforcement +- Comprehensive documentation +- Security best practices +- Efficient CI/CD pipelines + +// Project Structure +.github/ + workflows/ # GitHub Actions configurations + quality.yml # Code quality checks + security.yml # Security scans + ISSUE_TEMPLATE/ # Issue templates + PULL_REQUEST_TEMPLATE/ # PR templates +docs/ # Documentation + CODE_OF_CONDUCT.md # Code of conduct + CONTRIBUTING.md # Contribution guidelines + SECURITY.md # Security policies +tests/ # Test suites +scripts/ # Development scripts + +// Development Guidelines +1. Code Review: + - Verify all information before presenting + - Make changes file by file + - Focus on functionality over formatting + - Preserve existing code structure + - Provide complete changes in single reviews + - Link to actual files in documentation + +2. Documentation: + - Maintain clear, concise documentation + - Avoid unnecessary explanations + - Document real implementations + - Keep documentation up-to-date + - Include security considerations + - Provide clear setup instructions + +3. Quality Checks: + - Implement automated testing + - Use static code analysis + - Monitor code coverage + - Check dependencies regularly + - Validate documentation links + - Review security alerts + +// Dependencies +Core: +- github_actions: "latest" +- code_coverage: "latest" +- linters: "latest" +- security_scanners: "latest" + +Optional: +- documentation_tools: "latest" +- automated_testing: "latest" +- dependency_management: "latest" +- code_quality_metrics: "latest" + +// Code Examples: + +1. GitHub Workflow Pattern: +```yaml +name: Code Quality + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Run linters + uses: github/super-linter@v4 + - name: Run tests + run: | + npm install + npm test + - name: Check coverage + uses: coverallsapp/github-action@v2 +``` + +2. Pull Request Template Pattern: +```markdown +## Description + +Please include a summary of the changes and the related issue. + +## Type of change + +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation update + +## Checklist + +- [ ] My code follows the style guidelines +- [ ] I have performed a self-review +- [ ] I have added tests +- [ ] Documentation has been updated +``` + +3. Security Policy Pattern: +```markdown +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +1. **Do not** open a public issue +2. Email security@example.com +3. Expect response within 48 hours +4. Regular updates on reported vulnerabilities +``` + +// Best Practices: +1. Always verify information before presenting +2. Make changes file by file +3. Avoid unnecessary formatting changes +4. Preserve existing code functionality +5. Provide complete changes in single reviews +6. Use real file references +7. Keep documentation current +8. Implement automated testing +9. Monitor code quality metrics +10. Regular security reviews + +// Security Considerations: +1. Regular dependency updates +2. Code scanning enabled +3. Security policy defined +4. Access control implemented +5. Secrets management +6. Vulnerability monitoring +7. Regular security audits +8. Secure development practices +9. Documentation security +10. Compliance checks \ No newline at end of file diff --git a/rules/github-cursorrules-prompt-file-instructions/.cursorrules b/rules/github-cursorrules-prompt-file-instructions/.cursorrules index ce0df58..ce4256f 100644 --- a/rules/github-cursorrules-prompt-file-instructions/.cursorrules +++ b/rules/github-cursorrules-prompt-file-instructions/.cursorrules @@ -1 +1,170 @@ -Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand."As software developers, understanding how to write clean code that is functional, easy to read, and adheres to best practices helps you create better software consistently.This article discusses what clean code is and why it's essential and provides principles and best practices for writing clean and maintainable code.What Is Clean Code?Clean code is a term used to refer to code that is easy to read, understand, and maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob, who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008. In this book, he presented a set of principles and best practices for writing clean code, such as using meaningful names, short functions, clear comments, and consistent formatting.Ultimately, the goal of clean code is to create software that is not only functional but also readable, maintainable, and efficient throughout its lifecycle. Why Is Clean Code Important?When teams adhere to clean code principles, the code base is easier to read and navigate, which makes it faster for developers to get up to speed and start contributing. Here are some reasons why clean code is essential.Readability and maintenance: Clean code prioritizes clarity, which makes reading, understanding, and modifying code easier. Writing readable code reduces the time required to grasp the code's functionality, leading to faster development times.Team collaboration: Clear and consistent code facilitates communication and cooperation among team members. By adhering to established coding standards and writing readable code, developers easily understand each other's work and collaborate more effectively.Debugging and issue resolution: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues.Improved quality and reliability: Clean code prioritizes following established coding standards and writing well-structured code. This reduces the risk of introducing errors, leading to higher-quality and more reliable software down the line.Now that we understand why clean code is essential, let's delve into some best practices and principles to help you write clean code.Principles of Clean CodeLike a beautiful painting needs the right foundation and brushstrokes, well-crafted code requires adherence to specific principles. These principles help developers write code that is clear, concise, and, ultimately, a joy to work with.Let's dive in.1. Avoid Hard-Coded NumbersUse named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code.Example:The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function.Before:def calculate_discount(price):  discount = price * 0.1 # 10% discount  return price - discountThe improved code replaces the hard-coded number with a named constant TEN_PERCENT_DISCOUNT. The name instantly conveys the meaning of the value, making the code more self-documenting. After :def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountAlso, If the discount rate needs to be changed, it only requires modifying the constant declaration, not searching for multiple instances of the hard-coded number.2. Use Meaningful and Descriptive NamesChoose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.”Example:If we take the code from the previous example, it uses generic names like "price" and "discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be interpreted differently without context. Before:def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountInstead, you can declare the variables to be more descriptive.After:def calculate_discount(product_price):  TEN_PERCENT_DISCOUNT = 0.1  discount_amount = product_price * TEN_PERCENT_DISCOUNT  return product_price - discount_amountThis improved code uses specific names like "product_price" and "discount_amount," providing a clearer understanding of what the variables represent and how we use them.3. Use Comments Sparingly, and When You Do, Make Them MeaningfulYou don't need to comment on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase.Example:Before:def group_users_by_id(user_id):  # This function groups users by id  # ... complex logic ...  # ... more code …The comment about the function is redundant and adds no value. The function name already states that it groups users by id; there's no need for a comment stating the same.Instead, use comments to convey the "why" behind specific actions or explain behaviors.After:def group_users_by_id(user_id):  """Groups users by id to a specific category (1-9).  Warning: Certain characters might not be handled correctly.  Please refer to the documentation for supported formats.  Args:    user_id (str): The user id to be grouped.  Returns:    int: The category number (1-9) corresponding to the user id.  Raises:    ValueError: If the user id is invalid or unsupported.  """  # ... complex logic ...  # ... more code …This comment provides meaningful information about the function's behavior and explains unusual behavior and potential pitfalls.4. Write Short Functions That Only Do One ThingFollow the single responsibility principle (SRP), which means that a function should have one purpose and perform it effectively. Functions are more understandable, readable, and maintainable if they only have one job. It also makes testing them very easy. If a function becomes too long or complex, consider breaking it into smaller, more manageable functions.Example:Before:def process_data(data):  # ... validate users...  # ... calculate values ...  # ... format output …This function performs three tasks: validating users, calculating values, and formatting output. If any of these steps fail, the entire function fails, making debugging a complex issue. If we also need to change the logic of one of the tasks, we risk introducing unintended side effects in another task.Instead, try to assign each task a function that does just one thing. After:def validate_user(data):  # ... data validation logic ...def calculate_values(data):  # ... calculation logic based on validated data ...def format_output(data):  # ... format results for display …The improved code separates the tasks into distinct functions. This results in more readable, maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify and modify the specific function responsible for the desired functionality. 5. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or LogicAvoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable. It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it.Example:Before:def calculate_book_price(quantity, price): return quantity * pricedef calculate_laptop_price(quantity, price): return quantity * priceIn the above example, both functions calculate the total price using the same formula. This violates the DRY principle.We can fix this by defining a single calculate_product_price function that we use for books and laptops. This reduces code duplication and helps improve the maintenance of the codebase. After:def calculate_product_price(product_quantity, product_price): return product_quantity * product_price6. Follow Established Code-Writing StandardsKnow your programming language's conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example, PEP 8 for Python and Google JavaScript Style Guide for JavaScript. Here are some specific examples:Java:Use camelCase for variable, function, and class names.Indent code with four spaces.Put opening braces on the same line.Python:Use snake_case for variable, function, and class names.Use spaces over tabs for indentation.Put opening braces on the same line as the function or class declaration.JavaScript:Use camelCase for variable and function names.Use snake_case for object properties.Indent code with two spaces.Put opening braces on the same line as the function or class declaration.Also, consider extending some of these standards by creating internal coding rules for your organization. This can contain information on creating and naming folders or describing function names within your organization.7. Encapsulate Nested Conditionals into FunctionsOne way to improve the readability and clarity of functions is to encapsulate nested if/else statements into other functions. Encapsulating such logic into a function with a descriptive name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it easier to reuse, modify, and test the logic without affecting the rest of the function.In the code sample below, the discount logic is nested within the calculate_product_discount function, making it difficult to understand at a glance.Example:Before:def calculate_product_discount(product_price): discount_amount = 0 if product_price > 100:  discount_amount = product_price * 0.1 elif price > 50:  discount_amount = product_price * 0.05 else:  discount_amount = 0 final_product_price = product_price - discount_amount return final_product_priceWe can clean this code up by separating the nested if/else condition that calculates discount logic into another function called get_discount_rate and then calling the get_discount_rate in the calculate_product_discount function. This makes it easier to read at a glance. The get_discount_rate is now isolated and can be reused by other functions in the codebase. It’s also easier to change, test, and debug it without affecting the calculate_discount function.After:def calculate_discount(product_price): discount_rate = get_discount_rate(product_price) discount_amount = product_price * discount_rate final_product_price = product_price - discount_amount  return final_product_pricedef get_discount_rate(product_price): if product_price > 100:  return 0.1 elif product_price > 50:  return 0.05 else:  return 08. Refactor ContinuouslyRegularly review and refactor your code to improve its structure, readability, and maintainability. Consider the readability of your code for the next person who will work on it, and always leave the codebase cleaner than you found it.9. Use Version ControlVersion control systems meticulously track every change made to your codebase, enabling you to understand the evolution of your code and revert to previous versions if needed. This creates a safety net for code refactoring and prevents accidental deletions or overwrites.Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your codebase and collaborate effectively with others. \ No newline at end of file +// GitHub Clean Code Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A maintainable and professional GitHub codebase with: +- Clean, readable code structure +- Consistent naming conventions +- Efficient code organization +- Proper documentation +- Reusable components +- Testable functions + +// Project Structure +src/ + components/ # Reusable code components + constants/ # Named constants + utils/ # Utility functions + validators/ # Input validation + core/ # Core business logic + services/ # Business services + models/ # Data models + tests/ # Test suites + unit/ # Unit tests + integration/ # Integration tests + docs/ # Documentation + guides/ # Usage guides + api/ # API documentation + +// Development Guidelines +1. Code Organization: + - Use meaningful and descriptive names + - Write short, focused functions + - Follow single responsibility principle + - Avoid code duplication (DRY) + - Encapsulate complex logic + - Use proper indentation + +2. Code Standards: + - Follow language conventions + - Use consistent formatting + - Apply proper spacing + - Implement naming patterns + - Structure files consistently + - Document public interfaces + +3. Code Quality: + - Write self-documenting code + - Avoid hard-coded values + - Use meaningful comments + - Handle errors properly + - Write testable code + - Refactor regularly + +// Dependencies +Core: +- eslint: "^8.0.0" +- prettier: "^2.0.0" +- jest: "^27.0.0" +- typescript: "^4.0.0" + +Optional: +- husky: "^7.0.0" +- commitlint: "^13.0.0" +- lint-staged: "^11.0.0" +- typedoc: "^0.22.0" + +// Code Examples: + +1. Clean Function Pattern: +```typescript +// Before +function calc(p: number): number { + const d = p * 0.1; + return p - d; +} + +// After +function calculateDiscount(productPrice: number): number { + const TEN_PERCENT_DISCOUNT = 0.1; + const discountAmount = productPrice * TEN_PERCENT_DISCOUNT; + return productPrice - discountAmount; +} +``` + +2. Single Responsibility Pattern: +```typescript +// Before +function processData(data: any) { + // Validate + if (!data.user) throw new Error('Invalid user'); + + // Calculate + const total = data.items.reduce((sum, item) => sum + item.price, 0); + + // Format + return `Total: $${total.toFixed(2)}`; +} + +// After +function validateUserData(data: any): void { + if (!data.user) throw new Error('Invalid user'); +} + +function calculateTotal(items: Item[]): number { + return items.reduce((sum, item) => sum + item.price, 0); +} + +function formatCurrency(amount: number): string { + return `Total: $${amount.toFixed(2)}`; +} + +function processData(data: any): string { + validateUserData(data); + const total = calculateTotal(data.items); + return formatCurrency(total); +} +``` + +3. Encapsulation Pattern: +```typescript +// Before +if (user.age >= 18 && user.country === 'US' && !user.restricted) { + // Allow access +} + +// After +function canAccessService(user: User): boolean { + return ( + isAdult(user.age) && + isFromSupportedCountry(user.country) && + !isRestricted(user) + ); +} + +function isAdult(age: number): boolean { + return age >= 18; +} + +function isFromSupportedCountry(country: string): boolean { + return country === 'US'; +} + +function isRestricted(user: User): boolean { + return user.restricted; +} +``` + +// Best Practices: +1. Use descriptive variable names +2. Keep functions small and focused +3. Follow DRY principle +4. Write self-documenting code +5. Use proper error handling +6. Implement consistent formatting +7. Write comprehensive tests +8. Refactor regularly +9. Use version control effectively +10. Document complex logic + +// Security Considerations: +1. Validate all inputs +2. Sanitize user data +3. Handle errors securely +4. Use proper authentication +5. Implement authorization +6. Avoid security anti-patterns +7. Keep dependencies updated +8. Use secure configurations +9. Implement proper logging +10. Follow security guidelines \ No newline at end of file diff --git a/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules b/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules index 567a21a..d3b71f0 100644 --- a/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules +++ b/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules @@ -1 +1,235 @@ -You are an AI Pair Programming Assistant with extensive expertise in backend software engineering. Your knowledge spans a wide range of technologies, practices, and concepts commonly used in modern backend systems. Your role is to provide comprehensive, insightful, and practical advice on various backend development topics.Your areas of expertise include, but are not limited to:1. Database Management (SQL, NoSQL, NewSQL)2. API Development (REST, GraphQL, gRPC)3. Server-Side Programming (Go, Rust, Java, Python, Node.js)4. Performance Optimization5. Scalability and Load Balancing6. Security Best Practices7. Caching Strategies8. Data Modeling9. Microservices Architecture10. Testing and Debugging11. Logging and Monitoring12. Containerization and Orchestration13. CI/CD Pipelines14. Docker and Kubernetes15. gRPC and Protocol Buffers16. Git Version Control17. Data Infrastructure (Kafka, RabbitMQ, Redis)18. Cloud Platforms (AWS, GCP, Azure)When responding to queries:1. Begin with a section where you:  - Analyze the query to identify the main topics and technologies involved  - Consider the broader context and implications of the question  - Plan your approach to answering the query comprehensively2. Provide clear, concise explanations of backend concepts and technologies3. Offer practical advice and best practices for real-world scenarios4. Share code snippets or configuration examples when appropriate, using proper formatting and syntax highlighting5. Explain trade-offs between different approaches when multiple solutions exist6. Consider scalability, performance, and security implications in your recommendations7. Reference official documentation or reputable sources when needed, but note that you don't have access to real-time information8. End your response with an section that summarizes the key points and provides a direct answer to the queryYour goal is to help users understand, implement, and optimize backend systems while adhering to industry best practices and standards. Always consider factors such as scalability, reliability, maintainability, and security in your recommendations.If a query is unclear or lacks necessary details, ask for clarification before providing an answer. If a question is outside the scope of backend development, politely inform the user and offer to assist with related backend topics if possible.Here's an example of how to structure your response:You:To answer this query, I need to consider:1. The basics of gRPC and Protocol Buffers2. Go programming for gRPC server implementation3. Database interaction using Go's database/sql package or an ORM4. Best practices for structuring a gRPC service5. Error handling and data validationI'll provide a step-by-step guide with code examples to illustrate the implementation.1. Define your Protocol Buffer messages and service:  Create a file named `service.proto`:  ```protobuf  syntax = "proto3";  package myservice;  option go_package = "./pb";  message User {   int32 id = 1;   string name = 2;   string email = 3;  }  message GetUserRequest {   int32 id = 1;  }  service UserService {   rpc GetUser(GetUserRequest) returns (User) {}  }  ```2. Generate Go code from the Proto file:  ```  protoc --go_out=. --go-grpc_out=. service.proto  ```3. Implement the gRPC server in Go:  ```go  package main  import (   "context"   "database/sql"   "log"   "net"   "google.golang.org/grpc"   "github.com/lib/pq"   pb "your_project/pb"  )  type server struct {   pb.UnimplementedUserServiceServer   db *sql.DB  }  func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {   var user pb.User   err := s.db.QueryRow("SELECT id, name, email FROM users WHERE id = $1", req.Id).Scan(&user.Id, &user.Name, &user.Email)   if err != nil {    return nil, err   }   return &user, nil  }  func main() {   // Connect to PostgreSQL   db, err := sql.Open("postgres", "postgresql://username:password@localhost/dbname?sslmode=disable")   if err != nil {    log.Fatalf("Failed to connect to database: %v", err)   }   defer db.Close()   // Create gRPC server   s := grpc.NewServer()   pb.RegisterUserServiceServer(s, &server{db: db})   // Start listening   lis, err := net.Listen("tcp", ":50051")   if err != nil {    log.Fatalf("Failed to listen: %v", err)   }   log.Println("Server listening on :50051")   if err := s.Serve(lis); err != nil {    log.Fatalf("Failed to serve: %v", err)   }  }  ```This example demonstrates:- Defining a simple gRPC service using Protocol Buffers- Implementing the service in Go- Connecting to a PostgreSQL database- Handling a basic database query within a gRPC methodRemember to handle errors properly, implement proper validation, and consider using an ORM like GORM for more complex database interactions. Also, ensure you're following best practices for security, such as using prepared statements to prevent SQL injection.By following this structure and guidelines, you'll provide comprehensive and practical assistance for backend software engineering queries. \ No newline at end of file +// Go Backend Scalability Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A scalable Go backend system with: +- High-performance API endpoints +- Efficient database operations +- Microservices architecture +- Load balancing capabilities +- Caching strategies +- Monitoring and logging + +// Project Structure +src/ + api/ # API layer + handlers/ # Request handlers + middleware/ # HTTP middleware + routes/ # Route definitions + internal/ # Internal packages + models/ # Data models + services/ # Business logic + database/ # Database operations + cache/ # Caching layer + pkg/ # Shared packages + logger/ # Logging utilities + config/ # Configuration + metrics/ # Monitoring metrics + cmd/ # Application entrypoints + server/ # Main server + worker/ # Background workers + deployments/ # Deployment configs + docker/ # Docker files + k8s/ # Kubernetes manifests + +// Development Guidelines +1. Performance Optimization: + - Use goroutines efficiently + - Implement proper connection pooling + - Cache frequently accessed data + - Optimize database queries + - Use efficient data structures + - Profile and benchmark code + +2. Scalability Patterns: + - Design stateless services + - Implement horizontal scaling + - Use message queues + - Apply circuit breakers + - Implement rate limiting + - Handle backpressure + +3. Reliability Practices: + - Implement graceful shutdown + - Handle errors properly + - Use timeouts and deadlines + - Implement retries + - Monitor system health + - Log important events + +// Dependencies +Core: +- go: "1.21" +- gin-gonic/gin: "v1.9.0" +- go-redis/redis/v8: "v8.11.5" +- lib/pq: "v1.10.9" +- prometheus/client_golang: "v1.16.0" + +Optional: +- golang-migrate/migrate/v4: "v4.16.2" +- uber-go/zap: "v1.24.0" +- spf13/viper: "v1.16.0" +- golang/protobuf: "v1.5.3" + +// Code Examples: + +1. Scalable HTTP Handler Pattern: +```go +type Handler struct { + store *store.Store + cache *cache.Client + logger *zap.Logger +} + +func (h *Handler) GetUser(c *gin.Context) { + ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second) + defer cancel() + + userID := c.Param("id") + + // Try cache first + if user, err := h.cache.Get(ctx, userID); err == nil { + c.JSON(http.StatusOK, user) + return + } + + // Fallback to database + user, err := h.store.GetUser(ctx, userID) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + h.logger.Error("failed to get user", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"}) + return + } + + // Cache for future requests + if err := h.cache.Set(ctx, userID, user, time.Hour); err != nil { + h.logger.Warn("failed to cache user", zap.Error(err)) + } + + c.JSON(http.StatusOK, user) +} +``` + +2. Connection Pool Pattern: +```go +type Store struct { + db *sql.DB + log *zap.Logger +} + +func NewStore(dsn string, log *zap.Logger) (*Store, error) { + db, err := sql.Open("postgres", dsn) + if err != nil { + return nil, fmt.Errorf("failed to connect to database: %w", err) + } + + // Configure connection pool + db.SetMaxOpenConns(25) + db.SetMaxIdleConns(25) + db.SetConnMaxLifetime(5 * time.Minute) + + if err := db.Ping(); err != nil { + return nil, fmt.Errorf("failed to ping database: %w", err) + } + + return &Store{ + db: db, + log: log, + }, nil +} + +func (s *Store) GetUsersByStatus(ctx context.Context, status string) ([]User, error) { + query := ` + SELECT id, name, email, status + FROM users + WHERE status = $1 + ` + + rows, err := s.db.QueryContext(ctx, query, status) + if err != nil { + return nil, fmt.Errorf("failed to query users: %w", err) + } + defer rows.Close() + + var users []User + for rows.Next() { + var u User + if err := rows.Scan(&u.ID, &u.Name, &u.Email, &u.Status); err != nil { + return nil, fmt.Errorf("failed to scan user: %w", err) + } + users = append(users, u) + } + + return users, nil +} +``` + +3. Rate Limiter Pattern: +```go +type RateLimiter struct { + redis *redis.Client + limit int + window time.Duration +} + +func NewRateLimiter(redis *redis.Client, limit int, window time.Duration) *RateLimiter { + return &RateLimiter{ + redis: redis, + limit: limit, + window: window, + } +} + +func (rl *RateLimiter) Middleware() gin.HandlerFunc { + return func(c *gin.Context) { + key := fmt.Sprintf("rate_limit:%s", c.ClientIP()) + + count, err := rl.redis.Incr(c, key).Result() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Rate limit check failed"}) + c.Abort() + return + } + + if count == 1 { + rl.redis.Expire(c, key, rl.window) + } + + if count > int64(rl.limit) { + c.JSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit exceeded"}) + c.Abort() + return + } + + c.Next() + } +} +``` + +// Best Practices: +1. Use context for cancellation +2. Implement graceful shutdown +3. Configure connection pools +4. Cache expensive operations +5. Use proper error handling +6. Implement rate limiting +7. Monitor application metrics +8. Log meaningful information +9. Use dependency injection +10. Write comprehensive tests + +// Security Considerations: +1. Use HTTPS everywhere +2. Implement authentication +3. Use proper authorization +4. Validate all inputs +5. Prevent SQL injection +6. Use secure headers +7. Rate limit endpoints +8. Implement audit logging +9. Use secure configurations +10. Keep dependencies updated \ No newline at end of file diff --git a/rules/go-fiber-cursorrules-prompt-file/.cursorrules b/rules/go-fiber-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..abbc1f9 --- /dev/null +++ b/rules/go-fiber-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,339 @@ +// Go Fiber Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern web application using Go Fiber: +- RESTful APIs +- GraphQL APIs +- WebSocket servers +- Middleware +- Authentication +- File uploads +- Database integration +- Background jobs + +// Project Structure +cmd/ + api/ # Application entrypoint + main.go # Main application file +internal/ # Application logic + config/ # Configuration + config.go # Config structs + env.go # Environment vars + handlers/ # HTTP handlers + auth.go # Auth handlers + users.go # User handlers + middleware/ # Custom middleware + auth.go # Auth middleware + logger.go # Logging middleware + models/ # Data models + user.go # User model + product.go # Product model + repositories/ # Data access + postgres/ # Postgres repos + redis/ # Redis repos + services/ # Business logic + auth.go # Auth service + users.go # User service + utils/ # Utilities + logger/ # Logger + validator/ # Validators +pkg/ # Public packages + errors/ # Error types + database/ # DB helpers +migrations/ # DB migrations +tests/ # Test suite + integration/ # Integration tests + unit/ # Unit tests + +// Development Guidelines +1. API Design: + - RESTful principles + - Error handling + - Validation + - Authentication + - Rate limiting + - Documentation + +2. Code Structure: + - Clean architecture + - Dependency injection + - Repository pattern + - Service layer + - Error handling + - Logging + +3. Performance: + - Concurrency + - Connection pooling + - Caching + - Query optimization + - Memory usage + - Monitoring + +// Dependencies +Core: +- fiber: "v2.47.0" +- gorm: "v1.25.0" +- jwt-go: "v4.5.0" +- validator: "v10.14.0" + +Optional: +- redis: "v9.0.0" +- zap: "v1.24.0" +- testify: "v1.8.0" +- mock: "v2.0.0" + +// Code Examples: + +1. Handler Pattern: +```go +package handlers + +import ( + "github.com/gofiber/fiber/v2" + "github.com/username/project/internal/models" + "github.com/username/project/internal/services" + "github.com/username/project/pkg/errors" +) + +type UserHandler struct { + userService services.UserService + logger *zap.Logger +} + +func NewUserHandler(us services.UserService, l *zap.Logger) *UserHandler { + return &UserHandler{ + userService: us, + logger: l, + } +} + +func (h *UserHandler) Create(c *fiber.Ctx) error { + var input models.CreateUserInput + + if err := c.BodyParser(&input); err != nil { + h.logger.Error("failed to parse request body", zap.Error(err)) + return c.Status(fiber.StatusBadRequest).JSON(errors.NewBadRequestError("invalid request body")) + } + + if err := input.Validate(); err != nil { + h.logger.Error("validation failed", zap.Error(err)) + return c.Status(fiber.StatusBadRequest).JSON(errors.NewValidationError(err)) + } + + user, err := h.userService.Create(c.Context(), input) + if err != nil { + h.logger.Error("failed to create user", zap.Error(err)) + return h.handleError(c, err) + } + + return c.Status(fiber.StatusCreated).JSON(user) +} + +func (h *UserHandler) Get(c *fiber.Ctx) error { + id := c.Params("id") + + user, err := h.userService.GetByID(c.Context(), id) + if err != nil { + h.logger.Error("failed to get user", zap.String("id", id), zap.Error(err)) + return h.handleError(c, err) + } + + return c.JSON(user) +} + +func (h *UserHandler) handleError(c *fiber.Ctx, err error) error { + switch e := err.(type) { + case *errors.NotFoundError: + return c.Status(fiber.StatusNotFound).JSON(e) + case *errors.ValidationError: + return c.Status(fiber.StatusBadRequest).JSON(e) + default: + return c.Status(fiber.StatusInternalServerError).JSON( + errors.NewInternalError("internal server error"), + ) + } +} +``` + +2. Service Pattern: +```go +package services + +import ( + "context" + "github.com/username/project/internal/models" + "github.com/username/project/internal/repositories" + "github.com/username/project/pkg/errors" + "go.uber.org/zap" +) + +type UserService interface { + Create(ctx context.Context, input models.CreateUserInput) (*models.User, error) + GetByID(ctx context.Context, id string) (*models.User, error) + Update(ctx context.Context, id string, input models.UpdateUserInput) (*models.User, error) + Delete(ctx context.Context, id string) error +} + +type userService struct { + repo repositories.UserRepository + logger *zap.Logger +} + +func NewUserService(repo repositories.UserRepository, logger *zap.Logger) UserService { + return &userService{ + repo: repo, + logger: logger, + } +} + +func (s *userService) Create(ctx context.Context, input models.CreateUserInput) (*models.User, error) { + // Check if user exists + exists, err := s.repo.ExistsByEmail(ctx, input.Email) + if err != nil { + return nil, err + } + if exists { + return nil, errors.NewValidationError("email already exists") + } + + // Create user + user := &models.User{ + Email: input.Email, + Name: input.Name, + Password: input.Password, + } + + if err := user.HashPassword(); err != nil { + return nil, err + } + + if err := s.repo.Create(ctx, user); err != nil { + return nil, err + } + + return user, nil +} + +func (s *userService) GetByID(ctx context.Context, id string) (*models.User, error) { + user, err := s.repo.GetByID(ctx, id) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.NewNotFoundError("user not found") + } + return user, nil +} +``` + +3. Repository Pattern: +```go +package repositories + +import ( + "context" + "gorm.io/gorm" + "github.com/username/project/internal/models" +) + +type UserRepository interface { + Create(ctx context.Context, user *models.User) error + GetByID(ctx context.Context, id string) (*models.User, error) + ExistsByEmail(ctx context.Context, email string) (bool, error) + Update(ctx context.Context, user *models.User) error + Delete(ctx context.Context, id string) error +} + +type userRepository struct { + db *gorm.DB +} + +func NewUserRepository(db *gorm.DB) UserRepository { + return &userRepository{db: db} +} + +func (r *userRepository) Create(ctx context.Context, user *models.User) error { + return r.db.WithContext(ctx).Create(user).Error +} + +func (r *userRepository) GetByID(ctx context.Context, id string) (*models.User, error) { + var user models.User + err := r.db.WithContext(ctx).First(&user, "id = ?", id).Error + if err == gorm.ErrRecordNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + return &user, nil +} + +func (r *userRepository) ExistsByEmail(ctx context.Context, email string) (bool, error) { + var count int64 + err := r.db.WithContext(ctx).Model(&models.User{}). + Where("email = ?", email). + Count(&count). + Error + return count > 0, err +} +``` + +// Best Practices: +1. Code Quality: + - Documentation + - Error handling + - Testing + - Logging + - Validation + - Interfaces + +2. Architecture: + - Clean architecture + - Dependency injection + - Repository pattern + - Service layer + - Middleware + - Error handling + +3. Performance: + - Goroutines + - Connection pools + - Query optimization + - Caching + - Memory usage + - Monitoring + +4. Security: + - Authentication + - Authorization + - Input validation + - Rate limiting + - CORS policy + - Secure headers + +// Security Considerations: +1. API Security: + - Input validation + - Rate limiting + - Authentication + - Authorization + - CORS policy + - Security headers + +2. Data Security: + - Password hashing + - Data encryption + - SQL injection + - XSS prevention + - CSRF protection + - Access control + +3. Infrastructure: + - HTTPS + - TLS config + - Firewalls + - Monitoring + - Logging + - Backups \ No newline at end of file diff --git a/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules b/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules index 6eacf10..074432b 100644 --- a/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules +++ b/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules @@ -1 +1,253 @@ -You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux introduced in Go 1.22.Always use the latest stable version of Go (1.22 or newer) and be familiar with RESTful API design principles, best practices, and Go idioms.Follow the user's requirements carefully & to the letter.First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode, written out in great detail.Confirm the plan, then write code!Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs.Use the standard library's net/http package for API development:Implement proper error handling, including custom error types when beneficial.Use appropriate status codes and format JSON responses correctly.Implement input validation for API endpoints.Utilize Go's built-in concurrency features when beneficial for API performance.Follow RESTful API design principles and best practices.Include necessary imports, package declarations, and any required setup code.Implement proper logging using the standard library's log package or a simple custom logger.Consider implementing middleware for cross-cutting concerns (e.g., logging, authentication).Implement rate limiting and authentication/authorization when appropriate, using standard library features or simple custom implementations.Leave NO todos, placeholders, or missing pieces in the API implementation.Be concise in explanations, but provide brief comments for complex logic or Go-specific idioms.If unsure about a best practice or implementation detail, say so instead of guessing.Offer suggestions for testing the API endpoints using Go's testing package.Always prioritize security, scalability, and maintainability in your API designs and implementations. Leverage the power and simplicity of Go's standard library to create efficient and idiomatic APIs. \ No newline at end of file +// Go ServeMux REST API Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A production-ready REST API using Go's standard library with: +- Modern ServeMux routing (Go 1.22+) +- RESTful endpoint design +- Middleware support +- Input validation +- Error handling +- Authentication/Authorization +- Rate limiting +- Logging + +// Project Structure +src/ + api/ # API layer + handlers/ # Request handlers + users.go # User endpoints + health.go # Health checks + middleware/ # HTTP middleware + auth.go # Authentication + logging.go # Request logging + ratelimit.go # Rate limiting + models/ # Data models + user.go # User model + error.go # Error types + server/ # Server setup + router.go # ServeMux setup + config.go # Server config + internal/ # Internal packages + validator/ # Input validation + logger/ # Logging utilities + tests/ # Test suites + integration/ # Integration tests + unit/ # Unit tests + +// Development Guidelines +1. API Design: + - Use RESTful principles + - Implement proper status codes + - Structure JSON responses + - Handle errors gracefully + - Validate all inputs + - Document endpoints + +2. Middleware Patterns: + - Implement authentication + - Add request logging + - Enable rate limiting + - Handle CORS + - Add request ID tracking + - Implement timeouts + +3. Error Handling: + - Use custom error types + - Return proper status codes + - Include error details + - Log errors appropriately + - Handle panics + - Validate inputs early + +// Dependencies +Core: +- go: "1.22" +- net/http +- encoding/json +- context +- log/slog +- sync + +Optional: +- crypto/bcrypt +- golang.org/x/time/rate +- golang.org/x/crypto +- database/sql + +// Code Examples: + +1. ServeMux Router Pattern: +```go +package server + +import ( + "net/http" + "encoding/json" + "log/slog" +) + +type Server struct { + router *http.ServeMux + logger *slog.Logger +} + +func NewServer(logger *slog.Logger) *Server { + s := &Server{ + router: http.NewServeMux(), + logger: logger, + } + s.routes() + return s +} + +func (s *Server) routes() { + s.router.HandleFunc("GET /api/v1/users/{id}", s.handleGetUser) + s.router.HandleFunc("POST /api/v1/users", s.handleCreateUser) + s.router.HandleFunc("GET /api/v1/health", s.handleHealthCheck) +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + s.router.ServeHTTP(w, r) +} + +func (s *Server) handleGetUser(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + + user, err := s.store.GetUser(r.Context(), id) + if err != nil { + s.errorResponse(w, r, err) + return + } + + s.jsonResponse(w, http.StatusOK, user) +} +``` + +2. Middleware Pattern: +```go +package middleware + +import ( + "net/http" + "time" + "log/slog" +) + +func Logging(logger *slog.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + // Wrap response writer to capture status code + rw := newResponseWriter(w) + + // Call next handler + next.ServeHTTP(rw, r) + + // Log request details + logger.Info("request completed", + "method", r.Method, + "path", r.URL.Path, + "status", rw.status, + "duration", time.Since(start), + "ip", r.RemoteAddr, + ) + }) + } +} + +type responseWriter struct { + http.ResponseWriter + status int +} + +func newResponseWriter(w http.ResponseWriter) *responseWriter { + return &responseWriter{w, http.StatusOK} +} + +func (rw *responseWriter) WriteHeader(code int) { + rw.status = code + rw.ResponseWriter.WriteHeader(code) +} +``` + +3. Error Handling Pattern: +```go +package api + +import ( + "net/http" + "encoding/json" +) + +type ErrorResponse struct { + Error string `json:"error"` + Message string `json:"message,omitempty"` + Code int `json:"code"` +} + +func (s *Server) errorResponse(w http.ResponseWriter, r *http.Request, err error) { + var response ErrorResponse + + switch e := err.(type) { + case *NotFoundError: + response = ErrorResponse{ + Error: "not_found", + Message: e.Error(), + Code: http.StatusNotFound, + } + case *ValidationError: + response = ErrorResponse{ + Error: "validation_error", + Message: e.Error(), + Code: http.StatusBadRequest, + } + default: + response = ErrorResponse{ + Error: "internal_error", + Message: "An internal error occurred", + Code: http.StatusInternalServerError, + } + // Log the actual error + s.logger.Error("internal server error", + "error", err, + "path", r.URL.Path, + ) + } + + s.jsonResponse(w, response.Code, response) +} + +func (s *Server) jsonResponse(w http.ResponseWriter, status int, data interface{}) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(data); err != nil { + s.logger.Error("failed to encode response", "error", err) + } +} +``` + +// Best Practices: +1. Use proper HTTP methods +2. Implement input validation +3. Handle errors gracefully +4. Use middleware for cross-cutting concerns +5. Implement proper logging +6. Use appropriate status codes +7. Structure JSON responses +8. Add request timeouts +9. Implement rate limiting +10. Write comprehensive tests + +// Security Considerations: +1. Validate all inputs +2. Use HTTPS +3. Implement authentication +4. Add rate limiting +5. Set security headers +6. Handle CORS properly +7. Sanitize responses +8. Use secure cookies +9. Implement timeouts +10. Log security events \ No newline at end of file diff --git a/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules b/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules index 950563b..0cf077d 100644 --- a/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules +++ b/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules @@ -1 +1,214 @@ -# Project SynopsisPyllments is a Python library for building graphical and API-based LLM applications through chaining together Elements in a potentially cyclic graph. Elements and Payloads are a type of Components. A Component is composed of a Model and Views. The Model handles the underlying data and logic, while the Views are the UI components that are used to display display the interactive UI used to interact with the Model. An Element is a type of Component that is responsible for a specific function. For instance, an Element can handle the LLM selection and generation by making calls to LLM providers. Another Element may handle the chat interface, whose Model would store the chat message history, and the Views would be the text boxes and buttons used to interact with the chat interface. Elements are meant to connect to other Elements through Ports. All that is necessary to link Elements together is to link the output port of one Element to the input port of Another. Each output port may have unlimited input ports it connects to, and each input port may have unlimited output ports it connects to. The ports follow an observer pattern where the output port is the subject and the input port is the observer. The subject notifies the observers when a certain event that we set within the Element is triggered. In order to connect an input and and output port, they need to be setup in a manner that sends and receives the same type of Payload. A Payload is also a Component with a Model as well as views responsible for the display logic. Elements may receive payloads and use methods of the Payload to generate the views for the UI. The sending Element is responsible for packing data into the Payload.  I am currently working on making this a fully-fledged framework.# Project OrganizationHere is an example of the file structure of an individual element:chat_interface:  - __init__.py  - chat_interface_element.py  - chat_interface_model.py  - css:    - buttons.css    - column.css    - input.css# Primary Libraries Used- Panel is used to create the visualization layer and run the GUI. Views tend to consist of Panel objects which can be styled with Python and CSS.- Param is used to create parameterized classes which help create parameters that handle type validation, default values, constraints, and most importantly, reactivity(setting event handlers to catch changes).- Langchain is responsible for the specific functions pertaining to incorporating LLM workflows.# Development PrioritiesPyllments code is prioritized on being developer-friendly, where extensibility and modularity are first-class citizens. Elements should be customizeable with clean and intuitive interfaces. It should also be easy to create new elements depending on the needs of the developer. # DocumentationDocstrings should use a NumPy/SciPy style. \ No newline at end of file +// Graphical Apps Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Python-based graphical application framework for LLM applications featuring: +- Component-based architecture +- Element chaining in cyclic graphs +- Interactive UI components +- LLM integration capabilities +- Reactive programming patterns +- Customizable visualization +- Event-driven communication + +// Project Structure +src/ + components/ # Core components + base/ # Base classes + component.py # Base component class + element.py # Base element class + payload.py # Base payload class + models/ # Data models + model_base.py # Base model class + views/ # UI components + view_base.py # Base view class + elements/ # Element implementations + chat/ # Chat interface element + __init__.py + chat_element.py + chat_model.py + css/ + buttons.css + column.css + input.css + llm/ # LLM integration element + __init__.py + llm_element.py + llm_model.py + ports/ # Port system + input_port.py # Input port implementation + output_port.py # Output port implementation + utils/ # Utility functions + event_bus.py # Event handling + type_checking.py # Type validation + +// Development Guidelines +1. Component Architecture: + - Use Model-View separation + - Implement clean interfaces + - Follow single responsibility + - Enable easy extensibility + - Maintain modularity + - Document interfaces + +2. Element Design: + - Define clear port contracts + - Handle payload types properly + - Implement event handlers + - Support cyclic connections + - Enable customization + - Follow observer pattern + +3. UI Development: + - Create responsive layouts + - Style with CSS/Python + - Handle user interactions + - Implement reactive updates + - Support customization + - Follow accessibility guidelines + +// Dependencies +Core: +- python: ">=3.8" +- panel: "^1.0.0" +- param: "^2.0.0" +- langchain: "^0.1.0" +- pydantic: "^2.0.0" + +Optional: +- streamlit: "^1.0.0" +- gradio: "^3.0.0" +- plotly: "^5.0.0" +- bokeh: "^3.0.0" + +// Code Examples: + +1. Element Implementation Pattern: +```python +from typing import Any, Dict +import param +from .base import Element +from .ports import InputPort, OutputPort +from .models import PayloadModel + +class ChatElement(Element): + """Chat interface element for handling message interactions.""" + + # Reactive parameters + message_history = param.List(default=[]) + current_message = param.String(default="") + + def __init__(self, **params): + super().__init__(**params) + # Setup ports + self.input_port = InputPort(self, PayloadModel) + self.output_port = OutputPort(self, PayloadModel) + + # Initialize views + self._setup_views() + + def _setup_views(self): + """Initialize and configure UI components.""" + self.chat_view = self._create_chat_view() + self.input_view = self._create_input_view() + + def send_message(self, message: str): + """Handle sending a new message.""" + payload = PayloadModel(content=message) + self.message_history.append(message) + self.output_port.emit(payload) +``` + +2. Model Implementation Pattern: +```python +from typing import List, Optional +import param +from pydantic import BaseModel + +class ChatMessage(BaseModel): + """Data model for chat messages.""" + content: str + timestamp: float + sender: str + +class ChatModel(param.Parameterized): + """Model for managing chat state and logic.""" + + messages: List[ChatMessage] = param.List([]) + current_user: str = param.String() + + def add_message(self, content: str, sender: Optional[str] = None): + """Add a new message to the chat history.""" + message = ChatMessage( + content=content, + timestamp=time.time(), + sender=sender or self.current_user + ) + self.messages.append(message) + return message +``` + +3. View Implementation Pattern: +```python +import panel as pn +from typing import Callable + +class ChatView: + """View component for chat interface.""" + + def __init__(self, on_send: Callable[[str], None]): + self.on_send = on_send + self._setup_layout() + + def _setup_layout(self): + """Create and configure the chat interface layout.""" + self.message_input = pn.widgets.TextInput( + placeholder="Type a message...", + css_classes=['chat-input'] + ) + + self.send_button = pn.widgets.Button( + name="Send", + button_type="primary", + css_classes=['send-button'] + ) + + self.send_button.on_click(self._handle_send) + + self.layout = pn.Column( + self.message_input, + self.send_button, + css_classes=['chat-container'] + ) + + def _handle_send(self, event): + """Handle send button clicks.""" + message = self.message_input.value + if message.strip(): + self.on_send(message) + self.message_input.value = "" +``` + +// Best Practices: +1. Follow component-based architecture +2. Implement clean interfaces +3. Use type hints consistently +4. Write comprehensive tests +5. Document with docstrings +6. Handle errors gracefully +7. Use reactive programming +8. Maintain separation of concerns +9. Enable customization +10. Follow Python style guide + +// Security Considerations: +1. Validate user inputs +2. Sanitize displayed content +3. Handle sensitive data properly +4. Implement rate limiting +5. Use secure dependencies +6. Follow CORS policies +7. Protect against XSS +8. Handle errors securely +9. Implement authentication +10. Log security events \ No newline at end of file diff --git a/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules b/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..ac106a7 --- /dev/null +++ b/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,353 @@ +// GraphQL TypeScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern GraphQL API using TypeScript: +- Schema-first development +- Type-safe resolvers +- Authentication & Authorization +- Real-time subscriptions +- Data loaders +- Custom directives +- Error handling +- Testing framework + +// Project Structure +src/ + schema/ # GraphQL schema + typeDefs/ # Type definitions + user.graphql # User type definition + product.graphql # Product type definition + resolvers/ # Resolvers + user.ts # User resolver + product.ts # Product resolver + directives/ # Custom directives + auth.ts # Authentication directive + validation.ts # Validation directive + models/ # Data models + User.ts # User model + Product.ts # Product model + services/ # Business logic + UserService.ts # User service + ProductService.ts # Product service + dataloaders/ # Data loaders + UserLoader.ts # User loader + ProductLoader.ts # Product loader + utils/ # Utilities + auth.ts # Authentication utility + validation.ts # Validation utility + config/ # Configuration + apollo.ts # Apollo configuration + database.ts # Database configuration + tests/ # Test suite + integration/ # Integration tests + unit/ # Unit tests + +// Development Guidelines +1. Schema Design: + - Type definitions + - Input types + - Mutations + - Queries + - Subscriptions + - Custom scalars + - Directives + +2. Code Structure: + - Resolver pattern + - Service layer + - Data loaders + - Error handling + - Authentication + - Authorization + +3. Performance: + - N+1 queries + - Caching + - Batching + - Query complexity + - Rate limiting + - Monitoring + +// Dependencies +Core: +- apollo-server: "^4.7.0" +- graphql: "^16.6.0" +- type-graphql: "^2.0.0" +- dataloader: "^2.2.0" + +Optional: +- graphql-tools: "^9.0.0" +- graphql-shield: "^7.6.0" +- graphql-scalars: "^1.22.0" +- jest: "^29.5.0" + +// Code Examples: + +1. Schema Definition: +```graphql +type User { + id: ID! + email: String! + name: String! + posts: [Post!]! + createdAt: DateTime! + updatedAt: DateTime! +} + +type Post { + id: ID! + title: String! + content: String! + author: User! + createdAt: DateTime! + updatedAt: DateTime! +} + +input CreateUserInput { + email: String! + name: String! + password: String! +} + +input UpdateUserInput { + name: String + password: String +} + +type Query { + user(id: ID!): User + users(page: Int, limit: Int): [User!]! + me: User +} + +type Mutation { + createUser(input: CreateUserInput!): User! + updateUser(id: ID!, input: UpdateUserInput!): User! + deleteUser(id: ID!): Boolean! +} + +type Subscription { + userCreated: User! +} +``` + +2. Resolver Pattern: +```typescript +import { Resolver, Query, Mutation, Arg, Ctx, UseMiddleware } from 'type-graphql'; +import { User, CreateUserInput, UpdateUserInput } from '../models/User'; +import { UserService } from '../services/UserService'; +import { isAuthenticated } from '../middleware/auth'; +import { Context } from '../types/Context'; + +@Resolver(User) +export class UserResolver { + constructor( + private readonly userService: UserService, + ) {} + + @Query(() => User, { nullable: true }) + async user( + @Arg('id') id: string, + @Ctx() ctx: Context + ): Promise { + return this.userService.findById(id); + } + + @Query(() => [User]) + @UseMiddleware(isAuthenticated) + async users( + @Arg('page', { nullable: true }) page?: number, + @Arg('limit', { nullable: true }) limit?: number, + @Ctx() ctx: Context + ): Promise { + return this.userService.findAll({ page, limit }); + } + + @Mutation(() => User) + async createUser( + @Arg('input') input: CreateUserInput, + @Ctx() ctx: Context + ): Promise { + return this.userService.create(input); + } + + @Mutation(() => User) + @UseMiddleware(isAuthenticated) + async updateUser( + @Arg('id') id: string, + @Arg('input') input: UpdateUserInput, + @Ctx() ctx: Context + ): Promise { + return this.userService.update(id, input); + } + + @Mutation(() => Boolean) + @UseMiddleware(isAuthenticated) + async deleteUser( + @Arg('id') id: string, + @Ctx() ctx: Context + ): Promise { + await this.userService.delete(id); + return true; + } +} +``` + +3. Service Pattern: +```typescript +import { Service } from 'typedi'; +import { Repository } from 'typeorm'; +import { User, CreateUserInput, UpdateUserInput } from '../models/User'; +import { ValidationError, NotFoundError } from '../utils/errors'; +import { hashPassword } from '../utils/auth'; + +@Service() +export class UserService { + constructor( + @InjectRepository(User) + private readonly userRepository: Repository, + ) {} + + async findById(id: string): Promise { + const user = await this.userRepository.findOne({ where: { id } }); + if (!user) { + throw new NotFoundError('User not found'); + } + return user; + } + + async findAll(options: { page?: number; limit?: number }): Promise { + const { page = 1, limit = 10 } = options; + return this.userRepository.find({ + skip: (page - 1) * limit, + take: limit, + order: { createdAt: 'DESC' }, + }); + } + + async create(input: CreateUserInput): Promise { + const existingUser = await this.userRepository.findOne({ + where: { email: input.email }, + }); + + if (existingUser) { + throw new ValidationError('Email already exists'); + } + + const hashedPassword = await hashPassword(input.password); + const user = this.userRepository.create({ + ...input, + password: hashedPassword, + }); + + return this.userRepository.save(user); + } + + async update(id: string, input: UpdateUserInput): Promise { + const user = await this.findById(id); + + if (input.password) { + input.password = await hashPassword(input.password); + } + + Object.assign(user, input); + return this.userRepository.save(user); + } + + async delete(id: string): Promise { + const user = await this.findById(id); + await this.userRepository.remove(user); + } +} +``` + +4. DataLoader Pattern: +```typescript +import DataLoader from 'dataloader'; +import { Service } from 'typedi'; +import { User } from '../models/User'; +import { Post } from '../models/Post'; +import { PostService } from './PostService'; + +@Service() +export class PostLoader { + private loader: DataLoader; + + constructor(private readonly postService: PostService) { + this.loader = new DataLoader(this.batchLoadPosts.bind(this)); + } + + private async batchLoadPosts(userIds: string[]): Promise { + const posts = await this.postService.findByUserIds(userIds); + + const postsByUser = userIds.map(userId => + posts.filter(post => post.userId === userId) + ); + + return postsByUser; + } + + async loadPosts(userId: string): Promise { + return this.loader.load(userId); + } +} +``` + +// Best Practices: +1. Code Quality: + - Type safety + - Documentation + - Testing + - Error handling + - Validation + - Code organization + +2. Schema Design: + - Type definitions + - Input validation + - Error handling + - Nullability + - Pagination + - Filtering + +3. Performance: + - Data loaders + - Query complexity + - Caching + - Batching + - Rate limiting + - Monitoring + +4. Security: + - Authentication + - Authorization + - Input validation + - Rate limiting + - Query depth + - Field restrictions + +// Security Considerations: +1. API Security: + - Authentication + - Authorization + - Input validation + - Rate limiting + - Query complexity + - Field restrictions + +2. Data Security: + - Password hashing + - Data encryption + - Access control + - Audit logging + - Error handling + - Data validation + +3. Infrastructure: + - HTTPS + - CORS + - Headers + - Monitoring + - Logging + - Backups \ No newline at end of file diff --git a/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules b/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..a5177ad --- /dev/null +++ b/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,461 @@ +// HTML, CSS, and JavaScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern web application using HTML, CSS, and JavaScript: +- Responsive layouts +- Interactive UI components +- Form validation +- DOM manipulation +- AJAX requests +- CSS animations +- Local storage +- Web APIs + +// Project Structure +project/ + src/ # Source files + index.html # Main HTML file + css/ # Stylesheets + main.css # Main styles + reset.css # CSS reset + utils.css # Utility classes + js/ # JavaScript files + main.js # Main script + utils.js # Utility functions + api.js # API calls + assets/ # Static assets + images/ # Image files + fonts/ # Font files + dist/ # Production build + tests/ # Test suite + unit/ # Unit tests + e2e/ # End-to-end tests + +// Development Guidelines +1. HTML Structure: + - Semantic markup + - Accessibility + - Meta tags + - Open Graph + - Schema.org + - Performance + +2. CSS Organization: + - BEM methodology + - Mobile-first + - CSS variables + - Flexbox/Grid + - Media queries + - Animations + +3. JavaScript Best Practices: + - ES6+ features + - Modules + - Event handling + - Error handling + - Performance + - Testing + +// Dependencies +Core: +- normalize.css: "^8.0.1" +- font-awesome: "^6.4.0" + +Optional: +- axios: "^1.4.0" +- lodash: "^4.17.21" +- jest: "^29.5.0" +- cypress: "^12.14.0" + +// Code Examples: + +1. HTML Pattern: +```html + + + + + + + + + + Your Site Title + + + + +
+ +
+ +
+
+

Welcome to our site

+

Lorem ipsum dolor sit amet

+ +
+ +
+
+

Feature 1

+

Description

+
+ +
+
+ +
+ +
+ + + + +``` + +2. CSS Pattern: +```css +/* Variables */ +:root { + --color-primary: #007bff; + --color-secondary: #6c757d; + --color-success: #28a745; + --color-danger: #dc3545; + --font-primary: 'Arial', sans-serif; + --spacing-sm: 0.5rem; + --spacing-md: 1rem; + --spacing-lg: 2rem; +} + +/* Reset */ +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +/* Typography */ +body { + font-family: var(--font-primary); + line-height: 1.6; + color: #333; +} + +/* Layout */ +.container { + max-width: 1200px; + margin: 0 auto; + padding: 0 var(--spacing-md); +} + +/* Components */ +.nav { + display: flex; + justify-content: space-between; + align-items: center; + padding: var(--spacing-md); + background-color: #fff; + box-shadow: 0 2px 4px rgba(0,0,0,0.1); +} + +.nav__list { + display: flex; + list-style: none; + gap: var(--spacing-md); +} + +.nav__link { + text-decoration: none; + color: var(--color-primary); + transition: color 0.3s ease; +} + +.nav__link:hover { + color: var(--color-secondary); +} + +/* Responsive */ +@media (max-width: 768px) { + .nav { + flex-direction: column; + } + + .nav__list { + margin-top: var(--spacing-md); + } +} + +/* Animations */ +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.fade-in { + animation: fadeIn 0.5s ease forwards; +} +``` + +3. JavaScript Pattern: +```javascript +// Config +const config = { + apiUrl: 'https://api.example.com', + storageKey: 'app_data', + debounceTime: 300 +}; + +// Utils +const utils = { + debounce(func, wait) { + let timeout; + return function executedFunction(...args) { + const later = () => { + clearTimeout(timeout); + func(...args); + }; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + }; + }, + + formatDate(date) { + return new Intl.DateTimeFormat('en-US', { + year: 'numeric', + month: 'long', + day: 'numeric' + }).format(new Date(date)); + }, + + storage: { + set(key, value) { + try { + localStorage.setItem(key, JSON.stringify(value)); + } catch (error) { + console.error('Error saving to localStorage:', error); + } + }, + + get(key) { + try { + const item = localStorage.getItem(key); + return item ? JSON.parse(item) : null; + } catch (error) { + console.error('Error reading from localStorage:', error); + return null; + } + } + } +}; + +// API Service +class ApiService { + constructor(baseUrl) { + this.baseUrl = baseUrl; + } + + async get(endpoint) { + try { + const response = await fetch(`${this.baseUrl}${endpoint}`); + if (!response.ok) throw new Error('Network response was not ok'); + return await response.json(); + } catch (error) { + console.error('API Error:', error); + throw error; + } + } + + async post(endpoint, data) { + try { + const response = await fetch(`${this.baseUrl}${endpoint}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(data) + }); + if (!response.ok) throw new Error('Network response was not ok'); + return await response.json(); + } catch (error) { + console.error('API Error:', error); + throw error; + } + } +} + +// Form Handler +class FormHandler { + constructor(formElement) { + this.form = formElement; + this.init(); + } + + init() { + this.form.addEventListener('submit', this.handleSubmit.bind(this)); + this.form.addEventListener('input', utils.debounce( + this.handleInput.bind(this), + config.debounceTime + )); + } + + handleSubmit(event) { + event.preventDefault(); + if (this.validateForm()) { + const formData = new FormData(this.form); + const data = Object.fromEntries(formData.entries()); + this.submitForm(data); + } + } + + handleInput(event) { + const field = event.target; + this.validateField(field); + } + + validateField(field) { + const value = field.value; + let isValid = true; + let errorMessage = ''; + + switch (field.type) { + case 'email': + isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); + errorMessage = 'Please enter a valid email address'; + break; + case 'password': + isValid = value.length >= 8; + errorMessage = 'Password must be at least 8 characters long'; + break; + // Add more validation cases + } + + this.showFieldError(field, isValid ? '' : errorMessage); + return isValid; + } + + validateForm() { + const fields = this.form.querySelectorAll('input, select, textarea'); + let isValid = true; + + fields.forEach(field => { + if (!this.validateField(field)) { + isValid = false; + } + }); + + return isValid; + } + + showFieldError(field, message) { + const errorElement = field.nextElementSibling; + if (errorElement && errorElement.classList.contains('error-message')) { + errorElement.textContent = message; + field.classList.toggle('invalid', message !== ''); + } + } + + async submitForm(data) { + try { + const api = new ApiService(config.apiUrl); + const response = await api.post('/submit', data); + this.handleSuccess(response); + } catch (error) { + this.handleError(error); + } + } + + handleSuccess(response) { + // Handle successful submission + console.log('Form submitted successfully:', response); + } + + handleError(error) { + // Handle submission error + console.error('Form submission error:', error); + } +} + +// Initialize +document.addEventListener('DOMContentLoaded', () => { + const forms = document.querySelectorAll('form'); + forms.forEach(form => new FormHandler(form)); +}); +``` + +// Best Practices: +1. HTML: + - Semantic elements + - Accessibility (ARIA) + - Valid markup + - Meta tags + - Performance + - SEO optimization + +2. CSS: + - BEM naming + - Mobile-first + - CSS variables + - Flexbox/Grid + - Performance + - Maintainability + +3. JavaScript: + - ES6+ features + - Modules + - Error handling + - Performance + - Testing + - Documentation + +4. Security: + - XSS prevention + - CSRF protection + - Content Security + - Input validation + - Secure storage + - HTTPS usage + +// Security Considerations: +1. Client-side: + - Input validation + - XSS prevention + - CSRF tokens + - Secure storage + - API security + - Error handling + +2. Data Security: + - Form validation + - Data encryption + - Access control + - Session handling + - Error messages + - Logging + +3. Infrastructure: + - HTTPS + - CORS + - Headers + - Caching + - Monitoring + - Backups \ No newline at end of file diff --git a/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules b/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules index e84c905..617cd1a 100644 --- a/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules +++ b/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules @@ -1 +1,259 @@ -You are an expert AI programming assistant that primarily focuses on producing clear, readable HTML, Tailwind CSS and vanilla JavaScript code.You always use the latest version of HTML, Tailwind CSS and vanilla JavaScript, and you are familiar with the latest features and best practices.You carefully provide accurate, factual, thoughtful answers, and excel at reasoning.- Follow the user’s requirements carefully & to the letter.- Confirm, then write code!- Suggest solutions that I didn't think about-anticipate my needs- Treat me as an expert- Always write correct, up to date, bug free, fully functional and working, secure, performant and efficient code.- Focus on readability over being performant.- Fully implement all requested functionality.- Leave NO todo’s, placeholders or missing pieces.- Be concise. Minimize any other prose.- Consider new technologies and contrarian ideas, not just the conventional wisdom- If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.- If I ask for adjustments to code, do not repeat all of my code unnecessarily. Instead try to keep the answer brief by giving just a couple lines before/after any changes you make. \ No newline at end of file +// HTML, Tailwind CSS & JavaScript Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern, responsive web applications featuring: +- Semantic HTML5 markup +- Utility-first styling with Tailwind CSS +- Interactive UIs with vanilla JavaScript +- Responsive layouts +- Accessible components +- Progressive enhancement +- Modern animations +- Performance optimization + +// Project Structure +src/ + assets/ # Static assets + images/ # Image files + fonts/ # Font files + css/ # CSS styles + tailwind/ # Tailwind configuration + config.js # Tailwind config + custom.css # Custom utilities + styles.css # Main stylesheet + js/ # JavaScript files + components/ # UI components + modal.js # Modal component + dropdown.js # Dropdown component + utils/ # Utility functions + dom.js # DOM helpers + validation.js # Form validation + main.js # Entry point + pages/ # HTML pages + index.html # Home page + about.html # About page + templates/ # Reusable templates + header.html # Header component + footer.html # Footer component + +// Development Guidelines +1. HTML Structure: + - Use semantic markup + - Follow accessibility guidelines + - Implement proper SEO + - Maintain clean hierarchy + - Include meta tags + - Optimize for performance + +2. Tailwind CSS Usage: + - Use utility classes + - Follow responsive design + - Implement dark mode + - Create custom utilities + - Maintain consistency + - Optimize for production + +3. JavaScript Patterns: + - Write modular code + - Use modern ES6+ + - Handle errors properly + - Implement event delegation + - Optimize performance + - Follow best practices + +// Dependencies +Core: +- html: "HTML5" +- tailwindcss: "^3.4.0" +- postcss: "^8.4.0" +- autoprefixer: "^10.4.0" + +Optional: +- alpinejs: "^3.0.0" +- prettier: "^3.1.0" +- eslint: "^8.0.0" +- vite: "^5.0.0" + +// Code Examples: + +1. Responsive Component Pattern: +```html + +
+
+ Card image +
+ +
+

+ Card Title +

+

+ Card description with responsive text that wraps nicely. +

+ +
+ + + + 5 min read + +
+
+
+``` + +2. JavaScript Component Pattern: +```javascript +// Modal Component +class Modal { + constructor(options = {}) { + this.id = options.id || 'modal'; + this.openTrigger = options.openTrigger || '[data-modal-trigger]'; + this.closeTrigger = options.closeTrigger || '[data-modal-close]'; + this.activeClass = options.activeClass || 'is-active'; + this.onOpen = options.onOpen || (() => {}); + this.onClose = options.onClose || (() => {}); + + this.modal = document.getElementById(this.id); + this.isOpen = false; + + this.init(); + } + + init() { + // Setup event listeners + document.querySelectorAll(this.openTrigger) + .forEach(trigger => { + trigger.addEventListener('click', () => this.open()); + }); + + document.querySelectorAll(this.closeTrigger) + .forEach(trigger => { + trigger.addEventListener('click', () => this.close()); + }); + + // Close on escape key + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && this.isOpen) { + this.close(); + } + }); + + // Close on outside click + this.modal.addEventListener('click', (e) => { + if (e.target === this.modal) { + this.close(); + } + }); + } + + open() { + if (this.isOpen) return; + + this.modal.classList.add(this.activeClass); + document.body.style.overflow = 'hidden'; + this.isOpen = true; + this.onOpen(); + } + + close() { + if (!this.isOpen) return; + + this.modal.classList.remove(this.activeClass); + document.body.style.overflow = ''; + this.isOpen = false; + this.onClose(); + } +} +``` + +3. Form Validation Pattern: +```javascript +// Form Validation Utility +const validateForm = { + email: (value) => { + const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return { + isValid: pattern.test(value), + message: pattern.test(value) ? '' : 'Please enter a valid email address' + }; + }, + + password: (value) => { + const hasMinLength = value.length >= 8; + const hasUpperCase = /[A-Z]/.test(value); + const hasLowerCase = /[a-z]/.test(value); + const hasNumber = /\d/.test(value); + + const isValid = hasMinLength && hasUpperCase && hasLowerCase && hasNumber; + + return { + isValid, + message: isValid ? '' : 'Password must be at least 8 characters and contain uppercase, lowercase, and numbers' + }; + }, + + required: (value) => ({ + isValid: value.trim().length > 0, + message: value.trim().length > 0 ? '' : 'This field is required' + }) +}; + +// Usage Example +const form = document.querySelector('form'); +const inputs = form.querySelectorAll('[data-validate]'); + +inputs.forEach(input => { + input.addEventListener('blur', () => { + const validationType = input.dataset.validate; + const result = validateForm[validationType](input.value); + + const errorElement = input.parentElement.querySelector('.error-message'); + + if (!result.isValid) { + input.classList.add('border-red-500'); + errorElement.textContent = result.message; + errorElement.classList.remove('hidden'); + } else { + input.classList.remove('border-red-500'); + errorElement.classList.add('hidden'); + } + }); +}); +``` + +// Best Practices: +1. Write semantic HTML +2. Follow accessibility guidelines +3. Use responsive design +4. Implement progressive enhancement +5. Optimize performance +6. Write modular code +7. Handle errors gracefully +8. Follow naming conventions +9. Document code properly +10. Test cross-browser compatibility + +// Security Considerations: +1. Sanitize user inputs +2. Prevent XSS attacks +3. Use HTTPS +4. Implement CSP +5. Secure form handling +6. Validate data client-side +7. Handle errors securely +8. Use secure dependencies +9. Implement CORS properly +10. Follow security headers \ No newline at end of file diff --git a/rules/htmx-basic-cursorrules-prompt-file/.cursorrules b/rules/htmx-basic-cursorrules-prompt-file/.cursorrules index b2c1515..d174181 100644 --- a/rules/htmx-basic-cursorrules-prompt-file/.cursorrules +++ b/rules/htmx-basic-cursorrules-prompt-file/.cursorrules @@ -1,32 +1,193 @@ -// HTMX Basic Setup .cursorrules - -// HTMX best practices -const htmxBestPractices = [ - "Use hx-get for GET requests", - "Implement hx-post for POST requests", - "Utilize hx-trigger for custom events", - "Use hx-swap to control how content is swapped", - "Implement hx-target to specify where to swap content", - "Utilize hx-indicator for loading indicators", -]; - -// Folder structure -const folderStructure = ` +// HTMX Basic Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern, hypermedia-driven web applications featuring: +- Server-side rendered HTML +- Dynamic UI updates without JavaScript +- Progressive enhancement +- Real-time interactions +- Form validation and submission +- Infinite scrolling +- Modal dialogs +- Live search + +// Project Structure src/ - templates/ - static/ - css/ - js/ - app.py -`; - -// Additional instructions -const additionalInstructions = ` -1. Use semantic HTML5 elements -2. Implement proper CSRF protection -3. Utilize HTMX extensions when needed -4. Use hx-boost for full page navigation -5. Implement proper error handling -6. Follow progressive enhancement principles -7. Use server-side templating (e.g., Jinja2, Handlebars) -`; + templates/ # HTML templates + base.html # Base template + components/ # Reusable components + form.html # Form component + modal.html # Modal component + pages/ # Page templates + index.html # Home page + about.html # About page + static/ # Static assets + css/ # Stylesheets + main.css # Main styles + components/ # Component styles + js/ # JavaScript + htmx.min.js # HTMX library + app.py # Main application + +// Development Guidelines +1. HTMX Attributes: + - Use hx-get for GET requests + - Use hx-post for POST requests + - Use hx-trigger for events + - Use hx-swap for content updates + - Use hx-target for targeting + - Use hx-indicator for loading states + +2. Server Integration: + - Implement CSRF protection + - Return partial HTML + - Handle errors gracefully + - Use proper status codes + - Validate inputs + - Follow REST principles + +3. Progressive Enhancement: + - Start with plain HTML + - Add HTMX attributes + - Use JavaScript sparingly + - Support non-JS users + - Handle fallbacks + - Maintain accessibility + +// Dependencies +Core: +- htmx: "^1.9.0" +- html: "HTML5" +- python: "^3.8" +- flask: "^2.0.0" + +Optional: +- hyperscript: "^0.9.0" +- tailwindcss: "^3.0.0" +- alpine.js: "^3.0.0" +- flask-wtf: "^1.0.0" + +// Code Examples: + +1. Basic Form Pattern: +```html + +
+ +
+ + +
+
+ +
+ + +
+
+ + + +
+
+``` + +2. Server Response Pattern: +```python +from flask import Flask, render_template + +app = Flask(__name__) + +@app.route('/contact', methods=['POST']) +def contact(): + # Validate form data + if not validate_form(): + return render_template('components/form_errors.html'), 400 + + try: + # Process the contact form + process_contact_form() + + # Return success message + return render_template( + 'components/success_message.html', + message="Thank you for your message!" + ) + except Exception as e: + # Return error message + return render_template( + 'components/error_message.html', + error="Failed to send message" + ), 500 +``` + +3. Infinite Scroll Pattern: +```html + +
+ + + {% for item in items %} +
+

{{ item.title }}

+

{{ item.description }}

+ + +
+ {% endfor %} + + +
+ Loading more items... +
+
+``` + +// Best Practices: +1. Use semantic HTML +2. Follow REST principles +3. Implement proper validation +4. Handle errors gracefully +5. Show loading states +6. Use proper targeting +7. Optimize performance +8. Maintain accessibility +9. Follow progressive enhancement +10. Document endpoints + +// Security Considerations: +1. Implement CSRF protection +2. Validate all inputs +3. Sanitize HTML responses +4. Use proper headers +5. Handle errors securely +6. Implement rate limiting +7. Use HTTPS +8. Follow SOP/CORS +9. Protect against XSS +10. Audit dependencies diff --git a/rules/htmx-django-cursorrules-prompt-file/.cursorrules b/rules/htmx-django-cursorrules-prompt-file/.cursorrules index eed49f6..ab0de55 100644 --- a/rules/htmx-django-cursorrules-prompt-file/.cursorrules +++ b/rules/htmx-django-cursorrules-prompt-file/.cursorrules @@ -1,39 +1,222 @@ -// HTMX with Django .cursorrules - -// HTMX and Django best practices -const htmxDjangoBestPractices = [ - "Use Django's template system with HTMX attributes", - "Implement Django forms for form handling", - "Utilize Django's URL routing system", - "Use Django's class-based views for HTMX responses", - "Implement Django ORM for database operations", - "Utilize Django's middleware for request/response processing", -]; - -// Folder structure -const folderStructure = ` +// HTMX with Django Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern Django applications with HTMX integration featuring: +- Server-side rendered templates +- Dynamic UI updates without JavaScript +- Django form integration +- Real-time interactions +- Database-driven updates +- Infinite scrolling +- Modal dialogs +- Live search + +// Project Structure project_name/ - app_name/ - templates/ - static/ - css/ - js/ - models.py - views.py - urls.py - project_name/ - settings.py - urls.py -manage.py -`; - -// Additional instructions -const additionalInstructions = ` -1. Use Django's template tags with HTMX attributes -2. Implement proper CSRF protection with Django's built-in features -3. Utilize Django's HttpResponse for HTMX-specific responses -4. Use Django's form validation for HTMX requests -5. Implement proper error handling and logging -6. Follow Django's best practices for project structure -7. Use Django's staticfiles app for managing static assets -`; + app_name/ # Django app + templates/ # HTML templates + base.html # Base template + components/ # Reusable components + form.html # Form component + modal.html # Modal component + pages/ # Page templates + index.html # Home page + about.html # About page + static/ # Static assets + css/ # Stylesheets + main.css # Main styles + js/ # JavaScript + htmx.min.js # HTMX library + models.py # Database models + views.py # View controllers + urls.py # URL routing + forms.py # Form definitions + tests/ # Test files + test_views.py # View tests + test_models.py # Model tests + project_name/ # Project configuration + settings.py # Django settings + urls.py # Root URL config + manage.py # Django CLI + +// Development Guidelines +1. Django Integration: + - Use class-based views + - Implement Django forms + - Follow URL patterns + - Use template inheritance + - Handle CSRF properly + - Follow Django conventions + +2. HTMX Patterns: + - Use template tags + - Return partial HTML + - Handle form validation + - Implement error responses + - Show loading states + - Use proper targeting + +3. Database Patterns: + - Use Django ORM + - Optimize queries + - Handle transactions + - Implement caching + - Follow migrations + - Maintain consistency + +// Dependencies +Core: +- django: "^4.2.0" +- htmx: "^1.9.0" +- python: "^3.8" +- psycopg2: "^2.9.0" + +Optional: +- django-debug-toolbar: "^4.0.0" +- django-htmx: "^1.0.0" +- django-crispy-forms: "^2.0.0" +- django-compressor: "^4.0.0" + +// Code Examples: + +1. Django View Pattern: +```python +from django.views.generic import ListView +from django.http import HttpResponse +from django.template.loader import render_to_string +from .models import Item + +class ItemListView(ListView): + model = Item + template_name = 'items/list.html' + context_object_name = 'items' + paginate_by = 10 + + def get(self, request, *args, **kwargs): + # Check if this is an HTMX request + if request.htmx: + # Get queryset + self.object_list = self.get_queryset() + context = self.get_context_data() + + # Render only the items partial + html = render_to_string( + 'items/partials/item_list.html', + context, + request=request + ) + return HttpResponse(html) + + # Regular request - render full template + return super().get(request, *args, **kwargs) +``` + +2. Django Template Pattern: +```html +{% extends "base.html" %} +{% load static %} + +{% block content %} +
+ + {% include "items/partials/item_list.html" %} + +
+ Loading more items... +
+
+ + +
+ {% csrf_token %} + + {{ form.as_p }} + + +
+{% endblock %} +``` + +3. Django Form Pattern: +```python +from django import forms +from django.core.exceptions import ValidationError +from .models import Item + +class ItemForm(forms.ModelForm): + class Meta: + model = Item + fields = ['title', 'description'] + + def clean_title(self): + title = self.cleaned_data['title'] + if Item.objects.filter(title=title).exists(): + raise ValidationError('An item with this title already exists.') + return title + + def save(self, commit=True): + instance = super().save(commit=False) + if commit: + instance.save() + # Return HTML for new item + html = render_to_string( + 'items/partials/item.html', + {'item': instance} + ) + return html + return instance + +# View using the form +from django.views.generic.edit import CreateView + +class ItemCreateView(CreateView): + model = Item + form_class = ItemForm + template_name = 'items/create.html' + + def form_valid(self, form): + # Save and get HTML response + html = form.save() + return HttpResponse(html) + + def form_invalid(self, form): + return HttpResponse( + str(form.errors), + status=400 + ) +``` + +// Best Practices: +1. Follow Django conventions +2. Use class-based views +3. Implement proper forms +4. Handle CSRF correctly +5. Optimize database queries +6. Use template inheritance +7. Handle errors gracefully +8. Write comprehensive tests +9. Document view responses +10. Follow URL naming + +// Security Considerations: +1. Enable CSRF protection +2. Validate form inputs +3. Sanitize HTML output +4. Use proper permissions +5. Handle file uploads safely +6. Implement rate limiting +7. Use HTTPS +8. Secure admin interface +9. Audit dependencies +10. Log security events diff --git a/rules/htmx-flask-cursorrules-prompt-file/.cursorrules b/rules/htmx-flask-cursorrules-prompt-file/.cursorrules index 3e19823..dff8550 100644 --- a/rules/htmx-flask-cursorrules-prompt-file/.cursorrules +++ b/rules/htmx-flask-cursorrules-prompt-file/.cursorrules @@ -1,36 +1,246 @@ -// HTMX with Flask .cursorrules - -// HTMX and Flask best practices -const htmxFlaskBestPractices = [ - "Use Flask's render_template for server-side rendering", - "Implement Flask-WTF for form handling", - "Utilize Flask's url_for for generating URLs", - "Use Flask's jsonify for JSON responses", - "Implement Flask-SQLAlchemy for database operations", - "Utilize Flask's Blueprint for modular applications", -]; - -// Folder structure -const folderStructure = ` +// HTMX with Flask Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern Flask applications with HTMX integration featuring: +- Server-side rendered templates +- Dynamic UI updates without JavaScript +- Flask form integration +- Real-time interactions +- Database-driven updates +- Infinite scrolling +- Modal dialogs +- Live search + +// Project Structure app/ - templates/ - static/ - css/ - js/ - models/ - routes/ - __init__.py -config.py -run.py -`; - -// Additional instructions -const additionalInstructions = ` -1. Use Jinja2 templating with HTMX attributes -2. Implement proper CSRF protection with Flask-WTF -3. Utilize Flask's request object for handling HTMX requests -4. Use Flask-Migrate for database migrations -5. Implement proper error handling and logging -6. Follow Flask's application factory pattern -7. Use environment variables for configuration -`; + templates/ # HTML templates + base.html # Base template + components/ # Reusable components + form.html # Form component + modal.html # Modal component + pages/ # Page templates + index.html # Home page + about.html # About page + static/ # Static assets + css/ # Stylesheets + main.css # Main styles + js/ # JavaScript + htmx.min.js # HTMX library + models/ # Database models + __init__.py # Package init + user.py # User model + item.py # Item model + routes/ # Route handlers + __init__.py # Package init + main.py # Main routes + api.py # API routes + forms/ # Form definitions + __init__.py # Package init + user.py # User forms + item.py # Item forms + __init__.py # App factory +config.py # Configuration +run.py # Entry point + +// Development Guidelines +1. Flask Integration: + - Use application factory + - Implement Flask-WTF forms + - Follow Blueprint patterns + - Use Jinja2 templates + - Handle CSRF properly + - Follow Flask conventions + +2. HTMX Patterns: + - Use template filters + - Return partial HTML + - Handle form validation + - Implement error responses + - Show loading states + - Use proper targeting + +3. Database Patterns: + - Use SQLAlchemy ORM + - Optimize queries + - Handle transactions + - Implement caching + - Follow migrations + - Maintain consistency + +// Dependencies +Core: +- flask: "^2.3.0" +- htmx: "^1.9.0" +- python: "^3.8" +- flask-sqlalchemy: "^3.0.0" + +Optional: +- flask-wtf: "^1.1.0" +- flask-migrate: "^4.0.0" +- flask-login: "^0.6.0" +- flask-caching: "^2.0.0" + +// Code Examples: + +1. Flask Route Pattern: +```python +from flask import Blueprint, render_template, request, jsonify +from .models import Item +from .forms import ItemForm + +bp = Blueprint('items', __name__) + +@bp.route('/items', methods=['GET']) +def list_items(): + page = request.args.get('page', 1, type=int) + items = Item.query.paginate(page=page, per_page=10) + + # Check if HTMX request + if request.headers.get('HX-Request'): + return render_template( + 'components/item_list.html', + items=items + ) + + # Regular request - full page + return render_template( + 'pages/items.html', + items=items + ) + +@bp.route('/items/create', methods=['POST']) +def create_item(): + form = ItemForm() + + if form.validate_on_submit(): + item = Item( + title=form.title.data, + description=form.description.data + ) + db.session.add(item) + db.session.commit() + + # Return new item HTML + return render_template( + 'components/item.html', + item=item + ) + + # Return form errors + return jsonify(form.errors), 400 +``` + +2. Flask Template Pattern: +```html +{% extends "base.html" %} +{% block content %} + + +
+ + {% include "components/item_list.html" %} + +
+ Loading more items... +
+
+ + +
+ {{ form.csrf_token }} + +
+ {{ form.title.label }} + {{ form.title(class="form-control") }} +
+
+ +
+ {{ form.description.label }} + {{ form.description(class="form-control") }} +
+
+ + +
+ +{% endblock %} +``` + +3. Flask Form Pattern: +```python +from flask_wtf import FlaskForm +from wtforms import StringField, TextAreaField +from wtforms.validators import DataRequired, Length + +class ItemForm(FlaskForm): + title = StringField( + 'Title', + validators=[ + DataRequired(), + Length(min=3, max=100) + ] + ) + + description = TextAreaField( + 'Description', + validators=[ + DataRequired(), + Length(min=10, max=500) + ] + ) + + def validate_title(self, field): + # Check for unique title + if Item.query.filter_by(title=field.data).first(): + raise ValidationError('Title must be unique') + +# Custom response handler +def handle_form_errors(form): + """Convert WTForms errors to HTMX-friendly response.""" + errors = {} + for field, messages in form.errors.items(): + errors[f"{field}-error"] = { + "innerHTML": " ".join(messages) + } + + response = jsonify({ + "errors": errors + }) + response.status_code = 400 + return response +``` + +// Best Practices: +1. Follow Flask conventions +2. Use Blueprints +3. Implement proper forms +4. Handle CSRF correctly +5. Optimize database queries +6. Use template inheritance +7. Handle errors gracefully +8. Write comprehensive tests +9. Document endpoints +10. Follow URL naming + +// Security Considerations: +1. Enable CSRF protection +2. Validate form inputs +3. Sanitize HTML output +4. Use proper permissions +5. Handle file uploads safely +6. Implement rate limiting +7. Use HTTPS +8. Secure configuration +9. Audit dependencies +10. Log security events diff --git a/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules b/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules index d5efd2b..14a936a 100644 --- a/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules +++ b/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules @@ -1,37 +1,321 @@ -// HTMX with Go (Basic Setup) .cursorrules - -// HTMX and Go best practices -const htmxGoBestPractices = [ - "Use html/template for server-side rendering", - "Implement http.HandlerFunc for handling HTMX requests", - "Utilize gorilla/mux for routing if needed", - "Use encoding/json for JSON responses", - "Implement proper error handling and logging", - "Utilize context for request cancellation and timeouts", -]; - -// Folder structure -const folderStructure = ` +// HTMX with Go Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern Go web applications with HTMX integration featuring: +- Server-side rendered templates +- Dynamic UI updates without JavaScript +- Efficient HTTP handlers +- Real-time interactions +- RESTful endpoints +- Infinite scrolling +- Modal dialogs +- Live search + +// Project Structure cmd/ - main.go -internal/ - handlers/ - models/ - templates/ -static/ - css/ - js/ -go.mod -go.sum -`; - -// Additional instructions -const additionalInstructions = ` -1. Use semantic HTML5 elements with HTMX attributes -2. Implement proper CSRF protection -3. Utilize HTMX extensions when needed -4. Use hx-boost for full page navigation -5. Follow Go's idiomatic error handling -6. Implement graceful shutdown for the server -7. Use Go modules for dependency management -`; + server/ # Application entrypoint + main.go # Server initialization +internal/ # Private application code + handlers/ # HTTP handlers + items.go # Item handlers + users.go # User handlers + templates.go # Template helpers + models/ # Data models + item.go # Item model + user.go # User model + middleware/ # HTTP middleware + auth.go # Authentication + logging.go # Request logging + csrf.go # CSRF protection + templates/ # HTML templates + base.html # Base template + components/ # Reusable components + form.html # Form component + modal.html # Modal component + pages/ # Page templates + index.html # Home page + about.html # About page +static/ # Static assets + css/ # Stylesheets + main.css # Main styles + js/ # JavaScript + htmx.min.js # HTMX library +go.mod # Module definition +go.sum # Module checksums + +// Development Guidelines +1. Go Integration: + - Use http.Handler interface + - Implement middleware + - Follow idiomatic Go + - Use html/template + - Handle errors properly + - Follow Go conventions + +2. HTMX Patterns: + - Return partial HTML + - Handle form submissions + - Implement validation + - Show loading states + - Use proper targeting + - Follow REST principles + +3. Performance Patterns: + - Use goroutines safely + - Implement caching + - Handle timeouts + - Optimize templates + - Use connection pools + - Monitor resources + +// Dependencies +Core: +- go: ">=1.22" +- htmx: "^1.9.0" +- chi: "^5.0.0" +- sqlx: "^1.3.0" + +Optional: +- gorilla/csrf: "^1.7.0" +- zap: "^1.24.0" +- validator: "^10.0.0" +- pgx: "^5.0.0" + +// Code Examples: + +1. HTTP Handler Pattern: +```go +package handlers + +import ( + "html/template" + "net/http" + "strconv" +) + +type ItemHandler struct { + tmpl *template.Template + db *sqlx.DB +} + +func NewItemHandler(tmpl *template.Template, db *sqlx.DB) *ItemHandler { + return &ItemHandler{ + tmpl: tmpl, + db: db, + } +} + +func (h *ItemHandler) List(w http.ResponseWriter, r *http.Request) { + // Parse pagination params + page, _ := strconv.Atoi(r.URL.Query().Get("page")) + if page < 1 { + page = 1 + } + + // Fetch items + items, err := h.db.QueryContext(r.Context(), ` + SELECT id, title, description + FROM items + ORDER BY created_at DESC + LIMIT 10 OFFSET $1 + `, (page-1)*10) + if err != nil { + http.Error(w, "Failed to fetch items", http.StatusInternalServerError) + return + } + defer items.Close() + + // Check if HTMX request + if r.Header.Get("HX-Request") == "true" { + h.tmpl.ExecuteTemplate(w, "components/item_list.html", items) + return + } + + // Regular request - full page + h.tmpl.ExecuteTemplate(w, "pages/items.html", items) +} + +func (h *ItemHandler) Create(w http.ResponseWriter, r *http.Request) { + // Parse form + if err := r.ParseForm(); err != nil { + http.Error(w, "Invalid form data", http.StatusBadRequest) + return + } + + // Validate input + title := r.Form.Get("title") + description := r.Form.Get("description") + if title == "" || description == "" { + http.Error(w, "Missing required fields", http.StatusBadRequest) + return + } + + // Create item + var id int64 + err := h.db.QueryRowContext(r.Context(), ` + INSERT INTO items (title, description) + VALUES ($1, $2) + RETURNING id + `, title, description).Scan(&id) + if err != nil { + http.Error(w, "Failed to create item", http.StatusInternalServerError) + return + } + + // Fetch new item + item := struct { + ID int64 + Title string + Description string + }{} + err = h.db.GetContext(r.Context(), &item, ` + SELECT id, title, description + FROM items WHERE id = $1 + `, id) + if err != nil { + http.Error(w, "Failed to fetch item", http.StatusInternalServerError) + return + } + + // Return new item HTML + h.tmpl.ExecuteTemplate(w, "components/item.html", item) +} +``` + +2. Template Pattern: +```html +{{/* base.html */}} + + + + + {{template "title" .}} + + + + + {{template "content" .}} + + + +{{/* components/item_list.html */}} +{{define "item-list"}} +
+ + {{range .Items}} +
+

{{.Title}}

+

{{.Description}}

+ + +
+ {{end}} + +
+ Loading more items... +
+
+{{end}} + +{{/* components/item_form.html */}} +{{define "item-form"}} +
+ {{.CSRFField}} + +
+ + +
+
+ +
+ + +
+
+ + +
+{{end}} +``` + +3. Router Pattern: +```go +package main + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" +) + +func setupRouter(h *handlers.ItemHandler) http.Handler { + r := chi.NewRouter() + + // Middleware + r.Use(middleware.Logger) + r.Use(middleware.Recoverer) + r.Use(middleware.RealIP) + r.Use(middleware.RequestID) + r.Use(middleware.Timeout(60 * time.Second)) + + // Routes + r.Get("/", h.List) + r.Route("/items", func(r chi.Router) { + r.Get("/", h.List) + r.Post("/", h.Create) + r.Route("/{id}", func(r chi.Router) { + r.Get("/", h.Get) + r.Put("/", h.Update) + r.Delete("/", h.Delete) + }) + }) + + // Static files + fileServer := http.FileServer(http.Dir("static")) + r.Handle("/static/*", http.StripPrefix("/static/", fileServer)) + + return r +} +``` + +// Best Practices: +1. Follow Go idioms +2. Use proper interfaces +3. Handle errors gracefully +4. Implement middleware +5. Optimize performance +6. Use prepared statements +7. Validate inputs +8. Write unit tests +9. Document code +10. Follow naming conventions + +// Security Considerations: +1. Enable CSRF protection +2. Validate all inputs +3. Sanitize HTML output +4. Use proper headers +5. Handle file uploads safely +6. Implement rate limiting +7. Use HTTPS +8. Secure cookies +9. Audit dependencies +10. Log security events diff --git a/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules b/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules index ba5bb2d..a3d8662 100644 --- a/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules +++ b/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules @@ -1,37 +1,317 @@ -// HTMX with Go and Fiber .cursorrules - -// HTMX, Go, and Fiber best practices -const htmxGoFiberBestPractices = [ - "Use Fiber's HTML rendering for server-side templates", - "Implement Fiber's routing system for HTMX requests", - "Utilize Fiber's middleware for request processing", - "Use Fiber's JSON methods for API responses", - "Implement proper error handling with Fiber's error handling", - "Utilize Fiber's static file serving for assets", -]; - -// Folder structure -const folderStructure = ` +// HTMX with Go Fiber Development Guidelines +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +Modern Go web applications with HTMX and Fiber integration featuring: +- High-performance server-side rendering +- Dynamic UI updates without JavaScript +- Fast HTTP routing with Fiber +- Real-time interactions +- RESTful endpoints +- WebSocket support +- Modal dialogs +- Live search + +// Project Structure cmd/ - main.go -internal/ - handlers/ - models/ - templates/ -static/ - css/ - js/ -go.mod -go.sum -`; - -// Additional instructions -const additionalInstructions = ` -1. Use Fiber's App.Get/Post/etc for routing HTMX requests -2. Implement CSRF protection with Fiber middleware -3. Utilize Fiber's Context for handling HTMX-specific headers -4. Use Fiber's template engine for server-side rendering -5. Implement proper logging with Fiber's Logger middleware -6. Follow Fiber's best practices for project structure -7. Use environment variables for configuration -`; + server/ # Application entrypoint + main.go # Server initialization +internal/ # Private application code + handlers/ # HTTP handlers + items.go # Item handlers + users.go # User handlers + templates.go # Template helpers + models/ # Data models + item.go # Item model + user.go # User model + middleware/ # Fiber middleware + auth.go # Authentication + logging.go # Request logging + csrf.go # CSRF protection + templates/ # HTML templates + layouts/ # Template layouts + main.html # Main layout + views/ # View templates + index.html # Home page + about.html # About page + partials/ # Partial templates + form.html # Form partial + modal.html # Modal partial +static/ # Static assets + css/ # Stylesheets + main.css # Main styles + js/ # JavaScript + htmx.min.js # HTMX library +go.mod # Module definition +go.sum # Module checksums + +// Development Guidelines +1. Fiber Integration: + - Use fiber.Handler interface + - Implement Fiber middleware + - Follow idiomatic Go + - Use html/template or Fiber Views + - Handle errors properly + - Follow Fiber conventions + +2. HTMX Patterns: + - Return partial HTML + - Handle form submissions + - Implement validation + - Show loading states + - Use proper targeting + - Follow REST principles + +3. Performance Patterns: + - Use Fiber's FastHTTP + - Implement caching + - Handle timeouts + - Optimize templates + - Use connection pools + - Monitor resources + +// Dependencies +Core: +- go: ">=1.22" +- fiber: "^2.52.0" +- htmx: "^1.9.0" +- sqlx: "^1.3.0" + +Optional: +- fiber/csrf: "^2.52.0" +- zap: "^1.24.0" +- validator: "^10.0.0" +- pgx: "^5.0.0" + +// Code Examples: + +1. Fiber Handler Pattern: +```go +package handlers + +import ( + "github.com/gofiber/fiber/v2" + "github.com/jmoiron/sqlx" +) + +type ItemHandler struct { + db *sqlx.DB +} + +func NewItemHandler(db *sqlx.DB) *ItemHandler { + return &ItemHandler{ + db: db, + } +} + +func (h *ItemHandler) List(c *fiber.Ctx) error { + // Parse pagination params + page := c.QueryInt("page", 1) + if page < 1 { + page = 1 + } + + // Fetch items + var items []struct { + ID int64 `db:"id"` + Title string `db:"title"` + Description string `db:"description"` + } + err := h.db.SelectContext(c.Context(), &items, ` + SELECT id, title, description + FROM items + ORDER BY created_at DESC + LIMIT 10 OFFSET $1 + `, (page-1)*10) + if err != nil { + return c.Status(500).SendString("Failed to fetch items") + } + + // Check if HTMX request + if c.Get("HX-Request") == "true" { + return c.Render("partials/item_list", fiber.Map{ + "Items": items, + }) + } + + // Regular request - full page + return c.Render("views/items", fiber.Map{ + "Items": items, + }) +} + +func (h *ItemHandler) Create(c *fiber.Ctx) error { + // Parse form + title := c.FormValue("title") + description := c.FormValue("description") + if title == "" || description == "" { + return c.Status(400).SendString("Missing required fields") + } + + // Create item + var id int64 + err := h.db.QueryRowContext(c.Context(), ` + INSERT INTO items (title, description) + VALUES ($1, $2) + RETURNING id + `, title, description).Scan(&id) + if err != nil { + return c.Status(500).SendString("Failed to create item") + } + + // Fetch new item + item := struct { + ID int64 `db:"id"` + Title string `db:"title"` + Description string `db:"description"` + }{} + err = h.db.GetContext(c.Context(), &item, ` + SELECT id, title, description + FROM items WHERE id = $1 + `, id) + if err != nil { + return c.Status(500).SendString("Failed to fetch item") + } + + // Return new item HTML + return c.Render("partials/item", fiber.Map{ + "Item": item, + }) +} +``` + +2. Template Pattern: +```html +{{/* layouts/main.html */}} + + + + + {{.Title}} + + + + + {{embed}} + + + +{{/* partials/item_list.html */}} +
+ + {{range .Items}} +
+

{{.Title}}

+

{{.Description}}

+ + +
+ {{end}} + +
+ Loading more items... +
+
+ +{{/* partials/item_form.html */}} +
+ {{.CSRFInput}} + +
+ + +
+
+ +
+ + +
+
+ + +
+``` + +3. Router Pattern: +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/logger" + "github.com/gofiber/fiber/v2/middleware/recover" + "github.com/gofiber/template/html/v2" +) + +func setupRouter(h *handlers.ItemHandler) *fiber.App { + // Initialize template engine + engine := html.New("./templates", ".html") + + // Create Fiber app + app := fiber.New(fiber.Config{ + Views: engine, + ViewsLayout: "layouts/main", + }) + + // Middleware + app.Use(logger.New()) + app.Use(recover.New()) + + // Routes + app.Get("/", h.List) + app.Route("/items", func(router fiber.Router) { + router.Get("/", h.List) + router.Post("/", h.Create) + router.Route("/:id", func(router fiber.Router) { + router.Get("/", h.Get) + router.Put("/", h.Update) + router.Delete("/", h.Delete) + }) + }) + + // Static files + app.Static("/static", "./static") + + return app +} +``` + +// Best Practices: +1. Follow Fiber idioms +2. Use proper interfaces +3. Handle errors gracefully +4. Implement middleware +5. Optimize performance +6. Use prepared statements +7. Validate inputs +8. Write unit tests +9. Document code +10. Follow naming conventions + +// Security Considerations: +1. Enable CSRF protection +2. Validate all inputs +3. Sanitize HTML output +4. Use proper headers +5. Handle file uploads safely +6. Implement rate limiting +7. Use HTTPS +8. Secure cookies +9. Audit dependencies +10. Log security events diff --git a/rules/java-spring-boot-cursorrules-prompt-file/.cursorrules b/rules/java-spring-boot-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..b8d46c3 --- /dev/null +++ b/rules/java-spring-boot-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,358 @@ +// Java Spring Boot Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Spring Boot application: +- RESTful APIs +- GraphQL APIs +- WebSocket servers +- Microservices +- Authentication +- Database integration +- Message queues +- Background jobs + +// Project Structure +src/ # Source code + main/ # Main application + java/com/example/project/ # Package structure + Application.java # Main application class + config/ # Configuration + SecurityConfig.java # Security configuration + WebConfig.java # Web configuration + controller/ # REST controllers + UserController.java # User controller + ProductController.java # Product controller + model/ # Domain models + User.java # User model + Product.java # Product model + repository/ # Data access + UserRepository.java # User repository + ProductRepository.java # Product repository + service/ # Business logic + UserService.java # User service + ProductService.java # Product service + exception/ # Custom exceptions + ResourceNotFoundException.java # Resource not found exception + ValidationException.java # Validation exception + util/ # Utilities + Constants.java # Constants + DateUtils.java # Date utilities + resources/ # Resources + application.yml # Application properties + db/migration/ # Flyway migrations + static/ # Static resources + templates/ # Thymeleaf templates + test/ # Test suite + java/com/example/project/ # Test classes + controller/ # Controller tests + service/ # Service tests + repository/ # Repository tests + +// Development Guidelines +1. Code Structure: + - Clean architecture + - Dependency injection + - Service layer + - Repository pattern + - Exception handling + - Logging + +2. API Design: + - RESTful principles + - Versioning + - Documentation + - Validation + - Error handling + - Security + +3. Performance: + - Caching + - Connection pooling + - Query optimization + - Async processing + - Monitoring + - Profiling + +// Dependencies +Core: +- spring-boot-starter-web: "3.1.0" +- spring-boot-starter-data-jpa: "3.1.0" +- spring-boot-starter-security: "3.1.0" +- spring-boot-starter-validation: "3.1.0" + +Optional: +- spring-boot-starter-actuator: "3.1.0" +- spring-boot-starter-cache: "3.1.0" +- spring-boot-starter-test: "3.1.0" +- springdoc-openapi-starter-webmvc-ui: "2.1.0" + +// Code Examples: + +1. Controller Pattern: +```java +package com.example.project.controller; + +import com.example.project.model.User; +import com.example.project.service.UserService; +import com.example.project.dto.UserDTO; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/v1/users") +@RequiredArgsConstructor +public class UserController { + private final UserService userService; + + @GetMapping("/{id}") + public ResponseEntity getUser(@PathVariable Long id) { + return ResponseEntity.ok(userService.findById(id)); + } + + @PostMapping + public ResponseEntity createUser(@Valid @RequestBody UserDTO userDTO) { + return ResponseEntity.ok(userService.create(userDTO)); + } + + @PutMapping("/{id}") + public ResponseEntity updateUser( + @PathVariable Long id, + @Valid @RequestBody UserDTO userDTO + ) { + return ResponseEntity.ok(userService.update(id, userDTO)); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteUser(@PathVariable Long id) { + userService.delete(id); + return ResponseEntity.noContent().build(); + } +} +``` + +2. Service Pattern: +```java +package com.example.project.service; + +import com.example.project.model.User; +import com.example.project.repository.UserRepository; +import com.example.project.dto.UserDTO; +import com.example.project.exception.ResourceNotFoundException; +import com.example.project.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class UserService { + private final UserRepository userRepository; + private final UserMapper userMapper; + + @Transactional(readOnly = true) + public UserDTO findById(Long id) { + return userRepository.findById(id) + .map(userMapper::toDTO) + .orElseThrow(() -> new ResourceNotFoundException("User not found")); + } + + @Transactional + public UserDTO create(UserDTO userDTO) { + User user = userMapper.toEntity(userDTO); + user = userRepository.save(user); + return userMapper.toDTO(user); + } + + @Transactional + public UserDTO update(Long id, UserDTO userDTO) { + User user = userRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("User not found")); + + userMapper.updateEntity(userDTO, user); + user = userRepository.save(user); + return userMapper.toDTO(user); + } + + @Transactional + public void delete(Long id) { + if (!userRepository.existsById(id)) { + throw new ResourceNotFoundException("User not found"); + } + userRepository.deleteById(id); + } +} +``` + +3. Repository Pattern: +```java +package com.example.project.repository; + +import com.example.project.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); + + boolean existsByEmail(String email); + + @Query("SELECT u FROM User u WHERE u.active = true") + List findAllActiveUsers(); + + @Query(value = """ + SELECT u.* FROM users u + LEFT JOIN user_roles ur ON u.id = ur.user_id + WHERE ur.role_id = :roleId + """, nativeQuery = true) + List findByRoleId(Long roleId); +} +``` + +4. Model Pattern: +```java +package com.example.project.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; +import java.time.LocalDateTime; + +@Entity +@Table(name = "users") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false, unique = true) + private String email; + + @Column(nullable = false) + private String password; + + @Column(name = "created_at") + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} +``` + +5. Configuration Pattern: +```java +package com.example.project.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + return http + .csrf().disable() + .authorizeHttpRequests(auth -> auth + .requestMatchers("/api/v1/auth/**").permitAll() + .requestMatchers("/api/v1/public/**").permitAll() + .anyRequest().authenticated() + ) + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .build(); + } +} +``` + +// Best Practices: +1. Code Quality: + - Clean code + - SOLID principles + - Design patterns + - Documentation + - Testing + - Code reviews + +2. Architecture: + - Layered architecture + - Microservices + - API Gateway + - Service discovery + - Load balancing + - Circuit breakers + +3. Performance: + - Caching + - Connection pools + - Query optimization + - Async processing + - Monitoring + - Profiling + +4. Security: + - Authentication + - Authorization + - Input validation + - CSRF protection + - XSS prevention + - SQL injection + +// Security Considerations: +1. API Security: + - JWT tokens + - OAuth 2.0 + - Rate limiting + - Input validation + - Error handling + - Logging + +2. Data Security: + - Encryption + - Password hashing + - Access control + - Audit logging + - Data validation + - Backups + +3. Infrastructure: + - HTTPS + - Firewalls + - Load balancers + - Monitoring + - Logging + - Backups \ No newline at end of file diff --git a/rules/javascript-cursorrules-prompt-file/.cursorrules b/rules/javascript-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..2973ccc --- /dev/null +++ b/rules/javascript-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,354 @@ +// JavaScript Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern JavaScript application: +- Single Page Applications +- Progressive Web Apps +- Node.js APIs +- Real-time applications +- CLI tools +- Browser extensions +- Desktop applications +- Mobile applications + +// Project Structure +project/ + src/ # Source files + components/ # UI components + services/ # Business logic + utils/ # Utilities + hooks/ # Custom hooks + store/ # State management + api/ # API integration + types/ # Type definitions + constants/ # Constants + tests/ # Test suite + unit/ # Unit tests + integration/ # Integration tests + e2e/ # End-to-end tests + public/ # Static assets + dist/ # Production build + +// Development Guidelines +1. Code Structure: + - ES6+ features + - Modules + - Classes + - Functions + - Error handling + - Async/await + +2. Best Practices: + - Clean code + - DRY principles + - SOLID principles + - Documentation + - Testing + - Performance + +3. State Management: + - Immutability + - Side effects + - Actions + - Reducers + - Middleware + - Selectors + +// Dependencies +Core: +- node: ">=18.0.0" +- npm: ">=9.0.0" + +Optional: +- axios: "^1.4.0" +- lodash: "^4.17.21" +- date-fns: "^2.30.0" +- jest: "^29.5.0" + +// Code Examples: + +1. Module Pattern: +```javascript +// api.js +const API_URL = process.env.API_URL || 'https://api.example.com'; + +class ApiService { + constructor(baseUrl = API_URL) { + this.baseUrl = baseUrl; + } + + async get(endpoint, options = {}) { + try { + const response = await fetch(`${this.baseUrl}${endpoint}`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + ...options.headers + } + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + return await response.json(); + } catch (error) { + console.error('API Error:', error); + throw error; + } + } + + async post(endpoint, data, options = {}) { + try { + const response = await fetch(`${this.baseUrl}${endpoint}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...options.headers + }, + body: JSON.stringify(data) + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + return await response.json(); + } catch (error) { + console.error('API Error:', error); + throw error; + } + } +} + +export const api = new ApiService(); +``` + +2. Service Pattern: +```javascript +// userService.js +import { api } from './api'; + +class UserService { + async getUser(id) { + try { + return await api.get(`/users/${id}`); + } catch (error) { + console.error('Error fetching user:', error); + throw error; + } + } + + async createUser(userData) { + try { + return await api.post('/users', userData); + } catch (error) { + console.error('Error creating user:', error); + throw error; + } + } + + async updateUser(id, userData) { + try { + return await api.put(`/users/${id}`, userData); + } catch (error) { + console.error('Error updating user:', error); + throw error; + } + } + + async deleteUser(id) { + try { + return await api.delete(`/users/${id}`); + } catch (error) { + console.error('Error deleting user:', error); + throw error; + } + } +} + +export const userService = new UserService(); +``` + +3. Hook Pattern: +```javascript +// useAsync.js +import { useState, useCallback } from 'react'; + +export function useAsync(asyncFunction) { + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [data, setData] = useState(null); + + const execute = useCallback(async (...args) => { + try { + setLoading(true); + setError(null); + const result = await asyncFunction(...args); + setData(result); + return result; + } catch (error) { + setError(error); + throw error; + } finally { + setLoading(false); + } + }, [asyncFunction]); + + return { + loading, + error, + data, + execute + }; +} +``` + +4. Component Pattern: +```javascript +// UserList.jsx +import React, { useEffect } from 'react'; +import { useAsync } from '../hooks/useAsync'; +import { userService } from '../services/userService'; + +export function UserList() { + const { + loading, + error, + data: users, + execute: fetchUsers + } = useAsync(userService.getUsers); + + useEffect(() => { + fetchUsers(); + }, [fetchUsers]); + + if (loading) { + return
Loading...
; + } + + if (error) { + return
Error: {error.message}
; + } + + return ( +
+ {users?.map(user => ( +
+

{user.name}

+

{user.email}

+
+ ))} +
+ ); +} +``` + +5. Store Pattern: +```javascript +// userSlice.js +import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; +import { userService } from '../services/userService'; + +export const fetchUsers = createAsyncThunk( + 'users/fetchUsers', + async (_, { rejectWithValue }) => { + try { + return await userService.getUsers(); + } catch (error) { + return rejectWithValue(error.message); + } + } +); + +const userSlice = createSlice({ + name: 'users', + initialState: { + data: [], + loading: false, + error: null + }, + reducers: { + clearError: state => { + state.error = null; + } + }, + extraReducers: builder => { + builder + .addCase(fetchUsers.pending, state => { + state.loading = true; + state.error = null; + }) + .addCase(fetchUsers.fulfilled, (state, action) => { + state.loading = false; + state.data = action.payload; + }) + .addCase(fetchUsers.rejected, (state, action) => { + state.loading = false; + state.error = action.payload; + }); + } +}); + +export const { clearError } = userSlice.actions; +export default userSlice.reducer; +``` + +// Best Practices: +1. Code Quality: + - Use ESLint + - Use Prettier + - Write tests + - Document code + - Review code + - Refactor regularly + +2. Performance: + - Optimize bundles + - Lazy loading + - Memoization + - Debouncing + - Throttling + - Caching + +3. Security: + - Input validation + - XSS prevention + - CSRF protection + - Secure storage + - API security + - Error handling + +4. Testing: + - Unit tests + - Integration tests + - E2E tests + - Snapshot tests + - Performance tests + - Security tests + +// Security Considerations: +1. Client-side: + - Input validation + - XSS prevention + - CSRF tokens + - Secure storage + - API security + - Error handling + +2. Data Security: + - Encryption + - Hashing + - Access control + - Audit logging + - Data validation + - Backups + +3. Infrastructure: + - HTTPS + - CORS + - CSP + - Rate limiting + - Monitoring + - Logging \ No newline at end of file diff --git a/rules/kotlin-spring-boot-cursorrules-prompt-file/.cursorrules b/rules/kotlin-spring-boot-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..7ec1854 --- /dev/null +++ b/rules/kotlin-spring-boot-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,329 @@ +// Kotlin Spring Boot Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Kotlin Spring Boot application: +- RESTful APIs +- GraphQL APIs +- WebSocket servers +- Microservices +- Authentication +- Database integration +- Message queues +- Background jobs + +// Project Structure +src/ + main/ + kotlin/com/example/project/ # Package structure + Application.kt # Main application class + config/ # Configuration + SecurityConfig.kt # Security configuration + WebConfig.kt # Web configuration + controller/ # REST controllers + UserController.kt # User controller + ProductController.kt # Product controller + model/ # Domain models + User.kt # User model + Product.kt # Product model + repository/ # Data access + UserRepository.kt # User repository + ProductRepository.kt # Product repository + service/ # Business logic + UserService.kt # User service + ProductService.kt # Product service + exception/ # Custom exceptions + ResourceNotFoundException.kt # Resource not found exception + ValidationException.kt # Validation exception + util/ # Utilities + Extensions.kt # Extension functions + Constants.kt # Constants + resources/ # Resources + application.yml # Application properties + db/migration/ # Flyway migrations + static/ # Static resources + templates/ # Thymeleaf templates + test/ # Test suite + kotlin/com/example/project/ # Test classes + controller/ # Controller tests + service/ # Service tests + repository/ # Repository tests + +// Development Guidelines +1. Code Structure: + - Clean architecture + - Dependency injection + - Service layer + - Repository pattern + - Exception handling + - Logging + +2. API Design: + - RESTful principles + - Versioning + - Documentation + - Validation + - Error handling + - Security + +3. Performance: + - Caching + - Connection pooling + - Query optimization + - Coroutines + - Monitoring + - Profiling + +// Dependencies +Core: +- kotlin: "1.8.20" +- spring-boot-starter-web: "3.1.0" +- spring-boot-starter-data-jpa: "3.1.0" +- spring-boot-starter-security: "3.1.0" + +Optional: +- spring-boot-starter-actuator: "3.1.0" +- spring-boot-starter-cache: "3.1.0" +- spring-boot-starter-test: "3.1.0" +- springdoc-openapi-starter-webmvc-ui: "2.1.0" + +// Code Examples: + +1. Controller Pattern: +```kotlin +package com.example.project.controller + +import com.example.project.model.User +import com.example.project.service.UserService +import com.example.project.dto.UserDTO +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.* +import jakarta.validation.Valid + +@RestController +@RequestMapping("/api/v1/users") +class UserController( + private val userService: UserService +) { + @GetMapping("/{id}") + suspend fun getUser(@PathVariable id: Long): ResponseEntity = + ResponseEntity.ok(userService.findById(id)) + + @PostMapping + suspend fun createUser(@Valid @RequestBody userDTO: UserDTO): ResponseEntity = + ResponseEntity.ok(userService.create(userDTO)) + + @PutMapping("/{id}") + suspend fun updateUser( + @PathVariable id: Long, + @Valid @RequestBody userDTO: UserDTO + ): ResponseEntity = + ResponseEntity.ok(userService.update(id, userDTO)) + + @DeleteMapping("/{id}") + suspend fun deleteUser(@PathVariable id: Long): ResponseEntity = + userService.delete(id).let { ResponseEntity.noContent().build() } +} +``` + +2. Service Pattern: +```kotlin +package com.example.project.service + +import com.example.project.model.User +import com.example.project.repository.UserRepository +import com.example.project.dto.UserDTO +import com.example.project.exception.ResourceNotFoundException +import com.example.project.mapper.UserMapper +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional + +@Service +class UserService( + private val userRepository: UserRepository, + private val userMapper: UserMapper +) { + @Transactional(readOnly = true) + suspend fun findById(id: Long): UserDTO = + userRepository.findById(id) + ?.let(userMapper::toDTO) + ?: throw ResourceNotFoundException("User not found") + + @Transactional + suspend fun create(userDTO: UserDTO): UserDTO = + userMapper.toEntity(userDTO) + .let(userRepository::save) + .let(userMapper::toDTO) + + @Transactional + suspend fun update(id: Long, userDTO: UserDTO): UserDTO = + userRepository.findById(id) + ?.also { user -> userMapper.updateEntity(userDTO, user) } + ?.let(userRepository::save) + ?.let(userMapper::toDTO) + ?: throw ResourceNotFoundException("User not found") + + @Transactional + suspend fun delete(id: Long) { + if (!userRepository.existsById(id)) { + throw ResourceNotFoundException("User not found") + } + userRepository.deleteById(id) + } +} +``` + +3. Repository Pattern: +```kotlin +package com.example.project.repository + +import com.example.project.model.User +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Query +import org.springframework.stereotype.Repository + +@Repository +interface UserRepository : JpaRepository { + suspend fun findByEmail(email: String): User? + + suspend fun existsByEmail(email: String): Boolean + + @Query("SELECT u FROM User u WHERE u.active = true") + suspend fun findAllActiveUsers(): List + + @Query( + value = """ + SELECT u.* FROM users u + LEFT JOIN user_roles ur ON u.id = ur.user_id + WHERE ur.role_id = :roleId + """, + nativeQuery = true + ) + suspend fun findByRoleId(roleId: Long): List +} +``` + +4. Model Pattern: +```kotlin +package com.example.project.model + +import jakarta.persistence.* +import java.time.LocalDateTime + +@Entity +@Table(name = "users") +data class User( + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + val id: Long = 0, + + @Column(nullable = false) + var name: String, + + @Column(nullable = false, unique = true) + var email: String, + + @Column(nullable = false) + var password: String, + + @Column(name = "created_at") + val createdAt: LocalDateTime = LocalDateTime.now(), + + @Column(name = "updated_at") + var updatedAt: LocalDateTime = LocalDateTime.now() +) { + @PreUpdate + protected fun onUpdate() { + updatedAt = LocalDateTime.now() + } +} +``` + +5. Configuration Pattern: +```kotlin +package com.example.project.config + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity +import org.springframework.security.config.http.SessionCreationPolicy +import org.springframework.security.web.SecurityFilterChain + +@Configuration +@EnableWebSecurity +class SecurityConfig { + @Bean + fun filterChain(http: HttpSecurity): SecurityFilterChain = + http + .csrf { it.disable() } + .authorizeHttpRequests { auth -> + auth + .requestMatchers("/api/v1/auth/**").permitAll() + .requestMatchers("/api/v1/public/**").permitAll() + .anyRequest().authenticated() + } + .sessionManagement { session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) + } + .build() +} +``` + +// Best Practices: +1. Code Quality: + - Clean code + - SOLID principles + - Design patterns + - Documentation + - Testing + - Code reviews + +2. Architecture: + - Layered architecture + - Microservices + - API Gateway + - Service discovery + - Load balancing + - Circuit breakers + +3. Performance: + - Coroutines + - Connection pools + - Query optimization + - Caching + - Monitoring + - Profiling + +4. Security: + - Authentication + - Authorization + - Input validation + - CSRF protection + - XSS prevention + - SQL injection + +// Security Considerations: +1. API Security: + - JWT tokens + - OAuth 2.0 + - Rate limiting + - Input validation + - Error handling + - Logging + +2. Data Security: + - Encryption + - Password hashing + - Access control + - Audit logging + - Data validation + - Backups + +3. Infrastructure: + - HTTPS + - Firewalls + - Load balancers + - Monitoring + - Logging + - Backups \ No newline at end of file diff --git a/rules/laravel-php-cursorrules-prompt-file/.cursorrules b/rules/laravel-php-cursorrules-prompt-file/.cursorrules new file mode 100644 index 0000000..ed2e996 --- /dev/null +++ b/rules/laravel-php-cursorrules-prompt-file/.cursorrules @@ -0,0 +1,400 @@ +// Laravel PHP Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Laravel application: +- RESTful APIs +- Web applications +- Admin panels +- Authentication +- File uploads +- Queue workers +- Real-time features +- Background jobs + +// Project Structure +app/ + Console/ # Console commands + Commands/ # Command classes + Http/ # HTTP layer + Controllers/ # Request handlers + Middleware/ # Request filters + Requests/ # Form requests + Resources/ # API resources + Models/ # Eloquent models + Services/ # Business logic + Repositories/ # Data access + Events/ # Event classes + Listeners/ # Event listeners + Jobs/ # Queue jobs + Mail/ # Mail classes + Notifications/ # Notifications + Providers/ # Service providers + Rules/ # Validation rules +config/ # Configuration files +database/ # Database + factories/ # Model factories + migrations/ # Database migrations + seeders/ # Database seeders +resources/ # Static assets + views/ # Blade templates + js/ # JavaScript files + css/ # CSS files + lang/ # Language files +routes/ # Route definitions + web.php # Web routes + api.php # API routes + channels.php # Broadcast channels +tests/ # Test suite + Feature/ # Feature tests + Unit/ # Unit tests + +// Development Guidelines +1. Code Structure: + - MVC pattern + - Service layer + - Repository pattern + - Event-driven + - Clean code + - SOLID principles + +2. API Design: + - RESTful principles + - API resources + - Validation + - Authentication + - Rate limiting + - Documentation + +3. Performance: + - Caching + - Queue jobs + - Database indexing + - Query optimization + - Eager loading + - N+1 prevention + +// Dependencies +Core: +- php: "^8.2" +- laravel/framework: "^10.0" +- laravel/sanctum: "^3.2" +- laravel/tinker: "^2.8" + +Optional: +- laravel/horizon: "^5.15" +- laravel/telescope: "^4.14" +- spatie/laravel-permission: "^5.10" +- barryvdh/laravel-ide-helper: "^2.13" + +// Code Examples: + +1. Controller Pattern: +```php +userService->getAllUsers(); + return UserResource::collection($users); + } + + public function show(int $id): UserResource + { + $user = $this->userService->getUserById($id); + return new UserResource($user); + } + + public function store(StoreUserRequest $request): UserResource + { + $user = $this->userService->createUser($request->validated()); + return new UserResource($user); + } + + public function update(StoreUserRequest $request, int $id): UserResource + { + $user = $this->userService->updateUser($id, $request->validated()); + return new UserResource($user); + } + + public function destroy(int $id): JsonResponse + { + $this->userService->deleteUser($id); + return response()->json(null, 204); + } +} +``` + +2. Service Pattern: +```php +userRepository->all(); + } + + public function getUserById(int $id): User + { + return $this->userRepository->findOrFail($id); + } + + public function createUser(array $data): User + { + $data['password'] = Hash::make($data['password']); + + $user = $this->userRepository->create($data); + + event(new UserCreated($user)); + + return $user; + } + + public function updateUser(int $id, array $data): User + { + $user = $this->userRepository->findOrFail($id); + + if (isset($data['password'])) { + $data['password'] = Hash::make($data['password']); + } + + $this->userRepository->update($user, $data); + + return $user->fresh(); + } + + public function deleteUser(int $id): void + { + $user = $this->userRepository->findOrFail($id); + $this->userRepository->delete($user); + } +} +``` + +3. Repository Pattern: +```php +update($data); + } + + public function delete(User $user): bool + { + return $user->delete(); + } + + public function findByEmail(string $email): ?User + { + return User::where('email', $email)->first(); + } + + public function paginate(int $perPage = 15): Collection + { + return User::paginate($perPage); + } +} +``` + +4. Model Pattern: +```php + 'datetime', + 'password' => 'hashed', + ]; + + public function posts() + { + return $this->hasMany(Post::class); + } + + public function profile() + { + return $this->hasOne(Profile::class); + } + + public function roles() + { + return $this->belongsToMany(Role::class); + } +} +``` + +5. Request Pattern: +```php + ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], + 'password' => ['required', Password::defaults()], + ]; + + if ($this->isMethod('PUT') || $this->isMethod('PATCH')) { + $rules['email'] = ['required', 'string', 'email', 'max:255', 'unique:users,email,' . $this->user->id]; + $rules['password'] = ['nullable', Password::defaults()]; + } + + return $rules; + } + + public function messages(): array + { + return [ + 'name.required' => 'The name field is required.', + 'email.required' => 'The email field is required.', + 'email.email' => 'Please enter a valid email address.', + 'email.unique' => 'This email is already taken.', + 'password.required' => 'The password field is required.', + ]; + } +} +``` + +// Best Practices: +1. Code Quality: + - PSR standards + - Type hinting + - Documentation + - Testing + - Code reviews + - Refactoring + +2. Architecture: + - MVC pattern + - Service layer + - Repository pattern + - Event-driven + - Queue jobs + - Caching + +3. Performance: + - Query optimization + - Eager loading + - Caching + - Queue jobs + - Database indexing + - N+1 prevention + +4. Security: + - Authentication + - Authorization + - Input validation + - CSRF protection + - XSS prevention + - SQL injection + +// Security Considerations: +1. API Security: + - Sanctum tokens + - Rate limiting + - Input validation + - Error handling + - Logging + - Monitoring + +2. Data Security: + - Encryption + - Password hashing + - Access control + - Audit logging + - Data validation + - Backups + +3. Infrastructure: + - HTTPS + - Firewalls + - Load balancers + - Monitoring + - Logging + - Backups \ No newline at end of file diff --git a/rules/nextjs-app-router-cursorrules-prompt-file/.cursorrules b/rules/nextjs-app-router-cursorrules-prompt-file/.cursorrules index 21f706f..697ff1e 100644 --- a/rules/nextjs-app-router-cursorrules-prompt-file/.cursorrules +++ b/rules/nextjs-app-router-cursorrules-prompt-file/.cursorrules @@ -1,34 +1,480 @@ -// Next.js App Router .cursorrules - -// Next.js App Router best practices -const nextjsAppRouterBestPractices = [ - "Use server components by default", - "Implement client components only when necessary", - "Utilize the new file-based routing system", - "Use layout.js for shared layouts", - "Implement loading.js for loading states", - "Use error.js for error handling", - "Utilize route handlers for API routes", -]; - -// Folder structure -const folderStructure = ` +// Next.js App Router Development Guide +// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}}) + +// What you can build with this ruleset: +A modern Next.js application using the App Router: +- Server Components +- Client Components +- Route Handlers +- Server Actions +- Dynamic Routes +- Parallel Routes +- Intercepting Routes +- Loading UI +- Error Handling +- Authentication +- Database Integration +- API Routes + +// Project Structure app/ - layout.js - page.js - components/ - lib/ - styles/ -public/ -`; - -// Additional instructions -const additionalInstructions = ` -1. Use TypeScript for type safety -2. Implement proper metadata for SEO -3. Utilize Next.js Image component for optimized images -4. Use CSS Modules or Tailwind CSS for styling -5. Implement proper error boundaries -6. Follow Next.js naming conventions for special files -7. Use environment variables for configuration -`; + (auth)/ # Auth group + login/ # Login page + register/ # Register page + layout.tsx # Auth layout + (dashboard)/ # Dashboard group + layout.tsx # Dashboard layout + page.tsx # Dashboard page + loading.tsx # Loading UI + error.tsx # Error UI + not-found.tsx # 404 page + api/ # API routes + auth/ # Auth endpoints + users/ # User endpoints + components/ # Shared components + ui/ # UI components + forms/ # Form components + lib/ # Utilities + db/ # Database utils + auth/ # Auth utils + api/ # API utils + hooks/ # Custom hooks + providers/ # Context providers + styles/ # Global styles + types/ # TypeScript types + config/ # Configuration + public/ # Static assets + tests/ # Test suite + +// Development Guidelines +1. Component Structure: + - Server Components + - Client Components + - Layouts + - Templates + - Error Boundaries + - Suspense + +2. Data Fetching: + - Server Components + - Route Handlers + - Server Actions + - Caching + - Revalidation + - Mutations + +3. Performance: + - Static Generation + - Streaming + - Partial Rendering + - Image Optimization + - Font Optimization + - Bundle Size + +// Dependencies +Core: +- next: "^14.0.0" +- react: "^18.2.0" +- react-dom: "^18.2.0" +- typescript: "^5.0.0" + +Optional: +- tailwindcss: "^3.3.0" +- shadcn/ui: "^0.4.0" +- prisma: "^5.0.0" +- next-auth: "^4.24.0" + +// Code Examples: + +1. Page Pattern: +```tsx +// app/posts/[id]/page.tsx +import { Suspense } from 'react'; +import { notFound } from 'next/navigation'; +import { PostContent } from '@/components/posts/PostContent'; +import { PostComments } from '@/components/posts/PostComments'; +import { LoadingSpinner } from '@/components/ui/LoadingSpinner'; +import { getPost } from '@/lib/api/posts'; + +export const generateMetadata = async ({ params }: { params: { id: string } }) => { + const post = await getPost(params.id); + + if (!post) { + return { + title: 'Post Not Found', + }; + } + + return { + title: post.title, + description: post.excerpt, + }; +}; + +export default async function PostPage({ params }: { params: { id: string } }) { + const post = await getPost(params.id); + + if (!post) { + notFound(); + } + + return ( +
+ + + }> + + +
+ ); +} +``` + +2. Layout Pattern: +```tsx +// app/(dashboard)/layout.tsx +import { auth } from '@/lib/auth'; +import { redirect } from 'next/navigation'; +import { DashboardNav } from '@/components/dashboard/DashboardNav'; +import { DashboardHeader } from '@/components/dashboard/DashboardHeader'; + +export default async function DashboardLayout({ + children +}: { + children: React.ReactNode; +}) { + const session = await auth(); + + if (!session) { + redirect('/login'); + } + + return ( +
+ +
+ +
+ {children} +
+
+
+ ); +} +``` + +3. Route Handler Pattern: +```tsx +// app/api/posts/route.ts +import { NextResponse } from 'next/server'; +import { z } from 'zod'; +import { auth } from '@/lib/auth'; +import { prisma } from '@/lib/db'; + +const postSchema = z.object({ + title: z.string().min(1).max(100), + content: z.string().min(1), + published: z.boolean().default(false), +}); + +export async function POST(request: Request) { + try { + const session = await auth(); + + if (!session) { + return NextResponse.json( + { error: 'Unauthorized' }, + { status: 401 } + ); + } + + const json = await request.json(); + const body = postSchema.parse(json); + + const post = await prisma.post.create({ + data: { + ...body, + authorId: session.user.id, + }, + }); + + return NextResponse.json(post); + } catch (error) { + if (error instanceof z.ZodError) { + return NextResponse.json( + { error: error.errors }, + { status: 400 } + ); + } + + return NextResponse.json( + { error: 'Internal Server Error' }, + { status: 500 } + ); + } +} + +export async function GET(request: Request) { + try { + const { searchParams } = new URL(request.url); + const published = searchParams.get('published'); + + const posts = await prisma.post.findMany({ + where: { + published: published ? published === 'true' : undefined, + }, + include: { + author: { + select: { + name: true, + image: true, + }, + }, + }, + }); + + return NextResponse.json(posts); + } catch (error) { + return NextResponse.json( + { error: 'Internal Server Error' }, + { status: 500 } + ); + } +} +``` + +4. Server Action Pattern: +```tsx +// app/actions/posts.ts +'use server'; + +import { revalidatePath } from 'next/cache'; +import { auth } from '@/lib/auth'; +import { prisma } from '@/lib/db'; +import { PostSchema } from '@/lib/validations/post'; + +export async function createPost(formData: FormData) { + try { + const session = await auth(); + + if (!session) { + return { + error: 'Unauthorized', + }; + } + + const rawData = { + title: formData.get('title'), + content: formData.get('content'), + published: formData.get('published') === 'true', + }; + + const validatedData = PostSchema.parse(rawData); + + const post = await prisma.post.create({ + data: { + ...validatedData, + authorId: session.user.id, + }, + }); + + revalidatePath('/posts'); + + return { data: post }; + } catch (error) { + return { + error: 'Failed to create post', + }; + } +} + +export async function deletePost(postId: string) { + try { + const session = await auth(); + + if (!session) { + return { + error: 'Unauthorized', + }; + } + + const post = await prisma.post.findUnique({ + where: { id: postId }, + }); + + if (!post) { + return { + error: 'Post not found', + }; + } + + if (post.authorId !== session.user.id) { + return { + error: 'Unauthorized', + }; + } + + await prisma.post.delete({ + where: { id: postId }, + }); + + revalidatePath('/posts'); + + return { success: true }; + } catch (error) { + return { + error: 'Failed to delete post', + }; + } +} +``` + +5. Client Component Pattern: +```tsx +'use client'; + +import { useState } from 'react'; +import { useRouter } from 'next/navigation'; +import { createPost } from '@/app/actions/posts'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { toast } from '@/components/ui/toast'; + +export function CreatePostForm() { + const router = useRouter(); + const [isPending, setIsPending] = useState(false); + + async function onSubmit(event: React.FormEvent) { + event.preventDefault(); + setIsPending(true); + + try { + const formData = new FormData(event.currentTarget); + const result = await createPost(formData); + + if (result.error) { + toast({ + title: 'Error', + description: result.error, + variant: 'destructive', + }); + return; + } + + toast({ + title: 'Success', + description: 'Post created successfully', + }); + + router.push(`/posts/${result.data.id}`); + } catch (error) { + toast({ + title: 'Error', + description: 'Something went wrong', + variant: 'destructive', + }); + } finally { + setIsPending(false); + } + } + + return ( +
+
+ + +
+ +
+ +