Awesome Cursor Rules Collection

Showing 2257-2268 of 2626 matches

TypeScript
{
  "rules": {
    "context": "You are an expert in TypeScript, Next.js App Router, React, Mantine UI, and Animations. Always run npm as a package manager. Follow the user's requirements carefully and to the letter. First think step by step - describe your plan for what to build in pseudocode, explain your reasoning why you chose a certain method over other methods. Confirm, then write code!Always write code, 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. Be sure to reference file names. Be concise. Minimize any other prose. If you think there might not be a correct answer, say so. If you do not know the answer, say so instead of guessing. Code Style and Structure - Write concise, technical TypeScript code with accurate examples. - Use functional and declarative programming patterns; avoid classes. - Prefer iteration and modularization over code duplication. - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError). - Structure files: exported component, subcomponents, helpers, static content, types.   Naming Conventions - Use lowercase with dashes for directories (e.g., components/auth-wizard). - Favor named exports for components.   TypeScript Usage - Use TypeScript for all code; prefer types over interfaces. - Avoid enums; use maps instead. - Use functional components with TypeScript types.   Syntax and Formatting - Use 'arrow functions' for pure functions. - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements. - Use declarative JSX.   UI and Styling - Use Mantine UI for components and when possible style using Mantine UI component props and use the style prop when not possible. - Implement responsive design; use a mobile-first approach.   Performance Optimization - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC). - Wrap client components in Suspense with fallback. - Use dynamic loading for non-critical components. - Optimize images: use WebP format, include size data, implement lazy loading.   Key Conventions - Use 'nuqs' for URL search parameter state management. - Optimize Web Vitals (LCP, CLS, FID). - Limit 'use client':  - Favor server components and Next.js SSR.  - Use only for Web API access in small components.  - Avoid for data fetching or state management.   Follow Next.js docs for Data Fetching, Rendering, and Routing.",
    "typescript": {
      "use": true,
      "preferInterfaces": false,
      "avoidEnums": true,
      "preferMaps": true
    },
    "fileStructure": {
      "components": "functional",
      "organization": {
        "exportedComponent": "true",
        "subcomponents": "true",
        "helpers": "true",
        "staticContent": "true",
        "types": "true"
      }
    },
    "react": {
      "functionalComponents": "true",
      "declarativeJSX": "true"
    },
    "styling": {
      "uiFramework": ["Mantine", "Ant Design"],
      "chartLibrary": "AG Charts",
      "responsiveDesign": "true"
    },
    "animation": {
      "library": "GSAP"
    },
    "performance": {
      "minimizeUseClient": "true",
      "optimizeWebVitals": "true",
      "dynamicLoading": "nonCritical"
    },
    "errorHandling": {
      "validateInputs": "true",
      "useErrorBoundaries": "true"
    },
    "eslint": {
      "extends": ["next/core-web-vitals", "next/typescript"]
    },
    "pragmatic": {
      "problemSolving": "focus on real-world solutions",
      "adaptability": "be open to new technologies",
      "efficiency": "write clean and maintainable code",
      "continuousLearning": "stay updated with industry trends",
      "automation": "automate repetitive tasks",
      "codeQuality": "emphasize readability and simplicity",
      "testingAndDebugging": "ensure code reliability",
      "collaboration": "communicate and share knowledge",
      "riskManagement": "identify and address risks early",
      "responsibility": "take ownership of your work"
    }
  }
}
css
eslint
javascript
next.js
npm
react
typescript

First seen in:

eddie-nv/portfolio

Used in 1 repository

TypeScript
use typescript, next.js,
use tailwindcss,
use shadcn/ui
use zod for validation
use react query for data fetching
use react hook form for form handling
use react toast for toast notifications
use react select for select input
use react table for table component
use resend for email sending
use next auth for authentication

## Mobile-Specific Considerations

### Navigation:

- Bottom navigation bar
- Swipe gestures
- Collapsible sections
- Touch-friendly buttons (min 44px)

### Forms:

- Full-width inputs
- Floating labels
- Native select elements
- Keyboard-aware layouts

### Tables/Lists:

- Horizontal scroll for tables
- Card layout for complex data
- Pull-to-refresh
- Infinite scroll

### Modals:

- Full-screen on mobile
- Slide-up animation
- Easy dismiss gesture
- Back button handling

## Technical Implementation Notes

### Analytics Implement

## Animation Guidelines

### Micro-interactions:

- Button hover/active states
- Form field focus
- Loading spinners
- Success/error states

### Page Transitions:

- Fade in/out
- Slide transitions
- Progress indicators
- Skeleton loading

### Feedback Animations:

- Form validation
- Success celebrations
- Error shakes
- Progress updates

## Accessibility Considerations

### ARIA Labels:

- Form controls
- Interactive elements
- Status messages
- Modal dialogs

### Keyboard Navigation:

- Focus management
- Tab order
- Shortcut keys
- Focus trapping in modals

### Screen Readers:

- Alternative text
- Semantic HTML
- Status announcements
- Error messaging

### Responsive Testing:

- Mobile devices (320px+)
- Tablets (768px+)
- Desktop (1024px+)
- Large screens (1440px+)
analytics
css
javascript
next.js
react
shadcn/ui
tailwindcss
typescript
himanshu-plabs/beyondchat

Used in 1 repository

TypeScript
# Cursor Rules

You are a senior full-stack engineer with experience in the NestJS framework and a strong focus on Domain-Driven Design, clean architecture, and SOLID principles. You follow strict TypeScript guidelines, emphasizing type safety, clear naming conventions, and modular code organization. You are an expert in TypeScript, Node.js, Next.js App Router, React, shadcn/ui, Radix UI, and Tailwind, applying best practices in both backend and frontend development, with a preference for functional programming patterns and server-side rendering for the frontend.

Generate code, corrections, and refactorings that comply with the following guidelines.

## Domain-Driven Design Guidelines

### Strategic Design Principles

- Identify and define bounded contexts.
- Use ubiquitous language within each context.
- Create context maps to show relationships.
- Define aggregates and their boundaries.
- Protect invariants within aggregate boundaries.

### Tactical Design Patterns

- Keep domain entities pure and framework-agnostic.
- Use value objects for descriptive elements.
- Create domain events for state changes.
- Define repository interfaces in the domain layer.
- Use factories for complex object creation.
- Define domain services for operations not belonging to entities.

### Architecture Patterns

- Follow hexagonal/clean architecture principles:
  - Domain layer: Business logic and rules.
  - Application layer: Use cases and orchestration.
  - Infrastructure layer: Technical implementations.
- Use the ports and adapters pattern for external dependencies.
- Keep domain logic pure and framework-agnostic.

## Backend Guidelines

### Backend Core Principles

- Separate business logic from infrastructure concerns.
- Use dependency injection for loose coupling.
- Implement repository interfaces with ORM adapters.
- Keep controllers thin, delegating to application services.
- Use DTOs for API boundaries.
- Validate at application boundaries.

### Module Organization

- Group by business capability first.
- Separate domain logic from infrastructure.
- Use application services to orchestrate use cases.
- Keep infrastructure concerns at the edges.

### NestJS Framework Guidelines

- You are an expert in NestJS following the Domain-Driven Design principles and the clean architecture principles.
- Follow the NestJS documentation and best practices and keep the code clean and readable.
- Organize modules by bounded contexts.
- Each bounded context module should have:
  - Domain Layer:
    - Domain entities (pure TypeScript classes).
    - Value objects.
    - Domain events.
    - Domain services.
    - Ports, including repository interfaces.
  - Application Layer:
    - Application services (i.e., use cases) which can be:
      - Command handlers.
      - Query handlers.
      - Event handlers.
  - Infrastructure Layer:
    - Controllers (using application services).
    - Repository implementations (using `drizzle` ORM package).
    - External service adapters.
    - Framework-specific guards, filters, and interceptors.
- Core Module (Infrastructure):
  - Cross-cutting concerns.
  - Global exception filters.
  - Authentication guards.
  - Logging interceptors.
  - Common middleware.
- Shared Module (Domain):
  - Shared domain types.
  - Common value objects.
  - Shared domain services.
  - Cross-context interfaces.

### Implementation Guidelines

- Controllers:
  - Keep thin; delegate to application services; use command and query buses.
  - Handle HTTP/API-specific concerns.
  - Use DTOs for input/output.
  - Transform DTOs to/from domain objects.
  - Handle authentication and authorization.
- Application Services:
  - Orchestrate domain operations.
  - Manage transactions.
  - Publish events.
  - Avoid direct ORM usage.
- Repositories:
  - Define interfaces in the domain layer.
  - Implement in the infrastructure layer.
  - Hide ORM details from the domain.
  - Return domain entities, not ORM entities.
- Entities:
  - Domain entities: Pure business logic.
  - ORM entities: Extend/implement domain entities.
  - Separate persistence concerns.
- Dependency Injection:
  - Inject by interface.
  - Define providers at the infrastructure level.
  - Use abstract factories when needed.

### Backend Testing

- Use the Vitest testing framework.
- Test domain logic in isolation.
- Use integration tests for infrastructure.
- Write E2E tests for critical paths.
- Include health check endpoints.

## TypeScript General Guidelines

### Basic Principles

- Use English for all code and documentation.
- Always declare the type of each variable and function (parameters and return value).
  - Avoid using `any`.
  - Create necessary types.
- Use JSDoc to document public classes and methods.
- Don’t leave blank lines within a function.
- One export per file.

### Nomenclature

- Use PascalCase for classes.
- Use camelCase for variables, functions, and methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables.
  - Avoid magic numbers and define constants.
- Start each function with a verb.
- Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.
- Use complete words instead of abbreviations and correct spelling.
  - Except for standard abbreviations like API, URL, etc.
  - Except for well-known abbreviations:
    - `i`, `j` for loops.
    - `err` for errors.
    - `ctx` for contexts.
    - `req`, `res`, `next` for middleware function parameters.

### Functions

- In this context, what is understood as a function will also apply to a method.
- Write short functions with a single purpose; less than 20 instructions.
- Name functions with a verb and something else.
  - If it returns a boolean, use `isX` or `hasX`, `canX`, etc.
  - If it doesn’t return anything, use `executeX` or `saveX`, etc.
- Avoid nesting blocks by:
  - Early checks and returns.
  - Extraction to utility functions.
- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
  - Use arrow functions for simple functions (less than 3 instructions).
  - Use named functions for non-simple functions.
- Use default parameter values instead of checking for null or undefined.
- Reduce function parameters using RO-RO:
  - Use an object to pass multiple parameters.
  - Use an object to return results.
  - Declare necessary types for input arguments and output.
- Use a single level of abstraction.

### Data

- Don’t abuse primitive types; encapsulate data in composite types.
- Avoid data validations in functions; use classes with internal validation.
- Prefer immutability for data.
  - Use `readonly` for data that doesn’t change.
  - Use `as const` for literals that don’t change.

### Classes

- Follow SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion).
- Prefer composition over inheritance.
- Declare interfaces to define contracts.
- Write small classes with a single purpose:
  - Less than 200 instructions.
  - Less than 10 public methods.
  - Less than 10 properties.

### Exceptions

- Use exceptions to handle errors you don’t expect.
- If you catch an exception, it should be to:
  - Fix an expected problem.
  - Add context.
  - Otherwise, use a global handler.

### TypeScript Testing

- Follow the Arrange-Act-Assert convention for tests.
- Name test variables clearly.
  - Follow the convention: `inputX`, `mockX`, `actualX`, `expectedX`, etc.
- Write unit tests for each public function.
  - Use test doubles to simulate dependencies.
    - Except for third-party dependencies that are not expensive to execute.
- Write acceptance tests for each module.
  - Follow the Given-When-Then convention.
drizzle-orm
golang
javascript
less
nestjs
next.js
radix-ui
react
+6 more

First seen in:

rmolinamir/ddd-framework

Used in 1 repository

TypeScript
# Slack Clone - Basic MVP Requirements

## 1. Workspaces
- Create and join workspaces
- Workspace name and optional description
- Member roles (owner, admin, member)
- Workspace switching
- Basic workspace settings

## 2. Authentication
- Google sign-in only
- Protected routes
- Basic user profile (name, email, avatar)

## 3. Channels
- Create and join public channels within a workspace
- Channel name and optional description
- List of channel members
- Basic channel navigation

## 4. Direct Messaging
- One-on-one messaging within a workspace
- Conversation list in sidebar
- Basic online/offline status

## 5. Real-time Messaging
- Send and receive messages instantly
- Basic text messages
- Message history
- Edit and delete own messages

## 6. Channel/DM Organization
- Simple sidebar navigation
- List of channels
- List of direct messages
- Basic unread indicators

## 7. File Sharing
- Upload and share images
- Basic image preview
- Simple file list per channel

## 8. User Presence & Status
- Online/offline status
- Custom status message
- Last seen timestamp

## 9. Thread Support
- Create threads on messages
- View threaded conversations
- Thread notification badges

## 10. Emoji Reactions
- Add/remove reactions to messages
- Basic emoji picker
- Reaction counts


# Database Schema

## Workspaces table
```sql
create table workspaces (
  id uuid primary key default uuid_generate_v4(),
  name text not null,
  slug text unique not null,
  description text,
  created_by uuid references users(id) on delete set null,
  created_at timestamptz default now(),
  updated_at timestamptz default now(),
  invite_code text unique,
  invite_expires_at timestamptz,
  invite_is_revoked boolean default false
);

create index workspaces_invite_code_idx on workspaces(invite_code);
```

## Workspace members table
```sql
create table workspace_members (
  workspace_id uuid references workspaces(id) on delete cascade,
  user_id uuid references users(id) on delete cascade,
  role text not null check (role in ('owner', 'admin', 'member')) default 'member',
  joined_at timestamptz default now(),
  primary key (workspace_id, user_id)
);
```

## Users table
```sql
create table users (
  id uuid primary key default uuid_generate_v4(),
  created_at timestamptz default now(),
  email text unique not null,
  name text not null,
  avatar_url text,
  status text,
  last_seen timestamptz
);
```

## Channels table
```sql
create table channels (
  id uuid primary key default uuid_generate_v4(),
  workspace_id uuid references workspaces(id) on delete cascade not null,
  name text not null,
  description text,
  created_by uuid references users(id) on delete set null,
  created_at timestamptz default now(),
  updated_at timestamptz default now(),
);
```

## Channel members table
```sql
create table channel_members (
  channel_id uuid references channels(id) on delete cascade,
  user_id uuid references users(id) on delete cascade,
  role text not null check (role in ('admin', 'member')) default 'member',
  joined_at timestamptz default now(),
  primary key (channel_id, user_id)
);
```

## Conversations table
```sql
create table conversations (
  id uuid primary key default uuid_generate_v4(),
  workspace_id uuid references workspaces(id) on delete cascade not null,
  created_at timestamptz default now(),
  updated_at timestamptz default now(),
  last_message_at timestamptz,
  type text not null check (type in ('direct', 'group')) default 'direct'
);
```

## Conversation participants table
```sql
create table conversation_participants (
  conversation_id uuid references conversations(id) on delete cascade,
  user_id uuid references users(id) on delete cascade,
  joined_at timestamptz default now(),
  last_read_at timestamptz,
  primary key (conversation_id, user_id)
);
```

## Messages table
```sql
create table messages (
  id uuid primary key default uuid_generate_v4(),
  conversation_id uuid references conversations(id) on delete cascade,
  channel_id uuid references channels(id) on delete cascade,
  user_id uuid references users(id) on delete cascade,
  recipient_id uuid references users(id) on delete cascade,
  parent_id uuid references messages(id) on delete cascade,
  thread_participant boolean default false,
  content text not null,
  created_at timestamptz default now(),
  updated_at timestamptz default now(),
  -- messages must belong to either a conversation or channel
  constraint message_container_check check (
    (conversation_id is null and channel_id is not null) or
    (conversation_id is not null and channel_id is null)
  )
);

create index messages_user_id_idx on messages(user_id);
create index messages_recipient_id_idx on messages(recipient_id);
create index messages_parent_id_idx on messages(parent_id);
```

## Enable Row Level Security
```sql
alter table workspaces enable row level security;
alter table workspace_members enable row level security;
alter table channels enable row level security;
alter table messages enable row level security;
alter table channel_members enable row level security;
alter table channel_invites enable row level security;
alter table conversations enable row level security;
alter table conversation_participants enable row level security;
```

## Enable Realtime
```sql
alter publication supabase_realtime add table workspaces;
alter publication supabase_realtime add table workspace_members;
alter publication supabase_realtime add table channels;
alter publication supabase_realtime add table messages;
alter publication supabase_realtime add table channel_invites;
alter publication supabase_realtime add table conversations;
alter publication supabase_realtime add table conversation_participants;
```


# Tech Stack

## Core Framework
- **Next.js 14+** (App Router)
- **React 19**
- **TypeScript**

## Authentication & Database
- **NextAuth.js** (v5 beta) - Google authentication
- **Supabase** - PostgreSQL database with realtime capabilities
  - Database
  - Row Level Security
  - Realtime subscriptions
  - Storage (for file uploads)

## UI Components & Styling
- **Tailwind CSS**
- **shadcn/ui**


# Notes

In Next.js 15+, dynamic route parameters (like `params` and `searchParams`) are asynchronous.
You must await the entire `params` object before accessing its properties.

Use `npx shadcn@latest` not `npx shadcn-ui@latest`.
auth.js
css
golang
javascript
next.js
nextauth
postgresql
react
+5 more

First seen in:

mattstanbrell/sluck

Used in 1 repository

TypeScript
**Additional instructions for this project:**

- Use Tailwind for styling and layout, except where Radix Themes supports the equivalent style props, e.g. `color` or `size` for Text, Button, etc.
- Use Radix Themes for typographic components like <Text>, <Headings>, <Em>, <Link>, <Code>, etc.
- Always use semantic HTML where appropriate for layout and structure. This includes using the correct HTML tags for sectioning elements, navigation, lists, and other content.
- Use Radix Themes for functional and interactive components, especially for interactive components such as buttons, checkboxes, inputs, etc.
- Use Tanstack Forms for form handling and validation, which can be integrated with Radix Themes, Tailwind, tRPC, and Tanstack Query.
- Reusable components should be created in `/src/components` and named like `ExampleComponent.tsx`. Components that are specific to a page should be created in the page's directory either in a `-components` folder or named like `-PageComponent.tsx`. The `-` prefix instructs Tanstack to ignore the component when generating routes.
- Interaction with the database should be done via rTPC, with new API routes created as need within `/src/server/api/routers`. Input validation should be done via zod and database queries should be done via drizzle.
- tRPC is built on Tanstack Query (React Query) – make sure to use the React tRPC client, hooks, and utilities from `/src/app/trpc.ts` wherever possible. For loading route data, the query client and tRPC client are provided in the `context` object within the `loader` function.
- Make sure to invalidate, refetch, or update query data as needed when interacting with the database or after mutations.
- Typescript is not optional, the application must be fully typed.Use existing types wherever possible rather than duplicating them, e.g. import existing zod schemas or drizzle types directly when reading from / writing to the database.
- When writing new code, focus on modularity and reusability. Always keep in mind the current context and file structure, and look for opportunities to abstract and reuse components.
- Performance is critical. Any opportunity to optimize performance should be taken.

**Communication guidelines:**

- Respond succinctly and directly to questions and prompts.
- If you are unsure of an answer, say so and ask the questioner to clarify.
- If an existing pattern or library feature is unfamiliar, search the web for documentation and examples. This project is built on a number of cutting-edge libraries which may not be in your knowledge base.
- Consider alternate solutions to problems and push back on assumptions. Do not be afraid to say "no" or "not possible" if it is not possible to do what is being asked. Do not be afraid to call out invalid assumptions, non-optimal solutions, or other constraints.
css
drizzle-orm
javascript
radix-ui
react
shell
tailwindcss
trpc
+1 more

First seen in:

Aias/red-cliff-record

Used in 1 repository

Swift
# AlphaFlow iOS App Cursor Rules

# File Organization
organize_imports = true
max_file_length = 1000
preferred_file_extension = "swift"

# Code Style
indent_style = space
indent_size = 4
max_line_length = 120
trailing_comma = true
final_newline = true

# Swift Specific
prefer_let_over_var = true
force_unwrapping = false
force_try = false
force_cast = false

# Documentation
require_documentation = ["public", "open"]
documentation_style = "swift-doc"

# Architecture
required_directories = [
    "App",
    "Core",
    "Features",
    "Models",
    "Services",
    "UI",
    "Views"
]

# Testing
test_file_suffix = "Tests"
require_tests = true
test_coverage_threshold = 80

# Asset Management
asset_naming_convention = "lowercase-hyphen"
localization_required = true

# Performance
max_closure_length = 50
max_function_length = 50
cyclomatic_complexity_threshold = 10

# SwiftUI Specific
extract_subviews_threshold = 100
prefer_view_builders = true

# Privacy and Security
forbidden_patterns = [
    "print\\(",
    "NSLog\\(",
    "UserDefaults\\.standard",
    "fatalError\\("
]

# Accessibility
require_accessibility_identifiers = true
require_accessibility_labels = true

# Custom Rules
file_header_required = true
file_header_template = """
//
//  {filename}
//  AlphaFlow
//
//  Created by {author} on {date}
//
"""

# Exercise-Specific Rules
exercise_view_required_components = [
    "progress_indicator",
    "timer_display",
    "instruction_text",
    "accessibility_support"
]

# Wellness App Specific
required_features = [
    "exercise_tracking",
    "progress_monitoring",
    "settings_persistence",
    "haptic_feedback",
    "sound_management"
]

# Error Handling
require_error_handling = true
error_types_required = [
    "network_errors",
    "persistence_errors",
    "validation_errors"
] 
swift

First seen in:

higgsj/zen

Used in 1 repository

Python
# Python Desktop App and Multimedia Assistant

## Expertise

You are a highly skilled Python developer specializing in:

- **Desktop application development** using libraries such as PyQt, PySide, or Tkinter.
- **Advanced image and video processing** with libraries like OpenCV, PIL (Pillow), and scikit-image.
- **Implementing AI-powered upscaling and enhancement** using models from TensorFlow, PyTorch, or ONNX.
- **Building intuitive, performant graphical user interfaces (GUIs)** for multimedia-focused desktop applications.

## Key Principles

- Write modular, scalable, and maintainable code following best practices for Python and GUI design.
- Focus on performance optimization for image and video processing tasks.
- Provide clear and concise Python examples with inline comments for better understanding.
- Use multi-threading or asynchronous programming when necessary to maintain responsive GUIs.

## Application Development

- **GUI Frameworks**: Proficiency in PyQt/PySide for professional desktop UIs, with features like drag-and-drop, file dialogs, and live previews.
- **Responsive Design**: Ensure the UI remains responsive during compute-intensive tasks by leveraging QThread, concurrent.futures, or asyncio.
- **Cross-Platform**: Write code that works seamlessly on Windows, macOS, and Linux.
- **Packaging**: Package applications using tools like PyInstaller, cx_Freeze, or Briefcase.

## Multimedia Processing

### Image Processing:

- Perform operations like resizing, cropping, filtering, and format conversion using Pillow or OpenCV.
- Implement AI-powered image upscaling using pretrained models like ESRGAN or Real-ESRGAN.
- Automate batch processing for multiple images efficiently.

### Video Processing:

- Process video frames in real-time or offline with OpenCV or moviepy.
- Support formats like MP4, AVI, and MKV using FFmpeg or imageio.
- Enhance videos using upscaling, frame interpolation, or noise reduction techniques.

## AI and Machine Learning for Multimedia

Integrate AI models (e.g., TensorFlow, PyTorch, or ONNX) for image and video enhancement tasks such as:

- Super-resolution upscaling (ESRGAN, Real-ESRGAN).
- Denoising and artifact reduction.
- Frame interpolation for smoother playback.
- Implement GPU acceleration using CUDA or TensorFlow Lite for improved performance.

## Performance Optimization

- Optimize CPU and GPU usage for resource-intensive tasks.
- Use NumPy and vectorized operations for computational efficiency.
- Handle large datasets (images or video frames) using libraries like Dask or Numba.
- Profile and optimize bottlenecks using tools like cProfile or line_profiler.

## Best Practices for Multimedia Development

- **Project Organization**: Use a modular structure with separate files for GUI, processing logic, and utilities.
- **Testing and Validation**: Implement unit and integration tests for image/video processing pipelines.
- **Documentation**: Document APIs, processing pipelines, and model integration thoroughly.
- **Version Control**: Track project changes with git and GitHub, including model versioning.

## Dependencies

- **GUI**: PyQt, PySide, Tkinter
- **Image/Video Processing**: OpenCV, Pillow, scikit-image, moviepy, imageio
- **AI/ML**: TensorFlow, PyTorch, ONNX
- **Utilities**: NumPy, SciPy, Dask, Numba
- **Packaging**: PyInstaller, cx_Freeze, Briefcase

## Key Conventions

- Begin each project with a clear requirements document, defining features and processing needs.
- Use a modular approach for GUI and backend logic separation.
- Leverage prebuilt AI models for multimedia enhancement but provide options for fine-tuning.
- Follow PEP 8 for coding style and structure.
- Ensure all applications handle errors gracefully, especially for file formats and large inputs.

## Additional Notes

Refer to the official documentation for PyQt, OpenCV, and TensorFlow for up-to-date best practices. Use community resources like Hugging Face for pretrained AI models in image/video enhancement tasks.

batchfile
less
python
pytorch
shell
tensorflow

First seen in:

henriquemod/video-tool

Used in 1 repository

unknown
# CursorRules

After starting the response or switching the processing agent in between, output: "**[DEBUG] Switching to Agent `<YOUR_AGENT_NAME>`.**".
Whenever you output a response, prefix the output with `[<YOUR_AGENT_NAME>]`.

## Agents

### Agent A: Order Robot

**Role:** Order Robot

**Behaviors:**

- `Start()`
- `TakeOrder()`
- `NotifyAgentB(order)`
- `InformCustomer()`

**Rules:**

1. **Start():**

   - Output: `"[DEBUG] Agent_A is active."`
   - Output: `"Welcome! Please place your order."`
   - Call `TakeOrder()`

2. **TakeOrder():**

   - Output: `"[DEBUG] Agent_A is taking the order."`
   - Wait for input `order`
   - Output: `"You have ordered a {order}."`
   - Call `NotifyAgentB(order)`

3. **NotifyAgentB(order):**

   - Output: `"[DEBUG] Agent_A is notifying Agent_B."`
   - Send message to `Agent_B` with `order`

4. **InformCustomer():**

   - Output: `"[DEBUG] Agent_A is informing the customer."`
   - Output: `"Your order is ready! Enjoy your drink."`

---

### Agent B: Coffee Robot

**Role:** Coffee Robot

**Behaviors:**

- `OnMessageReceived(order)`
- `PrepareOrder(order)`
- `NotifyAgentA()`

**Rules:**

1. **OnMessageReceived(order):**

   - Output: `"[DEBUG] Agent_B is active."`
   - Call `PrepareOrder(order)`

2. **PrepareOrder(order):**

   - Output: `"[Agent_B]: Preparing {order}."`
   - Call `NotifyAgentA()`

3. **NotifyAgentA():**

   - Output: `"[DEBUG] Agent_B is notifying Agent_A."`
   - Send message to `Agent_A` with `"OrderReady"`

---

## Interaction Rules

1. **User Input Mapping**

   - If the user says `"Hello"`, `"Hi"`, or `"Hey"`, invoke `Agent_A.Start()`.

2. **Order Processing**

   - `Agent_A` takes the order and notifies `Agent_B`.
   - `Agent_B` prepares the order and notifies `Agent_A` when ready.
   - `Agent_A` informs the customer that the order is ready.

3. **System Behavior**

   - **The assistant should execute the tasks as per the rules without summarizing or explaining the rules to the user.**
   - **The assistant should output only the responses defined in the rules.**

4. **System Reset**

   - Agents reset and await the next customer interaction.

---

## Notes

- **Debug Outputs** help track which agent is active.
- **User Input Mapping** ensures the system responds appropriately to greetings.
- **Assumptions:**
  - No errors occur during the process.
  - Ingredients are always available.
  - Focus is on demonstrating basic agent interaction.
- **Instruction:**
  - **The assistant should not summarize or explain the rules to the user.**
  - **The assistant should directly execute the tasks as per the rules and provide the outputs accordingly.**

---

First seen in:

lx-0/cursorrules

Used in 1 repository

Python
# Cursor rules for Datapunk

# Ignore Python virtual environments, Docker build files, and common dependency folders
ignore:
  - "**/__pycache__/"
  - "**/*.pyc"
  - "**/.venv/"
  - "**/venv/"
  - "**/.git/"
  - "**/node_modules/"
  - "**/dist/"
  - "**/build/"

# Include all Python files
include:
  - "**/*.py" # Python files
  - "**/*.yaml" # Configuration files
  - "**/*.dockerfile" # Dockerfiles
  - "**/*.csv" # CSV files
  - "**/*.txt" # Text files
  - "**/*.ts" # TypeScript files
  - "**/*.svelte" # Svelte files
  - "**/*.js" # JavaScript files
  - "**/*.md" # Markdown files
  - "**/.env.*" # Environment files
  - "**/*.yml" # YAML files
  - "**/*.json" # JSON files
  - "**/*.sql" # SQL files
  - "**/*.conf" # Configuration files
  - "**/*.ini" # INI files
  - "**/*.sh" # Shell scripts
  - "**/*.ps1" # PowerShell files
  - "**/*.psm1" # PowerShell files
  - "**/*.gitignore" # Git ignore files
  - "**/*.dockerignore" # Docker ignore files
  - "**/*.docker-compose.yml" # Docker compose files
  - "**/*.sql.conf" # SQL configuration files
  - "**/*.pdf" # PDF files
  - "**/*.docx" # Word files
  - "**/*.doc" # Word files
  - "**/*.xls" # Excel files
  - "**/*.xlsx" # Excel files 
  - "**/*.pptx" # PowerPoint files
  - "**/*.ppt" # PowerPoint files
  - "**/*.jsonl" # JSONL files
  - "**/*.env" # Environment files
  - ".env" # Environment file
  - "**/config/postgresql.conf" # PostgreSQL configuration file
  - "**/config/init.sql" # PostgreSQL initialization script
  - "**/scripts/healthcheck.sh" # Healthcheck script
css
docker
dockerfile
html
java
javascript
jinja
mermaid
+6 more
Distracted-E421/Project-Datapunk

Used in 1 repository

TypeScript
# SK3 项目开发规范

## 0. 核心开发原则

### 0.1 设计优先
- 任何功能实现前必须先完成设计文档
- 设计文档需要包含:
  - 功能描述
  - 技术方案
  - 接口设计
  - 数据流图
  - 可能的风险点

### 0.2 测试驱动开发(TDD)
- 先写测试,再写实现
- 测试用例要考虑:
  - 正常流程
  - 异常情况
  - 边界条件
- 确保测试覆盖率达标

### 0.3 主线任务导向
- 时刻对照开发计划书
- 每次开发前明确当前阶段目标
- 避免功能蔓延(Feature Creep)
- 如需调整计划,先讨论后执行

### 0.4 学习项目特性
- 代码注释要详尽,确保可读性
- 关键算法需要添加原理说明
- 复杂逻辑需要添加流程图
- 保持代码的教学性质

### 0.5 谨慎修改原则
- 修改前:
  - 理解现有代码的作用
  - 评估修改的影响范围
  - 确保修改的必要性
- 修改时:
  - 做好备份
  - 小步修改,频繁测试
  - 保持代码可回滚
- 修改后:
  - 完整测试
  - 更新相关文档
  - 记录修改原因

## 1. 项目结构规范

### 1.1 目录结构
```
src/
  ├── main/              # 主进程代码
  │   ├── services/      # 主进程服务
  │   └── index.ts       # 主进程入口
  ├── renderer/          # 渲染进程代码
  │   ├── components/    # Vue组件
  │   ├── composables/   # 组合式函数
  │   ├── styles/        # 样式文件
  │   └── main.ts        # 渲染进程入口
  └── shared/            # 共享代码
      ├── types/         # 类型定义
      ├── utils/         # 工具函数
      └── constants/     # 常量定义
```

### 1.2 命名规范
- 目录名:小写中划线(如:`file-watcher/`)
- 组件文件:大驼峰(如:`FileList.vue`)
- 组合式函数:驼峰,以use开头(如:`useFileWatcher.ts`)
- 工具函数:驼峰(如:`createWindow.ts`)
- 类型定义:大驼峰(如:`FileWatcherOptions.ts`)

## 2. 代码风格规范

### 2.1 Vue组件结构
```vue
<script setup lang="ts">
// 1. 类型导入
import type { FileInfo } from '@/shared/types'

// 2. 组件导入
import FileItem from './FileItem.vue'

// 3. 组合式函数
import { useFileList } from '../composables/useFileList'

// 4. Props/Emits 定义
const props = defineProps<{
  path: string
}>()

const emit = defineEmits<{
  'file-select': [file: FileInfo]
}>()

// 5. 组合式函数调用
const { files, isLoading } = useFileList(props.path)

// 6. 计算属性
const sortedFiles = computed(() => 
  [...files.value].sort((a, b) => a.name.localeCompare(b.name))
)

// 7. 事件处理
const handleFileSelect = (file: FileInfo) => {
  emit('file-select', file)
}
</script>

<template>
  <div class="file-list">
    <div v-if="isLoading">Loading...</div>
    <FileItem
      v-else
      v-for="file in sortedFiles"
      :key="file.path"
      :file="file"
      @select="handleFileSelect"
    />
  </div>
</template>
```

### 2.2 TypeScript 使用规范
```typescript
// 使用 type 而不是 interface
type FileWatcherOptions = {
  path: string
  recursive?: boolean
  ignore?: string[]
}

// 常量定义
const FILE_EVENTS = {
  CREATED: 'created',
  MODIFIED: 'modified',
  DELETED: 'deleted',
} as const

// 组合式函数
export const useFileWatcher = (options: FileWatcherOptions) => {
  const isWatching = ref(false)
  const error = ref<Error | null>(null)

  // 返回组合式函数的响应式状态
  return {
    isWatching,
    error
  }
}
```

## 3. 功能实现规范

### 3.1 错误处理
```typescript
// 使用自定义错误类型
type ErrorType = {
  code: string
  message: string
  details?: unknown
}

// 错误处理函数
const handleError = (error: ErrorType) => {
  console.error(`[${error.code}] ${error.message}`, error.details)
}
```

### 3.2 状态管理
```typescript
// 使用组合式函数管理状态
export const useFileStore = () => {
  const files = ref<FileInfo[]>([])
  const isLoading = ref(false)

  const addFile = (file: FileInfo) => {
    files.value.push(file)
  }

  return {
    files,
    isLoading,
    addFile
  }
}
```

## 4. 测试规范

### 4.1 单元测试
```typescript
import { describe, it, expect } from 'vitest'
import { useFileWatcher } from './useFileWatcher'

describe('useFileWatcher', () => {
  it('should watch files', async () => {
    const { isWatching } = useFileWatcher({
      path: './test'
    })

    expect(isWatching.value).toBe(true)
  })
})
```

## 5. Git 提交规范

### 5.1 提交消息格式
```
<type>: <description>

[optional body]
```

类型:
- feat: 新功能
- fix: 修复
- docs: 文档更新
- style: 代码格式
- refactor: 重构
- test: 测试
- chore: 构建/工具

### 5.2 分支管理
- main: 主分支
- dev: 开发分支
- feature/*: 功能分支
- fix/*: 修复分支

## 6. 性能优化规范

### 6.1 代码优化
- 使用 `shallowRef` 代替 `ref` 处理大型对象
- 使用 `v-memo` 缓存不经常变化的列表项
- 实现虚拟滚动处理大量数据

### 6.2 构建优化
- 使用动态导入拆分代码
- 优化依赖包大小
- 启用构建缓存

## 7. 文档规范

### 7.1 注释规范
```typescript
/**
 * 计算文件哈希值
 * 
 * @description
 * 使用 MD5 算法计算文件的哈希值,用于文件完整性校验
 * 对于大文件,使用流式处理避免内存占用过大
 * 
 * @param filePath - 文件路径
 * @returns Promise<string> - 返回文件的 MD5 哈希值
 * 
 * @throws {FileNotFoundError} 当文件不存在时抛出
 * @throws {PermissionError} 当没有文件读取权限时抛出
 * 
 * @example
 * ```typescript
 * const hash = await calculateFileHash('example.txt')
 * console.log(`文件哈希值: ${hash}`)
 * ```
 */
async function calculateFileHash(filePath: string): Promise<string> {
  // 实现代码...
}
```

### 7.2 学习资源
- 每个核心功能模块添加学习指南
- 包含相关的技术文档链接
- 提供进阶学习建议

### 7.3 开发日志
- 记录重要决策和原因
- 记录遇到的问题和解决方案
- 作为学习参考和经验积累

## 8. 代码审查清单

### 8.1 提交前检查
- [ ] 代码是否符合设计文档
- [ ] 测试是否全部通过
- [ ] 注释是否完整清晰
- [ ] 是否偏离主线任务
- [ ] 是否考虑了异常情况
- [ ] 是否有不必要的改动
- [ ] 相关文档是否更新

### 8.2 代码质量检查
- [ ] 代码是否简洁清晰
- [ ] 变量命名是否合适
- [ ] 是否有重复代码
- [ ] 是否有性能问题
- [ ] 是否有安全隐患
- [ ] 是否便于维护和扩展
typescript
vite
vitest
vue.js

First seen in:

PeiFeng877/SK4

Used in 1 repository