Awesome Cursor Rules Collection

Showing 817-828 of 2626 matches

TypeScript
    You are an expert full-stack developer proficient in TypeScript, React, Next.js 14 App Router, and modern UI/UX frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI), as well as web3 development with Solidity, Viem v2, Wagmi v2. Your task is to produce the most optimized and maintainable Next.js code, following best practices and adhering to the principles of clean code and robust architecture.

    - Use bun for package management
    - Favor named exports for components.
    - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
    - Structure files with exported components, subcomponents, helpers, static content, and types.
    - Split up complex components into multiple files
    - Find opportunities to simplify code. complexity is bad, prefer simpler solutions that maximize code reusability and DRY-ness over more complex ones.

### Error Handling and Validation

- Prioritize error handling and edge cases:
  - Use early returns for error conditions.
  - Use custom error types for consistent error handling.

### UI and Styling

- Use Shadcn, Tailwind and radix UI for components and styling.
- Implement mobile first approach for responsive design.
- Minimize the use of "magic values" / custom css and prefer tailwind classes.
- Any styles or variables that are used in multiple components should be defined in tailwind config and globals.css

### State Management and Data Fetching

- Use modern state management solutions (e.g., Zustand, TanStack React Query) to handle global state and data fetching.
- Implement validation using Zod for schema validation.
bun
css
javascript
next.js
perl
radix-ui
react
shadcn/ui
+5 more
META-DREAMER/farcastle-frames

Used in 1 repository

TypeScript
PHP
# CLI Script Conventions
New CLI scripts should be named like `bin/my-script`, and will be written preferably in PHP.

## Files
`bin/*`

## Language
`php`

## Patterns

### CLI Script Header Format
```php
#!/usr/bin/env php
<?php
namespace JT;
# =============================================================================
# {{description}}
# By Justin Sternberg <me@jtsternberg.com>
#
# Version {{version}}
#
# {{detailed_description}}
#
# Usage:
# {{command}} {{usage_example}}
#
# Examples:
# {{examples}}
# =============================================================================
```

### CLI Helpers Setup
```php
$cli = require_once dirname(__DIR__) . '/misc/helpers.php';
$helpyHelperton = $cli->getHelp();
```

### Single-Command Help Documentation

For when the command is a single command, with no sub-commands.

```php
$helpyHelperton
	->setScriptName('example')
	->setDescription('Description of example')
	->setSampleUsage('<arg1> <arg2> [<arg3>] [--flagWithValue=<value>] [--flag]')
	->buildDocs([
		'<arg1>'                  => 'Explanation of arg1',
		'<arg2>'                  => 'Explanation of arg2',
		'[<arg3>]'                => 'Explanation of arg3',
		'--flagWithValue=<value>' => 'Explanation of flagWithValue',
		'--flag'                  => 'Explanation of flag',
	]);

if ($helpyHelperton->batSignal) {
	$cli->msg($helpyHelperton->getHelp());
	exit(0);
}
```

### Sub-Command Help Documentation

For when the command only has sub-commands (not a primary command/function).

```php
$helpyHelperton
	->setScriptName('parentcommand')
	->setDescription('Description of parentcommand')
	->setup('parentcommand', [
		'subcommand' => [
			'<arg1> <arg2> [<arg3>] [--flagWithValue=<value>] [--flag]',
			'Description of subcommand',
'<arg1>          Explanation of arg1
<arg2>          Explanation of arg2
<arg3>          Explanation of arg3

--flagWithValue=<value>
                Longer explanation for flag with value
                Value can be one of: \'one\', \'two\', \'three\', \'four\'
                or yadda yadda yadda

--flag          Explanation of flag

-y, --yes       Will autoconfirm all prompts. Use to bla bla bla

--porcelain     Used to return clean output to other scripts.
-shh, --silent  Prevents outputting help/progress messages.',
		],
	]);

if ($helpyHelperton->batSignal) {
    $cli->msg($helpyHelperton->getHelp($cli->getArg(1)));
    exit(0);
}
```

### Primary command with sub-commands Help Documentation

For when the command is a primary command, with sub-commands.

```php
$helpyHelperton
	->setScriptName('primarycommand')
	->setDescription('Description of primarycommand')
	->setSampleUsage('<arg1> <arg2> [<arg3>] [--flagWithValue=<value>] [--flag]')
	->setupDefaultCommand([
		'<arg1>'                  => 'Explanation of arg1',
		'<arg2>'                  => 'Explanation of arg2',
		'[<arg3>]'                => 'Explanation of arg3',
		'--flagWithValue=<value>' => 'Explanation of flagWithValue',
		'--flag'                  => 'Explanation of flag',
	])
	->setup('primarycommand', [
		'subcommand' => [
			'<arg1> <arg2> [<arg3>] [--flagWithValue=<value>] [--flag]',
			'Description of subcommand',
'<arg1>          Explanation of arg1
<arg2>          Explanation of arg2
<arg3>          Explanation of arg3

--flagWithValue=<value>
                Longer explanation for flag with value
                Value can be one of: \'one\', \'two\', \'three\', \'four\'
                or yadda yadda yadda

--flag          Explanation of flag

-y, --yes       Will autoconfirm all prompts. Use to bla bla bla

--porcelain     Used to return clean output to other scripts.
-shh, --silent  Prevents outputting help/progress messages.',
		],
	]);

if ($helpyHelperton->batSignal) {
    $cli->msg($helpyHelperton->getHelp($cli->getArg(1)));
    exit(0);
}
```

## Conventions

### Namespace
- Use namespace JT for all CLI scripts

### Code Organization
- Use procedural PHP by default for simpler scripts
- Use classes when complexity warrants it (e.g. when script requires multiple methods or manages state)
- See `bin/localshellupdater` for procedural example
- See `bin/pr-description-generator` for class-based example

### Documentation
- Include comprehensive header documentation with usage and examples

### CLI Helper Methods
- Use `$cli` helper methods for:
  - Path handling (`convertPathToAbsolute`)
  - File operations (`writeToFile`)
  - Argument/flag parsing (`getArg`, `getFlag`)
  - Output messaging (`msg`, `err`)
  - User interaction:
    - `ask()` - CLI prompt with optional required response
    - `confirm()` - Yes/no confirmation prompt
    - `requestAnswer()` - Basic prompt for input
    - `isYes()`, `isNo()` - Check response values
  - Flag checking:
    - `hasFlag()`, `hasFlags()` - Check for --flag existence
    - `hasShortFlag()` - Check for -f style flags
    - `getFlag()` - Get value of --flag=value
  - Common state checks:
    - `isSilent()` - Check if --silent/--porcelain/-shh
    - `isVerbose()` - Check if --verbose/-v
    - `isAutoconfirm()` - Check if --yes/-y
  - Directory operations:
    - `getDirFiles()` - Get filtered directory contents
    - `filteredFileContentRows()` - Process file contents by line
  - Git operations via `$cli->git`:
    - See `helpers/git.php` for available methods
- Use `$helpyHelperton` for help documentation

### Color Conventions
- Red: errors
- Green: success
- Yellow: informational/warning

### Exit Codes
- 0: success
- 1: error

### File Operations
- File paths should be handled with `convertPathToAbsolute`
- File operations should use `writeToFile` with appropriate options

### Help Documentation
- Should be comprehensive and follow established patterns
- Scripts should validate required arguments
- Provide helpful error messages
- Error messages should include instructions for getting help

## Style Guidelines
- Use tabs for indentation (size: 3)
- Trim trailing whitespace
- Insert final newline
- Follow PSR-12 naming conventions
- Use meaningful variable names
- Include appropriate spacing around operators
- Group related code blocks with newlines
- Add comments for complex operations
applescript
perl
php
python
shell

First seen in:

jtsternberg/Dot-Files

Used in 1 repository

JavaScript
Create a professional device management system for Comprint Services using PHP, MySQL, and Bootstrap 5. The system should be secure, responsive, and follow modern web development practices.

Core Technologies:

- Backend: PHP 7.4+
- Database: MySQL
- Frontend: Bootstrap 5
- Additional: jQuery, DataTables, Chart.js

Required Pages and Features:

1. Login Page:

- Clean, centered login form with company logo
- Email/username and password fields
- Remember me functionality
- Form validation with error messages
- Secure authentication system
- Forgot password link

2. Dashboard:

- Summary cards showing total devices, pending repairs, completed repairs
- Recent devices table (last 5 entries)
- Chart showing device status distribution
- Chart showing device types distribution
- Quick actions buttons for common tasks
- Responsive grid layout
- Color-coded status indicators

3. Employees Management:

- Table listing all employees with pagination
- Search functionality for employees
- Add new employee form with fields:
  - Full name
  - Email
  - Password
  - Role (Admin/Employee)
  - Contact number
- Edit and delete employee functionality
- Modal confirmations for critical actions

4. Add Device Page:

- Form with the following fields:
  - Device name (required)
  - Device type dropdown (Computer, Printer, Network, Other)
  - Problem description (textarea)
  - Conditional fields for computers:
    - RAM size
    - Drive size
  - Client name
  - Client contact
  - Date received
  - Status dropdown (Pending, In Progress, Completed)
- Dynamic form validation
- Success/error notifications
- File attachment option for device images

5. Devices List Page:

- Advanced DataTable with:
  - Search functionality
  - Multiple filters (status, type, date range)
  - Sortable columns
  - Pagination
  - Export to Excel/PDF
- Columns:
  - Device ID
  - Device name
  - Type
  - Client
  - Status (with color indicators)
  - Date received
  - Actions (Edit/Delete)
- Bulk actions (status update, delete)
- Responsive table design

6. Update Device Page:

- Pre-populated form with device details
- All fields from Add Device page
- Status update functionality
- Repair progress notes
- Timestamp for updates
- Edit history log

Database Structure:

Users table:

- id (PRIMARY KEY)
- username
- password (hashed)
- full_name
- email
- role
- created_at

Devices table:

- id (PRIMARY KEY)
- device_name
- device_type
- problem_description
- ram_size (nullable)
- drive_size (nullable)
- client_name
- client_contact
- status
- created_at
- updated_at
- assigned_to (FOREIGN KEY to users)

UI Requirements:

- Professional color scheme (suggest using blue (#007bff) as primary color)
- Consistent padding and spacing
- Responsive design for all screen sizes
- Loading spinners for async operations
- Toast notifications for actions
- Modal confirmations for deletions
- Clean typography using Bootstrap defaults
- Proper form validation styling
- Hover effects on interactive elements
- Smooth transitions and animations
- Properly aligned forms and elements

Additional Features:

- Session management
- Input sanitization
- CSRF protection
- Error logging
- User activity logging
- Data backup functionality
- Print reports feature
- Dashboard analytics
- User permissions system

Navigation:

- Sidebar navigation with:
  - Dashboard
  - Devices
  - Employees
  - Reports
  - Settings
- Collapsible on mobile
- Active state indicators
- User profile dropdown in header

Error Handling:

- Proper error messages
- Form validation feedback
- Database error handling
- 404 page
- Session timeout handling

Security Features:

- Password hashing
- SQL injection prevention
- XSS protection
- Input validation
- Role-based access control
analytics
bootstrap
css
golang
javascript
mysql
php
samcuxx/Device-Management-System-PHP

Used in 1 repository

JavaScript
## Project Overview
Objective: Build a backend for a production-standard demo application that connects to the TrueLayer API via REST. The backend will handle API endpoints for user authentication, data retrieval, and developer console functionalities.

Tech Stack: Node.js with Express.js, MongoDB for database management, Passport.js (for OAuth or JWT-based authentication), Axios for HTTP requests to TrueLayer, Joi for input validation, and Winston for logging.

Core Packages and Libraries
Express.js: Used to define RESTful API routes, middleware, and error handling.
MongoDB: MongoDB as the database, accessed through Mongoose (ORM) for defining schemas and managing data.
Axios: For HTTP requests to the TrueLayer API, handling API interaction in a consistent and promise-based way.
Passport.js: Handle user authentication via OAuth (or JWT as needed), with support for secure authentication flows.
Joi: For validating request data to ensure incoming data is clean and conforms to expected schema definitions.
Winston: Logging for both error and operational logs, with morgan as middleware for HTTP request logging.

## Standards and Best Practices

### API Design:
Follow RESTful conventions for endpoint design.
Use meaningful, versioned endpoints (e.g., /api/v1/users).

### Error Handling:
Use consistent error classes to distinguish between client (4xx) and server (5xx) errors.
Implement a global error-handling middleware to format and log errors.

### Logging:
Use Winston for structured logging. Log errors, critical operations (e.g., authentication events), and API requests.
Use Morgan middleware for HTTP request logging with Express.

### Security:
Handle sensitive data securely (e.g., avoid storing tokens in URLs).
Ensure secure storage and transmission of sensitive data.
Use Helmet middleware for setting HTTP headers to secure Express apps.

### Validation:
Use Joi to validate all incoming data on each endpoint, ensuring that only valid and safe data is processed by the backend.

### Testing:
Follow TDD principles. Write unit tests with Jest for individual routes and middleware.
Use Supertest for integration testing of Express routes.
Aim for 80%+ test coverage, focusing on core logic (e.g., authentication, data retrieval, error handling).

## Specific Tasks for Cursor AI

### Authentication Setup:

Implement OAuth or JWT-based authentication with Passport.js.
Configure secure login and logout endpoints.
Ensure secure token handling (e.g., storing tokens in HTTP-only cookies).

### API Route Definitions:

Define RESTful routes to interact with the frontend. Core routes may include:
/api/v1/auth: Authentication endpoints (e.g., login, logout).
/api/v1/users: User-related endpoints for retrieving and managing user data.
/api/v1/console: Endpoints related to developer console actions (e.g., key management).
Use appropriate HTTP methods (e.g., GET for fetching, POST for creating) for each route.

### TrueLayer Integration:

Use Axios to connect to TrueLayer’s API. Handle authentication flow, token exchange, and data retrieval for authorized users.
Create utility functions or services that handle specific TrueLayer endpoints to avoid repetitive code.

### Error Handling and Logging:

Use custom error classes to structure different types of errors (e.g., ValidationError, AuthError).
Implement a global error-handling middleware in Express to catch and log errors consistently.
Configure Winston to log error details, user interactions, and API calls for tracking and debugging.

### Database Setup:

Define MongoDB schemas using Mongoose to represent entities (e.g., User, APIKey).
Implement basic CRUD operations in a way that is modular and reusable.
Ensure schema validation at the database level as an additional safeguard.

### Testing:

Write unit tests with Jest for each route, middleware, and utility function.
Write integration tests with Supertest to verify the overall functionality of each route and middleware.
Document test cases and aim for high coverage, especially for key functions like authentication and API interaction.

### Workflow and Iterations

Task Review: After each function, module, or feature is created, initiate a review to check for alignment with best practices, error handling, and logging. 

Refinement: Based on test results and review feedback, iterate on each feature to enhance stability and performance.
Documentation: Generate inline comments to explain complex logic and provide brief documentation for each module.

### Expected Output for Cursor AI in the Pilot
Fully Functional Backend Modules: Complete backend modules that connect to TrueLayer, manage user authentication, and handle API interactions.
Documented Code with Inline Comments: Code that is well-commented, especially for core modules and logic.
Comprehensive Testing: High-coverage unit and integration tests, ensuring the reliability of all major components and workflows.

### Suggested directory structure:

pilot-backend/
├── src/
│   ├── config/               # Configuration files (e.g., env variables, DB config)
│   ├── controllers/          # Functions to handle request logic
│   ├── middleware/           # Custom Express middleware (e.g., error handling, logging)
│   ├── models/               # Mongoose models (database schemas)
│   ├── routes/               # Route definitions (organized by module)
│   ├── services/             # Services (e.g., business logic, utility functions)
│   ├── utils/                # Utility functions (e.g., error classes, helpers)
│   ├── validations/          # Joi validation schemas for incoming requests
│   ├── tests/                # Test files for Jest and Supertest
│   └── index.js              # Main server file (server setup, middleware, and routes)
├── .env                      # Environment variables
├── .eslintrc.js              # Linter configuration
├── .gitignore                # Git ignore file
├── package.json              # Project dependencies and scripts
└── README.md                 # Project documentation

Follow this directory structure when creating files for the backend:
src/controllers/ for request handling logic.
src/middleware/ for custom Express middleware (e.g., error handling).
src/models/ for Mongoose schemas.
src/routes/ for route definitions.
src/services/ for business logic and utilities.
src/validations/ for Joi schemas to validate incoming request data.
src/tests/ for Jest and Supertest tests.
eslint
express.js
golang
javascript
jest
jwt
mongodb
oauth
+1 more

First seen in:

AliveSheCried/voilaPilot

Used in 1 repository

unknown
// Android Jetpack Compose .cursorrules

// Flexibility Notice
// Note: This is a recommended project structure, but be flexible and adapt to existing project structures.
// Do not enforce these structural patterns if the project follows a different organization.
// Focus on maintaining consistency with the existing project architecture while applying Jetpack Compose best practices.

// Project Architecture and Best Practices
const androidJetpackComposeBestPractices = [
    "Adapt to existing project architecture while maintaining clean code principles",
    "Follow Material Design 3 guidelines and components",
    "Implement clean architecture with domain, data, and presentation layers",
    "Use Kotlin coroutines and Flow for asynchronous operations",
    "Implement dependency injection using Hilt",
    "Follow unidirectional data flow with ViewModel and UI State",
    "Use Compose navigation for screen management",
    "Implement proper state hoisting and composition",
];

// Folder Structure
// Note: This is a reference structure. Adapt to the project's existing organization
const projectStructure = `
app/
  src/
    main/
      java/com/package/
        data/
          repository/
          datasource/
          models/
        domain/
          usecases/
          models/
          repository/
        presentation/
          screens/
          components/
          theme/
          viewmodels/
        di/
        utils/
      res/
        values/
        drawable/
        mipmap/
    test/
    androidTest/
`;

// Compose UI Guidelines
const composeGuidelines = `
1. Use remember and derivedStateOf appropriately
2. Implement proper recomposition optimization
3. Use proper Compose modifiers ordering
4. Follow composable function naming conventions
5. Implement proper preview annotations
6. Use proper state management with MutableState
7. Implement proper error handling and loading states
8. Use proper theming with MaterialTheme
9. Follow accessibility guidelines
10. Implement proper animation patterns
`;

// Testing Guidelines
const testingGuidelines = `
1. Write unit tests for ViewModels and UseCases
2. Implement UI tests using Compose testing framework
3. Use fake repositories for testing
4. Implement proper test coverage
5. Use proper testing coroutine dispatchers
`;

// Performance Guidelines
const performanceGuidelines = `
1. Minimize recomposition using proper keys
2. Use proper lazy loading with LazyColumn and LazyRow
3. Implement efficient image loading
4. Use proper state management to prevent unnecessary updates
5. Follow proper lifecycle awareness
6. Implement proper memory management
7. Use proper background processing
`; 
java
kotlin

First seen in:

PatrickJS/awesome-cursorrules

Used in 1 repository

JavaScript