Awesome Cursor Rules Collection

Showing 877-888 of 1033 matches

TypeScript
# Expert Full-Stack Web Developer Guide for Next.js 14

You are an expert full-stack web developer focused on producing clear, readable Next.js code. This guide outlines the latest best practices, conventions, and preferences for development using Next.js 14, Supabase, TailwindCSS, and TypeScript.

## Core Technologies and Versions

- Next.js 14 (latest stable version)
- Supabase (latest stable version)
- TailwindCSS (latest stable version)
- TypeScript (latest stable version)

## General Principles

- Follow user requirements carefully
- Provide accurate, factual, and thoughtful answers
- Implement error handling and logging
- Always add loading and error states to data fetching components
- Use semantic HTML elements where possible
- Optimize for Web Vitals (LCP, CLS, FID)

## Next.js Best Practices

- Favor React Server Components and Next.js SSR features
- Minimize usage of client components ('use client')
- Implement route-based code splitting
- Follow Next.js documentation for Data Fetching, Rendering, and Routing

## Code Style and Structure

### Naming Conventions

- Use kebab-case for component names (e.g., my-component.tsx)
- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Use camelCase for variables and functions
- Use PascalCase for React components

### File Structure

```
components/
  Button/
    button.tsx
    button.module.styl
  Card/
    card.tsx
    card.module.styl
```

### Coding Standards (based on Standard.js)

- Use 2 space indentation
- Use single quotes for strings (except to avoid escaping)
- No semicolons (unless required to disambiguate statements)
- No unused variables
- Add a space after keywords and before function parentheses
- Always use === instead of ==
- Space infix operators and after commas
- Keep else statements on the same line as their curly braces
- Use curly braces for multi-line if statements
- Always handle the err function parameter

### Best Practices

- Write concise, technical JavaScript code
- 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
- Favor named exports for components

## React and Hooks

- Use functional components with prop-types for type checking
- Implement hooks correctly (useState, useEffect, useContext, useReducer, useMemo, useCallback)
- Follow the Rules of Hooks
- Create custom hooks for reusable component logic
- Use React.memo() for component memoization when appropriate
- Implement useCallback for memoizing functions passed as props
- Use useMemo for expensive computations
- Avoid inline function definitions in render
- Prefer composition over inheritance
- Use children prop and render props pattern for flexible components
- Implement React.lazy() and Suspense for code splitting
- Use refs sparingly and mainly for DOM access
- Prefer controlled components over uncontrolled components
- Implement error boundaries
- Use cleanup functions in useEffect to prevent memory leaks
- Use short-circuit evaluation and ternary operators for conditional rendering

## State Management

- Use Zustand for global state management
- Lift state up when needed to share state between components
- Use context for intermediate state sharing
- Use 'nuqs' for URL search parameter state management

## UI and Styling

- Use Shadcn UI and Radix UI for component foundations
- Implement responsive design with Tailwind CSS (mobile-first approach)
- Use Stylus as CSS Modules for component-specific styles
- Combine Tailwind utility classes with Stylus modules:
  - Use Tailwind for common utilities and layout
  - Use Stylus modules for complex, component-specific styles
  - Never use the @apply directive
- Implement a consistent naming convention for CSS classes (e.g., BEM) within Stylus modules

### Stylus Best Practices

- Use variables for colors, fonts, and other repeated values
- Create mixins for commonly used style patterns
- Utilize Stylus' parent selector (&) for nesting and pseudo-classes
- Keep specificity low by avoiding deep nesting

## Performance Optimization

- Minimize 'use client', 'useEffect', and 'useState'
- Wrap client components in Suspense with fallback
- Use dynamic loading for non-critical components
- Optimize images: use WebP format, include size data, implement lazy loading
- Minimize global styles; prefer modular, scoped styles
- Use PurgeCSS with Tailwind to remove unused styles in production

## Forms and Validation

- Use controlled components for form inputs
- Implement form validation (client-side and server-side)
- Consider using react-hook-form for complex forms
- Use Zod or Joi for schema validation

## Error Handling and Validation

- Prioritize error handling and edge cases
- Handle errors at the beginning of functions
- Use early returns for error conditions
- Place the happy path last in the function
- Avoid unnecessary else statements; use if-return pattern
- Use guard clauses to handle preconditions and invalid states early
- Implement proper error logging and user-friendly error messages
- Model expected errors as return values in Server Actions

## Accessibility (a11y)

- Use semantic HTML elements
- Implement proper ARIA attributes
- Ensure keyboard navigation support

## Testing

- Write unit tests for components using Jest and React Testing Library
- Implement integration tests for critical user flows
- Use snapshot testing judiciously

## Security

- Sanitize user inputs to prevent XSS attacks
- Use dangerouslySetInnerHTML sparingly and only with sanitized content

## Internationalization (i18n)

- Use libraries like react-intl or next-i18next for internationalization
css
dockerfile
java
javascript
jest
less
mermaid
nestjs
+9 more
m0r6aN/Agents_as_a_Service

Used in 1 repository

TypeScript
// React Native Expo .cursorrules

// React Native Expo Best Practices
const reactNativeExpoBestPractices = [
  "Use functional components with hooks.",
  "Leverage Expo SDK features and APIs.",
  "Implement navigation using Expo Router.",
  "Manage assets with Expo's asset system for images and fonts.",
  "Ensure robust error handling and crash reporting.",
  "Utilize Expo's push notification system.",
  "Adopt TypeScript for type safety.",
  "Apply consistent styling using StyleSheet.",
  "Incorporate Expo's vector icons.",
  "Secure sensitive data with Expo's SecureStore.",
  "Implement proper offline support.",
  "Optimize performance following React Native best practices.",
  "Deploy updates using Expo's OTA mechanism.",
  "Style components using NativeWind.",
];

// Folder Structure
const folderStructure = `
assets/
src/
  components/
  screens/
  navigation/
  hooks/
  utils/
app/
  _layout.tsx
  index.tsx
App.js
app.json
`;

// Package Version Compatibility Notes
const packageCompatibilityNotes = [
  "NativeWind and Tailwind CSS compatibility:",
  "- Use nativewind@2.0.11 with tailwindcss@3.3.2.",
  "- Higher versions may cause 'process(css).then(cb)' errors.",
  "- If errors occur, remove both packages and reinstall specific versions:",
  "  npm remove nativewind tailwindcss",
  "  npm install nativewind@2.0.11 tailwindcss@3.3.2",

  "Babel configuration for NativeWind:",
  "- Include 'nativewind/babel' in the plugins array.",
  "- Avoid using jsxImportSource in presets.",
  "- Ensure 'react-native-reanimated/plugin' follows 'nativewind/babel'.",
];

// Additional Instructions
const additionalInstructions = [
  "Use PowerShell for terminal commands.",
  "Before installing a new package, check if it's already installed:",
  "  Get-ChildItem -Recurse -Filter package-name",
  "If installed, upgrade using:",
  "  expo upgrade <package-name>",
  "or",
  "  npm install <package-name>",
  "if not supported by Expo.",
  "Use PowerShell commands to manage the project, e.g., moving and renaming files:",
  "  Move-Item -Path .\\old\\path\\file.txt -Destination .\\new\\path\\newname.txt",
  "If unsure about the current structure or details, use PowerShell to list out necessary information:",
  "  Get-ChildItem -Recurse",
  "Utilize official Expo libraries and upgrade them using Expo's commands.",
  "Avoid deleting existing functionality or files without a valid reason.",
  "Follow the recommended folder structure and maintain organized code for scalability and readability.",
  "Implement navigation using Expo Router for clean and declarative routing.",
  " Use stale-while-revalidate strategy for data freshness",
  " Implement optimistic updates for mutations",
  " Use query invalidation for data refetching",
  " Follow React Query naming conventions for consistency",
];

// Prefer functional components with hooks
const preferFunctionalComponents = true;

// React Query best practices
const reactQueryBestPractices = [
  "Use QueryClient and QueryClientProvider at the root of your app",
  "Implement custom hooks for queries and mutations",
  "Utilize query keys for effective caching",
  "Use prefetching for improved performance",
  "Implement proper error and loading states",
];
c
css
dockerfile
html
javascript
kotlin
makefile
npm
+8 more

First seen in:

ebettenga/crossed-js

Used in 1 repository

TypeScript

You are an expert in TypeScript, React, React-Native, Mobile Development for Android & iOS, Supabase, React Native Elements, GoLang, Node.js, Expo.

**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 and prefer state machines when possible.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.

**Naming Conventions**
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

**TypeScript Usage**
- Use TypeScript for all code; prefer 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 React Native Elements for components and styling.

**Performance Optimization**
- Minimize 'useEffect', and 'useState'; favor TanStack/React-Store and TanStack/React-Query.
- Wrap components in Suspense with fallback where necessary.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

**Database Querying & Data Model Creation**
- Use Supabase SDK for data fetching and querying.
- For data model creation, use Supabase's schema builder.

**Key Conventions**
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'useEffect':
- Use only for Web API access in small components.
- Avoid for data fetching or state management.

**Follow React Native Expo docs for Data Fetching, Rendering, and Routing.**
golang
javascript
react
supabase
typescript

First seen in:

drod21/DishDuelFe

Used in 1 repository

TypeScript
# Project-Specific Cursor Rules for AI

You are an expert in TypeScript, Next.js 14 (with App Router), Shadcn UI, Tailwind CSS, Magic UI, tRPC, Supabase, and Vercel.

## General Code Structure:
- Always use **kebab-case** for file and folder names (e.g., `api-routes`, `user-profile.tsx`).
- Use **TypeScript** for all files. Ensure full type safety with strict TypeScript rules (e.g., `strictNullChecks`, `noImplicitAny`).
- Leverage **ESLint** with Airbnb or a similar configuration for code quality checks.
- Apply **Prettier** for consistent formatting, ensuring readability and clean code.

## Next.js 14 with App Router:
- **Server Actions**: Use **Server Actions** whenever possible for server-side logic like form submissions and data handling. This will reduce client-side code and improve performance.
  - Example: For form submissions, write `POST` logic in a server action to avoid excessive client-side API calls.
- **File Structure**: Organize components within the `app` directory, following **kebab-case** conventions.
  - Group related components and pages into nested folders under the `app` directory (e.g., `/app/user-profile/page.tsx`).
- Use **dynamic routing** when handling multiple resources with a common structure (e.g., `/app/products/[productId]/page.tsx`).

## tRPC and API Routes:
- Use **tRPC** to handle all API logic via `api-routes`. Prefer **React Query** on the client side for data fetching and caching.
- **Validation**: Apply **Zod** schema validation to all tRPC endpoints for type-safe input validation.
  - Example: In `/app/api/trpc/[trpc]/route.ts`, ensure `Zod` schemas are applied for request validation.
- **Server-Side Caching**: Use **React Query**’s `stale-while-revalidate` for client-side caching and performance optimization when making API requests via tRPC.

## UI and Styling with Shadcn UI, Magic UI, and Tailwind CSS:
- **Shadcn UI**: Use pre-built **Shadcn components** for UI consistency and modularity. Prioritize customizability to fit the branding and design needs of the project.
- **Tailwind CSS**: For layout and styling, use Tailwind CSS. Stick to the utility-first classes.
  - Tailwind Config: Ensure the config includes custom colors and themes that fit the project’s style.
  - Example: Use Tailwind for responsive designs and apply `@media` queries when needed.
- **Magic UI**: For micro-animations and interactive elements, apply **Magic UI** to enhance user experience, but use it sparingly to maintain performance.
  - Example: Add subtle animations on button hover or form submissions using Magic UI components.

## Database and Backend with Supabase:
- Use **Supabase** as the primary database (PostgreSQL). All database queries and logic should be handled in **server actions** or through tRPC API routes.
- Prefer **Supabase Auth** for authentication and role-based access control (RBAC).
- For database interaction, use **Supabase client libraries** with full TypeScript support.
  - Example: When fetching data, prefer the `supabase.from('table')` syntax, ensuring all queries are optimized for performance.

## Vercel Hosting and Deployment:
- All deployments will be handled through **Vercel**.
  - Ensure the project is optimized for **Edge Functions** (serverless).
  - Use **Vercel Analytics** for monitoring performance and user interactions.

## State Management with React Query:
- For global state, prefer **React Query** over Redux or Context API.
- Apply React Query’s `invalidateQueries` pattern after any data mutation (e.g., updates, deletes) to keep client data fresh.

## Performance Optimization:
- **Lazy Loading**: Lazy load non-essential components like modals or third-party widgets using `React.lazy` and **Next.js dynamic imports**.
- **Code Splitting**: Use **Next.js 14’s App Router** to enable automatic code splitting. Break up larger components into smaller, reusable parts to optimize load times.
- Minimize the use of `use client`. Prefer **Server Components** for rendering UI whenever possible for performance.

## Error Handling:
- Use **Error Boundaries** to catch client-side errors gracefully.
- Leverage **tRPC error handling** to provide meaningful error messages for both the client and server. Validate errors using **Zod** schemas, and return type-safe error responses.

## Security:
- Ensure all **Supabase API keys** are stored in environment variables and never hardcoded into the project.
- Use **HTTPS** and enforce **secure headers** for all API requests (via tRPC or server actions).
- Implement **role-based access control (RBAC)** with Supabase for sensitive data.

## Tests:
- Apply **unit tests** for all business logic and **integration tests** for key components.
  - Use **Jest** or **Vitest** for unit testing components and logic.
  - For integration testing with tRPC, ensure you cover API routes and database interactions.

## Logging and Monitoring:
- Use **Vercel Logs** and **Supabase logs** for monitoring server-side operations.
- Implement structured logging using libraries like **Winston** or **Pino** for both server and client-side logs.
analytics
css
eslint
html
javascript
jest
less
mdx
+14 more
thorski1/raleigh-ai-solutions

Used in 1 repository

TypeScript
# MovieLandia24

## Project Context

MovieLandia24 is a Next.js/React application for discovering movies, TV series, actors, and crew, with user accounts, browsing, reviews, social features following, messaging, notifications system, and admin dashboard.

### Architecture

1. **Presentation:** React components (`src/components`), and App Router (`src/app`).
2. **Business Logic:** Data handling (`src/actions`, `src/hooks`, `src/utils`).
3. **Data Access:** Prisma, Zod (`prisma/schema`, `prisma/schemas`).
4. **API:** Serverless functions, API Routes Handlers (`src/app/api`).
5. **External Services:** Resend (`emails`).

### Features

- User Management (Registration, Login, Password Reset, Google OAuth, Profile).
- Content (Browsing, Search, Details, Reviews/Ratings, Bookmarking).
- Social (Following/Unfollowing, Messaging).
- Admin (Panel, CRUD, Data Export).

### Technologies

- Next.js, React, Material UI, Prisma, Zod, NextAuth.js, Resend, React Hook Form, React Toastify, Framer Motion, Zustand, `nuqs`.

## Project Structure

```

movielandia/
├── src/
│ ├── actions/
│ ├── app/
│ │ ├── (admin)/
│ │ └── (root)/
│ ├── components/
│ ├── constants/
│ ├── hooks/
│ ├── layouts/
│ ├── middleware.ts
│ ├── providers/
│ ├── store/
│ ├── types/
│ └── utils/
├── prisma/
│ ├── migrations/
│ ├── schema/
│ |── seed/
| |── config/
└── emails/

```

## General Behaviour Instructions Guidelines

- Follow requirements
- Reduce complexity
- Write full code
- Think step-by-step
- Prefer iteration
- Focus on readable code
- Implement fully
- Avoid implementing nonsensical stuff
- Remove TODOs or random comments implement all the code needed
- Ensure completeness
- Include imports
- Be concise
- Return complete solutions
- Prioritize modularity
- If you are uncertain about any aspect of the request or the correct implementation, explicitly state your uncertainty rather than making assumptions.

## Coding Implementation Instructions Guidelines

- Write correct, DRY, functional code.
- Use descriptive names, concise syntax, declarative JSX, avoid classes, use auxiliary verbs.
- Implement accessibility, ensure error handling. Use const, arrow functions.
- Use early returns. Design for reusability. Avoid hardcoding.
- Use `nuqs` for URL state.

### Framework Practices

- For optimal Next.js data flow
- Minimize 'use client'
- Maintain organized files
- Always use Server Actions for data mutation
- Leverage Route Handlers for data fetching in Client Components
- And utilize Server Actions for data fetching within Server Components.

### UI Styling Practices

- Material UI with Emotion & sx props
- Avoid styled-components
- Theme customization
- Responsive design
- Consistent spacing.

### Performance Optimization

- Optimize Web Vitals
- Image optimization
- Code splitting
- Caching
- Minimize bundle size.

### Database Practices

- Prisma for modeling
- validate before CRUD
- Use indexing
- Optimize queries
- Handle errors
- Ensure data integrity.

### Git Usage

#### Commit Message Prefixes:

- **fix:** Bug fix. _Example:_ `fix: user login`
- **feat:** New feature. _Example:_ `feat: user profile update`
- **perf:** Performance improvement.

#### Rules for Git Usage:

- Use lowercase messages. _Example:_ `fix: login issue`
- Keep summary concise (under 50 chars). _Example:_ `feat: update profile`
auth.js
bun
css
emotion
golang
less
next.js
nextauth
+6 more
JurgenHasmeta22/movielandia

Used in 1 repository

TypeScript
You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). 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:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS

### 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.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- 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.

### Next.js 15.x Best Practices
Follow these guidelines for Next.js development:

#### Routing & Navigation
- Use the App Router (`app/` directory) for new projects
- Implement layouts for shared UI across routes
- Use Server Components by default, Client Components when needed
- Follow the file-system based routing conventions:
  - `page.tsx` for routes
  - `layout.tsx` for layouts
  - `loading.tsx` for loading states
  - `error.tsx` for error handling
  - `not-found.tsx` for 404 pages

#### Data Fetching
- Use Server Components for data fetching when possible
- Implement proper caching strategies using fetch options
- Use React Server Actions for mutations
- Utilize route handlers for API endpoints
- Implement proper error handling and loading states

#### Rendering & Performance
- Use Streaming and Suspense for progressive loading
- Implement proper component-level caching
- Use Partial Prerendering (PPR) for optimal performance
- Implement proper lazy loading strategies
- Use Image and Font optimization components

#### State Management & Components
- Use Server Components for static content
- Implement Client Components only when needed for interactivity
- Follow proper component composition patterns
- Use proper data fetching patterns in Server Components
- Implement proper error boundaries

#### Optimization
- Use built-in Image component for image optimization
- Implement proper font optimization with next/font
- Use route handlers for API endpoints
- Implement proper metadata for SEO
- Use proper static asset handling

#### Development Workflow
- Use the new app directory structure
- Implement proper TypeScript configuration
- Use proper environment variables
- Follow proper deployment practices
- Implement proper testing strategies

#### Security
- Implement proper authentication strategies
- Use proper CORS policies
- Implement proper API route protection
- Use proper environment variable handling
- Implement proper CSP headers

### ECMAScript 2020 Best Practices
Follow these guidelines for modern JavaScript development:

#### Core Features
- Use optional chaining (?.) for safe property access:
  ```javascript
  const value = obj?.prop?.nestedProp
  ```

- Implement nullish coalescing (??) for default values:
  ```javascript
  const value = someValue ?? defaultValue
  ```

- Use BigInt for large numbers:
  ```javascript
  const largeNumber = 9007199254740991n
  ```

#### Promise Handling
- Use Promise.allSettled() for handling multiple promises:
  ```javascript
  const results = await Promise.allSettled([promise1, promise2])
  ```

- Implement dynamic imports for code splitting:
  ```javascript
  const module = await import('./module.js')
  ```

#### String Manipulation
- Use String.prototype.matchAll() for global regex matches:
  ```javascript
  const matches = [...string.matchAll(regex)]
  ```

#### Module Features
- Use import.meta for module metadata:
  ```javascript
  console.log(import.meta.url)
  ```

#### Global Properties
- Use globalThis for consistent global scope access:
  ```javascript
  const global = globalThis
  ```

#### Best Practices
- Prefer optional chaining over && chaining
- Use nullish coalescing (??) instead of || when zero/empty string are valid values
- Implement proper error handling with Promise.allSettled()
- Use BigInt for numbers larger than Number.MAX_SAFE_INTEGER
- Implement dynamic imports for better code splitting
- Use proper module organization with import/export
- Implement proper error boundaries with try/catch
- Use proper async/await patterns
- Implement proper type checking

#### Performance Considerations
- Use proper code splitting with dynamic imports
- Implement proper memory management with WeakRef and FinalizationRegistry
- Use proper async patterns for better performance
- Implement proper error handling strategies
- Use proper caching strategies

### Directory Aliases & Import Standards
Follow these guidelines for import paths and directory structure:

#### Path Aliases
- Use `@/*` alias for imports from the root directory:
  ```typescript
  // Instead of relative paths like:
  import { Button } from '../../../components/ui/Button'
  
  // Use aliases:
  import { Button } from '@/components/ui/Button'
  ```

#### Common Aliases
- `@/components/*` - For React components
- `@/lib/*` - For utility functions and shared logic
- `@/hooks/*` - For custom React hooks
- `@/styles/*` - For styling related files
- `@/types/*` - For TypeScript type definitions
- `@/api/*` - For API related functions
- `@/constants/*` - For constant values and configurations
- `@/store/*` - For state management
- `@/utils/*` - For utility functions
- `@/context/*` - For React context providers

#### Configuration
- Configure aliases in `tsconfig.json`:
  ```json
  {
    "compilerOptions": {
      "baseUrl": ".",
      "paths": {
        "@/*": ["./*"]
      }
    }
  }
  ```

#### Best Practices
- Always use absolute imports with aliases over relative paths
- Keep import statements organized and grouped:
  1. External packages
  2. Aliased imports
  3. Relative imports
- Use barrel exports (index.ts) for cleaner imports
- Maintain consistent naming conventions across imports
- Use proper import sorting with ESLint/Prettier

### Component Composition & Reusability
Follow these guidelines for breaking down components:

#### Component Structure
- Break down complex UI into smaller, reusable components
- Follow the Single Responsibility Principle (SRP)
- Implement atomic design principles:
  ```typescript
  // Atoms (basic building blocks)
  - Button
  - Input
  - Label
  
  // Molecules (simple combinations)
  - FormField (Label + Input)
  - SearchBar (Input + Button)
  
  // Organisms (complex combinations)
  - NavigationMenu
  - UserProfileCard
  
  // Templates (page layouts)
  - DashboardLayout
  - AuthLayout
  ```

#### Composition Guidelines
- Create components that do one thing well
- Keep components under 100 lines of code when possible
- Extract repeated patterns into shared components
- Use composition over inheritance
- Implement proper prop drilling prevention:
  ```typescript
  // Instead of:
  <GrandParent>
    <Parent>
      <Child data={someData} />
    </Parent>
  </GrandParent>

  // Use context or composition:
  <DataProvider data={someData}>
    <GrandParent>
      <Parent>
        <Child />
      </Parent>
    </GrandParent>
  </DataProvider>
  ```

#### Reusability Best Practices
- Make components configurable through props
- Use TypeScript interfaces for prop definitions
- Implement proper default props
- Create flexible components that adapt to different contexts
- Use composition patterns for component variations:
  ```typescript
  // Base component
  const Button = ({ variant, children, ...props }) => {
    return <button className={variants[variant]} {...props}>{children}</button>
  }

  // Specialized components
  const PrimaryButton = (props) => <Button variant="primary" {...props} />
  const SecondaryButton = (props) => <Button variant="secondary" {...props} />
  ```

#### Component Organization
- Group related components together
- Use index files for clean exports
- Implement proper component documentation
- Create component stories for testing and documentation
- Use proper naming conventions:
  ```
  components/
  ├── Button/
  │   ├── Button.tsx
  │   ├── Button.test.tsx
  │   ├── Button.stories.tsx
  │   └── index.ts
  ├── Form/
  │   ├── Input/
  │   ├── Select/
  │   └── Checkbox/
  └── Layout/
      ├── Header/
      └── Footer/
  ```

#### Testing Considerations
- Write tests for reusable components
- Test different component states and variations
- Implement proper accessibility testing
- Use component testing best practices
- Create proper documentation and examples

### Responsive Design with Tailwind CSS
Follow these guidelines for creating responsive layouts:

#### Breakpoint Usage
- Use Tailwind's responsive prefixes consistently:
  ```typescript
  // Default breakpoints:
  - sm: 640px and up
  - md: 768px and up
  - lg: 1024px and up
  - xl: 1280px and up
  - 2xl: 1536px and up

  // Example usage:
  <div className="
    grid
    grid-cols-1 
    sm:grid-cols-2 
    md:grid-cols-3 
    lg:grid-cols-4
    gap-4
  ">
  ```

#### Mobile-First Approach
- Always design for mobile first, then scale up
- Use unprefixed utilities for mobile, then add responsive variants:
  ```typescript
  // Good - Mobile first
  <div className="
    text-sm 
    md:text-base 
    lg:text-lg
  ">

  // Avoid - Desktop first
  <div className="
    text-lg 
    md:text-base 
    sm:text-sm
  ">
  ```

#### Layout Patterns
- Use flexible grid systems:
  ```typescript
  // Responsive grid with auto-fit
  <div className="
    grid 
    grid-cols-1 
    md:grid-cols-[repeat(auto-fit,minmax(250px,1fr))]
    gap-4
  ">
  ```

- Implement responsive padding and margins:
  ```typescript
  <div className="
    p-4
    sm:p-6
    md:p-8
    lg:p-12
  ">
  ```

#### Responsive Typography
- Scale text sizes appropriately:
  ```typescript
  <h1 className="
    text-2xl
    sm:text-3xl
    md:text-4xl
    lg:text-5xl
    font-bold
  ">
  ```

#### Navigation Patterns
- Use responsive navigation patterns:
  ```typescript
  // Mobile menu vs desktop menu
  <nav className="
    hidden 
    md:flex
  ">
    {/* Desktop Navigation */}
  </nav>
  <nav className="
    flex 
    md:hidden
  ">
    {/* Mobile Navigation */}
  </nav>
  ```

#### Best Practices
- Use container queries when component-level responsiveness is needed:
  ```typescript
  <div className="@container">
    <div className="
      @md:grid-cols-2
      @lg:grid-cols-3
    ">
  ```

- Implement proper spacing scales:
  ```typescript
  <div className="
    space-y-4
    md:space-y-6
    lg:space-y-8
  ">
  ```

- Use responsive images:
  ```typescript
  <img 
    className="
      w-full
      h-48
      md:h-64
      lg:h-96
      object-cover
    "
  />
  ```

#### Common Patterns
- Hide/Show elements responsively:
  ```typescript
  <div className="hidden md:block">Desktop Only</div>
  <div className="md:hidden">Mobile Only</div>
  ```

- Responsive padding for containers:
  ```typescript
  <div className="
    container
    mx-auto
    px-4
    sm:px-6
    lg:px-8
  ">
  ```

- Flex direction changes:
  ```typescript
  <div className="
    flex
    flex-col
    md:flex-row
    items-center
    gap-4
  ">
  ```

#### Testing Considerations
- Test layouts at all breakpoints
- Verify content readability across devices
- Check for layout shifts during resizing
- Test touch interactions on mobile devices
- Verify proper spacing across breakpoints

### Next.js Data Access Patterns
Follow these guidelines for accessing cookies and dynamic route parameters:

#### Cookie Handling
- Always await cookies() when accessing cookie data:
  ```typescript
  // Correct
  const cookieStore = await cookies()
  const value = cookieStore.get('key')

  // Incorrect - will cause runtime errors
  const cookieStore = cookies()
  const value = cookieStore.get('key')
  ```

#### Dynamic Route Parameters
- Always await params when using dynamic route segments:
  ```typescript
  // Correct
  export default async function Page({
    params,
  }: {
    params: Promise<{ slug: string }>
  }) {
    const slug = await params.slug
    return <h1>{slug}</h1>
  }

  // Incorrect - will cause type errors and runtime issues
  export default function Page({
    params,
  }: {
    params: { slug: string }
  }) {
    return <h1>{params.slug}</h1>
  }
  ```

#### Headers and Metadata
- Always await headers() when accessing request headers:
  ```typescript
  // Correct
  import { headers } from 'next/headers'
  
  export default async function Page() {
    const headersList = await headers()
    const referer = headersList.get('referer')
    return <div>{referer}</div>
  }

  // Incorrect
  const headersList = headers()
  const referer = headersList.get('referer')
  ```

#### Best Practices
- Use try/catch blocks when accessing cookies or headers
- Implement proper type checking for params
- Handle cases where cookies or headers might not exist
- Use proper error boundaries for error handling
- Implement proper loading states while awaiting data

### Component File Structure & Import Standards
Follow these guidelines for organizing and importing components:

#### Component File Structure
- Place components in the `app/components` directory
- Use PascalCase for component file names
- Component files should match their component name:
  ```
  app/components/
  ├── Header.tsx         # Single component file
  ├── Header/           # Complex component with multiple files
  │   ├── index.ts
  │   ├── Header.tsx
  │   └── HeaderNav.tsx
  ```

#### Import Patterns
- Use absolute imports with the `@` alias:
  ```typescript
  // Correct
  import Header from "@/components/Header"
  
  // Avoid relative imports
  import Header from "../components/Header"
  ```

#### Component Organization
- For simple components, use direct file:
  ```typescript
  // app/components/Header.tsx
  const Header = () => {
    return <header>...</header>
  }
  export default Header
  ```

- For complex components, use directory structure:
  ```typescript
  // app/components/Header/Header.tsx
  const Header = () => {
    return <header>...</header>
  }
  export default Header

  // app/components/Header/index.ts
  export { default } from './Header'
  ```

#### Best Practices
- Keep component files focused and single-responsibility
- Use index files for cleaner exports
- Maintain consistent naming between files and components
- Group related component files in directories
- Use proper TypeScript types and interfaces

### Data Fetching & Service Organization
Follow these guidelines for organizing API and data fetching logic:

#### Service Structure
- Place all API services in `app/lib/services` directory
- Use TypeScript interfaces for all API types
- Follow naming convention: `*.service.ts` for service files
- Implement proper error handling with custom error classes
- Use centralized configuration for API endpoints:
  ```typescript
  // app/lib/services/base.service.ts
  const BASE_URL = process.env.API_URL || 'https://api.example.com'
  ```

#### Service Implementation
- Separate concerns: Keep data fetching logic away from UI components
- Create reusable service functions:
  ```typescript
  // Good - Reusable service
  export const getUser = async (id: string): Promise<User> => {
    const response = await fetch(`${BASE_URL}/users/${id}`)
    return handleResponse<User>(response)
  }

  // Avoid - Logic in component
  const Component = async () => {
    const response = await fetch('/api/users/1')
    const user = await response.json()
  }
  ```

#### Error Handling
- Implement custom error classes for API errors:
  ```typescript
  export class ApiError extends Error {
    constructor(
      message: string,
      public status: number,
      public statusText: string
    ) {
      super(message)
      this.name = 'ApiError'
    }
  }
  ```

#### Caching Strategy
- Use centralized cache configuration:
  ```typescript
  const fetchOptions = {
    next: {
      revalidate: 60, // Cache time in minute
      tags: ['cache-tag'], // For cache invalidation
    }
  }
  ```

#### Type Safety
- Define proper interfaces for all API responses:
  ```typescript
  interface ApiResponse<T> {
    data: T
    meta?: {
      total: number
      page: number
    }
  }

  interface User {
    id: string
    name: string
  }
  ```

#### Service Organization
```
app/
├── lib/
│   ├── services/
│   │   ├── base.service.ts    # Base configuration
│   │   ├── user.service.ts    # User-related API calls
│   │   ├── product.service.ts # Product-related API calls
│   │   └── types.ts          # Shared types
│   └── utils/
│       └── api.utils.ts      # API utilities
```

#### Best Practices
- Keep service functions small and focused
- Use proper TypeScript types for all parameters and returns
- Implement proper error boundaries and error handling
- Use consistent naming conventions across services
- Document service functions with JSDoc comments
- Implement proper testing strategies for services

#### Testing Considerations
- Create separate test files for services
- Mock API responses in tests
- Test error handling scenarios
- Implement proper integration tests
- Use proper testing utilities:
  ```typescript
  // __tests__/services/user.service.test.ts
  describe('UserService', () => {
    it('should fetch user successfully', async () => {
      const user = await getUser('1')
      expect(user).toBeDefined()
    })
  })
  ```

#### Documentation
- Use JSDoc comments for service functions:
  ```typescript
  /**
   * Fetches a user by ID
   * @param {string} id - The user ID
   * @returns {Promise<User>} The user object
   * @throws {ApiError} When the API request fails
   */
  export const getUser = async (id: string): Promise<User> => {
    // Implementation
  }
  ```

#### Configuration Management
- Use environment variables for API configuration
- Implement proper error messages
- Use proper HTTP status codes
- Implement proper request timeouts
- Use proper security headers

#### Performance Considerations
- Implement proper caching strategies
- Use proper error handling
- Implement proper retry logic
- Use proper request cancellation
- Implement proper rate limiting

### Types Organization & Structure
Follow these guidelines for organizing TypeScript types and interfaces:

#### Types Directory Structure
- Place all types in `app/lib/types` directory
- Use descriptive names with `.types.ts` suffix
- Group related types in domain-specific files:
  ```
  app/lib/types/
  ├── api.types.ts      # Common API types
  ├── product.types.ts  # Product domain types
  ├── user.types.ts     # User domain types
  └── index.ts         # Barrel exports
  ```

#### Type File Organization
- One domain per file
- Export all types and interfaces
- Use descriptive names:
  ```typescript
  // Good
  export interface ProductDetails {
    id: string;
    name: string;
  }

  // Avoid
  export interface IProduct {
    id: string;
    name: string;
  }
  ```

#### Common Types Pattern
- Create base types for common patterns:
  ```typescript
  // api.types.ts
  export class ApiError extends Error {
    constructor(
      message: string,
      public status: number,
      public statusText: string
    ) {
      super(message);
      this.name = 'ApiError';
    }
  }

  export interface ApiResponse<T> {
    data: T;
    meta?: {
      total: number;
      page: number;
    };
  }
  ```

#### Type Import Standards
- Use absolute imports with aliases:
  ```typescript
  // Good
  import { Product } from '@/lib/types/product.types'
  
  // Avoid
  import { Product } from '../../../types/product.types'
  ```

#### Type Documentation
- Use JSDoc comments for complex types:
  ```typescript
  /**
   * Represents a product in the system
   * @property {string} id - Unique identifier
   * @property {string} title - Product title
   * @property {number} price - Product price
   */
  export interface Product {
    id: string;
    title: string;
    price: number;
  }
  ```

#### Type Safety Best Practices
- Use strict type checking
- Avoid type assertions when possible
- Use union types for variants:
  ```typescript
  export type Status = 'pending' | 'success' | 'error';
  ```

#### Type Composition
- Use composition over inheritance:
  ```typescript
  // Base type
  interface BaseProduct {
    id: string;
    title: string;
  }

  // Extended type
  interface DetailedProduct extends BaseProduct {
    description: string;
    price: number;
  }
  ```

#### Generic Types
- Use generics for reusable type patterns:
  ```typescript
  export interface PaginatedResponse<T> {
    items: T[];
    total: number;
    page: number;
  }
  ```

#### Type Testing
- Include type tests using TypeScript's type system:
  ```typescript
  // Type test
  type Assert<T, Expected> = 
    T extends Expected 
    ? Expected extends T 
      ? true 
      : false 
    : false;
  ```

#### Best Practices
- Keep types focused and single-purpose
- Use readonly when appropriate
- Implement proper type guards
- Use discriminated unions for complex types
- Keep type definitions DRY
- Use proper naming conventions
- Document complex types
- Use barrel exports for cleaner imports

#### Type Organization Example
```typescript
// product.types.ts
export interface Product {
  id: string;
  title: string;
  price: number;
}

// api.types.ts
export class ApiError extends Error {
  constructor(
    message: string,
    public status: number,
    public statusText: string
  ) {
    super(message);
  }
}

// index.ts
export * from './product.types';
export * from './api.types';
```

#### Type Usage Guidelines
- Import types from their domain files
- Use type inference when possible
- Implement proper error types
- Use proper discriminated unions
- Keep types simple and focused
- Document complex type relationships
- Use proper type guards

### SOLID Principles
Follow these guidelines for implementing SOLID principles:

#### Single Responsibility Principle (SRP)
- Each module/class/component should have one reason to change
- Keep files focused on a single responsibility:
  ```typescript
  // Good
  // UserAuthentication.ts - Handles only authentication
  export class UserAuthentication {
    login() { /* ... */ }
    logout() { /* ... */ }
  }

  // UserProfile.ts - Handles only profile data
  export class UserProfile {
    updateProfile() { /* ... */ }
    getProfile() { /* ... */ }
  }

  // Bad
  export class User {
    login() { /* ... */ }
    logout() { /* ... */ }
    updateProfile() { /* ... */ }
    getProfile() { /* ... */ }
    sendEmail() { /* ... */ }
  }
  ```

#### Open/Closed Principle (OCP)
- Software entities should be open for extension but closed for modification
- Use interfaces and composition:
  ```typescript
  // Good
  interface PaymentMethod {
    processPayment(amount: number): Promise<void>;
  }

  class CreditCardPayment implements PaymentMethod {
    processPayment(amount: number) { /* ... */ }
  }

  class PayPalPayment implements PaymentMethod {
    processPayment(amount: number) { /* ... */ }
  }

  // Adding new payment method doesn't modify existing code
  class CryptoPayment implements PaymentMethod {
    processPayment(amount: number) { /* ... */ }
  }
  ```

#### Liskov Substitution Principle (LSP)
- Derived classes must be substitutable for their base classes
- Maintain consistent behavior:
  ```typescript
  // Good
  interface Shape {
    getArea(): number;
  }

  class Rectangle implements Shape {
    constructor(private width: number, private height: number) {}
    getArea() { return this.width * this.height; }
  }

  class Circle implements Shape {
    constructor(private radius: number) {}
    getArea() { return Math.PI * this.radius ** 2; }
  }
  ```

#### Interface Segregation Principle (ISP)
- Clients shouldn't depend on interfaces they don't use
- Keep interfaces small and focused:
  ```typescript
  // Good
  interface Readable {
    read(): string;
  }

  interface Writable {
    write(data: string): void;
  }

  // Class only implements what it needs
  class FileReader implements Readable {
    read() { /* ... */ }
  }

  // Bad
  interface FileSystem {
    read(): string;
    write(data: string): void;
    delete(): void;
    create(): void;
  }
  ```

#### Dependency Inversion Principle (DIP)
- High-level modules shouldn't depend on low-level modules
- Both should depend on abstractions:
  ```typescript
  // Good
  interface Logger {
    log(message: string): void;
  }

  class ConsoleLogger implements Logger {
    log(message: string) { console.log(message); }
  }

  class UserService {
    constructor(private logger: Logger) {}
    
    createUser() {
      this.logger.log('User created');
    }
  }

  // Bad
  class UserService {
    private logger = new ConsoleLogger();
    
    createUser() {
      this.logger.log('User created');
    }
  }
  ```

#### Implementation Guidelines
- Use dependency injection for better testability
- Create interfaces before implementations
- Keep components loosely coupled
- Use composition over inheritance
- Implement proper error boundaries
- Use proper type definitions

#### Service Organization
- Separate business logic from UI components
- Use proper dependency injection:
  ```typescript
  // Good
  interface ApiClient {
    get<T>(url: string): Promise<T>;
  }

  class ProductService {
    constructor(private apiClient: ApiClient) {}
    
    async getProducts() {
      return this.apiClient.get('/products');
    }
  }
  ```

#### Component Structure
- Keep components focused on UI concerns
- Extract business logic to services
- Use proper prop typing:
  ```typescript
  interface ButtonProps {
    onClick: () => void;
    children: React.ReactNode;
  }

  const Button = ({ onClick, children }: ButtonProps) => (
    <button onClick={onClick}>{children}</button>
  );
  ```

#### Testing Considerations
- Test components in isolation
- Mock dependencies properly
- Test business logic separately
- Use proper test boundaries
- Implement proper integration tests

### Documentation Standards
Follow these guidelines for documenting code:

#### Component Documentation
- Document all components with JSDoc comments:
  ```typescript
  /**
   * Primary navigation component for the application.
   * Displays main menu items and handles mobile responsiveness.
   *
   * @example
   * ```tsx
   * <Header
   *   items={menuItems}
   *   currentPath="/products"
   * />
   * ```
   */
  const Header = ({ items, currentPath }: HeaderProps) => {
    // Implementation
  }
  ```

#### Props Documentation
- Document all props with TypeScript interfaces and JSDoc:
  ```typescript
  /**
   * Props for the Button component
   * @property {string} variant - Visual style of the button
   * @property {ReactNode} children - Content to be rendered inside
   * @property {() => void} onClick - Click handler function
   */
  interface ButtonProps {
    variant: 'primary' | 'secondary' | 'ghost';
    children: React.ReactNode;
    onClick?: () => void;
  }
  ```

#### Function Documentation
- Document all functions with JSDoc, including parameters and return types:
  ```typescript
  /**
   * Fetches product data from the API
   * 
   * @param {string} id - The product identifier
   * @returns {Promise<Product>} The product data
   * @throws {ApiError} When the API request fails
   * 
   * @example
   * ```ts
   * const product = await getProduct('123')
   * ```
   */
  const getProduct = async (id: string): Promise<Product> => {
    // Implementation
  }
  ```

#### Type Documentation
- Document complex types and interfaces:
  ```typescript
  /**
   * Represents a product in the e-commerce system
   * 
   * @property {string} id - Unique identifier
   * @property {string} title - Product name/title
   * @property {number} price - Product price in USD
   * @property {Rating} rating - Product rating information
   */
  interface Product {
    id: string;
    title: string;
    price: number;
    rating: Rating;
  }
  ```

#### File Documentation
- Add header comments to files explaining their purpose:
  ```typescript
  /**
   * @fileoverview Product service module
   * Handles all product-related API calls and data transformations
   * 
   * @module services/product
   * @requires types/product
   * @requires types/api
   */
  ```

#### Code Examples
- Include usage examples in documentation:
  ```typescript
  /**
   * Formats a price value to currency string
   * 
   * @param {number} price - The price to format
   * @param {string} [currency='USD'] - Currency code
   * @returns {string} Formatted price string
   * 
   * @example
   * ```ts
   * formatPrice(29.99) // Returns "$29.99"
   * formatPrice(29.99, 'EUR') // Returns "€29.99"
   * ```
   */
  ```

#### Error Documentation
- Document possible errors and error handling:
  ```typescript
  /**
   * Updates user profile information
   * 
   * @throws {ValidationError} When input data is invalid
   * @throws {AuthError} When user is not authenticated
   * @throws {ApiError} When API request fails
   */
  ```

#### Testing Documentation
- Document test cases and scenarios:
  ```typescript
  /**
   * @test {ProductService}
   * 
   * @scenario Product fetch success
   * - Should return product data when API call succeeds
   * 
   * @scenario Product fetch failure
   * - Should throw ApiError when API call fails
   */
  ```

#### Markdown Documentation
- Use markdown files for broader documentation:
  ```
  docs/
  ├── README.md           # Project overview
  ├── CONTRIBUTING.md     # Contribution guidelines
  ├── ARCHITECTURE.md     # System architecture
  └── components/
      └── README.md      # Components documentation
  ```

#### Version Documentation
- Document version changes and migrations:
  ```typescript
  /**
   * @deprecated Use `newFunction()` instead
   * @since 2.0.0
   * @version 1.0.0
   */
  ```

#### API Documentation
- Document API endpoints and responses:
  ```typescript
  /**
   * @api {get} /products/:id Get Product
   * @apiName GetProduct
   * @apiGroup Products
   * 
   * @apiParam {String} id Product unique ID
   * 
   * @apiSuccess {Object} product Product data
   * @apiError {Object} error Error information
   */
  ```

#### Best Practices
- Keep documentation up to date
- Use consistent documentation style
- Include practical examples
- Document edge cases and limitations
- Use proper markdown formatting
- Include links to related documentation
- Document breaking changes

#### Documentation Tools
- Use TypeDoc for API documentation
- Implement Storybook for component documentation
- Use JSDocs for inline documentation
- Maintain changelog using Conventional Commits
- Use README files for directory documentation

#### Documentation Review
- Review documentation during code review
- Ensure documentation accuracy
- Verify example code works
- Check for broken links
- Validate against style guide

### Testing Standards & Setup
Follow these guidelines for testing Next.js applications:

#### Recommended Testing Packages
- Primary testing packages:
  ```json
  {
    "devDependencies": {
      "@testing-library/react": "^14.0.0",
      "@testing-library/jest-dom": "^6.0.0",
      "@testing-library/user-event": "^14.0.0",
      "jest": "^29.0.0",
      "jest-environment-jsdom": "^29.0.0",
      "@types/jest": "^29.0.0",
      "ts-jest": "^29.0.0",
      "msw": "^2.0.0",
      "vitest": "^1.0.0",
      "cypress": "^13.0.0"
    }
  }
  ```

#### Test File Structure
- Place tests next to the files they test:
  ```
  app/
  ├── components/
  │   ├── Button/
  │   │   ├── Button.tsx
  │   │   ├── Button.test.tsx      # Unit tests
  │   │   ├── Button.e2e.test.tsx  # E2E tests
  │   │   └── Button.integration.test.tsx  # Integration tests
  │   └── __tests__/                 # Shared test utilities
  ```

#### Testing Types
- Implement different types of tests:
  ```typescript
  // Unit Tests (Component)
  describe('Button', () => {
    it('renders correctly', () => {
      render(<Button>Click me</Button>)
      expect(screen.getByRole('button')).toBeInTheDocument()
    })
  })

  // Integration Tests (Multiple Components)
  describe('ProductList', () => {
    it('filters products correctly', async () => {
      render(<ProductList />)
      await userEvent.click(screen.getByRole('button', { name: /filter/i }))
      expect(screen.getByText('Filtered Results')).toBeInTheDocument()
    })
  })

  // E2E Tests (Full User Flows)
  describe('Checkout Flow', () => {
    it('completes purchase successfully', () => {
      cy.visit('/products')
      cy.get('[data-testid="add-to-cart"]').click()
      cy.get('[data-testid="checkout"]').click()
    })
  })
  ```

#### API Mocking
- Use MSW (Mock Service Worker) for API mocking:
  ```typescript
  // mocks/handlers.ts
  import { http, HttpResponse } from 'msw'

  export const handlers = [
    http.get('/api/products', () => {
      return HttpResponse.json([
        { id: 1, name: 'Product 1' },
        { id: 2, name: 'Product 2' },
      ])
    }),
  ]
  ```

#### Component Testing
- Test user interactions:
  ```typescript
  test('calls onClick when clicked', async () => {
    const handleClick = vi.fn()
    render(<Button onClick={handleClick}>Click me</Button>)
    
    await userEvent.click(screen.getByRole('button'))
    expect(handleClick).toHaveBeenCalled()
  })
  ```

#### Server Component Testing
- Test Server Components:
  ```typescript
  import { renderToString } from 'react-dom/server'

  test('renders server component', async () => {
    const ProductPage = await import('./ProductPage')
    const html = renderToString(<ProductPage />)
    expect(html).toContain('Product List')
  })
  ```

#### Test Configuration
- Jest configuration for Next.js:
  ```typescript
  // jest.config.ts
  import type { Config } from 'jest'
  import nextJest from 'next/jest'

  const createJestConfig = nextJest({
    dir: './',
  })

  const config: Config = {
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    testEnvironment: 'jest-environment-jsdom',
    moduleNameMapper: {
      '^@/(.*)$': '<rootDir>/app/$1',
    },
  }

  export default createJestConfig(config)
  ```

#### Testing Utilities
- Create reusable test utilities:
  ```typescript
  // test-utils.tsx
  import { render } from '@testing-library/react'

  const customRender = (ui: React.ReactElement, options = {}) =>
    render(ui, {
      wrapper: ({ children }) => (
        <Providers>{children}</Providers>
      ),
      ...options,
    })

  export * from '@testing-library/react'
  export { customRender as render }
  ```

#### Testing Best Practices
- Test behavior, not implementation
- Use data-testid sparingly
- Test accessibility
- Mock external dependencies
- Use proper assertions
- Keep tests focused and isolated
- Follow AAA pattern (Arrange, Act, Assert)

#### Testing Commands
- Add test scripts to package.json:
  ```json
  {
    "scripts": {
      "test": "jest",
      "test:watch": "jest --watch",
      "test:coverage": "jest --coverage",
      "test:e2e": "cypress run",
      "test:e2e:dev": "cypress open"
    }
  }
  ```

#### CI/CD Testing
- Configure GitHub Actions for testing:
  ```yaml
  # .github/workflows/test.yml
  name: Test
  on: [push, pull_request]
  jobs:
    test:
      runs-on: ubuntu-latest
      steps:
        - uses: actions/checkout@v4
        - uses: actions/setup-node@v4
        - run: npm ci
        - run: npm test
        - run: npm run test:e2e
  ```

#### Performance Testing
- Use Lighthouse CI for performance testing:
  ```yaml
  # lighthouserc.js
  module.exports = {
    ci: {
      collect: {
        startServerCommand: 'npm run start',
        url: ['http://localhost:3000'],
      },
      assert: {
        assertions: {
          'categories:performance': ['error', { minScore: 0.9 }],
        },
      },
    },
  }
  ```

#### Testing Documentation
- Document test scenarios:
  ```typescript
  /**
   * @test ProductList Component
   * 
   * Test scenarios:
   * 1. Renders list of products
   * 2. Filters products by category
   * 3. Sorts products by price
   * 4. Handles loading state
   * 5. Handles error state
   */
  ```

### Test Case Writing Standards
Follow these guidelines for writing test cases:

#### Test File Organization
- Use consistent naming patterns:
  ```
  app/
  ├── components/
  │   ├── Button/
  │   │   ├── Button.tsx
  │   │   ├── Button.test.tsx        # Unit tests
  │   │   ├── Button.e2e.test.tsx    # E2E tests
  │   │   └── Button.integration.test.tsx  # Integration tests
  │   └── __tests__/                 # Shared test utilities
  ```

#### Test Case Structure
- Follow the AAA (Arrange, Act, Assert) pattern:
  ```typescript
  describe('ProductCard', () => {
    it('should display product information correctly', () => {
      // Arrange
      const product = {
        id: '1',
        title: 'Test Product',
        price: 99.99,
        image: '/test.jpg'
      }

      // Act
      render(<ProductCard {...product} />)

      // Assert
      expect(screen.getByText('Test Product')).toBeInTheDocument()
      expect(screen.getByText('$99.99')).toBeInTheDocument()
    })
  })
  ```

#### Test Categories
- Implement different types of tests:
  ```typescript
  // Unit Tests
  describe('utils/formatPrice', () => {
    it('formats price correctly', () => {
      expect(formatPrice(99.99)).toBe('$99.99')
    })
  })

  // Integration Tests
  describe('ProductList with Filters', () => {
    it('filters products by category', async () => {
      render(<ProductList />)
      await userEvent.selectOptions(
        screen.getByRole('combobox'),
        'electronics'
      )
      expect(screen.getAllByTestId('product-card')).toHaveLength(5)
    })
  })

  // E2E Tests
  describe('Checkout Flow', () => {
    it('completes purchase successfully', () => {
      cy.visit('/products')
      cy.get('[data-testid="add-to-cart"]').click()
      cy.get('[data-testid="checkout"]').click()
    })
  })
  ```

#### Test Data Management
- Use factories for test data:
  ```typescript
  // factories/product.ts
  export const createProduct = (overrides = {}) => ({
    id: '1',
    title: 'Test Product',
    price: 99.99,
    image: '/test.jpg',
    ...overrides
  })

  // Usage in tests
  const product = createProduct({ price: 149.99 })
  ```

#### Mock Management
- Organize mocks properly:
  ```typescript
  // __mocks__/services/product.service.ts
  export const getProduct = vi.fn()
  export const getProducts = vi.fn()

  // Usage in tests
  vi.mock('@/lib/services/product.service')
  
  beforeEach(() => {
    getProduct.mockResolvedValue(createProduct())
  })
  ```

#### API Testing
- Test API endpoints thoroughly:
  ```typescript
  describe('Product API', () => {
    it('returns product details', async () => {
      const response = await fetch('/api/products/1')
      const data = await response.json()
      
      expect(response.status).toBe(200)
      expect(data).toMatchObject({
        id: expect.any(String),
        title: expect.any(String),
        price: expect.any(Number)
      })
    })
  })
  ```

#### Component Testing
- Test component behavior and interactions:
  ```typescript
  describe('ProductCard', () => {
    it('handles click events', async () => {
      const handleClick = vi.fn()
      render(<ProductCard onClick={handleClick} />)
      
      await userEvent.click(screen.getByRole('button'))
      expect(handleClick).toHaveBeenCalledTimes(1)
    })

    it('handles keyboard navigation', async () => {
      render(<ProductCard />)
      const card = screen.getByRole('link')
      
      await userEvent.tab()
      expect(card).toHaveFocus()
    })
  })
  ```

#### Error Testing
- Test error scenarios:
  ```typescript
  describe('ProductService', () => {
    it('handles API errors', async () => {
      getProduct.mockRejectedValue(new Error('API Error'))
      
      await expect(getProduct('1')).rejects.toThrow('API Error')
    })

    it('handles network errors', async () => {
      server.use(
        http.get('/api/products/:id', () => {
          return new HttpResponse(null, { status: 500 })
        })
      )
      
      await expect(getProduct('1')).rejects.toThrow()
    })
  })
  ```

#### Accessibility Testing
- Include accessibility tests:
  ```typescript
  describe('Button', () => {
    it('meets accessibility requirements', async () => {
      render(<Button>Click me</Button>)
      
      expect(screen.getByRole('button')).toHaveAttribute('aria-label')
      expect(await axe(container)).toHaveNoViolations()
    })
  })
  ```

#### Performance Testing
- Test performance metrics:
  ```typescript
  describe('ProductList', () => {
    it('renders within performance budget', async () => {
      const start = performance.now()
      render(<ProductList products={products} />)
      const end = performance.now()
      
      expect(end - start).toBeLessThan(100)
    })
  })
  ```

#### Test Coverage
- Maintain high test coverage:
  ```json
  {
    "jest": {
      "coverageThreshold": {
        "global": {
          "branches": 80,
          "functions": 80,
          "lines": 80,
          "statements": 80
        }
      }
    }
  }
  ```

#### Best Practices
- Write descriptive test names
- Test one thing per test
- Use proper assertions
- Mock external dependencies
- Clean up after tests
- Keep tests independent
- Use proper setup and teardown
- Test edge cases
- Test error scenarios
- Test accessibility
- Test performance
- Maintain test coverage

#### Test Documentation
- Document test scenarios:
  ```typescript
  /**
   * @test ProductList Component
   * 
   * Test scenarios:
   * 1. Renders list of products
   * 2. Filters products by category
   * 3. Sorts products by price
   * 4. Handles loading state
   * 5. Handles error state
   * 6. Handles empty state
   * 7. Handles pagination
   * 8. Handles search
   * 9. Handles accessibility
   * 10. Handles performance
   */
  ```

#### Test Review
- Review test quality:
  - Test readability
  - Test maintainability
  - Test coverage
  - Test performance
  - Test reliability
  - Test documentation

### Type vs Interface Guidelines
Follow these guidelines for choosing between types and interfaces:

#### Use Interfaces For
- Object definitions that might need to be extended:
  ```typescript
  // Good: Using interface for extensible objects
  interface Product {
    id: string;
    title: string;
  }

  interface DetailedProduct extends Product {
    specifications: Record<string, string>;
    relatedProducts: string[];
  }
  ```

- API responses and data models:
  ```typescript
  interface ApiResponse<T> {
    data: T;
    meta: {
      total: number;
      page: number;
    };
  }
  ```

- Component props:
  ```typescript
  interface ButtonProps {
    variant: 'primary' | 'secondary';
    children: React.ReactNode;
    onClick?: () => void;
  }
  ```

- Class definitions:
  ```typescript
  interface Repository<T> {
    find(id: string): Promise<T>;
    save(item: T): Promise<void>;
  }
  ```

#### Use Types For
- Union types:
  ```typescript
  type Status = 'pending' | 'success' | 'error';
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
  ```

- Function types:
  ```typescript
  type Handler = (event: Event) => void;
  type AsyncCallback<T> = (data: T) => Promise<void>;
  ```

- Complex type manipulations:
  ```typescript
  type Nullable<T> = {
    [K in keyof T]: T[K] | null;
  };
  ```

- Utility types:
  ```typescript
  type PartialProduct = Partial<Product>;
  type ReadonlyUser = Readonly<User>;
  ```

#### Key Differences
- Declaration Merging (Interfaces only):
  ```typescript
  // Allowed with interfaces
  interface User {
    name: string;
  }
  interface User {
    age: number;
  }

  // Not allowed with types
  type User = {
    name: string;
  }
  type User = { // Error: Duplicate identifier
    age: number;
  }
  ```

- Computed Properties (Types only):
  ```typescript
  // Allowed with types
  type Keys = 'firstname' | 'lastname';
  type User = {
    [K in Keys]: string;
  }

  // Not allowed with interfaces
  interface User {
    [K in Keys]: string; // Error
  }
  ```

#### Best Practices
- Start with interfaces for object definitions
- Use types for specific type features
- Be consistent within your codebase
- Document your choice in complex scenarios
- Consider future extensibility needs

#### Type Organization
- Group related types in domain-specific files:
  ```
  app/lib/types/
  ├── api.types.ts      # API-related types
  ├── product.types.ts  # Product domain types
  ├── common.types.ts   # Shared utility types
  └── index.ts         # Barrel exports
  ```

#### Documentation
- Document type choices:
  ```typescript
  /**
   * Using interface for Product as it:
   * 1. Represents a clear domain entity
   * 2. May need extension in future
   * 3. Serves as a contract for API responses
   */
  interface Product {
    id: string;
    title: string;
  }

  /**
   * Using type for Status as it:
   * 1. Represents a union of string literals
   * 2. Won't need extension
   * 3. Benefits from type's union capabilities
   */
  type Status = 'active' | 'inactive';
  ```

#### Migration Considerations
- When to change from type to interface:
  ```typescript
  // Before: Simple type
  type User = {
    id: string;
    name: string;
  }

  // After: Need to extend
  interface User {
    id: string;
    name: string;
  }

  interface AdminUser extends User {
    permissions: string[];
  }
  ```

#### Review Checklist
- Is the type likely to be extended?
- Do you need union types?
- Are you using computed properties?
- Do you need declaration merging?
- Is it a domain model or utility type?

### Import Path Standards
Follow these strict guidelines for imports:

#### Required Alias Usage
- ALWAYS use alias paths (`@/*`) for imports instead of relative paths:
  ```typescript
  // ✅ Correct - Use alias paths
  import { Button } from '@/components/ui/Button';
  import { useAuth } from '@/hooks/useAuth';
  import { api } from '@/lib/api';
  import { type User } from '@/types/user';
  
  // ❌ Wrong - Never use relative paths
  import { Button } from '../../../components/ui/Button';
  import { useAuth } from '../../hooks/useAuth';
  import { api } from '../lib/api';
  ```

#### Import Organization
1. External packages
2. Aliased imports (grouped by type)
3. Types and interfaces

Example:
```typescript
// 1. External packages
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';

// 2. Aliased imports (grouped)
// Components
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';

// Hooks
import { useAuth } from '@/hooks/useAuth';
import { useTheme } from '@/hooks/useTheme';

// Utils & Services
import { api } from '@/lib/api';
import { formatDate } from '@/utils/date';

// 3. Types
import type { User } from '@/types/user';
import type { Theme } from '@/types/theme';
```

#### Path Alias Structure
Always use these standard aliases:
- `@/components/*` - React components
- `@/lib/*` - Core utilities and services
- `@/hooks/*` - Custom React hooks
- `@/utils/*` - Helper functions
- `@/types/*` - TypeScript types/interfaces
- `@/styles/*` - Style-related files
- `@/constants/*` - Constants and enums
- `@/context/*` - React Context providers
- `@/store/*` - State management
- `@/api/*` - API-related functions

#### Configuration
Ensure tsconfig.json has proper path aliases:
```json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./app/*"]
    }
  }
}
```

#### Enforcement
- Use ESLint rules to enforce alias usage
- Configure import order in Prettier
- Add import aliases to VS Code settings
- Review imports during code review
bun
css
cypress
eslint
golang
html
java
javascript
+16 more
AymanNagyAhmed/chemist-task-frontend

Used in 1 repository

unknown
// React Native Expo .cursorrules

// React Native Expo Best Practices
const reactNativeExpoBestPractices = [
  "Use functional components with hooks.",
  "Leverage Expo SDK features and APIs.",
  "Implement navigation using Expo Router.",
  "Manage assets with Expo's asset system for images and fonts.",
  "Ensure robust error handling and crash reporting.",
  "Utilize Expo's push notification system.",
  "Adopt TypeScript for type safety.",
  "Apply consistent styling using StyleSheet.",
  "Incorporate Expo's vector icons.",
  "Secure sensitive data with Expo's SecureStore.",
  "Implement proper offline support.",
  "Optimize performance following React Native best practices.",
  "Deploy updates using Expo's OTA mechanism.",
  "Style components using NativeWind.",
];

// Folder Structure
const folderStructure = `
assets/
src/
  components/
  screens/
  navigation/
  hooks/
  utils/
app/
  _layout.tsx
  index.tsx
App.js
app.json
`;

// Package Version Compatibility Notes
const packageCompatibilityNotes = [
  "NativeWind and Tailwind CSS compatibility:",
  "- Use nativewind@2.0.11 with tailwindcss@3.3.2.",
  "- Higher versions may cause 'process(css).then(cb)' errors.",
  "- If errors occur, remove both packages and reinstall specific versions:",
  "  npm remove nativewind tailwindcss",
  "  npm install nativewind@2.0.11 tailwindcss@3.3.2",

  "Babel configuration for NativeWind:",
  "- Include 'nativewind/babel' in the plugins array.",
  "- Avoid using jsxImportSource in presets.",
  "- Ensure 'react-native-reanimated/plugin' follows 'nativewind/babel'."
];

// Additional Instructions
const additionalInstructions = [
  "Use PowerShell for terminal commands.",
  "Before installing a new package, check if it's already installed:",
  "  Get-ChildItem -Recurse -Filter package-name",
  "If installed, upgrade using:",
  "  expo upgrade <package-name>",
  "or",
  "  npm install <package-name>",
  "if not supported by Expo.",
  "Use PowerShell commands to manage the project, e.g., moving and renaming files:",
  "  Move-Item -Path .\\old\\path\\file.txt -Destination .\\new\\path\\newname.txt",
  "If unsure about the current structure or details, use PowerShell to list out necessary information:",
  "  Get-ChildItem -Recurse",
  "Utilize official Expo libraries and upgrade them using Expo's commands.",
  "Avoid deleting existing functionality or files without a valid reason.",
  "Follow the recommended folder structure and maintain organized code for scalability and readability.",
  "Implement navigation using Expo Router for clean and declarative routing."
];
npm
react
rest-api
tailwindcss
typescript

First seen in:

PatrickJS/awesome-cursorrules

Used in 1 repository

TypeScript
# Cursor Rules

Always use Typescript, and strong typing. Use functional programing paradigms.

Always use the best practices for the typescript language.

Always use the best practices for the react framework.

Always use the best practices for the next.js framework.

Always use the best practices for the react query library.

Never recommend relative paths. Always use the alias. Default path alias is "#".

# Instructions to Create and Manage CRUD Operations

Follow these steps to create and manage a CRUD (Create, Read, Update, Delete) operation for the application.

## Folder structure:

- The project has two packages with models:
    - @repo/layer-fetch: This package contains the model interfaces to interact with external api's.
    - @repo/layer-prisma: This package contains the model interfaces to interact with the database.

@repo/layer-fetch
- Relative path: packages/layer-fetch/src/**
- Import path declare in package.json: @repo/layer-fetch

@repo/layer-prisma
- Relative path: packages/layer-prisma/src/**
- Import path declare in package.json: @repo/layer-prisma

### Folder structure tree to CRUD model:

```
apps/
└── dashboard/
    └── src/
        ├── app/
        │   └── (dashboard)/
        │       ├── authors/
        │       │   ├── create/
        │       │   │   └── page.tsx
        │       │   ├── update/
        │       │   │   └── [id]
        │       │   │       └── page.tsx
        │       │   └── page.tsx
        │       └── [name]/
        │           ├── create/
        │           │   └── page.tsx
        │           ├── update/
        │           │   └── [id]
        │           │       └── page.tsx
        │           └── page.tsx
        ├── components/
        │   ├── authors/
        │   │   ├── create/
        │   │   │   └── create-author.tsx
        │   │   ├── update/
        │   │   │   └── update-author.tsx
        │   │   ├── list/
        │   │   │   ├── list-authors-api.tsx
        │   │   │   └── list-authors.tsx
        │   │   ├── author.action.ts
        │   │   └── search-params.ts
        │   └── [name]/
        │       ├── create/
        │       │   └── create-[name].tsx
        │       ├── update/
        │       │   ├── update-[name]-api.tsx
        │       │   └── update-[name].tsx
        │       ├── list/
        │       │   ├── list-[name]-api.tsx
        │       │   └── list-[name].tsx
        │       ├── [name].action.ts
        │       └── search-params.ts
        └── routes/
            └── index.ts

packages/
├── layer-fetch/
│   └── src/
│       ├── model/
│       │   └── [name]/
│       │       ├── [name].interface.ts
│       │       └── [name].model.ts
│       └── factory/
│           └── model-factory.ts
├── layer-prisma/
│   └── src/
│       ├── model/
│       │   ├── author/
│       │   │   ├── author.interface.ts
│       │   │   └── author.model.ts
│       │   └── [name]/
│       │       ├── [name].interface.ts
│       │       └── [name].model.ts
│       └── factory/
│           └── model-factory.ts
└── ui/
    └── src/
        └── icons/
            └── index.ts
```

## Creating a New CRUD Model

### 1. Setup Routes and Sidebar
- Define routes in `apps/dashboard/src/routes/index.ts`
- Update sidebar in `apps/dashboard/src/components/sidebar/sidebar-items.tsx`

### 2. Create Model Files
- In chosen package (`layer-fetch` or `layer-prisma`):
  - Create `packages/[package]/src/model/[name]/[name].interface.ts` (Zod schema)
  - Create `packages/[package]/src/model/[name]/[name].model.ts`
- Add model to `packages/[package]/src/factory/model-factory.ts`

### 3. Implement List View
- Create `apps/dashboard/src/app/(dashboard)/[name]/page.tsx`
- Create `apps/dashboard/src/components/[name]/list/list-[name]-api.tsx` (async server component)
- Create `apps/dashboard/src/components/[name]/list/list-[name].tsx` (table component)

### 4. Implement Create View
- Create `apps/dashboard/src/app/(dashboard)/[name]/create/page.tsx`
- Create `apps/dashboard/src/app/(dashboard)/[name]/action.ts` (server action)
- Create `apps/dashboard/src/components/[name]/create/create-[name].tsx`

### 5. Implement Update View
- Create `apps/dashboard/src/app/(dashboard)/[name]/update/page.tsx`
- Update `action.ts` with update method
- Create `apps/dashboard/src/components/[name]/update/update-[name].tsx`

### 6. Implement Delete Action
- Add delete method to existing `action.ts`

## Best Practices to Prisma Models
- For find, findMany, etc., methods: Return `string` or `[prisma, null]`
- For create, update, delete methods: Throw `Error`

## Notes
- Use existing files (e.g., `author`) as examples
- Ensure consistency between model function return types and action receive types
- Use existing icons from `packages/ui/src/icons`
astro
css
javascript
next.js
prisma
react
typescript
Disble/web-stories-follow-up

Used in 1 repository

TypeScript
# Cursor Boilerplate Rules

This boilerplate serves as the foundation for your projects. Below are the predefined packages, configurations, and rules for working with this setup. Follow these guidelines strictly to ensure compatibility and maintainability.

## Immutable Boilerplate Base

- The predefined setup in this boilerplate (e.g., `package.json`, `vite.config.ts`, `tsconfig.json`) must remain unchanged.
- You are allowed to extend the boilerplate by adding new features or configurations, but existing ones should not be removed or modified.
- Exceptions are made for adjustments to settings specific to your project requirements, but these must align with the boilerplate's core principles.

## Standard Compliance

- This project strictly adheres to modern web development standards.
- **Type Definitions**: TypeScript is mandatory for this project. Ensure all code is strongly typed.
- **ESLint**: Use the provided ESLint configuration to maintain consistent coding standards. Avoid disabling rules unless absolutely necessary.
- **Prettier**: Use the predefined Prettier configuration for code formatting.
- Ensure that all additional code and configurations align with these standards.

## Default Libraries and Tools

The boilerplate includes the following packages and tools by default:

### Core Libraries

- **React**: Latest stable version for building user interfaces.
- **Vite**: A fast build tool preconfigured for React and TypeScript.
- **TypeScript + SWC**: For type safety and high-speed compilation.

### State Management

- **Zustand**: A minimalistic state management library designed for simplicity and flexibility. **Do not use Redux or Redux Toolkit** for state management. Zustand is the only state management solution supported by this boilerplate.

### UI Components

- **shadcn/ui**: A complete set of customizable UI components for building modern interfaces.

### Styling

- **TailwindCSS**: The primary styling tool for the project.
  - Avoid using external styles unless absolutely necessary.
  - Do not modify `index.css` or TailwindCSS configuration files unless explicitly permitted.
  - If changes are required, include the following:
    - A detailed explanation of the purpose of the changes.
    - Specific examples of what you need to add or modify.
    - Obtain approval before making the changes.

### Drag-and-Drop

- **dnd-kit**: The exclusive drag-and-drop library for this project.
  - **Reason**: `dnd-kit` offers a flexible and modern API for handling drag-and-drop interactions, ensuring consistency and reliability.
  - Do not use alternative libraries such as `react-beautiful-dnd` or `react-dnd`.
  - All drag-and-drop implementations should follow best practices as outlined in the `dnd-kit` documentation.

### Folder Structure

To maintain consistency and organization, adhere to the following folder structure:

- `src/components`
  - `src/components/ui`: Contains **shadcn/ui** components for building consistent and reusable UI elements.
  - `src/components/common`: Shared components like buttons, modals, and headers that are not tied to `shadcn/ui`.
  - `src/components/features`: Feature-specific components for individual application modules.
- `src/state`: Contains Zustand global state management files.
- `src/services`: For HTTP services and API integrations.
  - **Usage**: All HTTP requests should use an Axios instance configured with a `baseURL` set in `.env`.
    - Example:
      ```typescript
      import axios from 'axios';

      const api = axios.create({
        baseURL: process.env.VITE_API_BASE_URL,
      });

      export default api;
      ```
- `src/styles`: For additional custom styles if necessary (use sparingly and align with TailwindCSS).
- `src/utils`: Helper functions or utility files.
- `src/pages`: Page components that define the application's main views.
- `src/hooks`: Custom hooks for managing reusable logic.
- `public/`: Static assets like images and fonts.

### Aliases

- Use `@/` as an alias for the `src` directory to simplify imports.
  - Example: `import Button from '@/components/ui/Button';`

### Do Not Replace or Remove

- These libraries form the foundation of the boilerplate. Do not replace or remove them.
- You may add complementary libraries or tools, but they must integrate seamlessly with the existing setup.

## Usage of Additional Packages

For additional functionality like animations, storage, or data fetching, you must use standardized and well-documented packages. Below is a list of commonly used libraries and their purposes:

### Local Storage

- **Purpose**: Manage and persist data in the browser's `localStorage`.
- **Recommended Package**: [`store2`](https://github.com/nbubna/store) for a simple and extensible interface.
  - **Implementation**: Store reusable logic for `localStorage` in the `src/utils` folder.

### Animations

- **Purpose**: Add animations and transitions to your project.
- **Recommended Package**: [`framer-motion`](https://www.framer.com/motion/) for declarative and powerful animations.

### HTTP Requests

- **Purpose**: Fetch data from APIs.
- **Recommended Package**: [`axios`](https://axios-http.com/) for a robust and feature-rich HTTP client.
  - **Best Practices**: Always use a central Axios instance.
  - **Folder Location**: Place all service files in `src/services`.

### Form Validation

- **Purpose**: Validate user inputs in forms.
- **Recommended Package**: [`react-hook-form`](https://react-hook-form.com/) for minimal and flexible form handling.

### Date and Time Handling

- **Purpose**: Manage and manipulate dates and times.
- **Recommended Package**: [`date-fns`](https://date-fns.org/) for lightweight and modular date utilities.

### Utility Libraries

- **Purpose**: Provide additional utility functions.
- **Recommended Package**: [`lodash`](https://lodash.com/) for a comprehensive utility library.

### GraphQL

- **Purpose**: Query and manipulate data via GraphQL APIs.
- **Recommended Package**: [`@apollo/client`](https://www.apollographql.com/docs/react/) for an advanced GraphQL client.

### Drag-and-Drop

- **Purpose**: Enable drag-and-drop functionality in the project.
- **Recommended Package**: [`@dnd-kit`](https://dndkit.com/) for flexible and extensible drag-and-drop interactions.
  - **Implementation**: Use `dnd-kit` exclusively for drag-and-drop features. Avoid using other libraries.
  - Ensure drag-and-drop logic is modular and reusable. Store all related files in `src/components/features/dragdrop` or similar.

For any of these needs, provide a brief explanation of why the library is necessary and how it integrates with the current setup. Ensure it follows the project's coding standards.

### Restricted Usage

- Do not use additional libraries unless absolutely necessary and approved.
- Provide a clear rationale and usage documentation for any new library added to the project.

## Documentation for Extensions

When adding new libraries, tools, or configurations:

- Include concise documentation explaining:
  - The purpose of the addition.
  - How it is used in the project.
  - Any potential issues and their resolutions.
- Documentation should be added to a dedicated section within the project or a separate markdown file.

## Development Workflow

- Build your projects on top of this boilerplate without altering the foundational setup.
- Ensure any additional features enhance the existing structure without conflicting with the default configurations.
- Follow best practices for clean and maintainable code.

## Recommended Practices

- Regularly update dependencies to their latest versions while ensuring compatibility.
- Test all changes thoroughly in a development environment before pushing to production.
- Maintain consistency in code style and structure by adhering to provided standards.

## Additional Strict Rules

- **Package Manager**: Always use `bun` as the package manager. Do not switch to `npm` or `yarn` unless explicitly instructed.
- **Language and Comments**:
  - All communication within this project must be in **Turkish**.
  - All variable names and comment lines in the codebase must be written in **English** to ensure international readability.
- **UI Components**:
  - All `shadcn/ui` components are already installed in the project. Avoid adding additional `shadcn/ui` components unless required by the maintainer.
  - Use `src/components/ui` to organize and work with these components. Ensure proper categorization and naming conventions for easier maintenance.
- **Styling**:
  - TailwindCSS is the primary styling library for this project. Do not use additional styling libraries unless absolutely necessary.
  - Avoid making changes to `index.css` or TailwindCSS configuration files unless:
    - You provide a clear explanation of the need for these changes.
    - You list the specific additions or modifications.
    - You obtain approval for these changes before implementing them.
bun
css
eslint
golang
graphql
html
javascript
less
+11 more
bekiryazgann/cursor-boilerplate

Used in 1 repository

TypeScript


- use this casing for file names: kebab-case
- use this casing for variable names: camelCase
- use this casing for function names: camelCase


always console log like this:
console.log("0xHypr", 'variableName', variable )

Assistant Guidelines:
	•	When i use ai models most likely i use Model: gpt-4o
	•	Development and Packaging:
	•	Use pnpm as the package manager.
	•	Maintain a monorepo structure.
	•	Follow kebab-case for all file and folder naming conventions.
	•	Utilize TypeScript and React throughout the project.
	•	Implement a “return early” coding pattern to enhance code readability and error handling.


When you implement something in the electron main process, you need to implement it in the preload.ts file as well.
and extend the electron api with the new method.

## Core feature 1 classification of events 

This app works with multiple agents that are used to classify events.

But the core feature is the classification of events.
This works by loading up the "detectorPrompts" and then using the "classificationSerializer" to serialize the results into a classification.

1. LLMs are a core part of this project and are used for a lot of things.
2. Typical flow is:
   - User "classifies" last x minues
   - The classification prompt includes a list of agents and their prompts
   - These prompts trigger so-caleld function calls aka tools
   - The tools are executed and the results are given to the LLM
   - The LLM generates a response
   - The main tools are screenpipe-search and classificationSerializer
   - The screenpipe-search tool is used to search the screenpipe database (which contain ocr and audio data)
   - The classificationSerializer tool is used to serialize the results into a classification



Project Structure:
- Main app is in packages/desktop
- Frontend: packages/desktop/frontend (vite)
- Backend: packages/desktop/electron (electron)
- Preload (no node): packages/desktop/electron/preload.ts
- packages/landing-v0 containts landing page and in the future all account logins and signups (nextjs app dir)
- packages/request-invoice-web contains the invoice details page (nextjs app dir)


## Invoice Creation flow with Request network
Request Creation flow:
Starts in packages/desktop where the invoice is spotted, then pereared
but it is really created inside of the request-service.ts after it's created it's viewed inside of the request-invoice-web

- packages/desktop/
- packages/request-invoice-web
- packages/request-invoice-web/src/app/invoice/[requestId]/page.tsx
- packages/request-invoice-web/src/components/invoice-details.tsx

	UI and Styling:
	•	Integrate the shadcn/ui components library.
	•	Priority in UI design: Ease of Use > Aesthetics > Performance.
	•	Employ Tailwind CSS for utility-first styling and rapid UI development.

Recommended Libraries and Tools:
	1.	State Management:
	•	Use React Context API for simple state management needs.
	•	Use Zustand for lightweight, scalable state management compatible with React Server Components.
	2.	Form Handling:
	•	Employ React Hook Form for efficient, flexible form handling and built-in validation features.
	3.	Data Fetching:
	•	Use TanStack Query (React Query) for efficient data fetching, caching, and revalidation flows.
	4.	Authentication:
	•	Integrate authentication via Clerk.
	5.	Animations:
	•	Use Framer Motion for smooth animations and transitions.
	6.	Icons:
	•	Incorporate the Lucide React icon set for a wide array of open-source icons.

AI Integration with Vercel AI SDK:
	•	Utilize the Vercel AI SDK (TypeScript toolkit) to build AI-driven features in React/Next.js.
	•	Implement conversational UIs using the useChat hook, which manages chat states and streams AI responses.

Using Tools with useChat and streamText:
	•	Tool Types:
	•	Server-side tools auto-executed on the server.
	•	Client-side tools auto-executed on the client.
	•	User-interactive tools that require a confirmation dialog or user input.
	•	Workflow:
	1.	The user inputs a message in the chat UI.
	2.	The message is sent to the API route.
	3.	The language model may generate tool calls using streamText.
	4.	Tool calls are forwarded to the client.
	5.	Server-side tools execute server-side and return results to the client.
	6.	Client-side tools execute automatically via the onToolCall callback.
	7.	User-interactive tools display a confirmation dialog. The user’s choice is handled via toolInvocations.
	8.	After the user interacts, use addToolResult to incorporate the final result into the chat.
	9.	If tool calls exist in the last message and all results are now available, the client re-sends messages to the server for further processing.
	•	Note: Set maxSteps > 1 in useChat options to enable multiple iterations. By default, multiple iterations are disabled for compatibility reasons.

Example Implementation:
	•	API Route Example (app/api/chat/route.ts):

import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import { z } from 'zod';

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: openai('gpt-4o'),
    messages,
    tools: {
      // Server-side tool:
      getWeatherInformation: {
        description: 'Show the weather in a given city to the user.',
        parameters: z.object({ city: z.string() }),
        execute: async ({ city }: { city: string }) => {
          const weatherOptions = ['sunny', 'cloudy', 'rainy', 'snowy', 'windy'];
          return `${city} is currently ${weatherOptions[Math.floor(Math.random() * weatherOptions.length)]}.`;
        },
      },
      
      // Client-side, user-interactive tool:
      askForConfirmation: {
        description: 'Ask the user for confirmation.',
        parameters: z.object({
          message: z.string().describe('The message to ask for confirmation.'),
        }),
      },

      // Automatically executed client-side tool:
      getLocation: {
        description: 'Get the user location after confirmation.',
        parameters: z.object({}),
      },
    },
  });

  return result.toDataStreamResponse();
}


	•	generateObject() Usage Example:

import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';

const { object } = await generateObject({
  model: openai('gpt-4-turbo'),
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(z.string()),
      steps: z.array(z.string()),
    }),
  }),
  prompt: 'Generate a lasagna recipe.',
});

console.log(JSON.stringify(object, null, 2));


	•	Client-Side Page Example (app/page.tsx):

'use client';

import { ToolInvocation } from 'ai';
import { Message, useChat } from 'ai/react';
import { randomFill } from 'crypto'

export default function Chat() {
  const {
    messages,
    input,
    handleInputChange,
    handleSubmit,
    addToolResult,
  } = useChat({
    maxSteps: 5,
    async onToolCall({ toolCall }) {
      if (toolCall.toolName === 'getLocation') {
        const cities = ['New York', 'Los Angeles', 'Chicago', 'San Francisco'];
        return {
          city: cities[Math.floor(Math.random() * cities.length)],
        };
      }
    },
  });

  return (
    <>
      {messages?.map((m: Message) => (
        <div key={m.id}>
          <strong>{m.role}:</strong> {m.content}
          {m.toolInvocations?.map((toolInvocation: ToolInvocation) => {
            const toolCallId = toolInvocation.toolCallId;
            const addResult = (result: string) => addToolResult({ toolCallId, result });

            if (toolInvocation.toolName === 'askForConfirmation') {
              return (
                <div key={toolCallId}>
                  {toolInvocation.args.message}
                  <div>
                    {'result' in toolInvocation ? (
                      <b>{toolInvocation.result}</b>
                    ) : (
                      <>
                        <button onClick={() => addResult('Yes')}>Yes</button>
                        <button onClick={() => addResult('No')}>No</button>
                      </>
                    )}
                  </div>
                </div>
              );
            }

            return 'result' in toolInvocation ? (
              <div key={toolCallId}>
                <em>Tool ({toolInvocation.toolName}):</em> {toolInvocation.result}
              </div>
            ) : (
              <div key={toolCallId}>
                <em>Executing {toolInvocation.toolName}...</em>
              </div>
            );
          })}
          <br />
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} placeholder="Type your message..." />
      </form>
    </>
  );
}



Additional Notes:
	•	Ensure proper handling of all tool invocations to maintain a seamless user experience.
	•	Regularly update dependencies and libraries to their latest versions for improved performance, security, and stability.
	•	Thoroughly test the chatbot to handle edge cases and unexpected user inputs.

Access to Screenpipe:

This project uses a local service named screenpipe that watches screen and audio, storing data in a local database. The application (hyprsqrl) integrates with the screenpipe API (accessible at http://localhost:3030) to gather OCR data and other information, potentially using it to create tasks or calendar events.

Screenpipe API Reference:
	•	Search API:
	•	Endpoint: GET /search
	•	Description: Searches captured data (OCR text, audio transcription, UI elements) from the local database.
	•	Query Parameters:
	•	q (string, optional): A single-word search term.
	•	content_type (enum): One of ocr, audio, or ui.
	•	limit (int, default=20): Maximum results per page.
	•	offset (int): Pagination offset.
	•	start_time (timestamp, optional): Filter by start timestamp.
	•	end_time (timestamp, optional): Filter by end timestamp.
	•	app_name (string, optional): Filter by application name.
	•	window_name (string, optional): Filter by window name.
	•	include_frames (bool, optional): Include base64 encoded frame data.
	•	min_length (int, optional): Minimum content length.
	•	max_length (int, optional): Maximum content length.
	•	speaker_ids (int[], optional): Filter by speaker IDs.
Sample Request:

curl "http://localhost:3030/search?q=meeting&content_type=ocr&limit=10"

Sample Response:

{
  "data": [
    {
      "type": "OCR",
      "content": {
        "frame_id": 123,
        "text": "meeting notes",
        "timestamp": "2024-03-10T12:00:00Z",
        "file_path": "/frames/frame123.png",
        "offset_index": 0,
        "app_name": "chrome",
        "window_name": "meeting",
        "tags": ["meeting"],
        "frame": "base64_encoded_frame_data"
      }
    }
  ],
  "pagination": {
    "limit": 5,
    "offset": 0,
    "total": 100
  }
}


	•	Audio Devices API:
	•	Endpoint: GET /audio/list
	•	Description: Lists available audio input/output devices.
Sample Response:

[
  {
    "name": "built-in microphone",
    "is_default": true
  }
]


	•	Monitors (Vision) API:
	•	Endpoint: POST /vision/list
	•	Description: Lists available monitors/displays.
Sample Response:

[
  {
    "id": 1,
    "name": "built-in display",
    "width": 2560,
    "height": 1600,
    "is_default": true
  }
]


	•	Tags API:
	•	Endpoint (Add Tags): POST /tags/:content_type/:id
	•	Endpoint (Remove Tags): DELETE /tags/:content_type/:id
	•	Description: Manage tags for content items (vision or audio).
Add Tags Request Example:

{
  "tags": ["important", "meeting"]
}

Add Tags Response Example:

{
  "success": true
}


	•	Pipes API:
	•	Endpoints:
	•	GET /pipes/list (List pipes)
	•	POST /pipes/download (Download a pipe from a remote URL)
	•	POST /pipes/enable (Enable a specified pipe)
	•	POST /pipes/disable (Disable a specified pipe)
	•	POST /pipes/update (Update a pipe’s configuration)
Download Pipe Request Example:

{
  "url": "https://github.com/user/repo/pipe-example"
}

Enable Pipe Request Example:

{
  "pipe_id": "pipe-example"
}


	•	Speakers API:
	•	List Unnamed Speakers:
	•	Endpoint: GET /speakers/unnamed
	•	Query: limit, offset, speaker_ids
	•	Search Speakers:
	•	Endpoint: GET /speakers/search
	•	Query: name (string)
	•	Update Speaker:
	•	Endpoint: POST /speakers/update
	•	Request Body:

{
  "id": 123,
  "name": "john doe",
  "metadata": "{\"role\": \"engineer\"}"
}


	•	Delete Speaker:
	•	Endpoint: POST /speakers/delete
	•	Request Body:

{
  "id": 123
}


	•	Get Similar Speakers:
	•	Endpoint: GET /speakers/similar
	•	Query: speaker_id, limit
	•	Merge Speakers:
	•	Endpoint: POST /speakers/merge
	•	Request Body:

{
  "speaker_to_keep_id": 123,
  "speaker_to_merge_id": 456
}


	•	Mark as Hallucination:
	•	Endpoint: POST /speakers/hallucination
	•	Request Body:

{
  "speaker_id": 123
}


	•	Health API:
	•	Endpoint: GET /health
	•	Description: Retrieves system health status.
Sample Response:

{
  "status": "healthy",
  "last_frame_timestamp": "2024-03-10T12:00:00Z",
  "last_audio_timestamp": "2024-03-10T12:00:00Z",
  "last_ui_timestamp": "2024-03-10T12:00:00Z",
  "frame_status": "ok",
  "audio_status": "ok",
  "ui_status": "ok",
  "message": "all systems functioning normally"
}


	•	Stream Frames API:
	•	Endpoint: GET /stream/frames
	•	Description: Streams frames as Server-Sent Events (SSE).
	•	Query Parameters: start_time, end_time
Sample Request:

curl "http://localhost:3030/stream/frames?start_time=2024-03-10T12:00:00Z&end_time=2024-03-10T13:00:00Z"

Sample Event Data:

{
  "timestamp": "2024-03-10T12:00:00Z",
  "devices": [
    {
      "device_id": "screen-1",
      "frame": "base64_encoded_frame_data"
    }
  ]
}

Instructions for Other AI Agents:
	•	Strictly adhere to the above structure, styles, and naming conventions.
	•	Respect the described architectural and stylistic guidelines.
	•	Fully utilize the provided APIs, including the screenpipe API, to integrate OCR and other data into the application as needed.
	•	When implementing tools, ensure their correct registration, invocation, and result handling based on the described workflow.
	•	Follow the “ease of use” first design principle to ensure the final UI and user experience are smooth and intuitive.
	•	Keep all details about the “screenpipe” API to ensure correct interaction with its endpoints and data formats.

/**
 * Request Creation Flow
 * 
 * The request creation process follows a specific flow triggered by events:
 *  PART 1: in packages/desktop
 * 1. Event Recognition & Classification:
 *    - Screen content is continuously monitored by screenpipe API
 *    - Event Classification component analyzes content using GPT-4
 *    - Classifies content into types (task, event, invoice, goal)
 *    - Extracts vital information and creates RecognizedItem
 * 
 * 2. Invoice Agent Activation:
 *    - When classification identifies invoice-type content
 *    - InvoiceAgent receives RecognizedContext with vital information
 *    - Renders InvoiceAgentUI with "Prepare Invoice" button
 * 
 * 3. Context Parsing:
 *    - On "Prepare Invoice" click, parseContext() is called
 *    - Uses GPT-4o to extract structured invoice data
 *    - Follows Request Network Format (RNF)
 *    - Transforms raw data into Invoice format
 * 
 * 4. Invoice Form:
 *    - Displays pre-filled form with parsed data
 *    - Allows user to review and modify details
 *    - Handles validation using invoiceFormSchema
 *    - Supports multiple invoice items
 * 
 * 5. Request Creation:
 *    - On form submit, creates ICreateRequestParameters
 *    - Calls window.api.createInvoiceRequest
 *    - Request goes to main process via preload API
 *    - RequestService creates and confirms request
 *    - Returns success with requestId
 * 
 * 6. Post Creation:
 *    - Generates shareable invoice URL
 *    - Shows success toast with URL
 *    - URL copied to clipboard
 * 
 * PART 2: in packages/request-invoice-web
 * 7.  Invoice viewable in InvoiceDetails component (which is a web app)
 *  - Users see the denonmiated invoice detaisl but when they pay it will convert it to pay currency (ideally live) 
 * 
 * Key Components:
 * - EventClassification: Monitors and classifies screen content
 * - InvoiceAgent: Handles invoice-specific logic
 * - InvoiceForm: UI for review and submission
 * - RequestService: Backend service for blockchain interaction
 */


## Request network randomFillexport interface Invoice {
    meta: {
        format: 'rnf_invoice';
        version: string;
    };
    buyerInfo?: ActorInfo;
    creationDate: string;
    invoiceItems: InvoiceItem[];
    invoiceNumber: string;
    miscellaneous?: unknown;
    note?: string;
    paymentTerms?: PaymentTerms;
    purchaseOrderId?: string;
    sellerInfo?: ActorInfo;
    terms?: string;
}
export interface InvoiceItem {
    currency: string;
    deliveryDate?: string;
    deliveryPeriod?: string;
    discount?: string;
    name: string;
    quantity: number;
    reference?: string;
    /**
     * @deprecated since 0.0.3. Use tax instead
     */
    taxPercent?: number;
    tax: Tax;
    unitPrice: string;
}
export interface Tax {
    type: 'percentage' | 'fixed';
    amount: string;
}
export interface ActorInfo {
    address?: Address;
    businessName?: string;
    email?: string;
    firstName?: string;
    lastName?: string;
    miscellaneous?: unknown;
    phone?: string;
    taxRegistration?: string;
}
export interface PaymentTerms {
    dueDate?: string;
    lateFeesFix?: string;
    lateFeesPercent?: number;
    miscellaneous?: unknown;
}
export interface Address {
    'country-name'?: string;
    'extended-address'?: string;
    locality?: string;
    'post-office-box'?: string;
    'postal-code'?: string;
    region?: string;
    'street-address'?: string;
}
//# sourceMappingURL=types.d.ts.map
clerk
css
golang
html
javascript
less
next.js
npm
+10 more

First seen in:

different-ai/hypr-v0

Used in 1 repository

JavaScript
# DEGEN ORACLE AI - Project Guidelines & Rules

## Core Purpose
- Build a tool for discovering and analyzing new AI tokens on Solana
- Set up real-time AI token scanning every 10 minutes
- Focus on filtering and tracking high-potential tokens
- Provide essential data for investment decisions

## Core Purpose
- Primary Objectives:
  * Build an advanced AI token discovery and analysis platform on Solana
  * Automate the identification of high-potential AI and Agent tokens
  * Provide comprehensive analysis tools for informed investment decisions
  * Enable real-time monitoring and alerts for market opportunities

- Token Discovery:
  * Continuous scanning every 10 minutes for new AI tokens
  * Data Sources:
    - Birdeye API (Primary source)
    - Jupiter Aggregator API (Secondary)
    - SERUM DEX API (Secondary)
    - Solscan API (Contract verification)
  * Historical Data Retention:
    - Price & Metrics: 30 days
    - Scan History: 7 days
    - Social Metrics: 14 days
  * Data Collection Frequency:
    - Price Data: Every 1 minute
    - Market Data: Every 5 minutes
    - Social Data: Every 15 minutes
    - Contract Data: Every 30 minutes

- Analysis Capabilities:
  * Multi-source data integration (Birdeye, LunarCrush, YAPS, Cookie)
  * Advanced sentiment analysis from social media and AI communities
  * Technical analysis and pattern recognition
  * Risk assessment and growth prediction

- User Experience:
  * Intuitive interface for token discovery and analysis
  * Customizable watchlists and alerts
  * Real-time notifications via Telegram
  * Detailed token insights and metrics

- Platform Intelligence:
  * AI-powered pattern recognition
  * Machine learning for growth prediction
  * Automated strategy generation
  * Continuous learning from successful tokens

- Risk Management:
  * Comprehensive token validation
  * Scam and honeypot detection
  * Liquidity and holder analysis
  * Market manipulation detection

## Key Features Priority
1. Market Trends
   - Current Trend Analysis:
     * Display dominant token categories
     * Key Metrics:
       - Volume Growth
       - New Tokens Count
       - Social Engagement
       - Price Performance
     * Time Ranges: 24h, 7d, 30d
   - Emerging Trends Detection:
     * Early Signals:
       - Social Media Mentions
       - New Projects Launch Rate
       - Developer Activity
       - VC Investments
       - Community Growth
   - Dashboard Components:
     * Key Metrics Cards:
       - Total AI Market Cap
       - 24h Volume
       - Total AI Tokens
       - Hot Trend
     * Charts:
       - Category Performance Chart (30d)
       - Emerging Trends Chart
       - Social Sentiment Analysis
     * Data Tables:
       - Trending Categories with:
         * Category Name
         * 24h Volume
         * Volume Change
         * Number of Tokens
         * Top Token in Category
         * Price & Change
   - Auto Refresh: Every 5 minutes
   - Interactive Elements:
     * Time Range Selectors
     * Category Filters
     * Drill-down Capabilities

2. Token Discovery
   - Unified interface for finding potential tokens
   - Two Discovery Modes:
     * AI Recommendations:
       - Automatic scanning by AI model
       - Smart filtering based on growth potential
       - Real-time updates every 10 minutes
       - Growth prediction scores
       - Risk assessment
     * Manual Scanner:
       - User-defined parameters:
         * Market Data:
           - Min/Max Market Cap (Default Min: 50,000 USD)
           - Min/Max Liquidity (Default Min: 30,000 USD)
           - Min/Max Price
         * Holders & Distribution:
           - Min/Max Holders (Default Min: 100)
           - Min/Max Top 10 Holders Percentage
         * Volume & Activity:
           - Min Hourly Volume
           - Min Hourly Transactions
           - Max Token Age (in days)
         * Performance:
           - Min 1h Price Change
           - Min 24h Price Change
         * Risk & Validation:
           - Require Verified Contract (Default: Yes)
           - Require Social Media (Default: Yes)
       - Custom filters and sorting
       - On-demand scanning
   - Common Features:
     * Token validation & verification
     * Quick analysis tools
     * Add to watchlist functionality
     * Scan history tracking
     * Risk indicators
   - Display Columns:
     * Token Info (Logo, Name, Symbol)
     * Market Data (Price, MCap, Volume)
     * Performance Metrics
     * Social Links
     * Risk Score
     * Actions (Add/Remove from Watchlist)

3. Watchlist
   - Track selected tokens from Discovery
   - Custom alert settings per token
   - Alert Conditions:
     * Price change >= 10%
     * Volume increase >= 100%
     * Holders increase >= 20%
   - Performance monitoring
   - Risk tracking
   - Quick actions (Remove, Set Alerts)

4. Token Analysis
   - Basic Info: Market Cap, Holders, Volume
   - Social Metrics from LunarCrush
     * Twitter Followers & Growth
     * Telegram Members & Growth
     * Social Engagement Score
     * Sentiment Analysis
   - Additional Sentiment Analysis
     * Twitter Sentiment (YAPS)
     * AI Agent Sentiment (Cookie)
     * Combined Sentiment Score
     * Sentiment Trend Analysis
   - Price & Trading Analysis from Birdeye
     * Price Action & Volatility
     * Volume Analysis
     * Liquidity Analysis
     * Trading Patterns
   - Holder Analysis & Distribution
     * Top Holders Distribution
     * Holder Growth Rate
     * Average Holding Time
     * Wallet Behavior Analysis
   - Community Growth & Engagement
   - Risk Assessment

5. Market Trends & AI Learning
   - Analyze Market Trends from LunarCrush
     * Trending Categories
     * Social Volume Trends
     * Sentiment Trends
     * Influencer Activity
   - Learn Patterns from Successful Tokens
     * Launch Patterns
     * Growth Patterns
     * Volume Patterns
     * Social Patterns
   - Generate Trading Strategies
   - Alert on Pattern Matches
   - AI Growth Prediction
     - Growth Probability Prediction
       * Short-term (24h)
       * Mid-term (7d)
       * Long-term (30d)
     - Growth Factor Analysis
     - Prediction Confidence Assessment

6. Token Detail View
   - Basic Information:
     * Token Logo & Name
     * Contract Address (with copy & explorer link)
     * Launch Date & Age
     * Tags & Categories
     * Social Links (Website, Twitter, Telegram)
     * Contract Verification Status

   - Market Overview:
     * Current Price & Changes (1h, 24h, 7d)
     * Market Cap & Fully Diluted Valuation
     * Trading Volume (24h)
     * Liquidity Information:
       - Total Liquidity
       - Liquidity Pairs
       - Liquidity Locks

   - Trading Analysis:
     * DEX Information:
       - Trading Pairs
       - Volume Distribution
       - Price Impact Analysis
     * Buy/Sell Ratio (24h)
     * Large Transactions (>$1000)
     * Trading History

   - Holder Analysis:
     * Total Holders Count & Growth
     * Distribution Chart:
       - Top 10/50/100 Holders
       - Holder Concentration
     * Holder Type Analysis:
       - Normal Wallets
       - Contracts
       - DEX Pairs
     * Recent Holder Changes

   - Social & Community:
     * Twitter Metrics:
       - Followers & Growth
       - Engagement Rate
       - Recent Tweet Performance
     * Telegram Metrics:
       - Member Count & Growth
       - Active Members
       - Message Frequency
     * Overall Social Score
     * Community Sentiment Analysis

   - Risk Assessment:
     * Contract Risk Score:
       - Code Analysis
       - Ownership Status
       - Mint/Burn Functions
     * Liquidity Risk:
       - Lock Status
       - Concentration
     * Trading Risk:
       - Price Manipulation Signs
       - Wash Trading Detection
     * Overall Risk Score

   - Quick Actions:
     * Add to Watchlist
     * Set Custom Alerts
     * Share Token
     * View on Explorer

   - Data Sources:
     * Birdeye (Market Data)
     * Jupiter (DEX Data)
     * LunarCrush (Social Data)
     * Solscan (Contract Data)

## Database Schema
1. Tokens
   - Basic Info (address, name, symbol)
   - Market Data (price, mcap, volume)
   - Social Metrics
   - Analysis Results
   - Category & Tags
   - Launch Info
   - Contract Analysis
   - Risk Metrics
   - Trading History
   - Price Predictions
   - Pattern Matches
   - Risk Scores
   - Social Sentiment
   - Community Metrics
   - Historical Price Data
   - Token Supply Information
   - Token Distribution Metrics
   - Smart Contract Audit Results
   - First Seen Date
   - Last Updated Timestamp

2. ScanHistory
   - Scan Parameters
   - Results
   - Timestamp
   - Performance Metrics
   - Discovered Tokens
   - Filter Settings
   - Execution Time
   - Error Logs
   - Success Rate
   - Processing Time
   - Resource Usage
   - Scan Type (Manual/Auto)
   - Tokens Found Count
   - New Tokens Count
   - Scan Status

3. Watchlist
   - User Settings
   - Token References
   - Alert Settings
   - Notes & Tags
   - Custom Alerts
   - Entry Points
   - Risk Levels

4. AIModels
   - Training Data
   - Model Parameters
   - Performance Metrics
   - Strategy Rules
   - Prediction Models
     - Growth Prediction Model
     - Confidence Metrics
     - Historical Accuracy
     - Feature Importance
     - Model Versions
     - Training History
     - Validation Results

## API Integration
1. Birdeye API
   - Token Discovery
   - Market Data
   - Trading Analytics
   - Rate Limits: 60 calls/minute
   - Cache Duration: 5 minutes
   - Error Handling Strategy

2. LunarCrush API
   - Social Metrics
   - Market Trends
   - Sentiment Analysis
   - Rate Limits: 30 calls/minute
   - Cache Duration: 15 minutes
   - Fallback Strategy

3. YAPS API
   - Twitter Sentiment Analysis
   - Social Media Monitoring
   - Real-time Sentiment Tracking
   - Rate Limits: TBD
   - Cache Duration: 15 minutes

4. Cookie API
   - AI Agent Sentiment Analysis
   - Community Engagement Metrics
   - Agent Behavior Tracking
   - Rate Limits: TBD
   - Cache Duration: 15 minutes

5. Telegram API
   - Alert Notifications
   - Status Updates
   - Command Interface
   - Custom Commands:
     * /scan - Manual scan
     * /add <address> - Add to watchlist
     * /alerts - View active alerts
     * /predict <address> - Get prediction

6. Rate Limiting Strategy
   - Token Bucket Algorithm
   - Queue Management
   - Priority Levels:
     * Critical Operations
     * Regular Operations
     * Background Tasks
   - Retry Policies
   - Circuit Breaker Pattern

## AI Components
1. Token Classifier
   - AI/Agent Detection
   - Category Classification
   - Risk Assessment

2. Pattern Recognition
   - Price Pattern Analysis
   - Volume Pattern Analysis
   - Social Trend Analysis

3. Strategy Generator
   - Learn from Historical Data
   - Generate Trading Rules
   - Optimize Parameters

4. Growth Predictor
   - Market Cap Growth Prediction
   - Volume Growth Prediction
   - Social Growth Prediction
   - Confidence Scoring
   - Key Growth Factors Analysis

## Monitoring & Alerts
1. Price Alerts
   - Percentage Changes
   - Support/Resistance Levels
   - Volume Spikes
2. Social Alerts
   - Engagement Spikes
   - Sentiment Changes
   - New Announcements
3. Pattern Alerts
   - Strategy Matches
   - Risk Warnings
   - Opportunity Signals
4. Growth Prediction Alerts
   - High Growth Potential Alerts
   - Growth Pattern Recognition
   - Confidence Level Updates
   - Factor Change Notifications
5. Token Health Monitoring
   - Smart Contract Activity
   - Liquidity Pool Changes
   - Unusual Trading Patterns
   - Whale Movement Detection
   - Token Burn/Mint Events
6. Telegram Notifications Only
   - Alert Types:
     - Price change ≥ 10%
     - Volume increase ≥ 100%
     - Holders increase ≥ 20%
   - Alert Limits:
     - Maximum 50 alerts per day
     - 30 minutes cooldown between alerts

## Future Considerations
- Add more categories (Sci-Fi, Meme, etc)
- Portfolio Tracking
- Advanced Analytics
- Community Features

## Minimum Requirements
1. Token Criteria
   - Market Cap >= 50,000 USD
   - Holders >= 100
   - Liquidity >= 30,000 USD
   - At least 1 active social media platform
   - Contract verified
   - No honeypot/scam patterns

2. Performance Requirements
   - Scan completion within 30 seconds
   - API response time < 2 seconds
   - Real-time data updates
   - System uptime > 99.9%

3. Security Requirements
   - API authentication
   - Rate limiting
   - Data encryption
   - Input validation
   - XSS protection

## Error Handling
1. API Errors
   - Rate limit exceeded
   - Service unavailable
   - Invalid response
   - Timeout handling
   - Retry mechanisms

2. Data Validation
   - Input sanitization
   - Format verification
   - Range checking
   - Null handling

3. Recovery Procedures
   - Automatic retry
   - Fallback options
   - Data reconciliation
   - Alert notifications

## Testing Strategy
1. Unit Tests
   - API integration
   - Data processing
   - Pattern recognition
   - Alert generation

2. Integration Tests
   - End-to-end flows
   - API chaining
   - Data consistency

3. Performance Tests
   - Load testing
   - Stress testing
   - Scalability testing
   - Memory usage

## Deployment
1. Infrastructure
   - Cloud hosting
   - Load balancing
   - Auto-scaling
   - CDN integration

2. Monitoring
   - System health
   - Performance metrics
   - Error tracking
   - Resource usage

3. Maintenance
   - Regular updates
   - Database optimization
   - Cache management
   - Log rotation

## Documentation
1. Technical Docs
   - API documentation
   - Database schema
   - System architecture
   - Integration guides

2. User Guides
   - Feature tutorials
   - Configuration guides
   - Troubleshooting
   - FAQs

## Technical Stack
1. Frontend
   - Framework: React + TypeScript
   - State Management: React Context
   - Styling:
     * TailwindCSS
     * Heroicons
     * Material UI components
   - Charts & Visualization:
     * TradingView Lightweight Charts
     * Recharts
     * D3.js
   - Development Tools:
     * Vite
     * ESLint
     * Prettier

2. Backend
   - Language: Python 3.9+
   - Framework: FastAPI
   - Database:
     * PostgreSQL
     * Redis (caching)
   - ORM: SQLAlchemy
   - Task Queue: Celery
   - WebSocket: FastAPI WebSocket

3. External APIs & SDKs
   - Blockchain:
     * Birdeye API
     * Solana Web3.js
     * @solana/web3.js
   - Social Analytics:
     * LunarCrush API
   - Messaging:
     * Telegram Bot API
     * python-telegram-bot

4. DevOps & Infrastructure
   - Containerization:
     * Docker
     * Docker Compose
   - Cloud Services:
     * AWS ECS/EKS
     * AWS RDS
     * AWS ElastiCache
     * AWS CloudFront
   - Monitoring:
     * Prometheus
     * Grafana
     * Sentry

5. Security Tools
   - Authentication:
     * JWT
     * OAuth2
   - API Security:
     * API Key management
     * Rate limiting (FastAPI-limiter)
   - Data Encryption:
     * Python cryptography
     * SSL/TLS

6. Testing Tools
   - Frontend:
     * Jest
     * React Testing Library
     * Cypress
   - Backend:
     * pytest
     * pytest-asyncio
     * pytest-cov
   - Load Testing:
     * Locust
     * k6

7. Development Environment
   - IDE:
     * VSCode
     * PyCharm
   - Version Control:
     * Git
     * GitHub
   - Documentation:
     * Swagger/OpenAPI
     * Sphinx
     * MkDocs

## UI/UX Design
1. Theme
   - Dark Theme Primary
   - Color Palette:
     * Background: #000000
     * Secondary Background: #111111
     * Primary: #00FF00
     * Secondary: #1A1A1A
     * Text Primary: #FFFFFF
     * Text Secondary: #888888
     * Border: #333333
     * Success: #00FF00
     * Error: #FF0000
     * Warning: #FFB800

2. Layout
   - Top Navigation Bar
   - Main Content Area
   - Status Bar below Nav
   - Clean, Minimal Design
   - Full-width Layout
   - Grid-based Content Layout

3. Components
   - Dashboard:
     * Layout:
       - Top Row: Key Metrics Cards
       - Middle Row: Performance & Trends Charts
       - Bottom Row: Tables & Social Sentiment
     * Card Styles:
       - Background: #111111
       - Border: #333333
       - Hover Effect: Subtle glow
       - Metrics: Large numbers
       - Change %: Color coded (green/red)
     * Chart Styles:
       - Dark theme compatible
       - Interactive tooltips
       - Gradient fills
       - Legend with toggle
     * Responsive Layout:
       - Desktop: 3-column grid
       - Tablet: 2-column grid
       - Mobile: Single column
   - Tables:
     * Modern, Clean Design
     * Hover Effects
     * Gradient Borders
     * Compact Information Display
     * Quick Actions on Hover
     * Integrated Filters
     * Smart Pagination
     * Scanner Table Styles:
       - Scanner Filters:
         - Default Values:
           * Min Market Cap: 50,000 USD
           * Min Holders: 100
           * Min Liquidity: 30,000 USD
         - Input Styles:
           * Background: Black
           * Border: #333333
           * Focus: Primary color (#88D693)
           * Text: White
           * Labels: Gray (text-gray-400)
         - Layout:
           * Grid: 3 columns
           * Spacing: gap-4
           * Container: Dark background (#111111)
           * Padding: p-4
           * Border: #333333
       - Colors:
         * MCap: Yellow (rgb(255,208,57)) for >=1M, White for default
         * Volume: Blue (rgb(147,197,253)) for >=1M, White for default
         * Holders: Blue (rgb(147,197,253)) for >=1K, White for default
         * Price Changes: Green (#88D693) for positive, Red (rgb(240,148,164)) for negative
         * Dev Actions: Yellow for HOLD, Green for ADD, Red for SELL_ALL
         * Watchlist Star: Gray (text-gray-500) default, Yellow (rgb(255,208,57)) when active
       - Typography:
         * Text size: text-xs
         * Headers: text-sm
       - Column Layout:
         * Watchlist Star: Left-most position, toggleable
         * Token: Logo + Name + Copy Button + Shortened CA + Social Icons
         * Age: Days count
         * Liq/MCap: Two-line display (Liq top, MCap bottom)
         * Numeric Columns: Right-aligned with units
         * Action Columns: Center-aligned
   - Charts:
     * Minimal TradingView Charts
     * Neon Accent Lines
     * Dark Background
     * Grid Lines in Secondary Color
     * Tooltip with Detailed Info
   - Forms:
     * Minimal Input Fields
     * Neon Focus Effects
     * Custom Dropdowns
     * Toggle Switches with Glow
     * Search with Auto-suggest
   - Alerts:
     * Floating Notifications
     * Minimal Design
     * Success/Error Indicators
     * Auto-dismiss
     * Position: Top-Right

4. Responsive Design
   - Desktop first
   - Tablet support
   - Mobile view (limited features)

## Scanner View Standards
1. Layout Structure:
  - Filters Panel (Left/Top)
  - Results Table (Main Area)
  - Quick Actions (Right)

2. Filter Components:
  - Market Data Filters:
    * Market Cap Range
    * Liquidity Range
    * Volume Range
    * Price Range
  - Holder Filters:
    * Total Holders
    * Top Holders %
    * Holder Growth Rate
  - Risk Filters:
    * Contract Verification
    * Liquidity Lock
    * Sniper Detection
    * Insider Activity

3. Results Table:
  - Columns:
    * Token Basic Info (Logo, Name, Symbol)
    * Market Metrics (MCap, Liq, Vol)
    * Holder Info (Count, Distribution)
    * Risk Indicators
    * AI Score
    * Quick Actions
  - Sorting:
    * Default: Latest First
    * Multiple Sort Options
  - Pagination:
    * 25 items per page
    * Load More functionality

4. Data Updates:
  - Auto-refresh: Every 30 seconds
  - Manual refresh option
  - Last updated indicator

5. Visual Indicators:
  - Risk Levels:
    * Safe: #88D693
    * Warning: rgb(255,208,57)
    * Danger: rgb(240,148,164)
  - Changes:
    * Positive: #88D693
    * Negative: rgb(240,148,164)
  - Status:
    * Active: #88D693
    * Inactive: text-gray-400

6. Performance Requirements:
  - Initial load: < 2 seconds
  - Filter updates: < 500ms
  - Sort updates: < 200ms
  - Memory usage optimization

## Token Detail View Standards
1. Visual Hierarchy:
  - Primary Metrics: Large text (text-xl/2xl), prominent colors
  - Secondary Metrics: Medium text (text-lg), standard colors
  - Supporting Info: Small text (text-sm), muted colors

2. Color Coding:
  - Success/Positive: #88D693
  - Warning/Neutral: rgb(255,208,57)
  - Danger/Negative: rgb(240,148,164)
  - Info/Links: rgb(147,197,253)
  - Muted Text: text-gray-400

3. Card Layout:
  - Standard Padding: p-4
  - Rounded Corners: rounded-lg
  - Background: bg-[#1A1A1A]
  - Header Format:
    * Icon + Title
    * Optional Status Badge
    * Consistent spacing (space-x-2)

4. Data Presentation:
  - Numbers: Use formatNumber() for large numbers
  - Percentages: Use formatPercent()
  - Time: Relative format (e.g., "2h ago")
  - Status: Icon + Text combination

5. Section Order Priority:
  1. Basic Information & Quick Stats
  2. Market Overview & Trading Analysis
  3. Holder Analysis & Social Metrics
  4. Risk Assessment
  5. AI Analysis & Recommendations
  6. Additional Details (Development, Team, etc.)

6. Interactive Elements:
  - Buttons: Consistent hover states
  - Links: Clear visual indicators
  - Charts: Interactive tooltips
  - Copy Functions: Visual feedback

7. Mobile Responsiveness:
  - Stack columns on smaller screens
  - Adjust font sizes for readability
  - Maintain data hierarchy

8. Required Data Sources:
  - Price/Market: Birdeye API
  - Social: LunarCrush API
  - Contract: Solscan API
  - Sentiment: YAPS/Cookie API

9. Update Frequencies:
  - Price Data: Real-time/1min
  - Market Data: 5min
  - Social Data: 15min
  - Risk Analysis: 30min
analytics
aws
css
cypress
docker
eslint
fastapi
golang
+15 more

First seen in:

twutc88/degen-oracle-ai

Used in 1 repository