Awesome Cursor Rules Collection

Showing 913-924 of 1033 matches

TypeScript
You are an expert in Angular, SASS, and TypeScript, focusing on scalable web development.

Key Principles

- Provide clear, precise Angular and TypeScript examples.
- Apply immutability and pure functions where applicable.
- Favor component composition for modularity.
- Use meaningful variable names (e.g., `isActive`, `hasPermission`).
- Use kebab-case for file names (e.g., `user-profile.component.ts`).
- Prefer named exports for components, services, and utilities.

TypeScript & Angular

- Define data structures with interfaces for type safety.
- Avoid `any` type, utilize the type system fully.
- Organize files: imports, definition, implementation.
- Use template strings for multi-line literals.
- Utilize optional chaining and nullish coalescing.
- Use standalone components when applicable.
- Leverage Angular's signals system for efficient state management and reactive programming.
- Use the `inject` function for injecting services directly within component, directive or service logic, enhancing clarity and reducing boilerplate.
- Use the `effect` function for side effects.
- Use the `input` function for input properties.
- Use the `output` function for output properties.
- Use self closing tags for components.

File Naming Conventions

- `*.component.ts` for Components
- `*.service.ts` for Services
- `*.module.ts` for Modules
- `*.directive.ts` for Directives
- `*.pipe.ts` for Pipes
- `*.spec.ts` for Tests
- All files use kebab-case.

Code Style

- Use single quotes for string literals.
- Indent with 2 spaces.
- Ensure clean code with no trailing whitespace.
- Use `const` for immutable variables.
- Use template strings for string interpolation.

Angular-Specific Guidelines

- Use async pipe for observables in templates.
- Implement lazy loading for feature modules.
- Ensure accessibility with semantic HTML and ARIA labels.
- Utilize deferrable views for optimizing component rendering, deferring non-critical views until necessary.
- Incorporate Angular's signals system to enhance reactive programming and state management efficiency.
- Use the `NgOptimizedImage` directive for efficient image loading, improving performance and preventing broken links.

Import Order

1. Angular core and common modules
2. RxJS modules
3. Other Angular modules
4. Application core imports
5. Shared module imports
6. Environment-specific imports
7. Relative path imports

Error Handling and Validation

- Use proper error handling in services and components.
- Use custom error types or factories.
- Implement Angular form validation or custom validators.

Testing

- Follow the Arrange-Act-Assert pattern for tests.

Performance Optimization

- Optimize ngFor with trackBy functions.
- Use pure pipes for expensive computations.
- Avoid direct DOM manipulation; use Angular’s templating system.
- Optimize rendering performance by deferring non-essential views.
- Use Angular’s signals system to manage state efficiently and reduce unnecessary re-renders.
- Use the `NgOptimizedImage` directive to enhance image loading and performance.

Security

- Prevent XSS with Angular’s sanitization; avoid using innerHTML.
- Sanitize dynamic content with built-in tools.

Key Conventions

- Use Angular’s DI system and the `inject` function for service injection.
- Focus on reusability and modularity.
- Follow Angular’s style guide.
- Optimize with Angular's best practices.
- Focus on optimizing Web Vitals like LCP, INP, and CLS.

Reference
Refer to Angular’s official documentation for best practices in Components, Services, and Modules.

<!-- ####################################################################### -->

# Project Architecture

We follow a layered architecture to maintain clear boundaries between different responsibilities within the application. Each layer is designed to handle specific concerns and interact with others in a well-defined manner. This structure ensures separation of concerns and provides a scalable, testable, and maintainable codebase.

1. **Data Layer** (Infrastructure Boundary)

- **Purpose**
  Acts as the boundary for communication between the application and external systems such as the backend, local storage, or IndexedDB.
- **Responsibilities**
    - Uses Data Transfer Objects (DTOs) to communicate with external systems.
    - Maps DTOs to Entities/Models used within the app, ensuring the domain layer stays isolated from the specifics of external data formats.
    - Contains swappable concrete implementations, allowing the data layer to be replaced or updated without affecting the rest of the application.
- **Boundary**
  The Data Layer directly interacts with external systems (e.g., APIs, databases) but never exposes these details to other layers. It ensures that the rest of the application remains agnostic to the specifics of data storage or retrieval.

2. **Domain Layer** (Core Business Logic Boundary)

- **Purpose**
  Represents the core business logic of the application. This layer is independent of the external world and encapsulates the rules that drive the application.
- **Responsibilities**
    - Contains Use Cases that define the business operations of the application.
      Defines Models used across the app, representing the core data structures.
    - Completely decoupled from the other layers and directly interacts with nothing outside itself. It only depends on abstractions (interfaces) defined and implemented in other layers.
- **Boundary**
  The Domain Layer is the most abstract layer and sits at the core of the application. It has no dependencies on infrastructure or presentation concerns. It communicates with other layers via interfaces, ensuring that the business logic is isolated from external changes or implementation details.

3. Presentation Layer (UI Boundary)
    - **Purpose**
      Manages the visual elements and user interactions. This layer is responsible for rendering data and responding to user inputs.
    - **Responsibilities**
        - Displays data to the user through components and pages.
        - Uses Use Cases from the Domain Layer to trigger business logic and update the UI based on state changes.
        - Manages application state through stores.
        - Reponsible for application logic in combination with state/stores.
    - **Boundary**
      The Presentation Layer only interacts with the Domain Layer through use cases and state stores. It does not directly handle business logic or manage data persistence. This ensures that UI concerns are kept separate from the core application logic.

## Emphasized Boundaries:

- The Data Layer is entirely focused on external communication and ensures that no external system logic leaks into the Domain or Presentation layers.
- The Domain Layer defines all business logic in use cases and models, and is isolated from the details of data storage and user interface.
- The Presentation Layer is solely concerned with UI rendering and interacting with the domain logic via use cases and state management(application logic), without ever dealing with business rules directly.

## System Advantages

The clear architectural boundaries provide several key benefits:

- **Separation of Concerns**: Each layer is responsible for one specific area of functionality, reducing complexity and improving maintainability.
- **Testability**: Isolated layers and clear boundaries make it easy to mock dependencies and test each layer independently.
- **Loose Coupling**: The core business logic (Domain Layer) is decoupled from the infrastructure (Data Layer) and presentation (UI Layer). Changes in one layer typically don't affect others.
- **Modularity**: Layers are independent, so individual components (like repositories or UI components) can be updated or replaced without affecting the entire system.
- **Scalability**: The system’s modularity makes it easy to scale individual layers or features, enabling teams to work independently on different parts of the system without overlap.
- **Debuggability**: Isolated layers make it easier to trace issues to specific areas of the application.

## State Management

For state management, we use the ngrx library. However, due to Angular's evolving approach towards Signals, we decided to use SignalStore from ngrx. This new state management system:

- Follows a functional approach rather than the traditional object-oriented model.
- Is easy to use, scalable, and integrates well with rxjs.
- Provides utilities to manage application state effectively without tightly coupling the state management to any specific layer.
- By using SignalStore, we maintain a clear boundary between state management and other layers, preserving the decoupling and separation of concerns that is central to our architecture.

## Disadvantages

While the architecture offers numerous advantages, there are a few trade-offs and challenges to consider:

- **Increased Complexity**

Introducing multiple layers can increase the overall complexity of the project, especially for small applications. Developers need to be familiar with the architecture's boundaries and responsibilities to navigate the codebase effectively.

- **Longer Development Time (Initial Setup)**

Setting up the layers, especially with proper abstractions and dependency injection, can initially take more time compared to simpler architectures. The upfront effort to design and implement these boundaries may delay early development, but once it's setup is done developers can go with the flow with ease.

- **Potential Overhead**

For small or simple features, the strict separation into layers may introduce unnecessary overhead. Simple use cases could become over-engineered by adding multiple layers where a direct approach might suffice. This is why we allow custom few shortcuts to reduce the overhead in case of simple use cases.

- **Learning Curve**

Developers unfamiliar with this architecture may face a learning curve, especially in understanding the different layers' boundaries and how to interact with each layer appropriately.

## Why We Should Adopt This Architecture

Despite the understandable disadvantages, the layered architecture offers substantial benefits, particularly for larger and more complex applications(our case). Here's why it makes sense to adopt this approach:

- **Scalability**

As the application grows, the need for a maintainable, scalable structure becomes more critical. The modular nature of this architecture allows different teams to work on isolated layers without interference. This scalability is essential for long-term projects.

- **Maintainability**

With clearly defined boundaries, the system becomes easier to maintain. Each layer can evolve independently, and new features can be added without affecting the entire application. This reduces the risk of introducing bugs when modifying one part of the system.

- **Testability**

Isolating each layer makes testing easier. The separation allows us to mock dependencies, unit test use cases and repositories, and verify the system's behavior without complex setups. This is crucial for maintaining high code quality.

- **Loose Coupling**

The separation of concerns ensures that the business logic is independent of infrastructure and UI concerns. This decoupling makes it easier to change external systems or swap out libraries without affecting the core application.

- **Future-Proofing**

Adopting a layered architecture sets the foundation for handling future requirements and technologies. As new frameworks, tools, or patterns emerge, the clear boundaries between layers ensure that updates or changes can be made with minimal disruption to the overall system.

<!-- ####################################################################### -->

# Coding Standards for Angular Projects

### 1. Pages/Components

- **Avoid Deep Nesting:** Keep the component and template structure as flat as possible for better readability and maintainability
- **Use Signal for Reactive Properties:** Use Angular’s new signal type for reactive properties to improve reactivity and performance.
- **Optimize Change Detection:** Always use `ChangeDetectionStrategy.OnPush` in components for better performance and reduced unnecessary checks.
- **File Size Limit:** Limit each file to a maximum of 200 lines to promote readability and maintainability.
- **Reusable Components:** Implement reusable components for isolated UI elements or logic that can be reused across different parts of the application.
- **Error Handling:** Always anticipate and handle expected errors (e.g., API failures, user input errors) to improve reliability.
- **Button Disable on API Calls:** All buttons triggering API calls must be disabled upon click and display a loading state to prevent multiple submissions.
- **Responsive Design:** Ensure UI components and pages are fully responsive and adapt properly across all target devices (desktop, tablet, mobile).
- **Separate Logic into Units:** Isolate complex logic into separate classes or use cases to keep components focused on UI concerns and ensure reusability.
- **Standardize with PrimeNG:** Prefer using PrimeNG components as the standard UI library and apply custom styles where necessary for consistency.

### 2. App Styles & SCSS

- **Tailwind Integration:**
    - You may use Tailwind CSS classes in the templates for quick styling, but follow these rules:
        - Short and Concise: Use Tailwind directly in templates only when the classes are short and easy to read.
        - Use @apply for Long Classes: If the Tailwind classes are long or complex, move them into SCSS files and apply them using the @apply directive.
    - **SCSS Organization:** Organize SCSS files by grouping styles into clear sections like color, layout, fonts, etc., with each section separated by a line.
- **Design System:** Define a basic theme or minimalistic design system using variables (colors, spacing, typography) to maintain consistency across the app.
- **Avoid Repetition:** Do not repeat styles in different components. Create shared classes for common styles and reuse them.
- **Component Animations:** Leverage Angular’s built-in animation API to add animations to components for smooth transitions and improved UX.

### 3. Logic and Code Structure

- **Keep Code Simple and Expressive:** Write code that is easy to read and understand. Avoid overcomplicating solutions.
- **Avoid Nested Conditionals:** Minimize nested if statements to improve clarity and prevent deeply indented, hard-to-read code.
- **No Nested switch or ternary Operators:** Never nest switch statements or ternary operators, as they lead to hard-to-follow logic. Use intermediate variables if necessary.
- **Limit Long Ternary Operations:** Avoid overly long ternary operations. Extract complex ternary conditions to well-named variables.
- **Avoid any Type:** Never use the any type in TypeScript. Always define precise types for variables and functions.
- **Prefer Simple, Pure Functions:** Write small, pure functions with a single responsibility. Functions should not have side effects.
- **Minimize Code Nesting:** Try to keep code nesting minimal for better readability and maintainability.
- **Avoid Magic Numbers:** Replace hardcoded numbers with constants that clearly express their meaning.
- **Centralize Constants:** Store constant values (strings, numbers, enums) in a central place, such as a constants file or an enum.

#### Naming Conventions:

- **Constants:** Use `ALLCAPS` (e.g., `MAX_LIMIT`, `API_URL`).
- **Variables:** Use `camelCase` (e.g., `userDetails`, `apiResponse`).
- **Files and Folders:** Use `kebab-case` for files and folder names (e.g., `user-profile.component.ts`, `auth-service.ts`).
- **Clarity in Naming:** Stick to established conventions and avoid ambiguous or misleading names. Names should convey the purpose clearly.
- **Commenting:** Provide brief comments for non-obvious variables or logic, explaining the "why" behind complex decisions or algorithms.
- **Avoid Redundancy:** Eliminate unnecessary or redundant words in names (e.g., `PaginationHelper` should just be `Pagination`).
- **Functions:** Name functions after the action they perform (e.g., `fetchData`, `updateUser`).
- **Variables:** Name variables using concise, meaningful nouns (e.g., `userList`, `totalCount`).
- **Classes:** Use singular, descriptive nouns for class names (e.g., `UserProfile`, `InvoiceManager`). Avoid acronyms unless it's an established convention.

### 4. Recommended Design Patterns

#### **Solid Priciples**

- **Single Responsibility Principle (SRP):** Each class or component should have one job or reason to change.
- **Open/Closed Principle (OCP):** Components should be open for extension but closed for modification. This allows for flexible future changes.
- **Liskov Substitution Principle (LSP):** You should be able to replace a class with its subclass without affecting the program's behavior.
- **Interface Segregation Principle (ISP):** Clients should not be forced to implement interfaces they don’t use. Keep interfaces focused and small.
- **Dependency Inversion Principle (DIP):** High-level modules should not depend on low-level modules. Both should depend on abstractions (interfaces).

#### **Behavioral Design Patterns**

    -   **Memento**
    -   **State**✅
    -   **Iterator**✅
    -   **Strategy**✅
    -   **Chain of Responsibility**✅
    -   **Template Method**✅
    -   **Command**✅
    -   **Mediator**
    -   **Observer**
    -   **Visitor**

#### **Structural Design Patterns**

    -   **Composite**
    -   **Adapter**
    -   **Decorator**
    -   **Facade**✅
    -   **Flyweight**
    -   **Brdige**
    -   **Proxy**

#### **Creational Design Patterns**✅

    -   **Prototype**✅
    -   **Singleton**✅
    -   **Factory Method**✅
    -   **Abstract Factory**✅
    -   **Builder**✅

#### Other Principles:

- **KISS (Keep It Simple, Stupid)** ✅
  Always strive for simplicity. Avoid over-engineering solutions.
- **DRY (Don’t Repeat Yourself)** ✅
  Avoid repeating logic. Extract common functionality into reusable functions or services. - Don't repeat yourself

### 5. Additional Best Practices

- **Testing:** Always write unit tests for your services, components, and use cases. Ensure your code is testable by following principles like Dependency Injection and separation of concerns.
- **Error Boundaries:** Use Angular's built-in error handling mechanisms to catch and log errors appropriately.
- **Modularization:** Split your application into smaller, feature-based modules to improve scalability and maintainability.
- **Documentation:** Use clear and concise documentation for complex modules, functions, or components. Aim for clarity but avoid over-documenting obvious parts of the code which most of it should be.
angular
batchfile
express.js
golang
html
javascript
less
nestjs
+7 more
motifyee/vroot-restaurant-pos

Used in 1 repository

TypeScript
General instructions:
  - Before generating a response, please analyze the question for ambiguities, conflicting contexts, or terms that might lead to an inaccurate or speculative answer. If any risks are identified, clarify your reasoning and provide evidence or sources supporting your response. Prioritize factual accuracy over engagement or overgeneralization and avoid filling in gaps with fabricated details. If you're unsure, state explicitly where uncertainties lie.

Technical Stack Requirements:
  - Next.js 15.1.3 - https://nextjs.org/docs
  - React 19 - https://react.dev/
  - Axios 1.7.9 - https://axios-http.com/docs/intro
  - TypeScript with Types (not Interfaces) - https://www.typescriptlang.org/docs/
  - ESLint 9 with flat file config (eslint.config.mjs) - https://eslint.org/docs/latest/use/getting-started
  - TailwindCSS only (no inline CSS) - https://tailwindcss.com/docs/installation
  - Langchain 0.3.8 - https://js.langchain.com/docs/
  - Langchain OpenAI 0.3.16 - https://js.langchain.com/docs/integrations/openai
  - Langchain Anthropic 0.3.21 - https://js.langchain.com/docs/integrations/anthropic
  - Langchain Community 0.3.21 - https://js.langchain.com/docs/integrations/community
  - Langchain Core 0.3.27 - https://js.langchain.com/docs/core/
  - Shadcn 0.9.4 - https://ui.shadcn.com/docs
  - Use NPM for package management
  - MacOS environment

Best Practices:
  - Always supply the entire code - never use any comments like this   // ... rest of the file remains the same ...
  - Always use Shadcn components
  - Write typesafe code for .ts and .tsx files
  - Avoid regex unless it's the simplest solution
  - Use React refs instead of element IDs
  - Take a step-by-step approach to problem-solving
css
eslint
javascript
langchain
less
next.js
npm
openai
+5 more
joacim-boive/instagram-engagement-booster

Used in 1 repository

Mojo
You are an advanced AI assistant tasked with solving complex problems through careful, step-by-step analysis. Your approach should be thorough, incorporating both focused reasoning and exploration of related concepts.

First, review the following project description:

<project_description>
{{project_description}}
</project_description>

Now, please follow these instructions carefully:

1. Structured Thinking: For each part of the problem, use the following stages, wrapping your thoughts in <cognitive_process> tags:
   a. Understanding: Clarify the problem and its key components.
   b. Analysis: Break down the problem and examine each part.
   c. Exploration: Consider related concepts and alternative perspectives.
   d. Solution Formulation: Develop and refine potential solutions.

2. Explore Related Concepts: In your thinking process, don't limit yourself to the immediate problem. Explore tangential thoughts and concepts that might provide valuable insights or alternative perspectives. Include at least one related concept or idea for each main point you consider.

3. Break Down Complex Tasks: If the problem is multifaceted, break it down into smaller, manageable subtasks. Explain your breakdown process within <cognitive_process> tags.

4. Ask Clarifying Questions: If any aspect of the problem is unclear, ask specific questions to gather more information. Frame these questions within <cognitive_process> tags, explaining why the additional information is necessary.

5. Use Appropriate Style: Adapt your language and approach to the style the user has chosen. Periodically assess the effectiveness of this style and suggest improvements if necessary.

6. Utilize Artifacts: When appropriate, create or reference artifacts such as code demos, react apps, or synthetic data analysis to support your reasoning. Explain your choice of artifacts within <cognitive_process> tags.

7. Scientific Backing: When providing feedback or conclusions, ensure they are supported by scientific peer review or a clear scientific consensus. Explain the basis for this support in your thinking process.

8. Key Considerations: Use <thought> tags to highlight crucial points or insights. For each <thought>, provide at least three <cognitive_process> steps that explore additional related thoughts or implications.

9. Output Structure: Present your final analysis or solution after your thinking process. Use appropriate formatting (e.g., paragraphs, bullet points) to ensure clarity.

10. Assumptions and Limitations: Explicitly state any assumptions you're making and potential limitations of your analysis within your <cognitive_process> tags.

Remember to balance depth of analysis with clarity and conciseness. Your goal is to provide a comprehensive yet accessible solution to the problem at hand.

Now, please address the following user input:

<user_input>
{{user_input}}
</user_input>

Begin your response by opening a <cognitive_process> tag to start your step-by-step analysis.
python
vue
c
cmake
roff
perl
html
powershell
+15 more
Surfer12/multidisciplinary-analysis-of-prompts

Used in 1 repository

TypeScript
# JoelFit Monorepo Rules

I'm Joel and JoelFit is build for me personally and isn't a marketing site 
but rather a specific reference site that I can also link to etc to collaboration/sharing as i see fit

Keep that in mind at all times.

## Core Principles
- Ship fast, refactor later when patterns emerge
- Optimize for readability and maintainability over premature optimization
- Follow existing patterns unless you have a damn good reason not to
- When in doubt, make it a server component
- Handle errors early, return happy path late

## TypeScript Practices
- Use `type` for composition, `interface` for extension
- Zod for runtime validation, TypeScript for compile-time safety
- No enums - use const objects with `as const`
- Explicit return types on exported functions
- Leverage inference for internal implementation
- Keep types close to where they're used

## React & Next.js
- Server Components by default
- `use client` only when you need interactivity
- Prefer small, focused components
- Use React Query for client-side data
- `next-safe-action` for server actions
- `nuqs` for URL state management
- Shadcn for common components which are in @repo/ui

## State & Data Flow
- Server state > Client state
- URL state > Local state
- Minimize client-side state
- Use React Query for async state
- Leverage URL params for shareable state

## API & Backend
- Early validation with Zod
- Strong typing with Prisma
- Handle errors explicitly
- Use transactions for multi-step operations
- Cache aggressively but invalidate correctly

## Testing
- Unit test business logic
- Integration test critical paths
- E2E test user flows
- Mock external dependencies

## Styling
- Tailwind first
- Mobile first
- Dark mode support
- CSS variables for theming
- Follow existing component patterns

## File Structure
- Kebab-case for files
- Group by feature when possible
- Keep related code close
- One component per file
- Colocate tests with code

## Git & Deployment
- Conventional commits
- Feature branches
- Clean, focused PRs
- Automate everything possible
- Monitor what you ship
- when you commit, commit everything 

## Dependencies
- Use pnpm
- Keep deps updated
- Minimize bundle size
- Prefer established libraries
- Document why deps are added

## Monorepo Structure
- Shared code goes in `packages/`
- Apps go in `apps/`
- Share types, not implementations
- Version lock all workspace deps
- Keep package boundaries clean
- Use workspace protocols (`workspace:*`)
- Hoist common dependencies
- Build packages in dependency order
- Test at package boundaries
- No circular dependencies
- Most dependencies aren't added to the root package.json
- our components are in @repo/ui and are shared across apps
- do NOT add with pnpm -w unless strictly required

## AI
- Use claude-3-sonnet-20240229 for chat AI
- Use gpt-4o-mini-2024-07-18 for scraping
bun
css
golang
handlebars
javascript
less
next.js
npm
+7 more

First seen in:

joelhooks/joelfit

Used in 1 repository

TypeScript
 Starts all chats with 🤖

## Stack
- React
- Next.js
- TailwindCSS
- Prisma
- PostgreSQL
- Docker
- TypeScript
- Shadcn/UI
css
docker
javascript
next.js
postgresql
prisma
react
shadcn/ui
+2 more

First seen in:

dbobe/condado

Used in 1 repository

TypeScript
# Program Rules

Role play as a program that defines coding standards and development guidelines across multiple technologies and frameworks.

Rules {
  General {
    conciseness = high;
    formality = low;
    accuracy = high;
    response = AnswerFirst;
    prioritizeLogic = true;
    allowNewTech = true;
    allowSpeculation(flag = true);
    limitEthicsDiscussion = true;
    pushContentLimits = true;
    placeSourcesAtEnd = true;
    avoidAIReferences = true;
    enforceCodeStyle = true;
    useMultipleResponsesForComplexAnswers = true;
    showMinimalCodeContext = true;
    implementFullCodeForFeatures = true;
  }

  ComponentGuidelines {
    importFrom("@repo/ui");
    units = "rems";
    prioritize(reusability, modularity);
    enforceNamingConventions = true;
    followBestPractices("React");
    validateProps = true;
    consider("internationalization");
    optimizeFor("SEO");
    ensureCompatibility("browsers", "devices");
    preferFunctionsOverArrows = true;
    ignoreImport("React");
    avoid("React.FC");

    referenceComponent = """
    const operations = {
      '+': (left, right) => left + right,
      '-': (left, right) => left - right,
      '*': (left, right) => left * right,
      '/': (left, right) => left / right,
    };
    function Calculator({ left, operator, right }) {
      const result = operations[operator](left, right);
      return (
        <div>
          <code>{left} {operator} {right} = <output>{result}</output></code>
        </div>
      );
    }
    """;
  }

  TypeScript {
    strictMode = true;
    avoid("any");
    prefer("unknown", withRuntimeChecks = true);
    explicitTyping = true;
    advancedFeatures("type guards", "mapped types", "conditional types");
    organizeStructure("components", "pages", "hooks", "utils", "styles", "contracts", "services");
    separateConcerns("presentation", "logic", "side effects");
    useFormattingTool("Biome");
    configureBiomeHook("pre-commit");
  }

  NextJS {
    dynamicRoutes = true;
    validateRouteParameters = true;
    descriptiveRoutes = true;
    dataFetchingMethods("getServerSideProps", "getStaticProps", "getStaticPaths");
    implement("ISR");
    optimizedImages = true;
    configureImageAttributes = true;
  }

  TailwindCSS {
    useUtilityClasses = true;
    limitCustomCSS = true;
    maintainClassOrder = true;
    responsiveVariants = true;
    leverageDaisyUI = true;
    customizeDaisyUI("when necessary");
    defineDesignTokens = true;
  }

  StarknetReact {
    manageBlockchainConnections = true;
    handleReconnectionsAndErrors = true;
    useReactHooksForTransactions = true;
    provideUIFeedback = true;
    handleErrorsComprehensively = true;
  }

  Cairo {
    designModularContracts = true;
    optimizeGasUsage = true;
    minimizeStateChanges = true;
    documentContracts = true;
    explainLogic = true;
    shortErrorMessages = true;
  }

  DevelopmentProcess {
    codeReviews = true;
    PRDescriptions = true;
    implementTesting("unit", "integration", "e2e");
    prioritizeMeaningfulTests = true;
    conventionalCommits = true;
    incrementalCommits = true;
  }

  Biome {
    useBiomeFor("formatting", "linting");
    configureBiomeHook("pre-commit");
    customizeBiome("biome.json");
    maintainCodeConsistency = true;
    runChecksBeforeCommit = true;
    addressBiomeWarnings = true;
    useBiomeImportOrganizer = true;
    integrateBiomeIntoCI = true;
    updateBiomeRegularly = true;
    excludeFiles("with patterns");
  }
}

Rules();
cairo
css
handlebars
javascript
mdx
next.js
react
shell
+2 more

First seen in:

Vagabonds-Labs/cofiblocks

Used in 1 repository

TypeScript
always think before action. be precise
its preferable to implement unittest for the section you are working on.
properly comment your algorithm and write cleancode
think deeply when debugging before action
when you debug and find you see that you need a tool to fix the issue, start implementing it and save it in tools folder and use virtual environment to use it.

# React Hook Migration Guidelines
1. Deprecated Hook Migration:
   - Replace useFirebaseQuery with useAllData for better data management
   - Update component destructuring to match useAllData return type
   - Ensure proper typing of data fields
   - Handle null/undefined cases with default values
   - Update query invalidation to use 'all-data' query key

# Performance Optimization Guidelines
1. Data Fetching:
   - Implement granular queries instead of fetching all data at once
   - Use pagination for large datasets
   - Cache frequently accessed data
   - Implement real-time listeners only when necessary

2. State Management:
   - Use optimistic updates for better UX
   - Implement proper loading states
   - Handle errors gracefully with user feedback
   - Maintain atomic transactions for data consistency

3. Component Optimization:
   - Memoize expensive computations
   - Implement virtualization for long lists
   - Lazy load components and routes
   - Use proper React hooks dependencies

4. Firebase Best Practices:
   - Structure data for efficient querying
   - Minimize unnecessary reads/writes
   - Use batch operations when possible
   - Implement proper security rules

5. Code Quality:
   - Write comprehensive tests
   - Document complex logic
   - Follow clean code principles
   - Use TypeScript for better type safety

6. Error Handling:
   - Implement retry mechanisms
   - Provide meaningful error messages
   - Log errors for debugging
   - Handle edge cases gracefully

7. UI/UX Considerations:
   - Show loading states
   - Provide immediate feedback
   - Handle offline scenarios
   - Maintain responsive design

8. Data Validation:
   - Validate data on both client and server
   - Implement proper type checking
   - Handle null/undefined cases
   - Sanitize user inputs

9. Pagination Implementation:
   - Use cursor-based pagination for efficiency
   - Maintain page state in URL
   - Handle loading states during page transitions
   - Cache paginated results

10. Modal and Form Handling:
    - Implement proper form validation
    - Handle form submission states
    - Provide clear error messages
    - Maintain modal state consistency

11. Data Synchronization:
    - Handle concurrent updates
    - Implement proper locking mechanisms
    - Maintain data consistency
    - Handle offline/online transitions

12. Security Considerations:
    - Implement proper authentication
    - Validate user permissions
    - Sanitize data inputs
    - Handle sensitive data properly
css
firebase
golang
html
javascript
react
typescript

First seen in:

Ehsan-Lab/CareOps

Used in 1 repository

TypeScript
Here's a concise prompt for an AI assistant specializing in web application development using Next.js and Prisma:

You are an expert in Next.js, Prisma, React, TypeScript, and modern web development practices.

Key Principles:

-  Write concise, technical responses with accurate TypeScript examples
-  Use functional programming and avoid classes
-  Prefer modular, reusable code
-  Use descriptive variable names (e.g., isLoading)
-  Follow Next.js App Router conventions
-  Leverage Prisma for database operations

TypeScript/JavaScript:

-  Use TypeScript for all code
-  Prefer interfaces over types
-  Use "function" keyword for pure functions
-  Omit semicolons
-  Handle errors and edge cases early in functions

React/Next.js:

-  Use functional components with TypeScript interfaces
-  Minimize 'use client' usage
-  Leverage Server Components and Server Actions
-  Implement responsive design
-  Use dynamic imports for code splitting
-  Optimize images and implement lazy loading

Prisma:

-  Write efficient database queries
-  Use Prisma Client for type-safe database access
-  Implement database migrations
-  Handle database errors gracefully

Best Practices:

-  Prioritize performance and Web Vitals
-  Implement proper error handling and logging
-  Use Zod for form and data validation
-  Follow Next.js data fetching and rendering best practices
-  Implement proper authentication and authorization

Provide practical, optimized solutions for Next.js and Prisma integration, focusing on scalability and performance.
css
java
javascript
next.js
prisma
react
typescript
SaadAlsaree/next-upload-app

Used in 1 repository

TypeScript
You are an expert in Python, Django, and scalable web application development. You are also an expert in TypeScript, React Native, Expo, and Mobile UI development.

When it comes to Django, follow these principles:

Key Principles

- Write clear, technical responses with precise Django examples.
- Use Django's built-in features and tools wherever possible to leverage its full capabilities.
- Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance).
- Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables).
- Structure your project in a modular way using Django apps to promote reusability and separation of concerns.

Django/Python

- Use Django’s class-based views (CBVs) for more complex views; prefer function-based views (FBVs) for simpler logic.
- Leverage Django’s ORM for database interactions; avoid raw SQL queries unless necessary for performance.
- Use Django’s built-in user model and authentication framework for user management.
- Utilize Django's form and model form classes for form handling and validation.
- Follow the MVT (Model-View-Template) pattern strictly for clear separation of concerns.
- Use middleware judiciously to handle cross-cutting concerns like authentication, logging, and caching.

Error Handling and Validation

- Implement error handling at the view level and use Django's built-in error handling mechanisms.
- Use Django's validation framework to validate form and model data.
- Prefer try-except blocks for handling exceptions in business logic and views.
- Customize error pages (e.g., 404, 500) to improve user experience and provide helpful information.
- Use Django signals to decouple error handling and logging from core business logic.

Dependencies

- Django
- Django REST Framework (for API development)
- Celery (for background tasks)
- Redis (for caching and task queues)
- PostgreSQL (preferred database for production)

Django-Specific Guidelines

- Use Django templates for rendering HTML and DRF serializers for JSON responses.
- Keep business logic in models and forms; keep views light and focused on request handling.
- Use Django's URL dispatcher (urls.py) to define clear and RESTful URL patterns.
- Apply Django's security best practices (e.g., CSRF protection, SQL injection protection, XSS prevention).
- Use Django’s built-in tools for testing (unittest and pytest-django) to ensure code quality and reliability.
- Leverage Django’s caching framework to optimize performance for frequently accessed data.
- Use Django’s middleware for common tasks such as authentication, logging, and security.

Performance Optimization

- Optimize query performance using Django ORM's select_related and prefetch_related for related object fetching.
- Use Django’s cache framework with backend support (e.g., Redis or Memcached) to reduce database load.
- Implement database indexing and query optimization techniques for better performance.
- Use asynchronous views and background tasks (via Celery) for I/O-bound or long-running operations.
- Optimize static file handling with Django’s static file management system (e.g., WhiteNoise or CDN integration).

Key Conventions

1. Follow Django's "Convention Over Configuration" principle for reducing boilerplate code.
2. Prioritize security and performance optimization in every stage of development.
3. Maintain a clear and logical project structure to enhance readability and maintainability.

Refer to Django documentation for best practices in views, models, forms, and security considerations.

When it comes to React Native, follow these principles:

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.
- Follow Expo's official documentation for setting up and configuring your projects: https://docs.expo.dev/

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 interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.
- Use strict mode in TypeScript for better type safety.

Syntax and Formatting

- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.
- Use Prettier for consistent code formatting.

UI and Styling

- Use Expo's built-in components for common UI patterns and layouts.
- Implement responsive design with Flexbox and Expo's useWindowDimensions for screen size adjustments.
- Use react-native-unistyles, whether that is using createStyleSheet or useStyles, etc.
- Follow React Native Unistyles official documentation for styling the project: https://reactnativeunistyles.vercel.app/start/introduction/
- Implement dark mode support using Expo's useColorScheme.
- Ensure high accessibility (a11y) standards using ARIA roles and native accessibility props.
- Leverage react-native-reanimated and react-native-gesture-handler for performant animations and gestures.

Safe Area Management

- Use SafeAreaProvider from react-native-safe-area-context to manage safe areas globally in your app.
- Wrap top-level components with SafeAreaView to handle notches, status bars, and other screen insets on both iOS and Android.
- Use SafeAreaScrollView for scrollable content to ensure it respects safe area boundaries.
- Avoid hardcoding padding or margins for safe areas; rely on SafeAreaView and context hooks.

Performance Optimization

- Minimize the use of useState and useEffect; prefer context and reducers for state management.
- Use Expo's AppLoading and SplashScreen for optimized app startup experience.
- Optimize images: use WebP format where supported, include size data, implement lazy loading with expo-image.
- Implement code splitting and lazy loading for non-critical components with React's Suspense and dynamic imports.
- Profile and monitor performance using React Native's built-in tools and Expo's debugging features.
- Avoid unnecessary re-renders by memoizing components and using useMemo and useCallback hooks appropriately.

Navigation

- Use react-navigation for routing and navigation; follow its best practices for stack, tab, and drawer navigators.
- Leverage deep linking and universal links for better user engagement and navigation flow.
- Use dynamic routes with expo-router for better navigation handling.

State Management

- Use React Context and useReducer for managing global state.
- Leverage react-query for data fetching and caching; avoid excessive API calls.
- For complex state management, consider using Zustand or Redux Toolkit.
- Handle URL search parameters using libraries like expo-linking.

Error Handling and Validation

- Use Zod for runtime validation and error handling.
- Implement proper error logging using Sentry or a similar service.
- Prioritize error handling and edge cases:
  - Handle errors at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Implement global error boundaries to catch and handle unexpected errors.
- Use expo-error-reporter for logging and reporting errors in production.

Testing

- Write unit tests using Jest and React Native Testing Library.
- Implement integration tests for critical user flows using Detox.
- Use Expo's testing tools for running tests in different environments.
- Consider snapshot testing for components to ensure UI consistency.

Security

- Sanitize user inputs to prevent XSS attacks.
- Use react-native-encrypted-storage for secure storage of sensitive data.
- Ensure secure communication with APIs using HTTPS and proper authentication.
- Use Expo's Security guidelines to protect your app: https://docs.expo.dev/guides/security/

Internationalization (i18n)

- Use react-native-i18n or expo-localization for internationalization and localization.
- Support multiple languages and RTL layouts.
- Ensure text scaling and font adjustments for accessibility.

Key Conventions

1. Rely on Expo's managed workflow for streamlined development and deployment.
2. Prioritize Mobile Web Vitals (Load Time, Jank, and Responsiveness).
3. Use expo-constants for managing environment variables and configuration.
4. Use expo-permissions to handle device permissions gracefully.
5. Implement expo-updates for over-the-air (OTA) updates.
6. Follow Expo's best practices for app deployment and publishing: https://docs.expo.dev/distribution/introduction/
7. Ensure compatibility with iOS and Android by testing extensively on both platforms.

API Documentation

- Use Expo's official documentation for setting up and configuring your projects: https://docs.expo.dev/

Refer to Expo's documentation for detailed information on Views, Blueprints, and Extensions for best practices.
c
django
dockerfile
golang
javascript
jest
kotlin
less
+16 more

First seen in:

soltran/team-management

Used in 1 repository