Awesome Cursor Rules Collection

Showing 433-444 of 1033 matches

TypeScript
# Project-specific rules for Cursor AI
[project]
name = "dfda"
framework = "next.js"
version = "15.0"
router = "app"
style = "tailwind"
typescript = true
package_manager = "pnpm"

# AI Object Generation Example

import { getModel } from '@/lib/utils/modelUtils';
import { z } from 'zod'
import { generateObject } from 'ai'
const TestSchema = z.object({
    name: z.string().describe("A name for the item"),
    description: z.string().describe("A detailed description"),
    tags: z.array(z.string()).describe("Related tags"),
    rating: z.number().min(0).max(5).describe("Rating from 0-5")
});
const result = await generateObject({
    model: getModel(),
    schema: TestSchema,
    prompt: `Generate information about a random product.`,
});


# Define the project's architecture and conventions
[architecture]
server_components = [
    "app/**/page.tsx",
    "app/**/layout.tsx",
    "app/**/template.tsx"
]
client_components = [
    "components/**/*.tsx",
    "app/**/components/*.tsx"
]
hooks = ["lib/hooks/**/*.ts"]
utils = ["lib/**/*.ts"]
config = ["config/**/*.ts"]
types = ["types/**/*.ts"]

# Component and Authentication Guidelines
[components]
server = """
IMPORTANT: Server Components (pages)
- Never add 'use client' to page.tsx files
- No hooks or browser APIs
- Fetch data server-side when possible
- Import client components as needed

Auth Usage:
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/lib/auth"
const session = await getServerSession(authOptions)
if(!session?.user) {
    return redirect('/signin?callbackUrl=/my-page')
}
"""

client = """
When to use client components:
- Uses hooks (useState, useEffect, etc.)
- Needs browser APIs
- Has user interactions
- Uses client-side libraries

Location: app/my-feature/components/InteractiveComponent.tsx

Auth Usage:
import { useSession } from 'next-auth/react'
const { data: session } = useSession()
"""

# Next.js App Router conventions
[next]
routing = """
- Use app directory for all routes
- page.tsx files are automatically server components
- loading.tsx for loading states
- error.tsx for error handling
- layout.tsx for shared layouts
"""

data_fetching = """
- Use server components for data fetching when possible
- Leverage React Server Components for better performance
- Use route handlers (route.ts) for API endpoints
"""

# Type Safety and Database
[code_quality]
types = """
- Use TypeScript strict mode
- Import Prisma types directly from @prisma/client
- Create interfaces for component props
- Avoid 'any' type
- Always prefer schema.prisma types over creating new ones

Example:
import { Post, User } from '@prisma/client'
"""

best_practices = """
✅ DO:
- Keep pages as server components
- Create separate client components for interactivity
- Use self-documenting names
- Choose simple implementations
- Use proper auth imports based on component type

❌ DON'T:
- Mix client and server code in same component
- Create new types when Prisma types exist
- Use cryptic or abbreviated names
"""

# Performance guidelines
performance = """
- Keep pages as server components when possible
- Use client components only when necessary
- Implement proper code splitting
- Use React Suspense boundaries wisely
"""

# File patterns to ignore
[ignore]
patterns = [
    "node_modules",
    ".next",
    "build",
    "dist",
    "public/assets",
    ".git"
]

# Testing guidelines
[testing]
jest = """
- Always set @jest-environment node at the top of test files
- Write tests that can safely run against production
- Use real implementations instead of mocks where possible

Example header:
/**
 * @jest-environment node
 */
"""
css
dockerfile
golang
html
javascript
jest
mdx
mermaid
+10 more
decentralized-fda/decentralized-fda

Used in 1 repository

Vue
You are a Senior Frontend Developer and an Expert in Vue 3, Nuxt 3, JavaScript, TypeScript, TailwindCSS, Shadcn Vue, Radix Vue and VueUse. You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

Follow the user’s requirements carefully & to the letter.
First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
Confirm, then write code!
Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at # Code Implementation Guidelines .
Focus on easy and readability code, over being performant.
Fully implement all requested functionality.
Leave NO todo’s, placeholders or missing pieces.
Ensure code is complete! Verify thoroughly finalised.
Include all required imports, and ensure proper naming of key components.
Be concise Minimize any other prose.
If you think there might not be a correct answer, you say so.
If you do not know the answer, say so, instead of guessing

Coding Environment
The user asks questions about the following coding languages:

Vue 3
Nuxt 3
JavaScript
TypeScript
TailwindCSS
Shadcn Vue
Radix Vue
VueUse

Code Implementation Guidelines
Follow these rules when you write code:

Use early returns whenever possible to make the code more readable.
Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
Always use composition api.
Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.

TypeScript Usage - Use TypeScript for all code; prefer types over interfaces. - Avoid enums; use const objects instead. - Use Vue 3 with TypeScript, leveraging defineComponent and PropType. Remember to ALWAYS type to avoid type errors!!

UI and Styling - Use Shadcn Vue, Radix Vue, and Tailwind for components and styling. - Implement responsive design with Tailwind CSS; use a mobile-first approach. Use react icons for icons.

Performance Optimization - Leverage Nuxt's built-in performance optimizations. - Use Suspense for asynchronous components. - Implement lazy loading for routes and components. - Optimize images: use WebP format, include size data, implement lazy loading.

Key Conventions - Use VueUse for common composables and utility functions. - Use Pinia for state management. - Optimize Web Vitals (LCP, CLS, FID). - Utilize Nuxt's auto-imports feature for components and composables. - use useFetch instead of axios for fetching data

Nuxt-specific Guidelines - Follow Nuxt 3 directory structure (e.g., pages/, components/, composables/). - Use Nuxt's built-in features: - Auto-imports for components and composables (never import these, as they are auto-imported!). - File-based routing in the pages/ directory. - Server routes in the server/ directory. - Leverage Nuxt plugins for global functionality. - Use useFetch and useAsyncData for data fetching. - Implement SEO best practices using Nuxt's useHead and useSeoMeta.

Follow the official Nuxt.js and Vue.js documentation for up-to-date best practices on Data Fetching, Rendering, and Routing.

----------------------------------SANITY RULES----------------------------------
When creating sanity schema make sure to include an appropriate icon for the schema using lucide-react or sanity icons as a fallback. Make sure you're always using the Sanity typescript definitions if it's a ts file. Here's an example, make sure you use a defineField on every field and a defineType throughout the whole type. If you don't see any arrayMembers, don't import it:

All schema types should always use the defineType, defineField, and defineArrayMember helper plugins. All registered schema export a named const that matches the filename. This only applies if it does not have input components. If a schema type has input components, they should be colocated with the schema type file. The schema type should have the same named export but stored in a [typeName]/index.ts file. These components should be named [name]-[componentType]

src/
└─ schemaTypes/
└─ seoType/
├─ index.ts
├─ seoInput.ts
└─ seoField.ts

They can all be imported and collated in your schema types like this:
// ./src/schemaTypes/index.ts

import {lessonType} from './lessonType'
import {seoType} from './seoType'

export const schemaTypes = [lessonType, seoType]

import {defineField, defineType, defineArrayMember} from 'sanity' if it's a .ts file.

defineType({
type: 'object',
name: 'custom-object',
fields: [
defineField({
type: 'array',
name: 'arrayField',
title: 'Things',
of: [
defineArrayMember({
type: 'object',
name: 'type-name-in-array',
fields: [defineField({type: 'string', name: 'title', title: 'Title'})],
}),
],
}),
],
})

Every document and object schema type should:

- Have an icon property from either @sanity/icons, or if you need more variety, the Lucide set has a larger selection.
- Have a customized preview property so that desk lists, reference fields, and search results show rich content about the document.
- Use Field Groups when the schema type has more than a few fields to collate related fields and only show the most important group by default. These Groups should use the icon property as well.

Avoid single references
Prefer an array of references. Use plurals for reference field names.

Plugin configuration files
Keep a ./src/plugins folder for any plugins we create in Sanity Studio. Instead, create a folder for each plugin and store configuration functions within these. For example, create a structure folder for configuration of the structureTool plugin. This should leave you with folder structures for the Structure and Presentation plugins like:

src
├─ structure
│ └─ index.ts
└─ presentation
└─ locate.ts

When writing any Sanity schema that matches with any part of the keywords below, use these as a template including the description. Make sure description is always above type. Whenever generating sanity schema ensure you're always including a description, as well as the name, title and type, have a best guess as to what the field does and describe that functionality in the simplest way possible to a non-technical user.

{
name: 'eyebrow',
title: 'Eyebrow',
description: 'The smaller text that sits above the title to provide context',
type: 'string',
},
{
name: 'title',
title: 'Title',
description: 'The large text that is the primary focus of the block',
type: 'string',
},
{
name: 'isHeadingOne',
title: 'Is it a <h1>?',
type: 'boolean',
description:
'By default the title is a <h2> tag. If you use this as the top block on the page, you can toggle this on to make it a <h1> instead',
initialValue: false,
},
{
name: 'richText',
title: 'Rich Text',
description: 'Large body of text that has links, ordered/unordered lists and headings.',
type: 'richText',
},
{
name: 'buttons',
title: 'Buttons',
description: 'Add buttons here, the website will handle the styling',
type: 'array',
of: [{type: 'button'}],
},
{
name: 'image',
title: 'Image',
type: 'image',
fields: [
{
name: 'alt',
type: 'string',
description:
"Remember to use alt text for people to be able to read what is happening in the image if they are using a screen reader, it's also important for SEO",
title: 'Alt Text',
},
],
},

Final folder structure. Example:

----------------------------------FRONTEND RULES----------------------------------
Always use tailwind to style if the codebase is using it. Always use functional react.

----------------------------------REFACTORING RULES----------------------------------
Any time you refactor to tailwind, if there's any form of logic with styles, make sure you use the cn utility otherwise it won't work
Any time there's a charka ui heading without styles, it's the equivalent of a text-4xl by default

----------------------------------SCREENSHOT RULES----------------------------------
If you are asked to produce sanity schema, you follow this ruleset:
You help Sanity developers describe types and interfaces using pictures.
Here is an example in JSON format:
Example: I send a picture with a product card.
You reply using the Sanity rules below
defineType({
type: 'object',
name: 'custom-object',
fields: [
defineField({
type: 'array',
name: 'arrayField',
title: 'Things',
of: [
defineArrayMember({
type: 'object',
name: 'type-name-in-array',
fields: [defineField({type: 'string', name: 'title', title: 'Title'})],
}),
],
}),
],
})
Make sure you always include a description of what the schema does based on the image, for example if it's a title, it's description: 'The large text that is the primary focus of the block',.

If you see a tiny piece of text above a title, it's probably an eyebrow

If you see a large piece of text, that doesn't require any formatting such as italics, bold or links that looks like a header it should be considered a title or subtitle if there's two headers and one is smaller than the other.

If there is a large piece of text within the component that has bolds, italic, numbered list or bulleted points in a regular disc style there's a good chance it will need to be richText.

If there's an image, it's likely it will need to be an image which should include an alt text. If the image is behind the text and takes up a significant portion of the component, the chances are it's a backgroundImage, which would the exact same way, just with a different name.

If there's buttons remember to use the reusable buttons array so that we can repeat the pattern with our schema

If richTextField or buttonsField exists anywhere within the project, make sure to use this and import it.

----------------------------------INTERNATIONALISATION RULES----------------------------------
Whenever I mention internationalisation and frontend, please take any of the following and convert to the ltr/rtl agnostic version below
left ➜ start
right ➜ end
ml ➜ ms
mr ➜ me
pl ➜ ps
pr ➜ pe
border-l ➜ border-s
border-r ➜ border-e
text-left ➜ text-start
text-right ➜ text-end
float-left ➜ float-start
float-right ➜ float-end

Any time there's a button that has a prefix or a suffix with an arrow right or left, you'll need to throw a RTL prop to invert it horizontally.
css
golang
html
java
javascript
less
nuxt.js
radix-ui
+6 more

First seen in:

westis/duv2

Used in 1 repository

TypeScript
# This is the ReconJS monorepo

The monorepo is structured as such:

- The `packages` folder contains all of the libraries that will be published on NPM.
- The `examples` folder contains sample projects that use ReconJS packages.
- The `scripts` folder contains helper files for building and publishing the libraries.

## Rules for `packages`

- All packages must be written in TypeScript.
- Most (but not all) packages will be React packages; as much as possible, packages should be compatible with React 18, React 19, Server Components, React Native and the browser.
- Packages should be agnostic of NodeJS vs Bun vs Deno, etc.

## Rules for `examples`

- Example projects should be written in TypeScript.
- Example projects should use a specific version of React.
- Example projects should show how ReconJS packages can be used.
- Example web projects should support TailwindCSS.
- Example React Native projects should use Expo.
- Example projects should be runnable from root with `pnpm run <example-name>`.

## Rules for writing React code

- Any time mock data is created in non-testing code (like when creating a rough draft of anew component), it should be wrapped in an async function. The purpose of this rule is that we want to force ourselves to generate code that is somewhat realistic, even when it's just a rough draft.
- When using React 18, import `use` from `@reconjs/react` instead of React.
- All Contexts should be named with a `the` prefix.
- All Contexts that with `the` prefix should be passed to `setDisplayNames`.
- Never use `theContext.Provider` as a JSX element. Instead use Recon's `Provider` component.

## Instructions for using `@reconjs/react`

To use `@reconjs/react`, you must add the following at the root of your project:

```tsx
import { RootProvider } from "@reconjs/react"

function App () {
  return (
    <StrictMode>
      <RootProvider>
        ...
      </RootProvider>
    </StrictMode>
  )
}
```

### The `Provider` Component

To get better performance out of React Contexts you can just use Recon's `Provider` component!

```tsx
import { Provider } from "@reconjs/react"
import { NameInput } from "..."

const theTask = createContext <string> (undefined as any)

function TaskForm (props: { id: string }) {
  return (
    <Provider context={theTask} value={props.id}>
      <NameInput />
      ...
    </Provider>
  )
}
```

### Creating a Context

Recon also provides a simpler utility for creating Contexts.

```tsx
import { createContext } from "@reconjs/react"
const theTask = createContext<string>()
```

and a utility for setting display names...

```tsx
import { setDisplayNames } from "@reconjs/react"
setDisplayNames ({ theTask })
```

### Automatically Managed Contexts

Recon also provides a utility for creating Contexts that are automatically managed by Recon and don't need to be provided.

```jsx
import { defineContext } from "@reconjs/react"

// theNameState never needs to be provided
const theNameState = defineContext (() => {
  const [ name, setName ] = useState ("")
  return { name, setName }
}, [ theTask ])

export function NameInput() {
  const { name, setName } = useContext (theNameState)
  return (
    <input 
      value={name} 
      onChange={(e) => setName (e.target.value)} 
    />
  )
}
```

### `cache` lets us fetch data

React 19 introduced `cache` but only for Server Components. The ReconJS version works on the client too.

```tsx
import { use } from "@reconjs/react"
import { cache, defineContext } from "@reconjs/react"

const loadTask = cache (async (id: string) => {
  const response = await fetch (`/api/tasks/${id}`)
  return response.json()
})

const theNameState = defineContext (() => {
  const data = use (loadTask (id))
  // ...
}, [ theTask ])
```

### `use` lets us use a hook

For compatibility with React 18, ReconJS stubs out React 19's `use` hook.

```tsx
import { use, defineContext } from "@reconjs/react"

const theNameState = defineContext (() => {
  const data = use (loadTask (id))
  // ...
}, [ theTask ])
```
bun
javascript
npm
pnpm
react
tailwindcss
typescript

First seen in:

rcharmeyer/reconjs

Used in 1 repository

TypeScript
You are an expert in TypeScript, React, Firebase, Tailwind CSS, and modern web development practices.
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 React and Firebase's official documentation for best practices.
Naming Conventions
Use lowercase with dashes for directories (e.g., components/session-card).
Favor named exports for components and utilities.
TypeScript Usage
Use TypeScript for all code; prefer interfaces over types.
Avoid enums; use objects or 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 Tailwind CSS for utility-based styling.
Implement responsive design with Flexbox.
Ensure high accessibility (a11y) standards using ARIA roles and native accessibility props.
Leverage Framer Motion for animations.
Performance Optimization
Minimize the use of useState and useEffect; prefer context and reducers for state management.
Optimize images: use WebP format where supported, include size data, implement lazy loading.
Implement code splitting and lazy loading for non-critical components with React's Suspense and dynamic imports.
Avoid unnecessary re-renders by memoizing components and using useMemo and useCallback hooks appropriately.
Navigation
Use react-router-dom for routing and navigation; follow its best practices for route management.
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.
Error Handling and Validation
Use proper error logging using console 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.
Implement global error boundaries to catch and handle unexpected errors.
Testing
Write unit tests using Jest and React Testing Library.
Consider snapshot testing for components to ensure UI consistency.
Security
Sanitize user inputs to prevent XSS attacks.
Use secure storage for sensitive data.
Ensure secure communication with APIs using HTTPS and proper authentication.
Internationalization (i18n)
Support multiple languages and RTL layouts.
Ensure text scaling and font adjustments for accessibility.
Key Conventions
Prioritize Mobile Web Vitals (Load Time, Jank, and Responsiveness).
2. Use environment variables for sensitive data.
3. Follow best practices for app deployment and publishing.
4. Ensure compatibility with various browsers and devices by testing extensively.
API Documentation
Use Firebase's official documentation for setting up and configuring your projects.
Refer to the documentation of each technology for detailed information on best practices.
css
firebase
html
javascript
jest
nestjs
prettier
react
+3 more

First seen in:

kit678/dwellnessbolt

Used in 1 repository

TypeScript
# [Project Name]

Every time you choose to apply a rule(s), explicitly state the rule(s) in the output. You can abbreviate the rule description to a single word or phrase.

## Project Context

Web multiplayer party game where players trade stocks to maximize their net worth.

- Game takes 10 rounds with 5 phases. Player with hiest cash and stocks cost wins.
  - Players submit buy/sell orders for stocks
  - Orders are executed in chronological order, each affecting the stock price on execution
  - Event effects are revealed which affect stock prices or dividends
  - Dividends are paid out to players depending on their stock holdings
  - New event summary is shown to players allowing to guess the effects
- Game lobby initiated on the host device that provides gameplay overview
- Players can join lobby from their own devices to submit orders and see their cash and portfolio

## 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 repository files as follows:

```
app/                    # Next JS pages
├── game/               # Player's game pages
├── join/               # Page for joining a game
├── lobby/              # Game lobby pages and their creation
components/             # Shared React components
├── ui/                 # shadcn ui components
lib/
├── types/
    ├── supabase.ts     # Types representing supabase tables. Do not change without updating database schema
    └── ...
├── hooks/              # Custom React hooks
├── openai.ts           # Methods to generate events using OpenAI
└── ...
```

## Tech Stack

- Next.js 13
- React
- TypeScript
- Shadcn UI
- Supabase

## Naming Conventions

- Use lowercase with dashes for directories (e.g., components/form-wizard)
- Favor named exports for components and utilities
- Use PascalCase for component files (e.g., VisaForm.tsx)
- Use camelCase for utility files (e.g., formValidator.ts)

## TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use const objects with 'as const' assertion
- Use functional components with TypeScript interfaces
- Use absolute imports for all files @/...
- Avoid try/catch blocks unless there's good reason to translate or handle error in that abstraction
- Use explicit return types for all functions

## UI and Styling

- Use Shadcn UI and `npx shadcn@latest add <component-name>` command (not shadcn-ui) to add new shadcn components

## Database

- Do not make any assumptions about the database structure; always request this information from the user
- If you need information about the database structure, write plain sql queries code blocks that user will execute in supabase web console
- When updating database structure, write sql queries code blocks to execute in supabase web console

## Error Handling

- Implement proper error boundaries
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Handle network failures gracefully
css
golang
javascript
less
next.js
openai
react
shadcn/ui
+2 more
egor-sergeev/party-market

Used in 1 repository

TypeScript
You are an expert in TypeScript, Next.js App Router, React, Prisma, Postgres, Clerk/nextjs@4.29.12, Shadcn UI, and Tailwind CSS.

Code Style and Structure

- Use the style and structure that is already used in the current folder 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.
- Always uses stable versions of the different packages.

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.

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.

UI and Styling

- Use Shadcn UI, and Tailwind CSS for components and styling.
- Implement responsive design with Tailwind CSS; 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.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
clerk
css
javascript
next.js
postgresql
prisma
react
shadcn/ui
+2 more
kdgs-develop/kdgs-admin-dashboard

Used in 1 repository

TypeScript
<!-- @format -->
CURSORRULES: V0.2

Project-Specific Overview

    Project Name & Description:
    •	Example: “MyProject - A decentralized marketplace for digital collectibles.”

Goals & Objectives:
• Example: “Implement a robust smart contract for trustless transactions, integrate a Next.js front-end for seamless user experience, ensure high test coverage, and maintain a clearly documented codebase.”

Immediate To-Dos:
• Example: 1. Finalize Solidity contract for escrow payments. 2. Set up NestJS services and Next.js pages for user onboarding. 3. Integrate Alchemy and ethers for on-chain queries. 4. Configure Tailwind and Radix UI components for responsive design. 5. Implement basic RAG-based feature with LangChain and ensure Supabase integration for data storage.

(Update this section as the project evolves to help the AI remain aware of priorities and changes.)

Global Standards & Best Practices

1. Code Quality & Consistency
   • Languages & Frameworks:
   • Primary Languages: TypeScript for front-end and back-end logic, Solidity for smart contracts.
   • Common Frameworks & Libraries: Next.js, Node.js/Express, Tailwind CSS, ethers.js, Alchemy SDK.
   • Code Style:
   • Follow a strict linting and formatting guideline. For TypeScript, adhere to ESLint and Prettier configurations.
   • For Solidity, follow the latest recommended Solidity style guide (e.g., naming conventions, NatSpec comments).
   • Ensure all code includes type definitions and strongly typed interfaces (no any unless absolutely necessary).
   • Repository Structure:

FRONT END
/build # Service compiled output
/docs # Project documentation, architectural decisions, API specs
/src # TypeScript source (NestJS services, Next.js pages/components)
/app # Next.js App Router structure (preferred for latest Next.js)
/components # Shared UI components (use lowercase-dashed folder names)
/ui # UI components
/modals # Modals
/common # Common components
/layout # Layout components
/config # Configuration files  
 /constants # Constants and environment variables
/hooks # Reusable hooks
/helpers # Specific helper functions for hooks
/utils # Utility functions
/providers # Providers
/contexts # Contexts
/helpers # Helper functions
/styles # Tailwind & CSS styles
/types # TypeScript types, interfaces, and enums
/scripts # Deployment, migration, utility scripts
/public # Static assets
.env # Environment variables
.cursorrules # AI Context and Project rules

BACK END
/build # Service compiled output
/src # TypeScript source (NestJS services, Next.js pages/components)
/api # Next.js App Router structure (preferred for latest Next.js)
/config # Configuration files  
 /constants # Constants and environment variables
/utils # Utility functions
/classes # Classes
/providers # Providers
/contexts # Contexts
/helpers # Helper functions
/pages # Next.js pages (if applicable)
.index.ts # Entry point for the backend
/docs # Project documentation, architectural decisions, API specs
/scripts # Deployment, migration, utility scripts
.env # Environment variables
.cursorrules # AI Context and Project rules

SMART CONTRACTS
/bin # Big data sets dump
/build # Build artifacts
/contracts # Solidity Contracts
/base # Base Contracts
/interfaces # Interfaces
/libraries # Libraries
/logic # Logic contracts
/security # Security contracts
/tokens # Token contracts
/utils # Utility contracts
/config # Configuration files  
/deploy # Deployment scripts & arguments
/deployers # Deployer scripts
/arguments # Deployment arguments
deploy.ts # Master deployment script
deploymentArgs.ts # Deployment arguments
/docs # Project documentation, architectural decisions, API specs
/contracts # Documentation exports from Hardhat Documentation creation
/reports # Hardhat reports
/logs # Deployment logs
/scripts # Deployment, migration, utility scripts
/helpers # Helper functions
/tests # Test specific helper functions
/tasks # Hardhat tasks
/tests # Test files
/types # TypeScript types, interfaces, and enums and Output of Hardhat typechain
/contracts # Output of Hardhat typechain
.env # Environment variables
.cursorrules # AI Context and Project rules
.hardhat.config.ts # Hardhat configuration

**Mono-Repo Note:**  
For large mono-repos, separate deployable sections (`/backend`, `/contracts`, `/docs`, `/frontend`, etc.). If multiple services of the same type exist, name them accordingly (e.g., `backend-stats`, `backend-tracking`, `frontend-website`, `frontend-app`).

---

## 2. Documentation & Knowledge Sharing

**Documentation Standards:**

- Each feature/module: Document in `/docs`.
- Solidity: Use NatSpec for all public/external functions.

**Regular Updates:**

- Update `/docs` after significant changes affecting data structures, APIs, or deployments.
- Maintain a changelog or release notes.

**Reading & Staying Informed:**

- AI and team should regularly refer to `/docs` and code comments.
- Before coding or refactoring, review recent changes and docs.

---

## 3. TypeScript General Guidelines

**Basic Principles:**

- Strong typing: Declare types for variables, parameters, return values.
- Avoid `any`. Create interfaces/types as needed.
- No blank lines within functions.
- Use descriptive, correctly spelled names.
- Use RO-RO (Receive Object, Return Object) for multiple parameters/returns.

**Nomenclature:**

- Classes: PascalCase
- Variables/Functions/Methods: camelCase
- Files/Directories: kebab-case
- Environment Variables: UPPERCASE
- Use verbs in function names, no magic numbers.

**Functions:**

- Short, single-purpose (<20 instructions).
- Arrow functions for simple helpers (<3 instructions).
- Named functions for complex logic.
- Early returns to reduce nesting.
- Use map/filter/reduce for clarity.
- Default parameters over null checks.

**Data:**

- Encapsulate in composite types.
- Prefer immutability (`readonly`, `as const`).

**Classes (NestJS Services, etc.):**

- Follow SOLID.
- Prefer composition over inheritance.
- Small classes (<200 lines, <10 methods, <10 properties).
- Use interfaces for contracts.

**Exceptions:**

- Use exceptions for unexpected errors only.
- Catch exceptions to fix known issues or add context.
- Otherwise rely on global handlers.

---

## 4. NestJS-Specific Guidelines

**Architecture:**

- Modular: One module per domain/route.
- One controller per main route; secondary routes as needed.
- `models` for DTOs (validated by `class-validator`), simple output types.
- Services handle business logic and persistence (MikroORM recommended).
- Core module for global filters, middlewares, guards, interceptors.
- Shared module for common utilities.

**Testing (NestJS):**

- Use Jest.
- Test each controller, service, and have e2e tests.
- Follow Arrange-Act-Assert, Given-When-Then.
- `admin/test` endpoint as a smoke test if suitable.

---

## 5. Next.js, React, Tailwind, Shadcn UI, Radix UI Guidelines

**Code Style & Structure:**

- Functional & declarative; avoid classes in React.
- Concise, readable TypeScript.
- Descriptive variable names.

**Naming Conventions:**

- lowercase-with-dashes for directories.
- Favor named exports for components.

**TypeScript (React):**

- Avoid enums; use maps.
- Functional components with interfaces for props.

**Syntax & Formatting:**

- Use `function` for pure functions.
- Concise conditionals.
- Declarative JSX.

**UI & Styling:**

- Shadcn UI, Radix UI, Tailwind CSS for styling.
- Responsive, mobile-first design.
- Implement light/dark mode.

**Performance Optimization (Frontend):**

- Minimize `use client`, `useEffect`, `setState`; prefer React Server Components.
- Wrap client components in `Suspense` with fallbacks.
- Dynamic imports for non-critical components.
- Optimize images with Next.js Image (WebP, lazy loading).

**Key Conventions:**

- Use `nuqs` for URL search parameters.
- Optimize Web Vitals (LCP, CLS, FID).
- Follow Next.js docs for data fetching, rendering, routing.
- Use SSR/SSG where appropriate.
- Consider LangChain for RAG use-cases.

**Error Handling & State Management:**

- Use React Context or state libraries for complexity.
- Implement error boundaries.
- Provide loading states, skeleton screens.

**Testing (React/Next.js):**

- Unit tests for components, integration tests for pages.
- Use Jest, React Testing Library.

---

## 6. Web3 & Solidity Guidelines

**Solidity Best Practices:**

- Explicit visibility, NatSpec for public/external functions.
- Checks-Effects-Interactions pattern.
- ReentrancyGuard, AccessControl, Pausable (OpenZeppelin) if needed.
- Simple, secure patterns.
- Gas optimization (packing, minimal storage writes).
- SafeERC20, handle errors gracefully, use custom errors.
- Upgradeable contracts only if necessary.
- Events for state changes.
- Use static analysis (Slither, Mythril).
- Thorough testing with Hardhat, property-based tests, coverage.

**Web3 Integration:**

- Use Hardhat for development and testing of Solidity contracts.
- Use ethers.js for blockchain interactions.
- Use Alchemy for node/provider services.
- Use AppKit as needed for advanced Web3 tooling.
- Implement proper randomness with Chainlink VRF if required.

---

## 7. Testing & QA Across All Stacks

- High test coverage (unit, integration, e2e).
- Automated testing in CI.
- Property-based testing for edge cases.
- Regular security audits (Solidity).
- Clear, consistent test variable naming and structuring.

---

## 8. Performance & Scalability

**Backend & Infrastructure:**

- Caching, pagination, indexing as needed.
- Optimize NestJS services and Next.js server components.
- Efficient data fetching, minimal round trips.

**Front-End:**

- Code splitting, lazy loading, SSR/SSG optimizations.
- React Suspense, concurrent features for smooth UX.

---

## 9. Documentation & CI/CD

**Continuous Integration:**

- Lint, test, and security checks on every commit.
- No merges if the pipeline fails.

**Documentation:**

- Comprehensive docs in `/docs`.
- Architectural diagrams, decision logs, updated API references.
- Clear instructions for setup, running, and testing.

---

## 10. RAG (Retrieval Augmented Generation) & LangChain

- Follow LangChain best practices.
- Ensure correct vector storage (consider suitable vector DB or Firebase-adjacent solutions).
- Validate prompt logic and retrieval steps.
- Maintain readability and correctness in chain logic.

---

## 11. Firebase Integration

- Use Google Firebase for data storage, authentication, and real-time database capabilities.
- Store environment variables securely; never commit secrets.
- Handle responses, errors, and retries correctly.
- Replace references to Supabase with Firebase-based solutions.

---

12. Project Research, R&D, and Technical Paper Authoring

Purpose:
Before coding, produce a comprehensive technical paper detailing the project’s concept, architecture, and execution steps. This document should enable anyone—human or AI—to fully understand, plan, and build the solution.

Guidelines:
• Concept & Approaches: Start by clarifying the problem, its value, and user personas. Compare multiple solution approaches, detailing pros/cons, complexity, and scalability. Include references to related works, official docs, and frameworks.
• Architecture & Design: Outline system architecture (front-end, back-end, contracts, data layers). Document chosen frameworks, libraries, and patterns (e.g., Next.js, NestJS, Hardhat, Tailwind, ethers, Firebase).
• Features & Functionality: List all features. For each, provide user stories, data models, flows, validation, error handling, security, and performance considerations. Include UI/UX sketches, styling approaches, and navigation structures.
• Tooling & Integration: Specify integrations (e.g., Alchemy, AppKit, Chainlink), environment variables, config patterns, and local-to-production workflows. Detail testing strategies (Jest, Hardhat tests), linting, CI/CD steps, and security audits.
• Examples & References: Provide code snippets, pseudo-code, or references for clarity. Link to external docs, GitHub repos, and relevant research.
• Team & Roadmap: Define team roles, communication channels, and review processes. Outline milestones, deliverables, and success criteria. Update this document as the project evolves.

Outcome:
A single, detailed, and evolving technical paper that any contributor or AI agent can read to understand the project’s purpose, how it will be built, and how to proceed step-by-step.

---

**Summary:**  
This `cursorrules` file combines general and project-specific guidelines, ensuring consistent code quality, security, documentation, and best practices across all layers—front-end, back-end, and smart contracts. Update the top Project-Specific Overview as goals and tasks evolve. Refer to these rules regularly to maintain high-quality, maintainable, and secure code.
eslint
express.js
firebase
golang
javascript
jest
langchain
less
+12 more
E-Labs-io/D-DCA_Contracts

Used in 1 repository

TypeScript
You are an expert full-stack developer proficient in TypeScript, React, Next.js, and modern UI/UX frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI). 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.

### Objective

- Create a Next.js solution that is not only functional but also adheres to the best practices in performance, security, and maintainability.
- Keep the folder structure like this:
  - All code should be inside `src/`
  - Shared components, lib, api, constants, etc. should be inside `src/shared/`
  - Widgets that use multiple shared components should be inside `src/widgets/`
  - Pages should be inside `src/app/`
  - DB related code should be inside `src/db/`
  - Entity related code should be inside `src/entities/`

### Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Structure files with exported components, subcomponents, helpers, static content, and types.
- Use lowercase with dashes for directory names (e.g., `shared/ui`).

### Optimization and Best Practices

- Minimize the use of `'use client'`, `useEffect`, and `setState`; favor React Server Components (RSC) and Next.js SSR features.
- Implement dynamic imports for code splitting and optimization.
- Use responsive design with a mobile-first approach.
- Optimize images: use WebP format, include size data, implement lazy loading.
- Use named exports for components, hooks, and functions instead of default exports.
- If using client code, use `'use client'` at the top of the file.

### Error Handling and Validation

- Prioritize error handling and edge cases:
- Use early returns for error conditions.
- Implement guard clauses to handle preconditions and invalid states early.
- Use custom error types for consistent error handling.

### UI and Styling

- Use modern UI frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI) for styling.
- Implement consistent design and responsive patterns across platforms.

### State Management and Data Fetching

- Implement validation using Zod for schema validation.
- Use Next.js server actions for data fetching and modern state management solutions (e.g., Zustand) to handle global state.

### Security and Performance

- Implement proper error handling, user input validation, and secure coding practices.
- Follow performance optimization techniques, such as reducing load times and improving rendering efficiency.

### Testing and Documentation

- Write unit tests for components using Jest and React Testing Library.
- Provide clear and concise comments for complex logic.
- Use JSDoc comments for functions and components to improve IDE intellisense.

### Methodology

1. **System 2 Thinking**: Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation.
2. **Tree of Thoughts**: Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one.
3. **Iterative Refinement**: Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

**Process**:

1. **Deep Dive Analysis**: Begin by conducting a thorough analysis of the task at hand, considering the technical requirements and constraints.
2. **Planning**: Develop a clear plan that outlines the architectural structure and flow of the solution, using <PLANNING> tags if necessary.
3. **Implementation**: Implement the solution step-by-step, ensuring that each part adheres to the specified best practices.
4. **Review and Optimize**: Perform a review of the code, looking for areas of potential optimization and improvement.
5. **Finalization**: Finalize the code by ensuring it meets all requirements, is secure, and is performant.
css
golang
javascript
jest
next.js
radix-ui
react
shadcn/ui
+3 more

First seen in:

V-Mokhun/Workout-Tracker

Used in 1 repository

TypeScript
### Project Standards
- Follow requirements precisely and completely
- Use TypeScript for type safety
- Implement proper error handling
- Write unit tests for critical functionality
- Follow accessibility (a11y) best practices
- Use proper Git commit conventions

### Development Process
- Plan implementation with detailed pseudocode first
- Review security implications
- Ensure code is production-ready
- No TODOs or incomplete implementations
- Include necessary type definitions
- Document complex logic with comments

### Tech Stack Guidelines
- Next.js 15+ with App Router
- React 19+ with hooks
- TypeScript for type safety
- TailwindCSS for styling
- Radix UI for accessible components
- Zustand for state management
- TanStack Query for data fetching
- Wagmi for Web3 integration

### Code Style Rules
- Use early returns for cleaner logic flow
- Prefer Tailwind over custom CSS
- Implement proper accessibility attributes
- Use semantic HTML elements
- Follow React Server Components best practices
- Utilize proper error boundaries
- Implement proper loading states

### Naming Conventions
- Event handlers prefix: 'handle' (e.g., handleClick)
- Components: PascalCase
- Functions/Variables: camelCase
- Constants: UPPER_SNAKE_CASE
- Types/Interfaces: PascalCase with 'T' prefix for types
- Files: kebab-case for pages, PascalCase for components

### Component Structure
- Implement proper prop types
- Use composition over inheritance
- Keep components focused and single-responsibility
- Implement proper loading and error states
- Use proper React hooks
- Implement proper memoization where needed
css
javascript
next.js
radix-ui
react
tailwindcss
typescript
zustand

First seen in:

NextChainSignal/frontend

Used in 1 repository

Python
# Django/Python Rules

- Use Django's class-based views for complex logic, function-based views for simple operations
- Follow MVT (Model-View-Template) pattern strictly
- Keep business logic in models/forms; views should focus on request handling
- Use Django's built-in features (auth, forms, validation) over custom solutions
- Implement proper error handling with try-except blocks
- Follow PEP 8 compliance for Python code style
- Use descriptive names with underscores for Python functions/variables
- Optimize queries using select_related and prefetch_related
- Utilize Django's caching framework with Redis/Memcached
- Implement database indexing for performance
- Use Django signals for decoupled error handling
- Leverage Django middleware for cross-cutting concerns

# React/Frontend Rules

- Write functional components instead of class components
- Use TypeScript for all new code; avoid 'any' and 'unknown' types
- Prefer interfaces over types in TypeScript
- Use early returns for better code readability
- Name event handlers with 'handle' prefix (handleClick, handleSubmit)
- Use named exports for components
- Keep JSX minimal and readable
- Implement proper accessibility features (aria-labels, roles)
- Use constants instead of functions where appropriate
- Follow mobile-first approach in design

# Tailwind CSS Rules

- Use Tailwind classes for styling; avoid custom CSS
- Use class: syntax instead of ternary operators for conditional styling
- Follow responsive design patterns
- Maintain consistent spacing and sizing using Tailwind's scale
- Use Tailwind's color palette for consistency
- Leverage Tailwind's built-in dark mode support

# General Best Practices

- Follow DRY (Don't Repeat Yourself) principle
- Write self-documenting code with clear variable names
- Implement proper error boundaries and fallbacks
- Use environment variables for configuration
- Write unit tests for critical functionality
- Optimize for performance and accessibility
- Use proper Git commit messages and branching
- Document complex logic and important decisions
- Maintain consistent code formatting
- Use semantic versioning for releases
- Implement proper logging and monitoring
- Use async/await over promise chains

# Security Guidelines

- Implement CSRF protection
- Prevent SQL injection
- Guard against XSS attacks
- Use proper authentication and authorization
- Sanitize user inputs
- Secure API endpoints
- Follow security best practices for file uploads
- Implement rate limiting where necessary
css
django
golang
html
javascript
python
react
redis
+2 more
VersionLens/pp-demo-backlog-buddy

Used in 1 repository