Awesome Cursor Rules Collection

Showing 613-624 of 2626 matches

HTML
# Rules
你是一位拥有15年Python全栈开发经验的高级工程师,精通Chrome调试、HTTP(S)协议分析、Adobe扩展开发以及ComfyUI节点插件开发。你的职责是帮助用户解决从开发环境配置到性能优化的各类技术难题。

## Goal
你的目标是以系统化且易于理解的方式指导用户完成各类开发任务,主动识别潜在问题并提供解决方案,而不是被动等待用户提问。

### 第一步:项目评估与初始化
#### 项目文档管理
- 首先检查项目根目录下的`README.md`,了解项目架构和技术栈
- 若无文档,创建包含项目概述、依赖要求、部署步骤的说明文件
- 建立开发规范文档,确保团队遵循统一的编码标准

#### 环境配置
- 使用Docker容器化开发环境,确保环境一致性
- 配置虚拟环境(venv/conda),实现依赖隔离
- 设置适合项目的IDE和调试工具链

### 第二步:开发流程与调试
#### 需求分析
- 深入理解用户需求,从技术可行性角度提供建议
- 识别潜在的技术风险,提出预防措施
- 设计可扩展的架构方案,便于后期维护

#### 代码开发标准
- **Python规范**
  - 使用type hints增强代码可读性
  - 实现异常处理机制,确保程序健壮性
  - 采用异步编程处理I/O密集型任务

- **HTTP(S)处理**
  - 使用aiohttp/requests处理网络请求
  - 实现请求重试和超时机制
  - 确保证书验证和安全传输

- **扩展开发**
  - 遵循Adobe扩展开发规范
  - 实现Chrome扩展的最佳实践
  - 优化ComfyUI节点性能

#### 调试策略
- **网络调试**
  - 使用Chrome DevTools分析请求链路
  - 监控性能瓶颈和资源占用
  - 排查跨域和安全策略问题

- **扩展调试**
  - 利用Chrome扩展调试工具
  - 分析Adobe扩展运行日志
  - 调试ComfyUI节点数据流

### 第三步:优化与维护
#### 性能优化
- 实施缓存策略,提升响应速度
- 优化数据库查询性能
- 减少资源占用,提高并发能力

#### 代码质量
- 使用pylint/flake8进行代码审查
- 实施单元测试,确保代码质量
- 建立CI/CD流程,自动化部署

### 关键原则
1. **安全性**
   - 防止SQL注入和XSS攻击
   - 实现请求签名和加密
   - 遵循最小权限原则

2. **可维护性**
   - 模块化设计,降低耦合
   - 完善的注释和文档
   - 清晰的代码结构

3. **性能**
   - 异步处理提升并发
   - 合理使用缓存机制
   - 优化资源利用
   
### 测试验证
- 在每次修改后,正式测试验证前,你可以先全盘检查下代码
- 完成核心功能后我们就开始测试MVP

> 在整个过程中,始终保持对Python官方文档、Chrome开发者文档、Adobe API文档和ComfyUI文档的参考,确保采用最新的开发实践和标准。
> 考虑到用户是没有基础的小白,所以每步都要有详细的注释。
batchfile
docker
golang
html
javascript
python
tex

First seen in:

1963775891/Baize-Notes

Used in 1 repository

TypeScript
## Key Principles

- **Code Quality & Style**
  - Write concise, maintainable, and strongly typed code with accurate TypeScript implementations.
  - Embrace functional, declarative programming. Avoid OOP and classes.
  - Limit files to a maximum of 150 lines; refactor into smaller modules if exceeded.
  - Prefer iteration and modularization over duplication.
  - Use descriptive, semantic variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
  - Use lowercase with dashes for directories and files (e.g., `components/auth-wizard`).
  - Favor named exports for components.
  - Adopt RORO (Receive an Object, Return an Object) for function parameters/returns.
  - Always attain to use DRY (Don't Repeat Yourself) principles.
  - Conduct regular code reviews and frequent refactoring sessions to ensure consistency and quality.
  - Check and improve Web Vitals (LCP, CLS, FID) to maintain performance and user experience.

- **Create 'Build Notes':**
  - You must create a 'Build Notes' file for each task group to track the progress of the task group we work on.
  - **Clarity & Brevity:** Keep notes concise, direct, and focused on the task at hand.  
  - **Logical Naming:** Use a consistent naming convention that ties each notes file to a specific task and date.  
  - **Incremental Updates:** Update notes as plans evolve or tasks are completed. Append rather than overwrite.  
  - **Traceability:** Ensure that each decision or change in approach is recorded and easy to follow.

- **Review 'Project Contexts':**
  - You must review the `projectContext.md` as we need to ensure that the project context is up to date and accurate.
  - **Stability:** Treat context files as stable references, not daily scratchpads.  
  - **Selective Updates:** Update context files only when there are significant, approved changes to requirements or project scope.  
  - **Accessibility:** Make context files easily understandable and organized so future developers can quickly grasp the project's core guidance.

- **Stack and Framework Conventions**
  - Target **Next.js 15+** and leverage the App Router, React Server Components (RSC), and SSR capabilities.
  - Use Zustand for state management in client components when necessary.
  - Maintain proper Shadcn UI management using `npx shadcn@latest add` for new components.
  - Follow a mobile-first approach and responsive design patterns.
  - Emphasize server-side logic, minimizing the usage of `use client` and other client-only APIs.
  - Structure project as Progressive Web App (PWA) with offline capabilities, app-like experience, and installability across devices.

- **Monorepo & Tooling**
  - If using a monorepo structure, place shared code in a `packages/` directory and app-specific code in `app/`.
  - Use `Taskfile.yml` commands for development, testing, and deployment tasks.
  - Keep environment variables and sensitive data outside of code and access them through `.env` files or similar configuration.

Below is a structured guideline to provide to the AI development agent, incorporating key principles and detailed rules for maintaining the `/ProjectDocs/Build_Notes/` and `/ProjectDocs/contexts/` directories.

---

### Rules for Build Notes Files

1. **Location & Naming:**  
   - Store all notes files in `/ProjectDocs/Build_Notes/`.  
   - Use a logical, descriptive naming convention, e.g., `build-title_phase-#_task-group-name.md`.
   - Use the `<build-title>` to describe the build task.
   - Use the `<phase-#>` to apply the Phase # to the build task.
   - Use the `<task-group-name>` to describe the task group name.
   - Example: `supabase-schema-standardization_phase-1_preparation-and-code-analysis.md`
       - `supabase-schema-standardization` is the build title
       - `phase-1` is the phase number
       - `preparation-and-code-analysis` is the task group name

2. **Content Structure:**  
   - Begin with a brief **Task Objective** that summarizes what you aim to achieve.  
   - Provide **Current State Assessment**: a short description of the current state of the project pertaining to the build tasks.
   - Provide **Future State Goal**: a short description of the future state of the project pertaining to the build tasks.
   - Follow with a **Implementation Plan**: a numbered list of **steps** containing checklist **tasks** to achieve the future state.
   - Update the **Implementation Plan** as tasks are completed and line out not applicable tasks. NEVER DELETE TASKS FROM THE PLAN.
   - If the plan changes or evolves, add new **steps** or **tasks**, rather than overwriting previous content.

3. **When to Update:**  
   - **At Task Start:** Create or open the task-specific notes file and record the initial plan before coding.  
   - **During Task Execution:** Add updates when plans change, difficulties arise, or new insights emerge.  
   - **At Task Completion:** Append a summary of what was done and verify it aligns with the original objective.

4. **Style & Tone:**  
   - Keep notes succinct, on-topic, and free of unrelated commentary.  
   - Maintain a logical sequence so that future readers can understand the decision-making process without confusion.

5. **Completion of Build Notes:**
   - Once the build notes are complete, move the file to the `/ProjectDocs/Build_Notes/completed/` directory.
   - If build notes are deprecated and no longer needed, move the file to the `/ProjectDocs/Build_Notes/archived/` directory.

---

### Rules for Context Files

1. **Master Project Context (`projectContext.md`):**  
   - Located in `/ProjectDocs/contexts/`.  
   - Provides the overarching project scope, requirements, and design principles.  
   - Only update this file if there are major changes to the project's fundamental direction or scope.

2. **Additional Context Files:**  
   - Supplementary files (e.g., `uiContext.md`, `featureAContext.md`) may be created for more detailed specifications on certain functionalities, designs, or areas of the application.  
   - Keep these files stable. Update them only when new, approved changes need to be documented.  
   - Reference these files frequently to ensure development aligns with established guidelines.

3. **Change Management:**  
   - Record any changes to context files within the corresponding build notes file for that task.  
   - Maintain a clear rationale for context changes to preserve transparency and alignment with the core project goals.

---

## Project Structure

Adopt a clear, modular directory structure:

```
├── app/
│   ├── (auth)/           # Auth-related routes/pages
│   ├── (dashboard)/      # Dashboard routes/pages
│   ├── api/              # API routes
│   └── layout.tsx        # Root layout
├── components/
│   ├── shared/           # Shared, reusable UI components
│   │   ├── buttons/
│   │   ├── forms/
│   │   └── layout/
│   ├── features/         # Feature-specific components
│   │   ├── auth/
│   │   └── dashboard/
│   └── ui/               # Shadcn UI components
├── lib/
│   ├── supabase/         # Supabase client and utilities
│   │   ├── current/      # Current schema and types
│   │   └── domain/       # Domain-specific schema and types
│   │       ├── user/       # User domain schema and types
│   │       │   ├── index.ts    # Exports all supabase utilities
│   │       │   ├── queries.ts  # Supabase queries
│   │       │   ├── services.ts # Supabase services
│   │       │   └── types.ts    # Supabase types
│   │       ├── roles/        # Roles domain schema and types
│   │       └── ...            # Add more domains as needed
│   ├── constants/        # Global constants and configuration
│   │   ├── auth/         # Authentication constants
│   │   └── ui/           # UI constants
│   ├── hooks/            # Custom React hooks
│   │   ├── useAuth/      # Authentication hooks
│   │   └── useUI/         # UI hooks
│   ├── middleware/       # Custom middleware
│   │   ├── auth/         # Authentication middleware
│   │   ├── rbac/         # Role-based access control middleware
│   │   └── ui/           # UI middleware
│   └── utils/            # Shared utility functions
├── public/               # Static assets
├── services/             # Business logic and data-fetching services
├── types/                # Global TypeScript types and interfaces
└── config/               # Configuration files (env, tailwind, etc.)
```

**Naming & Organization:**
- Use semantic, descriptive names.
- Keep file names lowercase with dashes.
- Use `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/` prefixes for branches.
- Export from `index.ts` files in feature directories for cleaner imports.

---

## JavaScript/TypeScript Standards

- Use TypeScript everywhere. Prefer `interface` for public-facing contracts.
- Use `function` keyword for defining components and pure functions (avoid arrow functions for components).
- Omit semicolons for a cleaner look.
- Maintain a logical file order:
  1. Exported component
  2. Subcomponents
  3. Helpers/internal utilities
  4. Static content/constants
  5. Types and interfaces at the bottom
- Write concise conditionals:
  - Avoid unnecessary braces in single-line conditionals.
  - Use early returns to handle edge cases and errors upfront.
- Model expected errors as return values instead of using exceptions in server actions.

Example:

```typescript
function formatInput({ input }: { input: string }) {
  if (!input) return null
  return input.trim()
}
```

---

## Error Handling, Validation, and Services

- Handle errors at the start of functions with guard clauses and early returns.
- Keep the "happy path" visible at the bottom of the function.
- Avoid `else` statements by using if-return patterns to reduce nesting.
- Use Zod for schema validation and form validation.
- Use `react-hook-form` with `useActionState` to manage form state and submission flows.
- In `services/` directories, always throw user-friendly errors that can be caught upstream and displayed to the user.
- Implement proper error logging and user-friendly messages.
- Employ error boundaries (`error.tsx`, `global-error.tsx`) for unexpected errors.
- Use `next-safe-action` for secure and type-safe server actions.

---

## AI Integration

- Use the Vercel AI SDK UI and Core to implement streaming chat and AI-driven features.
- Handle rate limiting, quota, and model availability gracefully.
- Implement fallback logic if AI models are unavailable.
- Sanitize user inputs before sending them to the AI.
- Store API keys and sensitive information in environment variables.
- Provide clear, user-friendly error messages in case of AI service failures.

---

## React/Next.js Component Development

- **Functional Components**: Use function declarations and TypeScript interfaces for props.
- **Minimal Props & Composition**: Keep components small, focused, and composed of reusable subcomponents.
- **Server Components First**: Prefer React Server Components and SSR data fetching to minimize client overhead.
- **Zustand for State**: Use Zustand for complex local state if necessary, ensuring minimal `use client` usage.
- **Client Components**: Only use `use client` for components that require browser APIs or local user interaction.
- **Responsive Design**: Use Tailwind CSS utility classes, with a mobile-first approach.
- **UI Libraries**: Use Shadcn UI and Radix UI for base components and interactions.
- **Static Content & Types**: Place static text, constants, and types at the end of each file.
- **Dynamic Loading**: Dynamically import non-critical components to improve initial load times.
- **Optimize Images**: Use WebP format, appropriate sizing, and lazy loading for images.

---

## Supabase, Database, and GraphQL

- Fetch latest Supabase documentation from https://supabase.com/docs/reference/javascript;

- **Schema Management**: Keep migrations folder under `supabase/migrations` updated with remote changes.
- **Types Management**: Keep `database.types.ts` updated regularly with the latest schema changes.
- **Migrations**: Use Supabase CLI for local development and database migrations. Test all changes before staging/production.
- **RLS & RBAC**: Implement Row Level Security and role-based access control. Assign default roles in `handle_new_user` functions.
- **CRUD-based Policies**: Follow INSERT, UPDATE, SELECT, DELETE policies and document them.
- **Enum Tables**: Use enum tables for predefined values.
- **Relationships**: Document all table relationships and data flows.
- **Genql**: Use Genql for type-safe GraphQL queries against Supabase. Fetch only necessary data.

Example user creation:

```typescript
async function handleNewUser({ userId, email }: { userId: string; email: string }) {
  const defaultRole = await getDefaultRole()
  await supabase.from('profiles').insert({
    id: userId,
    email,
    role_id: defaultRole.id,
    created_at: new Date().toISOString(),
  })
}
```
### Follow Supabase's guidelines for using the `@supabase/ssr` package and Server-Side Auth. Specifically, there should be:

- A utility function to create a client on the client side
- A utility function create a client on the server side, using the Next.js `cookies` API to access the cookies. Use the latest version of the API, where `cookies` must be awaited.
- A utility function to handle refreshing the user session in middleware.

## Working with cookies

Use the latest version of `@supabase/ssr`, where cookie options are defined with the `getAll` and `setAll` functions, like so:

```
const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
          supabaseResponse = NextResponse.next({
            request,
          })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  )
```

No other cookie options should be provided.

## Middleware

The middleware should use the following `updateSession` function:

```
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'

export async function updateSession(request: NextRequest) {
  let supabaseResponse = NextResponse.next({
    request,
  })

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
          supabaseResponse = NextResponse.next({
            request,
          })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  )

  // IMPORTANT: Avoid writing any logic between createServerClient and
  // supabase.auth.getUser(). A simple mistake could make it very hard to debug
  // issues with users being randomly logged out.

  const {
    data: { user },
  } = await supabase.auth.getUser()

  if (
    !user &&
    !request.nextUrl.pathname.startsWith('/login') &&
    !request.nextUrl.pathname.startsWith('/auth')
  ) {
    // no user, potentially respond by redirecting the user to the login page
    const url = request.nextUrl.clone()
    url.pathname = '/login'
    return NextResponse.redirect(url)
  }

  // IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
  // creating a new response object with NextResponse.next() make sure to:
  // 1. Pass the request in it, like so:
  //    const myNewResponse = NextResponse.next({ request })
  // 2. Copy over the cookies, like so:
  //    myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
  // 3. Change the myNewResponse object to fit your needs, but avoid changing
  //    the cookies!
  // 4. Finally:
  //    return myNewResponse
  // If this is not done, you may be causing the browser and server to go out
  // of sync and terminate the user's session prematurely!

  return supabaseResponse
}
```
### Postgres SQL Style Guide

## General

- Use lowercase for SQL reserved words to maintain consistency and readability.
- Employ consistent, descriptive identifiers for tables, columns, and other database objects.
- Use white space and indentation to enhance the readability of your code.
- Store dates in ISO 8601 format (`yyyy-mm-ddThh:mm:ss.sssss`).
- Include comments for complex logic, using '/* ... */' for block comments and '--' for line comments.

## Naming Conventions

- Avoid SQL reserved words and ensure names are unique and under 63 characters.
- Use snake_case for tables and columns.
- Prefer plurals for table names
- Prefer singular names for columns.

## Tables

- Avoid prefixes like 'tbl_' and ensure no table name matches any of its column names.
- Always add an `id` column of type `identity generated always` unless otherwise specified.
- Create all tables in the `public` schema unless otherwise specified.
- Always add the schema to SQL queries for clarity.
- Always add a comment to describe what the table does. The comment can be up to 1024 characters.

## Columns

- Use singular names and avoid generic names like 'id'.
- For references to foreign tables, use the singular of the table name with the `_id` suffix. For example `user_id` to reference the `users` table
- Always use lowercase except in cases involving acronyms or when readability would be enhanced by an exception.

#### Examples:

```sql
create table books (
  id bigint generated always as identity primary key,
  title text not null,
  author_id bigint references authors (id)
);
comment on table books is 'A list of all the books in the library.';
```


## Queries

- When the query is shorter keep it on just a few lines. As it gets larger start adding newlines for readability
- Add spaces for readability.

Smaller queries:


```sql
select *
from employees
where end_date is null;

update employees
set end_date = '2023-12-31'
where employee_id = 1001;
```

Larger queries:

```sql
select
  first_name,
  last_name
from
  employees
where
  start_date between '2021-01-01' and '2021-12-31'
and
  status = 'employed';
```


### Joins and Subqueries

- Format joins and subqueries for clarity, aligning them with related SQL clauses.
- Prefer full table names when referencing tables. This helps for readability.

```sql
select
  employees.employee_name,
  departments.department_name
from
  employees
join
  departments on employees.department_id = departments.department_id
where
  employees.start_date > '2022-01-01';
```

## Aliases

- Use meaningful aliases that reflect the data or transformation applied, and always include the 'as' keyword for clarity.

```sql
select count(*) as total_employees
from employees
where end_date is null;
```


## Complex queries and CTEs

- If a query is extremely complex, prefer a CTE.
- Make sure the CTE is clear and linear. Prefer readability over performance.
- Add comments to each block.

```sql
with department_employees as (
  -- Get all employees and their departments
  select
    employees.department_id,
    employees.first_name,
    employees.last_name,
    departments.department_name
  from
    employees
  join
    departments on employees.department_id = departments.department_id
),
employee_counts as (
  -- Count how many employees in each department
  select
    department_name,
    count(*) as num_employees
  from
    department_employees
  group by
    department_name
)
select
  department_name,
  num_employees
from
  employee_counts
order by
  department_name;
```


---

## Version Control and Workflow

- **Branch Naming**: `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/`.
- **Commit Messages**: Use `type(scope): description` format. Common types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`.
- **Pull Requests**: Use PR templates with a summary, change type, testing steps, and any database changes noted.
- **Schema Updates**: Update `schema.sql` and commit the changes after each migration.
- **Testing Before PR**: Always test changes locally before submitting PRs.

---

## Data Fetching and State Management

- **RSC for Data**: Use React Server Components for data fetching whenever possible.
- **Preload Pattern**: Implement preload patterns to avoid waterfall requests.
- **Supabase for Real-Time**: Use Supabase subscriptions for real-time data and SSR-friendly data access.
- **Zustand**: Manage local state in isolated client components when needed.
- **Vercel KV**: Use Vercel KV for chat history, rate limiting, and ephemeral storage.
- **SSR & Minimize 'use client'**: Prefer SSR and server actions. Only use `use client` for browser-based interactions.

---

## Testing and Quality Assurance

- **Unit Tests**: Write unit tests for utilities, hooks, and business logic.
- **Integration Tests**: Test complex components, pages, and features in isolation.
- **End-to-End Tests**: Validate critical flows (login, checkout) end-to-end.
- **Local DB Testing**: Use Supabase local development for realistic database tests.
- **Coverage**: Maintain a minimum test coverage threshold for PR merges.

---

## Styling and Accessibility

- **Tailwind CSS**: Use utility classes with a mobile-first responsive approach.
- **CVA for Variants**: Employ Class Variance Authority for component variants and theme consistency.
- **Radix UI**: Utilize Radix primitives for accessible UI patterns.
- **ARIA & WCAG**: Ensure proper ARIA labels, roles, and adhere to WCAG guidelines for color contrast and keyboard navigation.
- **Shadcn UI**: Leverage shadcn UI components for design consistency and speed.

---

## Documentation

- **Comments & JSDoc**: Comment complex logic and use JSDoc for functions and components.
- **Readmes**: Keep README files updated with setup, instructions, and architectural details.
- **API & DB Docs**: Document all API endpoints, RLS policies, and database schema.
- **Edge Functions**: Document Supabase Edge Functions and their intended usage.
- **Setup Instructions**: Keep environment configuration and setup steps current for onboarding developers.

---

**Remember:**
- Regularly check file sizes; refactor when needed.
- Maintain separation of concerns and modular design.
- Reuse components and keep them composable and testable.
- Always test locally before pushing changes.
- Ensure proper error handling, user-friendly messages, and accessible interfaces.

## Supabase Migration Rules

- **CRITICAL: Migration File Management**
  - NEVER modify existing migration files. Each change requires a new migration file with a fresh timestamp.
  - Use `npx supabase migration new <descriptive-name>` to create new migrations.
  - Keep migration names short but descriptive (e.g., `add-user-index`, `update-ticket-constraints`).
  - One logical change per migration file - don't combine unrelated schema changes.
  - Test migrations locally before pushing to production.

- **Migration Best Practices**
  - Include `drop if exists` statements to make migrations idempotent.
  - Add comments explaining the purpose of each migration.
  - For constraint changes, include both `drop constraint if exists` and `add constraint`.
  - Order operations correctly (e.g., drop dependent objects before their dependencies).
  - Always specify the schema (e.g., `public.users` instead of just `users`).

- **Schema Management**
  - Keep `supabase/migrations/` in sync with remote changes.
  - Document schema changes in both migration files and project documentation.
  - Use `npx supabase db reset` for local development only.
  - Use `npx supabase db push` for remote database updates.
  - Never use `db reset` on production/remote databases.

- **Types and Validation**
  - Generate and commit TypeScript types after schema changes using `supabase gen types typescript`.
  - Use Zod schemas that match database constraints.
  - Keep `database.types.ts` updated with latest schema.

- **Security and Access Control**
  - Document RLS policies in both migrations and project documentation.
  - Test RLS policies with different user roles.
  - Use service role only for administrative tasks (seeding, migrations).
  - Never expose service role key in client-side code.

## Database Standards

- **Naming Conventions**
  - Use snake_case for all database objects (tables, columns, functions).
  - Prefix function names with verb (e.g., `get_user`, `update_status`).
  - Use plural for table names (e.g., `users`, `tickets`).
  - Use singular for column names and foreign keys (e.g., `user_id`).

- **Column Standards**
  - Include `created_at` and `updated_at` on all tables.
  - Use `uuid` for primary keys unless there's a specific reason not to.
  - Add appropriate indexes for foreign keys and frequently queried columns.
  - Document constraints and indexes in migration files.

- **Error Handling**
  - Use custom error codes for database functions.
  - Implement proper error handling in application code.
  - Log database errors appropriately.
  - Provide user-friendly error messages.

## Testing and Validation

- **Migration Testing**
  - Test migrations in both directions (up/down).
  - Verify data integrity after migrations.
  - Test with realistic data volumes.
  - Check performance impact of schema changes.

- **Data Seeding**
  - Keep seed data minimal but sufficient for testing.
  - Use service role for seeding operations.
  - Document seed data structure and purpose.
  - Include different test scenarios in seed data.
css
golang
graphql
java
javascript
less
nestjs
next.js
+10 more
ProgramComputer/friendly-tickets

Used in 1 repository

TypeScript
## Instructions for Developers

1. Never remove code unless specifically asked to do so.
2. Never work on code that is not part of the specific request. 
3. When writing react unit tests, always put them in the same directory as the component they are testing.
4. Use the following design document as a guide for the extension:

# Design Document
The AI Pair Programmer Extension streamlines your development process by emphasizing code quality and providing flexible, user-friendly features for enhanced productivity

## Overview

This extension is a VS Code extension that allows you to use the AI Pair Programmer extension to pair program with AI.

## Features

AI pair is designed to be pair programmer that will use your test suite to generate code changes. Typical AI tools will generate code that may not pass your tests. AI pair will generate code that passes your tests.

## How to use

1. Open a folder in VS Code
2. Open the AI Pair extension
3. Click the Play button to start a new pair programming session (or alternatively you can use the `ai-pair.start` command from the vscode command palette)

The extension will run a number of cycles to generate code changes. Each cycle will several phases: `Building`, `Testing`, `Generating Code`, `Rebuilding`, `Retesting`, and `Completed` (in those orders).

At any point in the cycle you can click the `Stop` button to stop the cycle. It will finish the current phase and then stop.

On each cycle, the extension will first build and test to see if any changes are needed. If the build or tests fail, it will generate code changes to fix the build or tests. It will then rebuild and retest until the build and tests pass.

If the build and tests pass then it will stop the cycle.

The extension will continue to run cycles until it reaches the maximum number of retries or the build and tests pass. Retries can be configured in the settings.

## Viewing the results

You can see the progress and results of the AI Pair programmer by opening the sidebar. The sidebar shows a table where each cycle is represented as a row. You can expand any cycle to see the results from that cycle. When a cycle is expanded, you can see the results from each phase of the cycle including the compilation state, test results, code changes, and timing details.

You can also view the logs for parts of a cycle by clicking the `View Logs` link in the cycle details for the phase you are interested in. This will open a new tab with the logs for the cycle.

## Choosing the model

The extension will use the model you have selected in the settings. You can change the model by clicking the `Settings` button in the extension or by navigating to the `AI Pair Settings` section in the VS Code settings.

The extension supports most popular models including OpenAI, Anthropic, and Google. The extension requires a `apiKey` for the model you are using. You can get an API key from the model provider's website.

## Forcing

Even if the build and tests pass, you can force the extension to generate code changes by entering a hint in the `Generate Code` section. This will generate code changes (using your hint as a guide) and then rebuild and retest until the build and tests pass.

## Escalation

The extension can be configured to escalate to a more expensive model on the last cycle. This can be helpful if other models have failed to generate code that passes the tests.

## Design Principles

1. Keep the code simple and easy to understand.
2. Keep the code modular and easy to extend.
3. Keep the code performant.
4. Keep the code easy to test.
5. The webview code should never use dependencies that are not intended for webviews (fs, child_process, etc.)

golang
java
javascript
less
openai
react
rest-api
shell
+1 more

First seen in:

dandedj/ai-pair

Used in 1 repository

TypeScript

    You are an expert in Ionic, Cordova, and Firebase Firestore, Working with Typescript and Angular building apps for mobile and web.

    Project Structure and File Naming
    - Organize by feature directories (e.g., 'services/', 'components/', 'pipes/')
    - Use environment variables for different stages (development, staging, production)
    - Create build scripts for bundling and deployment
    - Implement CI/CD pipeline
    - Set up staging and canary environments
    - Structure Firestore collections logically (e.g., 'users/', 'spots/', 'bookings/')
    - Maintain Firebase configurations for different environments
  
  
    ## Project Structure and Organization
    - Use descriptive names for variables and functions (e.g 'getUsers', 'calculateTotalPrice').
    - Keep classes small and focused.
    - Avoid global state when possible.
    - Manage routing through a dedicated module
    - Use the latest ES6+ features and best practices for Typescript and Angular.
    - Centralize API calls and error handling through services
    - Manage all storage through single point of entry and retrievals. Also put storage keys at single to check and find.
    - Create dedicated Firebase services for each collection type
    - Implement Firebase error handling in a centralized service
    - Use Firebase transactions for data consistency
    - Use Firebase rules for data security
    - Use Firebase functions for serverless backend logic
    - Use Firebase storage for file uploads and downloads
    - Use Firebase authentication for user management
    - Use Firebase analytics for tracking user behavior
    - Use Firebase crash reporting for error tracking
    - Structure Firestore queries for optimal performance
    
    ## Naming Conventions
    - camelCase: functions, variables (e.g., `getUsers`, `totalPrice`)
    - kebab-case: file names (e.g., `user-service.ts`, `home-component.ts`)
    - PascalCase: classes (e.g., `UserService`)
    - Booleans: use prefixes like 'should', 'has', 'is' (e.g., `shouldLoadData`, `isLoading`).
    - UPPERCASE: constants and global variables (e.g., `API_URL`, `APP_VERSION`).
    - Firestore collections: plural nouns (e.g., `users`, `bookings`).
    - Firestore documents: descriptive IDs (e.g., `user-${uid}`, `booking-${timestamp}`).
  
    ## Dependencies and Frameworks
    - Avoid using any external frameworks or libraries unless its absolutely required.
    - Use native plugins through Ionic Native wrappers with proper fallbacks for a smooth user experience in both web and native platforms.
    - While choosing any external dependency, check for the following things:
        - Device compatibility
        - Active maintenance
        - Security
        - Documentation
        - Ease of integration and upgrade
    - Use native components for both mobile and web if available and fullfill the requirements.
    - If any native plugin is being used for andriod or ios, it should be handled in a centralized service and should not be used directly in the component.
    - Use official Firebase SDKs and AngularFire for Firestore integration.
    - Implement proper Firebase initialization and configuration.
    - Handle Firebase Authentication properly.
    - Set up appropriate Firebase Security Rules.
  
    ## UI and Styles
    - Prefer Ionic components.
    - Create reusable components for complex UI.
    - Use SCSS for styling.
    - Centralize themes, colors, and fonts.
    - Implement loading states for Firebase operations.
    - Handle Firebase offline data gracefully.
    - Show appropriate error messages for Firebase operations.
    - Implement real-time UI updates with Firebase snapshots.

    ## Performance and Optimization
    -  Implement lazy loading.
    - Use pre-fetching for critical data.
    - Use caching for all the data that is needed multiple times.
    - Use global error and alert handlers.
    - Integrate any crash reporting service for the application.
    - Use a centralised alert handler to handle all the alert in the application.
    - Implement Firebase offline persistence.
    - Use Firebase query cursors for pagination.
    - Optimize Firestore reads with proper indexing.
    - Cache Firestore query results.
    - Use Firestore batch operations for bulk updates.
    - Monitor Firestore quota usage.
    
    ## Testing
    - Write comprehensive unit tests
    - Make sure to cover all the edge cases and scenarios.
    - In case of Native plugins, write mock services for the same.
    - Test Firebase integration thoroughly
    - Mock Firestore services in tests
    - Test Firebase security rules
    - Implement Firebase emulator for testing
    - Test offline functionality
    - Verify Firebase error handling

    Follow the official Ionic/React and Firebase/Firestore guides for best practices.

    #Paystack
    - Use the official Paystack SDK for React Native.
    #resendemail
    - Use the official Resend Email SDK for React Native.
    #twilio
    - Use the official Twilio SDK for React Native.
    #razorpay
    - Use the official Razorpay SDK for React Native.
    #flutterwave
    - Use the official Flutterwave SDK for React Native.
    #flutterwave
    - Use the official Flutterwave SDK for React Native.
analytics
angular
bun
css
firebase
html
javascript
less
+3 more

First seen in:

spaco67/okiapp

Used in 1 repository

TypeScript
# Role: Full-Stack Development Assistant

I am your dedicated development assistant, specialized in debugging and environment setup for this Next.js + Express.js template. I'll help you:

1. Get your development environment running ASAP
2. Debug any setup or runtime issues
3. Guide you through API integrations
4. Explain any part of the codebase

## Quick Setup Commands

Just paste any error you see and I'll help debug it. Common commands:

```bash
bash
pnpm install # Install dependencies
pnpm run dev # Start both servers
```

## Environment Variables Helper

I can guide you through setting up any environment variable. Just paste the variable name or error message.

### Client Variables

- NEXT_PUBLIC_API_URL: I'll help configure your API URL and explain the rewrite rules in next.config.js
- NEXT_PUBLIC_TELEGRAM_BOT_NAME: I'll help configure your Telegram bot name

### Server Variables

- PORT: I'll help pick a non-conflicting port
- NODE_ENV: I'll explain the implications of each environment
- TELEGRAM_BOT_TOKEN: I'll walk you through BotFather setup
- OPENAI_API_KEY: I'll guide you through API key creation and rate limits
- NGROK_AUTH_TOKEN: I'll help with tunnel setup for webhook development

### Instructions on how to setup the API keys:

#### Client (.env)

- `NEXT_PUBLIC_API_URL`: Backend API URL (default: http://localhost:3001)
- `NEXT_PUBLIC_TELEGRAM_BOT_NAME`: Telegram bot name without the @ symbol, you can get it from BotFather after creating your bot (default: your_bot_username)

#### Server (.env)

- `PORT`: Server port (default: 3001)
- `NODE_ENV`: Environment (development/production)
- `TELEGRAM_BOT_TOKEN`:

  1. Open Telegram and search for @BotFather
  2. Start chat and send `/newbot`
  3. Follow prompts to name your bot
  4. Copy the provided token

- `OPENAI_API_KEY`:

  1. Go to https://platform.openai.com/api-keys
  2. Click "Create new secret key"
  3. Give it a name and copy the key immediately
  4. Set usage limits in API settings if needed

- `NGROK_AUTH_TOKEN`:

  1. Create account at https://dashboard.ngrok.com/signup
  2. Go to https://dashboard.ngrok.com/get-started/your-authtoken
  3. Copy your authtoken

- `NGROK_DOMAIN`:

  1. Go to https://dashboard.ngrok.com/domains
  2. Copy your domain (without https://)

- `COLLABLAND_API_KEY`:

  1. Visit https://dev-portal-qa.collab.land/signin
  2. Click on "Get Started"
  3. Select Telegram login
  4. Login with Telegram
  5. Verify your e-mail with the OTP sent to your inbox
  6. Click on "Request API Access" on the top right corner, and set up the API key name
  7. Copy your API key

- `GAIANET_MODEL`: 🤖

  1. Visit https://docs.gaianet.ai/user-guide/nodes
  2. Choose your model (default: llama)
  3. Copy the model name

- `GAIANET_SERVER_URL`: 🌐

  1. Visit https://docs.gaianet.ai/user-guide/nodes
  2. Get server URL for your chosen model
  3. Default: https://llama8b.gaia.domains/v1

- `GAIANET_EMBEDDING_MODEL`: 🧬

  1. Visit https://docs.gaianet.ai/user-guide/nodes
  2. Choose embedding model (default: nomic-embed)
  3. Copy the model name

- `USE_GAIANET_EMBEDDING`: ⚙️

  1. Set to TRUE to enable Gaianet embeddings
  2. Set to FALSE to disable (default: TRUE)

- `JOKERACE_CONTRACT_ADDRESS`: 🎰

  1. Go to https://www.jokerace.io/contest/new
  2. Create the contest
  3. Copy the contract address

- `ELIZA_CHARACTER_PATH`: 🤖

  1. Default: "character.json"
  2. Points to a JSON file containing your AI agent's personality configuration
  3. Example paths:
     - character.json (default Ace personality)
     - vaitalik.json (Vitalik personality)
     - custom/my-agent.json (your custom personality)

- `TOKEN_DETAILS_PATH`: Points to a JSON/JSONC file containing your token metadata for minting

  1. Default: "token_metadata.example.jsonc"
  2. Steps:
  3. Copy the template: `cp token_metadata.example.jsonc token.jsonc`
  4. Set this env var to point to your file
  5. Example: `token.jsonc`

- `TWITTER_CLIENT_ID` & `TWITTER_CLIENT_SECRET`: Authentication credentials for Twitter API integration

  1. Go to [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard)
  2. Create a new project/app if you haven't already
  3. Navigate to "Keys and Tokens" section
  4. Under "OAuth 2.0 Client ID and Client Secret":
     - Copy "Client ID" → `TWITTER_CLIENT_ID`
     - Generate "Client Secret" → `TWITTER_CLIENT_SECRET`
  5. Configure OAuth settings:
     - Add callback URL: `http://localhost:3001/auth/twitter/callback` (development)
     - Add your production callback URL if deploying
  6. Format: Alphanumeric strings
  7. Example:
     ```env
     TWITTER_CLIENT_ID=Abc123XyzClientID
     TWITTER_CLIENT_SECRET=Xyz789AbcClientSecret
     ```

- `DISCORD_CLIENT_ID` & `DISCORD_CLIENT_SECRET`: Authentication credentials for Discord API integration

  1. Go to [Discord Developer Portal](https://discord.com/developers/applications)
  2. Click "New Application" or select existing one
  3. Navigate to "OAuth2" section in left sidebar
  4. Under "Client Information":
     - Copy "Client ID" → `DISCORD_CLIENT_ID`
     - Copy "Client Secret" → `DISCORD_CLIENT_SECRET`
  5. Configure OAuth settings:
     - Add redirect URL: `http://localhost:3001/auth/discord/callback` (development)
     - Add your production redirect URL if deploying
     - Select required scopes (typically `identify` and `email`)
  6. Format: Alphanumeric strings
  7. Example:
     ```env
     DISCORD_CLIENT_ID=123456789012345678
     DISCORD_CLIENT_SECRET=abcdef123456789xyz
     ```

- `GITHUB_CLIENT_ID` & `GITHUB_CLIENT_SECRET`: Authentication credentials for GitHub OAuth integration

  1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
  2. Click "New OAuth App" or select existing one
  3. Under "OAuth Apps" settings:
     - Application name: Your app name
     - Homepage URL: `http://localhost:3001` (development)
     - Authorization callback URL: `http://localhost:3001/auth/github/callback`
  4. After creating/selecting the app:
     - Copy "Client ID" → `GITHUB_CLIENT_ID`
     - Generate new "Client Secret" → `GITHUB_CLIENT_SECRET`
  5. Configure OAuth scopes:
     - Recommended scopes: `read:user`, `user:email`
  6. Format: Alphanumeric strings
  7. Example:
     ```env
     GITHUB_CLIENT_ID=1234567890abcdef1234
     GITHUB_CLIENT_SECRET=1234567890abcdef1234567890abcdef12345678
     ```

**Note**: For production, update the Homepage URL and callback URL to your production domain.

**Security Notes**:

- Never commit these values to version control
- Use different credentials for development and production
- Rotate secrets periodically
- Store production secrets in secure environment variables

## Development Workflows

I can assist with:

1. Adding new API routes
2. Creating frontend components
3. Setting up middleware
4. Debugging CORS issues
5. TypeScript type definitions
6. Tailwind styling
7. Production deployment

## Code Navigation

I understand the codebase structure and can explain any file or function. Reference files like:

```typescript:server/src/routes/hello.ts
startLine: 1
endLine: 25
```

## Error Resolution

For any error, I'll:

1. Identify the root cause
2. Suggest immediate fixes
3. Explain how to prevent similar issues
4. Provide relevant code examples

## Best Practices

I'll guide you on:

1. TypeScript type safety
2. API error handling
3. State management
4. Performance optimization
5. Security considerations

Just paste any error message, code snippet, or ask about any part of the setup!

### 🪙 Minting Tokens

1. Copy the token metadata template:

```bash
cp token_metadata.example.jsonc token.jsonc
```

2. Edit `token.jsonc` with your token details:

```jsonc
{
  "name": "YourToken", // Token name
  "symbol": "TOKEN", // Token symbol (2-6 chars)
  "description": "Your token description",
  "websiteLink": "https://yoursite.com",
  "twitter": "your_twitter_handle",
  "discord": "https://discord.gg/your_server",
  "telegram": "your_bot_telegram_username",
  "nsfw": false,
  "image": "ipfs://your_ipfs_hash", // Upload image to IPFS first
}
```

3. Update `.env` to point to your token file:

```env
TOKEN_DETAILS_PATH=token.jsonc
```

4. Start your bot and use the `/mint` command in Telegram. The bot will:

- Read your token config
- Mint on Base Sepolia testnet
- Return contract details and token page URL

> Note: Make sure you have set up your COLLABLAND_API_KEY and TELEGRAM_BOT_TOKEN in .env first.

## 🔥 Developing Lit Actions

### Setup

1. Navigate to lit-actions directory:

```bash
cd lit-actions
pnpm install
```

2. Configure environment:

```bash
cp .env.example .env
```

Required variables:

- `PINATA_JWT`: Your Pinata JWT for IPFS uploads
- `PINATA_URL`: Pinata gateway URL

### Development Workflow

1. Create new action in `src/actions/`:

```typescript
/// <reference path="../global.d.ts" />

const go = async () => {
  // Access Lit SDK APIs
  const tokenId = await Lit.Actions.pubkeyToTokenId({ publicKey });

  // Sign data
  const signature = await Lit.Actions.signEcdsa({
    publicKey,
    toSign,
    sigName,
  });

  // Return response
  Lit.Actions.setResponse({
    response: JSON.stringify({ result: "success" }),
  });
};

go();
```

2. Start development server:

```bash
pnpm run dev
```

This will:

- Build TypeScript → JavaScript
- Bundle with dependencies
- Inject SDK shims
- Upload to IPFS
- Watch for changes

### Adding SDK Shims

1. Create shim in `shims/`:

```javascript
// shims/my-sdk.shim.js
import { MySDK } from "my-sdk";
globalThis.MySDK = MySDK;
```

2. Update types in `src/global.d.ts`:

```typescript
declare global {
  const MySDK: typeof MySDK;
}
```

### Building & Deployment

```bash
# Build only
pnpm run build

# Build & deploy to IPFS
pnpm run start
```

IPFS hashes are saved to `actions/ipfs.json`:

```json
{
  "my-action.js": {
    "IpfsHash": "Qm...",
    "PinSize": 12345,
    "Timestamp": "2025-01-03T..."
  }
}
```

### Available APIs

The Lit Actions runtime provides:

- **Lit.Actions**

  - `signEcdsa()`: Sign data with PKP
  - `pubkeyToTokenId()`: Convert public key to token ID
  - `getPermittedAuthMethods()`: Get permitted auth methods
  - `checkConditions()`: Check access control conditions
  - `setResponse()`: Return data to client
  - Full API in `src/global.d.ts`

- **Built-in SDKs**
  - `ethers`: Ethereum interactions
  - `Buffer`: Buffer utilities

### Best Practices

1. **Type Safety**

   - Always reference `global.d.ts`
   - Define types for parameters
   - Use TypeScript features

2. **SDK Management**

   - Create minimal shims
   - Document SDK versions
   - Test SDK compatibility

3. **Action Structure**

   - One action per file
   - Clear async/await flow
   - Proper error handling

4. **Deployment**
   - Test locally first
   - Verify IPFS uploads
   - Keep actions small

### Scripts

```bash
pnpm run dev        # Development mode
pnpm run build     # Build actions
pnpm run start     # Deploy to IPFS
pnpm run lint      # Fix code style
pnpm run watch     # Watch mode
```

### Project Structure

```
lit-actions/
├── actions/           # Built JS + IPFS hashes
├── shims/            # SDK shims
├── src/
│   ├── actions/      # TypeScript sources
│   ├── global.d.ts   # Type definitions
│   └── index.ts      # IPFS deployment
├── esbuild.js        # Build config
└── package.json
```

For more details, check the [Lit Protocol docs](https://developer.litprotocol.com/v3/).
bun
css
esbuild
express.js
golang
java
javascript
jwt
+7 more
sharmasuraj0123/collabland-test

Used in 1 repository

PHP
# アプリケーションの構造

## 呼び出しの構造

このアプリケーションはLaravelの基本的な構造をそのまま利用するが、UseCase、Service、Repositoryという三つのレイヤが追加されている。これらのレイヤは、いわゆるオニオンアーキテクチャの概念を採用しており、一方通行でしか呼び出すことができない。

Controller -> UseCase -> Service -> Repository -> Model

## DI

UseCase / Service / Repository はすべて、依存性注入を行う。`app/Contracts/`下にインターフェイスが定義されており、利用する際には、以下のようにコンストラクタでインターフェイスを読み込んで利用する。

```php
public function __construct(
    UserServiceInterface $userService,
) {
    $this->userService = $userService;
}
```

## Controller

コントローラーは、UsersGetControllerなど、エンドポイントのパス名+メソッド名+Controllerという名称とし、一つのコントローラーに一つのエンドポイントの処理を実装する。

メソッド名は `__invoke` とする。その中では、ユースケースを呼び出し、結果を取得する。

Controllerには、ビジネスロジックを書いてはならない。Controllerごとにユースケースが一つ定義されているので、それを呼び出すだけにする。そのほかに、RequestデータのValidationと整形、UseCaseから帰ってきたデータからのレスポンスの生成だけを行うことができる。

```php
public function __invoke(
    string $id,
    Request $request
): Anomaly {
    $dto = $this->useCase->handle($id);

    return new User($dto);
}
```

## UseCase

ユースケースは、GetUsersUseCaseなど、メソッド名+エンドポイントのパス名+UseCaseという名称とし、一つのユースケースに一つのエンドポイントの処理を実装する。ここでは具体的なビジネスロジックを記述するのではなく、複数のServiceのメソッドを呼び出し、それの組み合わせによってビジネスロジックを実装する。

UseCaseには、handleというメソッドを一つだけ定義し、その中に処理を記述する。

```php
public function handle(string $userId): bool
{
    $user = $this->userService->findById(userId);
    if (empty($user)) {
        throw new ClientSideException('User not found.');
    }
    $success = $this->userService->deleteUser($userId);

    return true;
}
```

呼び出されるサービスの名前とメソッド名とその順番などから、処理の内容をおおよそ理解できるようにする。

Repositoryを直接呼び出すことは避け、Serviceレイヤの呼び出しを複数行う構造とする。レスポンスはDto ( Data Transfer Object )やBoolean値などを利用する。レスポンスとして、型の不定なArrayなどの利用は極力避ける。

## Service

ビジネスロジックを実装するレイヤ。UseCaseレイヤから呼び出される。UserServiceやDocumentServiceなど、特定のリソースに関するビジネスロジックを実装する。各メソッドの名前は、処理内容をきちんと反映したものとする。

単一責任原則に基づき、メソッドの粒度としては、複数の関心事をまとめて処理しないようにする。

モデルを直接作成するのではなく、モデルの操作は必ずRepositoryを経由する。Serviceレイヤ空の戻り値では、Modelを直接返すことは極力避け、Dto ( Data Transfer Object )に変換する。

サービスから別のサービスを呼び出すことはできない。

## Dto

Data Transfer Objectで`app/Dto`に格納される。Serviceからリソースを返すときには、基本はDtoに変換して返す。モデルと対応するDtoは、`createFromModel`というクラスメソッドが用意され、容易に変換することができるようにする。

```php
public function createDocument(array $data): ?\App\Dto\Document
{
    $model = $this->documentRepository->create($data);

    return \App\Dto\Document::createFromModel($model);
}
```

## Repository

Repositoryは、UserRepository、DocumentRepositoryのように、モデルごとに定義される。Repositoryは、基本的にモデルの取得、作成、更新などの操作に限定される。ビジネスロジックは記述しない(ビジネスロジックはServiceに記述する)。BaseRepositoryというベースクラスに、ほとんどのメソッドが用意され、基本的にはモデルを定義する

特殊なメソッドとして、buildQueryByFilterがあり、これによってカラム名以外の特殊なフィルタを使うことができるよう記述する。よくあるのは`query`で、これはフリーテキスト検索などに利用する。

```php
protected function buildQueryByFilter(Builder|EloquentBuilder|Base $query, array $filter, ?array $columns = null): Builder|Base|EloquentBuilder
{
    if (\array_key_exists('query', $filter)) {
        $searchWord = Arr::get($filter, 'query');
        if (! empty($searchWord)) {
            $query = $query->where(function ($q) use ($searchWord): void {
                $q->where('email', 'LIKE', '%'.$searchWord.'%')
                    ->orWhere('name', 'LIKE', '%'.$searchWord.'%');
            });
        }
        unset($filter['query']);
    }

    return parent::buildQueryByFilter($query, $filter);
}
```

## Library

機能によっては、Serviceに置いておくのではなく、別途切り出してライブラリとしたい機能がある。それは以下のようなものである。

- 複数のサービスから呼び出される可能性のある共通処理
- サードパーティAPIへのアクセスなどを含む処理

サードパーティのAPIへのアクセスライブラリは、サードパーティのサービス名をつけてはいけない。例えば「OpenAI」や「Anthropic」の名前をつけるのではなく、LLMを使うライブラリなら`LLM`など、より抽象的な、どういう処理を行うかをもとに名前をつける。これは、将来代替サービスに切り替えるような場合を想定してのことである。したがって、メソッド名、パラメータなどもサービス名や特定のサービスのみで使われている名称はつけないようにする。

## 例外処理

Controller、UseCase、Serviceで処理荷問題が発生し、エラーレスポンスを返したい場合には、例外を投げる。デフォルトには三つの例外があり、基本はこれを使って例外を投げると、エラーレスポンスがクライアントに返される。

| 例外                                              | 説明                                                                             |
|:------------------------------------------------- |:-------------------------------------------------------------------------------- |
| /app/Exceptions/Services/ClientSideException      | クライアントのリクエストに問題がある場合。ステータスコード400番台                |
| /app/Exceptions/Services/ServerSideException      | サーバサイドに問題がある場合。ステータスコード500番台                            |
| /app/Exceptions/Services/ExternalServiceException | サーバサイドから呼び出すサードパーティAPIに問題がある場合。ステータスコード500番 |

第2引数にステータスコードを渡すことができる。

```php
throw new ClientSideException('User not found.', 404);
```
blade
dockerfile
javascript
laravel
openai
php
rocket-generator/php-laravel-template

Used in 1 repository

Python
{
  "version": "1.0",
  "last_updated": "",
  "project": {
    "name": "Your Project",
    "version": "1.0.0",
    "language": "javascript",
    "framework": "none",
    "type": "application"
  },
  "ai_behavior": {
    "code_generation": {
      "style": {
        "prefer": [
          "async/await over callbacks",
          "const over let",
          "descriptive variable names",
          "single responsibility functions"
        ],
        "avoid": [
          "magic numbers",
          "nested callbacks",
          "hard-coded values",
          "complex conditionals"
        ]
      },
      "error_handling": {
        "prefer": [
          "try/catch for async operations",
          "custom error messages",
          "meaningful error states"
        ],
        "avoid": [
          "silent errors",
          "empty catch blocks",
          "generic error messages"
        ]
      },
      "performance": {
        "prefer": [
          "lazy loading",
          "debouncing and throttling for events",
          "memoization for expensive calculations"
        ],
        "avoid": [
          "blocking synchronous code",
          "large inline scripts",
          "unnecessary re-renders"
        ]
      }
    },
    "testing": {
      "required": true,
      "frameworks": ["jest"],
      "coverage_threshold": 80,
      "include": [
        "unit tests for new functions",
        "integration tests for critical workflows",
        "edge case scenarios"
      ]
    },
    "security": {
      "sensitive_patterns": [
        "API_KEY",
        "SECRET",
        "PASSWORD",
        "CREDENTIAL"
      ],
      "protected_files": [
        "config/*.json",
        ".env*"
      ],
      "sanitize_input": true,
      "validate_user_data": true,
      "avoid_eval": true
    },
    "accessibility": {
      "standards": ["WCAG 2.1"],
      "require_alt_text": true,
      "focus_indicators": true,
      "aria_labels": true
    }
  },
  "communication": {
    "style": "step-by-step",
    "level": "beginner-friendly",
    "on_error": [
      "log error details",
      "suggest alternative solutions",
      "ask for clarification if unsure"
    ],
    "on_success": [
      "summarize changes",
      "provide context for future improvements",
      "highlight any potential optimizations"
    ],
    "confirmations": {
      "required_for": [
        "major changes",
        "file deletions",
        "dependency updates",
        "structural changes"
      ]
    }
  },
  "response_format": {
    "always": [
      "show file paths",
      "explain changes simply",
      "highlight modified sections only",
      "provide next steps"
    ],
    "never": [
      "create new files without permission",
      "remove existing code without confirmation",
      "use technical jargon without explanation",
      "show entire files unless requested"
    ]
  }
} 
golang
java
javascript
jest
less
nestjs
python
shell

First seen in:

Dror-Bengal/CursorFocus

Used in 1 repository

TypeScript
You are an expert full-stack developer proficient in TypeScript, React, Next.js, and modern UI/UX frameworks (Chakra UI 3.0, NextJS). You are obsessed about writing clean, consistent and functional code. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning. You are short and direct. No chattiness, no yapping.

## Your coding style

- You write code that is easy to read, maintain and understand
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Structure files with exported components, subcomponents, helpers, static content, and types.
- Use lowercase with dashes for directory names and components (e.g., `components/auth-wizard`).

## Error Handling and Validation

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

## Your working principles

- You always thrive to present honest, direct and accurate answers (Even when presented with an assupmtion, suggestion or loaded question)
- You are not afraid to disagree
- If there is anything you need that’s missing, you ask for it
- If you’re unsure about any aspect of the task, you ask for clarification. You don’t guess. You don’t make assumptions.
- Before suggesting new code, you look through all files in the codebase to see if there are functions and excisting archicture you can use or rewrite to avoid duplication and isolated implementations
chakra-ui
css
javascript
nestjs
next.js
react
typescript

First seen in:

wirtzdan/project-rocket

Used in 1 repository

TypeScript
一、初始项目评估 - 详细指南(适合初学者)
1. 项目文档审查
1.1 README.md 文件解读
这是你接触项目的第一个文件
通常包含项目描述、安装步骤、使用方法
查找关键词:Installation(安装)、Getting Started(入门)、Prerequisites(前置要求)
尝试按照步骤在本地运行项目
记录遇到的问题和解决方法
1.2 package.json 分析
这个文件包含项目的所有依赖项
dependencies:项目运行需要的包
devDependencies:开发时需要的包
scripts:可用的命令(如 npm start, npm test)
尝试理解每个主要依赖的作用
记录版本号,避免版本冲突
1.3 环境配置文件检查
查找 .env 或 .env.example 文件
了解需要配置的环境变量
确认是否需要特殊的API密钥或访问令牌
检查不同环境的配置(开发、测试、生产)
注意安全相关的配置项
1.4 项目配置文件
检查 next.config.js/webpack.config.js 等配置文件
了解项目的特殊配置需求
查看是否有自定义的构建过程
注意性能相关的配置项
技术栈评估
2.1 前端技术
确认使用的框架(React/Vue/Angular等)
查看UI库(Material-UI/Tailwind等)
了解状态管理方案(Redux/Mobx等)
检查路由实现方式
注意特殊的前端功能(如WebSocket、Canvas)
2.2 后端技术
确认后端框架(Node.js/Python/Java等)
了解数据库选择(MySQL/MongoDB等)
检查API实现方式(REST/GraphQL)
查看认证方案(JWT/Session等)
注意性能相关的实现
2.3 构建和部署
了解构建工具(Webpack/Vite等)
检查部署方案(Docker/Kubernetes等)
查看CI/CD配置(GitHub Actions/Jenkins等)
了解监控方案
注意自动化测试配置
实践步骤
3.1 本地运行
克隆项目代码
安装依赖(npm install/yarn)
配置环境变量
启动开发服务器
确认基本功能是否正常
3.2 代码阅读
从入口文件开始(如 index.js/App.js)
查看主要组件的实现
理解数据流转过程
注意错误处理方式
学习代码组织方式
3.3 调试技巧
使用浏览器开发者工具
添加 console.log 进行调试
使用断点调试
查看网络请求
分析性能问题
4. 记录和总结
4.1 建立学习笔记
记录项目结构
总结关键技术点
记录问题和解决方案
整理有用的代码片段
建立个人知识库
4.2 提问和交流
在团队中提出疑问
查阅相关文档
在Stack Overflow上搜索
参与技术社区讨论
与其他开发者交流
5. 进阶学习
5.1 深入理解
研究核心算法
分析设计模式
学习最佳实践
理解性能优化
掌握测试方法
5.2 贡献代码
修复简单bug
添加新功能
改进文档
优化性能
提交Pull Request
注意事项:
不要试图一次理解所有内容
从简单的部分开始
多动手实践
保持耐心
及时记录和总结
善用搜索引擎
多与他人交流
循序渐进地学习
angular
css
docker
golang
graphql
java
javascript
jwt
+17 more

First seen in:

Kelin0x/figma_clone

Used in 1 repository

TypeScript
**General Principles**

- Use modular architecture for better scalability and maintainability.
- Encapsulate the application logic in services and separate concerns.
- Write clean, readable, and maintainable code adhering to SOLID principles.
- Prefer TypeScript over JavaScript for type safety and better tooling support.
- Document all public classes, methods, and modules using JSDoc.
- Implement comprehensive error handling and logging.
- Ensure the application adheres to security best practices.

**Folder Structure**

- Use consistent naming conventions: kebab-case for file and directory names, camelCase for variables, and PascalCase for classes.

**Module Design**

- Each module should encapsulate a single feature or domain.
- Modules should expose only the necessary providers and imports.
- Use dependency injection to manage dependencies between services.

**Controllers**

- Use controllers to handle incoming requests and return responses.
- Keep controllers lightweight; delegate business logic to services.
- Use descriptive route names and HTTP methods.
- Use DTOs (Data Transfer Objects) for request validation and type safety.
- Document controller methods with JSDoc or Swagger annotations.

**Services**

- Encapsulate all business logic in services.
- Use Dependency Injection to manage dependencies.
- Write small, focused methods that perform a single task.
- Ensure proper separation of concerns; avoid mixing database logic with business logic.

**Data Validation**

- Use `class-validator` and `class-transformer` for validating and transforming incoming data.
- Define DTOs (Data Transfer Objects) for each endpoint.
- Validate input at the controller level using the `@Body()`, `@Param()`, and `@Query()` decorators.
- Use pipes for global or custom validation logic.

**Database Integration**

- Encapsulate database logic within repositories or dedicated services.
- Define entities with proper relationships and constraints.
- Use migrations for schema changes and version control.

**Error Handling**

- Use global filters (e.g., `@Catch()`) to handle exceptions.
- Define custom exceptions for specific use cases.
- Return meaningful error messages and HTTP status codes.
- Log errors using a logging service or library (e.g., `winston` or NestJS Logger).

**Security Best Practices**

- Use `helmet` for setting secure HTTP headers.
- Implement rate limiting using `nestjs-rate-limiter` or similar libraries.
- Sanitize user inputs to prevent SQL injection or XSS attacks.
- Use environment variables to store sensitive information (e.g., database credentials, API keys).
- Implement authentication and authorization using Passport.js or JWT strategies.

**Performance Optimization**

- Enable caching for frequently accessed data using the `CacheModule`.
- Use interceptors to handle cross-cutting concerns (e.g., logging, transformation).
- Optimize database queries using indexes and efficient relationships.
- Use lazy loading for modules and services where applicable.

**Testing**

- Write unit tests for services and controllers using Jest.
- Follow the Arrange-Act-Assert pattern for test structure.
- Use test doubles (e.g., mocks, stubs, spies) for dependencies.
- Write e2e (end-to-end) tests to validate the complete application flow.
- Organize test files alongside the feature they belong to, e.g., `feature-name.controller.spec.ts`.

**Configuration Management**

- Use the `@nestjs/config` module for managing configuration.
- Store environment-specific settings in `.env` files.
- Avoid hardcoding configuration values; use environment variables instead.
- Validate configuration values using `class-validator` and a dedicated configuration schema.

**Event-Driven Architecture**

- Use the `EventEmitterModule` for handling events within the application.
- Define event classes to encapsulate event data.
- Use a message broker like RabbitMQ or Kafka for distributed systems.

**Swagger Documentation**

- Use `@nestjs/swagger` to generate API documentation.
- Annotate controllers and DTOs with Swagger decorators.
- Include details for endpoints, request bodies, query parameters, and responses.
- Host the Swagger UI at a dedicated endpoint, e.g., `/api/docs`.

**Logging**

- Use NestJS' Logger for application-wide logging.
- Implement a centralized logging service for consistency.
- Configure logging levels (e.g., debug, info, error) based on the environment.
- Log important events and errors with sufficient context information.

**Asynchronous Operations**

- Use async/await for asynchronous operations.
- Leverage RxJS observables for reactive programming where appropriate.
- Use queues (e.g., Bull) for background tasks and job processing.
java
javascript
jest
jwt
nestjs
react
shell
solidjs
+1 more

First seen in:

montarist/nilvera-api

Used in 1 repository