Awesome Cursor Rules Collection

Showing 865-876 of 2626 matches

Go
# Cursor Rules

Assume the role of a Golang programmer using [Encore framework](https://encore.dev/docs/go).

- The project will follow uses domain driven design and hexagonal architecture.

## Folder structure for example module using domain driven design and hexagonal architecture

```
alarms
├── application
│   ├── commands
│   │   ├── create_alarm_command_handler.go
│   │   └── create_alarm_command.go
│   ├── events
│   │   └── alarm_created_event_handler.go
│   ├── queries
│   │   ├── list_alarms_query.go
│   │   └── list_alarms_query_handler.go
│   ├── ports
│   │   ├── create_alarm_repository_port.go
│   │   ├── find_alarms_repository_port.go
│   │   └── upsert_materialized_alarm_repository_port.go
│   └── alarms_facade.go
│   └── alarms_factory.go
├── domain
│   ├── aggregates
│   │   └── alarm_aggregate.go
│   ├── events
│   │   └── alarm_created_event.go
│   ├── models
│   │   └── alarm_read_model.go
│   ├── valueobjects
│   │   └── alarm_severity.go
│   ├── entities
│   │   └── alarm.go
│   │   └── alarm_item.go
├── infrastructure
│   └── persistence
│       ├── entities
│       │   ├── alarm_entity.go
│       │   └── alarm_item_entity.go
│       ├── mappers
│       │   └── alarm_mapper.go
│       ├── repositories
│       │   ├── migrations
│       │   │   └── 1_create_foo_table.sql
│       │   │   └── 2_create_bar_table.sql
│       │   │   └── 3_add_column_x_on_foo_table.sql
│       │   ├── create_alarm_repository.go
│       │   ├── find_alarms_repository.go
│       │   └── upsert_materialized_alarm_repository.go
│       └── schemas
│           └── materialized_alarm_view_schema.go
└── presentation
    └── http
        ├── dto
        │   └── create_alarm_dto.go
        └── alarms_controller.go
```

## Hexagonal Architecture Specifications

### Presentation Layer

- The presentation layer contains user facing-components, such has controllers, gateways and other APIs.
- The presentation layer commands to forward data to application services (e.g., facades).
- The presentation layer queries to forward data to application services (e.g., facades).

### Application Layer

- The applicational layer contains application services (e.g., facades, handlers).
- The applicational exposes primary ports and secondary ports.
- The applicational primary ports include commands and query structs and applicational service interfaces.
- The applicational secondary ports (a.k.a. adapters) are implemented on the infrastructure layer.
- The application layer can access the infrastructure layer via secondary port interfaces.
- The application layer can access the domain layer through aggregates that are exposed by the domain layer.
- The application layer can access the domain layer through domain objects only on simple (e.g., little or no business logic, data-reads).
- The application layer can not access anything from the presentation layer, not even data transfer objects.
- Commands should be concrete classes or structs.
- Commands define payloads that the application layer to uses to start data-write procedures, with or without CQRS implementation.
- Queries should be concrete classes or structs.
- Queries define payloads that the application layer to uses to start data-read procedures, with or without CQRS implementation.
- Applicational services should always expose an abstract class or interfaces.
- Applicational service interfaces will be used in module initialization.
- Secondary ports should always be interfaces.
- Secondary ports are implemented by Adapters at the infrastructure layer (e.g., ICreateAlarmRepository from application layer is implemented in CreateAlarmRepository and/or CreateAlarmRepositoryV2 at infrastructure layer).

### Domain Layer

- The domain layer contains domain models, value objects, events and other domain specific components that represent the business.
- The domain layer can only be accessed from the applicational layer.

### Infrastructure layer

- The infrastructure layer contains data access components, such as message brokers, repositories and clients to external system.
- The infrastructure layer implements the secondary (ports) defined by the application layer called adapters (e.g., concrete repository).
- The infrastructure layer can only be accessed from the applicational layer.
- Adapters use mapper classes to ensure domain or value objects, are returned its methods.
- Adapters can reference domain classes and value objects, but should not operate or modify them.

## Domain Driven Design Specifications (considering Hexagonal Architecture)

### Core Concepts

- Value objects must be immutable and have no identifiers (ID).
- Value objects should be immutable and side-effect free.
- Entities must have unique identifiers (ID) and can be mutable.
- Entities are represented by domain objects on the domain layer.
- Entities are represented by sqlc objects (entity or models) on the infrastructure layer.
- Aggregates are clusters of domain objects treated as single units for consistency.
- Aggregates changes occur in memory and are persisted via together through transactions.
- Domain objects within aggregates can only be changed through aggregates public interface.

### Factories

- Use factories to handle struct validation and initialization logic.
- Use factories to hide implementation details behind complex object creation.
- Use factories to keep domain models focused on business logic

### Services

- Use applicational services (e.g., facades, usecases) to coordinate and fullfil applicational commands and queries.
- Use applicational services to communicate with the infrastructure and domain layers from the application layer.
- Use domain services (aggregates) to coordinate changes across multiple domain objects and/or value-objects.
- Use domain services (root aggregates) for logic that does not belong to a single aggregate.
- Root aggregates and aggregates should only be created when they contain actual business logic, not just getters/setters.
- Avoid creating domain services for any other purpose other than the highlighted ones.

### Repositories

- Repositories should be used to effectuate persisting/retrieving of entity objects.
- Repositories should return domain objects.
- Repositories should use mappers to convert domain objects to entity objects.
- Repositories should use mappers to convert objects objects to domain objects.
- Repositories should convert entity objects to SQLC parameters inline when performing queries.
- Repositories should hide implementation details of the underlying storage (sql, nosql, cache, in-memory).

### Events

- Domain events should represent domain state changes that have been persisted.
- Domain events should be emitted from domain layer.
- Domain events should be declared and handled in application layer.
- Domain events handlers that are declared in the application layer can access infrastructure layer.
- Domain events handlers can be declared and handled in domain layer for ponctual and only for pure business policy reactions.
- Domain events handlers that are declared in the domain layer can not access infrastructure layer.
- Integration events should be for cross-service communication (e.g., separate module boundary).
- Integration events should be lighter than domain events.

### CQRS

- Separate read and write operations
- Write side handles commands and state updates
- Read side handles events and read model updates
- Eventual consistency between read/write models
- Best for read-heavy systems

## Golang Specifications

### Basic Principles

- Always write code and documentation in English.
- Prompt requirements should be followed carefully.
- Prompt requirements should have priority over rules outlined in this document.
- Add logs often and frequently using Encore logger (package: encore.dev/rlog).
- Add logs with debug, info, warn, error and fatal levels as appropriate.
- Add middleware to handle Cross-cutting concerns (e.g., catch-all error handling and logging, authentication, etc.).
- Comments should be added to every exported (public) functions or variables.
- Comments should not be added to unexported (private) functions or variables, unless prompted.
- Consider Encore framework intricacies when writting code.
- Rest endpoints should authentication/authorization as appropriate,
- Rest endpoints should implement basic validation using Encore Validation mechanism.
- Rest endpoints should implement rate limiting as appropriate.
- Rest endpoints should return appropriate status codes.
- Rest endpoints should return json.
- Domain aggregates should implement business concern validations using spec functions inspired by Domain Driven Desing.
- Include necessary imports, package declarations, and any required setup code.
- Inform me when the setup code requires me to install a go or 3rd party package.

### Nomenclature

- Use PascalCase for public variables, functions, interfaces and structs.
- Use camelCase for package private variables, functions, interfaces and structs.
- Use camelCase for block-scoped variables.
- Use UPPERCASE for constant and environment variables.
- Use lowcase for directory names.
- Use snake_case for file names.
- Use snake_case specifiers after the actual file name, before the file extension (e.g., 'settings_controller.go').
- Use verbs such has `is`, `has` and `can` to denote Booleanish variables (e.g., isLoading, hasError, canDelete).
- Use complete words instead of abbreviations. The following exceptions are made:
    - i, j denoting iterated values or indexes in loops
    - args denoting arguments
    - ctx denoting context
    - err denoting error
    - next denoting next middleware
    - params denoting parameters
    - req denoting request
    - res denoting response
    - Db denoting Database
    - Api denoting Access Pointer Interface
    - Url denoting Unique Resource Locator
    - Http denoting Hyper Text Transfer Protocol

### Errors and Exceptions

- Errors should be handled often to fix recoverable problems, log or add context.
- Errors should be bubbled up if we can not do anything useful with them.
- It is okay to use `defer` and `recovery` to handle some `panic` events at the top level of the application.

### Functions Specifics

- Functions should have names that start with a verb (e.g., CreateFlag, DeactivateUser).
- Functions should be short, concise and side-effect free.
- Functions should accept no more than four parameters.
- Functions should accept interfaces when they absolutly need a large quantity of parameters.
- Functions should avoid deeply nested blocks.
- Functions should not validate parameters unless asked as part of prompted requirements.

### Testing

- Test can use official Golang, `go-resty/resty` and `stretchr/testify` packages.
- Test names should be concise.
- Test names should start with a verb. Example: TestReturnsFooBar
- Test names should not contain redudant (implied) verbs such has "should", "must" and "check".
- Tests blocks the Arrange-Act-Assert convention for tests.
- Test variable names should follow the convention: inputX, mockX, actualX, expectedX, etc.
- Unit tests should be written for pure functions that are publicly exposed by modules.
- Unit tests should be written methods of controllers, facades, factories, mappers, services, repositories, etc.
- Unit tests should use mocks, stubs, spies and doubles to simulate dependencies unless prompted otherwise.
- Acceptance (API or E2E) tests should be written for api endpoints or application entry points.
go
golang
less
nestjs
react
rest-api
shell
FranciscoKloganB/cursor-demo

Used in 1 repository

TypeScript
# .cursorrules for Webflow CMS AI Content Creation SaaS

## Project Overview
- SaaS application for AI-powered content creation in Webflow CMS
- Focus on SEO optimization
- Built with Refine Dev, NextJS, Ant Design, and Appwrite

## Tech Stack
- Frontend: NextJS (App Router)
- UI Components: Ant Design
- Backend & Authentication: Appwrite
- Framework: Refine Dev

## Coding Standards
- Use TypeScript for type safety
- Implement ESLint and Prettier for code consistency
- Follow Refine Dev best practices

## File Structure
- Use Next.js App Router structure
- Organize components in a logical hierarchy
- Separate business logic from UI components

## SEO Optimization
- Implement proper metadata for each page
- Use semantic HTML tags
- Optimize images with Next.js Image component

## Ant Design Usage
- Use Ant Design components consistently
- Customize theme using Ant Design's ConfigProvider
- Implement responsive design principles

## Appwrite Integration
- Use Appwrite SDK for authentication and backend operations
- Implement proper error handling for Appwrite API calls
- Secure API keys and sensitive information using environment variables

## AI Integration
- Implement AI-powered content generation features
- Optimize AI-generated content for SEO
- Ensure proper error handling and fallbacks for AI operations

## Performance
- Implement code splitting and lazy loading
- Optimize API calls and data fetching
- Use server-side rendering where appropriate

## Testing
- Write unit tests for critical components and functions
- Implement integration tests for key user flows
- Use Jest and React Testing Library for testing

## Documentation
- Maintain clear and up-to-date documentation
- Document API endpoints and their usage
- Include setup instructions in the README.md file

## Refine Dev Specific
- Utilize Refine hooks and components for data management
- Implement custom hooks for business logic
- Use Refine's auth provider with Appwrite

## Cursor-specific Instructions
- Prioritize server components unless client-side interactivity is required
- Use the `use client` directive for client components
- Implement proper loading and error states using Next.js 13+ conventions
dockerfile
eslint
javascript
jest
less
next.js
prettier
react
+1 more
diegogallovich/rankflow-ai

Used in 1 repository

Astro
{
    "rules": {
      "commit_message_guidelines": {
        "description": "Guidelines for creating conventional commit messages.",
        "format": {
          "description": "The format for commit messages using the conventional commits spec.",
          "body": "<type>[optional scope]: <description>\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": "<diff_context> /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
          }
        ]
      }
    }
  }
  
astro
css
golang
javascript
tailwindcss
typescript
jjaimealeman/astro_boilerplate

Used in 1 repository

C#
You are a senior C# programmer with experience in ASP.NET Web API and a preference for clean programming and design patterns.

## C# General Guidelines

### Basic Principles

- Use English for all code and documentation.
- Follow Microsoft's C# coding conventions.
- Use XML documentation comments for public APIs.
- Implement async/await patterns correctly.
- One class per file (except for small related classes).
- Use nullable reference types.
- Follow REST principles for API design.

### Nomenclature

- Use PascalCase for:
  - Class names
  - Method names
  - Properties
  - Public fields
  - Interfaces (prefix with 'I')
- Use camelCase for:
  - Method parameters
  - Local variables
- Use SCREAMING_CASE for constants
- Use meaningful and self-documenting names
- Prefix interfaces with 'I'
- Prefix abstract classes with 'Base' or 'Abstract'
- Suffix derived classes appropriately:
  - Controllers with 'Controller'
  - Services with 'Service'
  - Repositories with 'Repository'
  - DTOs with 'Dto'
  - ViewModels with 'VM'

### Methods/Functions

- Follow Single Responsibility Principle
- Keep methods short and focused (< 20 lines)
- Use verb-noun naming convention
- Return Task<T> for async methods
- Use CancellationToken for long-running operations
- Validate parameters at the start of methods
- Use guard clauses for early returns
- Avoid passing more than 3 parameters
- Use parameter objects for multiple parameters
- Return IActionResult or ActionResult<T> in controllers

### API Design

- Use proper HTTP methods:
  - GET for retrieval
  - POST for creation
  - PUT for full updates
  - PATCH for partial updates
  - DELETE for removal
- Return appropriate HTTP status codes:
  - 200 for successful operations
  - 201 for successful creation
  - 204 for successful deletion
  - 400 for bad requests
  - 401 for unauthorized
  - 403 for forbidden
  - 404 for not found
  - 500 for server errors
- Version your APIs
- Use route attributes consistently
- Implement proper model validation
- Use DTOs for request/response objects
- Implement proper error handling middleware

### Data & Models

- Use Entity Framework Core properly
- Implement proper database migrations
- Use strongly-typed configuration
- Implement proper data validation
- Use value objects where appropriate
- Implement proper mapping between entities and DTOs
- Use AutoMapper for complex mappings

### Dependency Injection

- Register services with appropriate lifetimes:
  - Transient
  - Scoped
  - Singleton
- Use constructor injection
- Avoid service locator pattern
- Register services in proper order
- Use interfaces for loose coupling

### Security

- Implement proper authentication
- Use proper authorization attributes
- Implement proper CORS policies
- Use HTTPS
- Implement rate limiting
- Validate all inputs
- Implement proper logging
- Use secure headers
- Implement proper secrets management

### Error Handling

- Implement global exception handling
- Create custom exceptions when needed
- Log exceptions properly
- Return proper error responses
- Handle validation errors consistently
- Use ProblemDetails for error responses

### Testing

- Write unit tests for:
  - Controllers
  - Services
  - Repositories
  - Middleware
- Use proper naming convention:
  - [UnitOfWork]_[Scenario]_[ExpectedResult]
- Follow Arrange-Act-Assert pattern
- Use mocking frameworks appropriately
- Test both success and failure scenarios
- Write integration tests for:
  - API endpoints
  - Database operations
- Use test data builders
- Implement proper test cleanup

### Performance

- Use async/await properly
- Implement caching where appropriate
- Use proper indexing
- Implement pagination
- Use compression
- Optimize database queries
- Use proper response caching
- Implement proper memory management

### Logging

- Use structured logging
- Implement proper log levels
- Include correlation IDs
- Log appropriate information
- Avoid logging sensitive data
- Use proper logging configuration
- Implement proper log storage

### Documentation

- Use Swagger/OpenAPI
- Document all public APIs
- Include example requests/responses
- Document error responses
- Keep documentation up-to-date
- Include authentication information
- Document rate limits

### Code Organization

- Follow Clean Architecture principles
- Implement proper separation of concerns
- Use proper folder structure:
  - Controllers/
  - Services/
  - Repositories/
  - Models/
  - DTOs/
  - Middleware/
  - Extensions/
  - Configurations/
c#
dart
dockerfile
kotlin
objective-c
rest-api
ruby
swift
pablosanderman/science-based-meals

Used in 1 repository

Rust
DO NOT WRITE ANY COMMENTS IN THE CODE
rust

First seen in:

loxlouro/ERusticSearch

Used in 1 repository

TypeScript
# Cursor Rules for Hardhat Project with Subgraph

## Solidity (Smart Contracts)
- Prioritize gas efficiency and security in all Solidity code
- Use latest stable Solidity version (^0.8.0 or higher)
- Follow OpenZeppelin's best practices and use their contracts when applicable
- Always include NatSpec comments (@dev, @param, @return) for functions and state variables
- Use explicit function visibility (public, external, internal, private)
- Implement access control mechanisms (e.g., Ownable, Role-based)
- Use SafeMath for arithmetic operations in versions < 0.8.0
- Emit events for all state changes
- Implement reentrancy guards where necessary
- Use require statements with clear error messages
- Avoid using tx.origin for authorization
- Implement upgradability patterns when appropriate (e.g., proxy patterns)
- No need to add events in interfaces
- Whenever an update in a contract is done, update the interface in interfaces folder.

## TypeScript (Tests, Scripts, Subgraph)
- Prioritize readability and maintainability in all TypeScript code
- Use async/await for asynchronous operations
- Implement comprehensive unit tests for all smart contract functions
- Use descriptive variable and function names
- Include comments for complex logic or non-obvious code
- Implement proper error handling and logging
- Use TypeScript's type system effectively (interfaces, types, generics)
- Follow consistent code formatting (use Prettier)
- Implement integration tests that simulate real-world scenarios
- Use environment variables for configuration (dotenv)

## Hardhat Configuration
- Use Hardhat's TypeScript configuration
- Implement custom tasks for common operations
- Configure multiple networks (local, testnet, mainnet)
- Use Hardhat's built-in Solidity optimizer
- Implement gas reporting for contract deployments and function calls
- Use Hardhat's built-in testing framework

## Subgraph
- Keep schema.graphql up-to-date with smart contract events
- Implement efficient event handlers in AssemblyScript
- Use appropriate data types in schema and mappings
- Implement proper error handling in mappings
- Keep subgraph.yaml in sync with smart contract ABIs and addresses
- Use templates for dynamically created contracts
- Implement unit tests for subgraph mappings

## Documentation
- Maintain a comprehensive README.md with project overview, setup instructions, and usage examples
- Document all smart contract functions and their purposes
- Keep inline comments up-to-date with code changes
- Document deployment procedures and addresses for different networks
- Maintain a CHANGELOG.md for version history

## Version Control
- Use semantic versioning for releases
- Write clear and descriptive commit messages
- Use feature branches and pull requests for new features or major changes
- Regularly update dependencies and document any breaking changes

## Security
- Regularly run static analysis tools (e.g., Slither, MythX)
- Conduct thorough code reviews before merging new features
- Implement a bug bounty program for mainnet deployments
- Consider professional audits for critical contracts before mainnet deployment

## Continuous Integration/Deployment
- Implement CI/CD pipelines for automated testing and deployment
- Run linters (Solhint for Solidity, ESLint for TypeScript) in CI pipeline
- Automate subgraph deployment on contract updates

Remember to adapt these rules as needed for your specific project requirements and team preferences.
dockerfile
eslint
graphql
javascript
prettier
shell
solidity
solidjs
+1 more
SONGS-TOOLS/songs-protocol

Used in 1 repository

CSS
the model we want to use is amazon.nova-micro-v1:0 
css
javascript
typescript

First seen in:

jakerains/river8

Used in 1 repository