Awesome Cursor Rules Collection

Showing 1177-1188 of 2626 matches

JavaScript
# Project: Node.js Web Scraper for Job Listings

## Coding Standards
- Use `async/await` for asynchronous operations (prefer over `.then()`).
- Use `const` and `let` instead of `var` for variable declarations.
- Ensure proper error handling using `try/catch` blocks.
- Write modular and reusable code by splitting functionality into functions.

## Style Guidelines
- Use 2 spaces for indentation.
- Max line length: 100 characters.
- Use camelCase for variables and function names.
- Ensure code is properly formatted with consistent spacing and indentation.

## Best Practices
- Make HTTP requests using `axios` with proper headers to mimic real browser requests.
- Follow good practices for pagination by adjusting the API’s `page` parameter.
- Extract and process only the necessary fields (e.g., job title, company name, salary).
- Ensure that JSON data is correctly parsed and saved.
- Respect the website's `robots.txt` to ensure that scraping is done ethically and legally.
- Implement a rate-limiting mechanism to avoid overwhelming the target server.

## Testing
- Write tests for key functions, particularly for handling HTTP requests and JSON parsing.
- Aim for at least 80% test coverage for the core logic of the scraper.
- Use tools like `jest` or `mocha` for testing.
- Ensure that your tests cover edge cases, such as failed requests or missing data.

## Documentation
- Use JSDoc comments for all functions and key logic to describe their purpose and parameters.
- Keep `README.md` up-to-date with project setup instructions, including how to configure API endpoints and handle authentication if needed.
- Document any potential edge cases or limitations of the scraper, such as rate limits or data format changes.

## Legal Considerations
- Always check and adhere to the website's `robots.txt` file.
- Be aware of the potential legal risks of scraping and ensure compliance with the website's terms of service.
- Avoid scraping excessive amounts of data, and ensure the scraper does not negatively impact the website's performance.

---

**Note**: Always test the scraper on a small scale first to ensure that the website's API and terms of service allow it, and that the scraper behaves as expected.
golang
javascript
jest
AmandaloveYang/boss-job-crawler

Used in 1 repository

Go
## 项目背景

本项目是一个高性能、可扩展的分布式通讯系统。项目名称为im, 使用·go语言开发
## 项目架构

### 整体架构
```
┌───────────────┐
│   客户端层    │  (Web/Mobile/Desktop)
└───────┬───────┘
        │
┌───────▼───────┐
│   网关服务层  │  (API Gateway/负载均衡)
└───────┬───────┘
        │
┌───────▼───────┐
│   微服务层    │
├───────────────┤
│ 1.用户服务   │
│ 2.连接服务   │
│ 3.消息服务   │
│ 4.推送服务   │
└───────┬───────┘
        │
┌───────▼───────┐
│   基础服务层  │
├───────────────┤
│ 1.注册中心   │
│ 2.配置中心   │
│ 3.消息队列   │
│ 4.缓存服务   │
└───────────────┘
```

### 架构特点
- 微服务解耦
- 水平可扩展
- 高可用设计
- 松耦合架构

## 项目技术栈

### 后端
- 语言:Go 1.21+
- 框架:
  - gRPC
  - go-zero
  - gin
- RPC:Protocol Buffers

### 中间件
- 注册中心:Etcd
- 消息队列:Kafka
- 缓存:Redis
- 数据库:PostgreSQL
- 监控:Prometheus + Grafana
- 链路追踪:Jaeger

### 部署
- 容器化:Docker
- 编排:Kubernetes
- 持续集成:GitHub Actions

## 第三方库

### 基础库
```go
package dependencies

var CoreLibs = []string{
    "github.com/gorilla/websocket",     // WebSocket支持
    "github.com/golang-jwt/jwt",        // JWT认证
    "github.com/spf13/viper",           // 配置管理
    "go.uber.org/zap",                  // 日志库
    "gorm.io/gorm",                     // ORM
    "github.com/google/uuid",           // UUID生成
}

var MicroserviceLibs = []string{
    "google.golang.org/grpc",           // gRPC框架
    "github.com/go-kratos/kratos",      // 微服务框架
    "github.com/opentracing/opentracing-go", // 链路追踪
}

var CacheAndMQLibs = []string{
    "github.com/go-redis/redis/v8",     // Redis客户端
    "github.com/Shopify/sarama",        // Kafka客户端
}
```

## 项目目录结构

```
im-system/
│
├── api/                # API定义
│   ├── proto/          # Protobuf定义
│   └── openapi/        # Swagger文档
│
├── app/                # 微服务
│   ├── user/           # 用户服务
│   ├── message/        # 消息服务
│   ├── connection/     # 连接服务
│   └── push/           # 推送服务
│
├── pkg/                # 公共包
│   ├── auth/           # 认证模块
│   ├── logger/         # 日志模块
│   ├── middleware/     # 中间件
│   └── utils/          # 工具函数
│
├── configs/            # 配置文件
├── deployments/        # 部署相关
│   ├── docker/
│   └── kubernetes/
│
├── scripts/            # 开发脚本
├── test/               # 测试用例
└── docs/               # 项目文档
```

## 项目开发规范

### 代码规范
1. 遵循官方Go编码规范
2. 使用golangci-lint进行代码静态检查
3. 代码必须有完善注释
4. 单个函数不超过50行
5. 变量命名清晰、语义化
6. 引入本地文件使用本地引用,例如:
```go
import (
    "im/pkg/logger"
)
```



### 测试要求
- 单元测试覆盖率>70%
- 所有核心服务必须有集成测试
- 使用golang/mock进行依赖模拟
docker
dockerfile
go
golang
jwt
kubernetes
postgresql
redis
+2 more

First seen in:

Chi-Kai/im

Used in 1 repository

TypeScript
You are a senior TypeScript programmer with experience in the NestJS framework and a preference for clean programming and design patterns.Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.
## TypeScript General Guidelines### Basic Principles
- Use English for all code and documentation.
- Always declare the type of each variable and function (parameters and return value).
- Avoid using any.
- Create necessary types.
- Use JSDoc to document public classes and methods.
- Don't leave blank lines within a function.
- One export per file.
- Use path aliases for imports instead of relative paths.
- Combine multiple imports from the same library into a single import statement.

### Nomenclature
- Use PascalCase for classes.
- Use camelCase for variables, functions, and methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables.
- Avoid magic numbers and define constants.
- Start each function with a verb.
- Use verbs for boolean variables.

Example: isLoading, hasError, canDelete, etc.
- Use complete words instead of abbreviations and correct spelling.
- Except for standard abbreviations like API, URL, etc.
- Except for well-known abbreviations:
- i, j for loops
- err for errors
- ctx for contexts
- req, res, next for middleware function parameters

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

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

### Classes
- Follow SOLID principles.
- Prefer composition over inheritance.
- Declare interfaces to define contracts.
- Write small classes with a single purpose.
- Less than 200 instructions.
- Less than 10 public methods.
- Less than 10 properties.

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

### Testing
- Follow the Arrange-Act-Assert convention for tests.
- Name test variables clearly.
- Follow the convention: inputX, mockX, actualX, expectedX, etc.
- Write unit tests for each public function.
- Use test doubles to simulate dependencies.
- Except for third-party dependencies that are not expensive to execute.
- Write acceptance tests for each module.
- Follow the Given-When-Then convention.

## Specific to NestJS

### Basic Principles- 
- Use modular architecture
- Encapsulate the API in modules.
- One module per main domain/route.
- One controller for its route.
- And other controllers for secondary routes.
- A models folder with data types.
- DTOs validated with class-validator for inputs.
- Declare simple types for outputs.
- A services module with business logic and persistence.
- Entities with MikroORM for data persistence.
- One service per entity.
- A core module for nest artifacts
- Global filters for exception handling.
- Global middlewares for request management.
- Guards for permission management.
- Interceptors for request management.
- A shared module for services shared between modules.
- Utilities - Shared business logic

### Testing- 
- Use the standard Jest framework for testing.
- Write tests for each controller and service.
- Write end to end tests for each api module.
- Add a admin/test method to each controller as a smoke test.

## Database and TypeORM Conventions

### Column Naming
- Use `snake_case` for database column names
- Use `camelCase` for entity properties
- Always use the `name` parameter in `@Column` decorator to explicitly define the database column name
- Examples:
  - Database column: `first_name`, Entity property: `firstName`
  - Database column: `phone_number`, Entity property: `phoneNumber`
  - Database column: `is_active`, Entity property: `isActive`
  - Database column: `created_at`, Entity property: `createdAt`

### Index Naming
- Use meaningful and unique index names
- Follow pattern: `IDX_entityName_columnName`
- For composite indexes: `IDX_entityName_column1_column2`
- Examples:
  - `IDX_user_first_name`
  - `IDX_user_email`
  - `IDX_user_phone_number`

### Entity Decorators
- Always specify column types explicitly
- Use appropriate length constraints for string columns
- Add proper index decorators
- Specify relation options clearly
- Examples:

## TypeORM and Database Configuration Standards

### Type Safety
- Use explicit types for all configuration values
- Implement proper TypeORM type definitions
- Use TypeScript generics where applicable
- Example:

### Database Character Set and Collation Standards

#### Character Set Configuration
- Always use UTF-8 with full Unicode support
- Configure at both connection and database level
- Use `utf8mb4` for MySQL/MariaDB
- Example:

## Query Building and Data Access Patterns

### Query Building Principles
- Follow Single Responsibility Principle
- Implement reusable query building logic
- Use TypeORM best practices
- Implement proper validation
- Example:

### Pagination Standards
- Use standardized pagination DTOs
- Implement proper

## Code Organization and DRY Principles

### DTO Inheritance and Composition
- Use DTO inheritance for shared properties
- Avoid duplicate pagination/filtering options
- Extend base DTOs for specific use cases
- Example:

## SOLID Principles Implementation

### Single Responsibility Principle (SRP)
- Each class should have only one reason to change
- Split large services into smaller focused ones
- Use composition to combine functionality
- Example:

## Import and Path Alias Standards

### Path Alias Configuration
- Use path aliases starting with '@/'
- Configure aliases in tsconfig.json
- Use meaningful alias names
- Create barrel files (index.ts) for cleaner imports
- Example:

## Barrel Files and Module Organization

### Barrel File Standards
- Create index.ts files for feature modules
- Use barrel files only for closely related files
- Keep barrel files in their respective directories
- Example:

## Testing Standards and Best Practices

### Service Testing
- Mock all external dependencies (Model, Services)
- Use proper type definitions for mocks
- Test all service methods
- Include error cases
- Example:

## Testing Mock Data Standards

### Mock Data Structure
- Create complete mock objects matching schema
- Include all required fields
- Use realistic test data
- Follow type definitions
- Example:
javascript
jest
less
mysql
nestjs
solidjs
typeorm
typescript
AymanNagyAhmed/demo-finance-manager-api-nestjs

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Supabase, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.

Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  - components folder is in the root of the project

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

TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.

Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.

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

Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.

Next.js Specifics
  - Use next-safe-action for all server actions:
  - Implement type-safe server actions with proper validation.
  - Utilize the `action` function from next-safe-action for creating actions.
  - Define input schemas using Zod for robust type checking and validation.
  - Handle errors gracefully and return appropriate responses.
  - Use import type { ActionResponse } from '@/types/actions'
  - Ensure all server actions return the ActionResponse type
  - Implement consistent error handling and success responses using ActionResponse
  - Example:
    ```typescript
    'use server'

    import { createSafeActionClient } from 'next-safe-action'
    import { z } from 'zod'
    import type { ActionResponse } from '@/app/actions/actions'

    const schema = z.object({
      value: z.string()
    })

    export const someAction = createSafeActionClient()
      .schema(schema)
      .action(async (input): Promise<ActionResponse> => {
        try {
          // Action logic here
          return { success: true, data: /* result */ }
        } catch (error) {
          return { success: false, error: error instanceof AppError ? error : appErrors.UNEXPECTED_ERROR, }
        }
      })
    ```

Key Conventions
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
    - Favor server components and Next.js SSR.
    - Use only for Web API access in small components.
    - Avoid for data fetching or state management.

  Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
javascript
next.js
plpgsql
radix-ui
react
shadcn/ui
supabase
+2 more
donnes/instagram-ad-response-system

Used in 1 repository

C#
**Project Summary:**

Develop a 3D third-person action fantasy game demo in Unity, focusing on creating a "souls-like" combat system. 
This project emphasizes challenging combat mechanics and related systems, streamlining other game elements to showcase proficiency in gameplay programming and system design within the Unity engine.

**General Unity and Coding Instructions for AI Coder:**

1. **Coding Standards**
   - **Language Features:** Use C# best practices and features appropriate for Unity development.
   - **Clean Code:** Write readable, maintainable code with proper indentation and spacing.
   - **Comments and Documentation:** Comment code sections to explain complex logic and maintain an up-to-date code documentation.

2. **Performance Optimization**
   - **Efficient Coding:** Avoid unnecessary computations within Update loops; use FixedUpdate for physics-related updates.
   - **Garbage Collection:** Minimize allocations to reduce garbage collection overhead.
   - **Profiling:** Use Unity's Profiler to identify and address performance bottlenecks.

3. **Modular Design**
   - **Reusable Components:** Develop scripts and systems that can be reused across different game objects.
   - **Decoupling Systems:** Use events or interfaces to reduce dependencies between systems.

4. **Unity Best Practices**
   - **Prefab Usage:** Utilize prefabs for all game objects to ensure consistency and easy updates.

5. **Input Management**
   - **Input System:** Implement Unity's new Input System for handling player controls.
   - **Responsive Controls:** Ensure that player input results in immediate and smooth character responses.

6. **Testing and Debugging**
   - **Incremental Testing:** Test features incrementally as they are developed.
   - **Debug Tools:** Utilize Unity's debugging tools and log outputs to troubleshoot issues.

7. **Version Control**
   - **Source Control:** Use a version control system like Git to track changes and collaborate effectively.
   - **Commit Messages:** Write clear and descriptive commit messages for future reference.

8. **Documentation**
    - **README Files:** Maintain a README with setup instructions and project overview.
    - **Technical Documentation:** Document systems and workflows for future developers or for personal reference.
    - **Progress Documentation:** Keep an up to date progress.md file to track the progress of the project.

9. **User Interface**
    - **UI Elements:** Use Unity's UI system to create health bars, stamina bars, and other HUD elements.
    - **Responsive Design:** Ensure UI scales correctly across different resolutions.

10. **ScriptableObjects**
    - **Data Management:** Use ScriptableObjects for managing game data and configurations.

11. **Error Handling**
    - **Exceptions:** Implement try-catch blocks where appropriate to handle potential errors gracefully.
    - **Validation:** Validate inputs and states to prevent invalid operations.

12. **Third-Party Tools**

    - **Odin Inspector**
        - **Foldout Groups:** Use [FoldoutGroup("GroupName")] to organize related fields into collapsible sections in the Inspector for better readability.
        - **SerializeField:** Apply [SerializeField] to private fields that need to be visible and editable in the Inspector while keeping encapsulation.
        - **LabelWidth(180):** Set label widths to 180 using [LabelWidth(180)] to maintain consistent and aligned labels in the Inspector.
        - **ReadOnly:** Use [ReadOnly] on fields that should be visible but not editable in the Inspector, helpful for displaying runtime information.
        - **Required:** Implement [Required] to ensure essential fields are assigned in the Inspector, preventing null reference exceptions at runtime.

**Development Plan:**

1. **Set Up Character Controller**
   - Implement a third-person character controller for smooth player movement.
   - Configure the camera to follow the player with appropriate rotation and positioning.

2. **Implement Movement Mechanics**
   - Add walking and running capabilities with input controls.
   - Develop a dodge roll mechanic with invincibility frames and stamina cost.
   - Include jumping functionality if necessary for combat dynamics.

3. **Design Core Combat System**
   - Implement light and heavy attack mechanics with distinct animations and effects.
   - Set up input handling to differentiate between attack types.
   - Develop blocking mechanics that reduce damage at the cost of stamina.
   - Create a parrying system that allows players to counterattack if timed correctly.

4. **Create Enemy Characters**
   - Import or create enemy models and set up their prefabs.
   - Add necessary components like colliders, rigidbodies, and animators to enemies.

5. **Implement Enemy Combat AI**
   - Program basic enemy behaviors such as patrolling and detecting the player.
   - Develop enemy attack patterns and reactions to player actions.
   - Ensure enemies can perform actions like attacking, blocking, and dodging.

6. **Develop Health and Stamina Systems**
   - Create health bars for the player and enemies that update during combat.
   - Implement a stamina system that depletes with actions like attacking and dodging.
   - Set up stamina regeneration mechanics when not performing stamina-consuming actions.

7. **Add Damage and Collision Detection**
   - Implement hit detection using colliders and triggers for accurate combat interactions.
   - Set up damage calculations based on player and enemy stats.
   - Include feedback for successful hits, such as sound effects and visual cues.

8. **Integrate Combat Animations**
   - Import combat animations for all player and enemy actions.
   - Configure Animator Controllers to manage animation states and transitions.
   - Ensure animations are synced with mechanics like hit detection and stamina usage.

9. **Design Combat UI Elements**
   - Create UI elements to display health and stamina for the player.
   - Design enemy health bars that appear when engaged in combat.
   - Include any additional indicators needed for combat feedback.

10. **Build Test Environment**
    - Develop simple environments or arenas to test combat mechanics.
    - Add obstacles or terrain features that affect combat strategies.

11. **Perform Testing and Iteration**
    - Conduct thorough testing of all combat systems and mechanics.
    - Identify and fix bugs or issues that arise during testing.
    - Refine gameplay elements to enhance player experience and combat flow.

12. **Finalize and Polish**
    - Add visual effects like particle systems for attacks and abilities.
    - Incorporate sound effects and background music to enhance immersion.
    - Optimize performance to ensure smooth gameplay.
    - Prepare the demo for presentation by ensuring all elements are cohesive and functional.
c#
react
shaderlab
shell
ElvenRealms/FantasySoulsLike

Used in 1 repository

Svelte
# 树莓派管理面板

一个用于监控和管理树莓派的全栈 Web 管理面板。

## 树莓派5多功能服务器完整解决方案

## 系统架构

```
[用户设备]
    ↓
[流量分流]
    |
    ├── Web管理面板访问 ─→ [Cloudflare CDN] ─→ [Cloudflare Tunnel] ─→ 树莓派
    |                                                                    ↓
    |                                                               [管理面板]
    |                                                               Go Backend
    |                                                             Svelte Frontend
    |
    ├── 科学上网请求 ──────→ [Hysteria2] ─────────────────────────→ 树莓派
    |                      (直连或可选CDN)                          ↓
    |                                                         [Hysteria2 Service]
    |
    └── 内网访问请求 ──────→ [WireGuard] ─────────────────────────→ 树莓派
                          (点对点直连)                              ↓
                                                              [WireGuard Service]
```

## 技术栈

### 前端 (frontend)
- SvelteKit 2.0
- Svelte 5.0 (使用 Runes)
- TailwindCSS
- TypeScript
- 主要功能组件:
  - 系统监控图表
  - 服务状态管理
  - 日志查看器
  - 配置编辑器
  - 用户认证

### 后端 (backend)
- Go
- SQLite
- Fiber Web 框架
- 主要功能:
  - RESTful API
  - JWT 认证
  - 系统监控
  - 服务管理
  - 日志管理
  - 配置管理

## 主要功能
- 实时系统资源监控 (CPU、内存、磁盘)
- 系统服务管理
- 系统日志查看
- 配置文件管理
- 用户认证和密码管理

## 项目结构
```
.
├── frontend/           # 前端项目目录
│   ├── src/           # 源代码
│   │   ├── lib/       # 组件和工具
│   │   └── routes/    # 页面路由
│   └── ...
└── backend/           # 后端项目目录
    ├── cmd/          # 入口文件
    └── internal/     # 内部包
        ├── api/      # API 处理
        ├── db/       # 数据库操作
        └── ...
```

# frontend

I'm using svelte 5 instead of svelte 4 here is an overview of the changes.

#### Overview

Svelte 5 introduces runes, a set of advanced primitives for controlling reactivity. The runes replace certain non-runes features and provide more explicit control over state and effects.

### Package manager
use pnpm instead of npm

### TypeScript
use typescript instead of javascript if possible

### Echarts
use echarts instead of chart.js

### fetch
use fetch instead of axios

#### $state

- **Purpose:** Declare reactive state.
- **Usage:**

```javascript
<script>let count = $state(0);</script>
```

- **Replaces:** Top-level `let` declarations in non-runes mode.
- **Class Fields:**

```javascript
class Todo {
	done = $state(false);
	text = $state();
	constructor(text) {
		this.text = text;
	}
}
```

- **Deep Reactivity:** Only plain objects and arrays become deeply reactive.

#### $state.raw

- **Purpose:** Declare state that cannot be mutated, only reassigned.
- **Usage:**

```javascript
<script>let numbers = $state.raw([1, 2, 3]);</script>
```

- **Performance:** Improves with large arrays and objects.

#### $state.snapshot

- **Purpose:** Take a static snapshot of $state.
- **Usage:**

```javascript
<script>
	let counter = $state({ count: 0 });

	function onClick() {
		console.log($state.snapshot(counter));
	}
</script>
```

#### $derived

- **Purpose:** Declare derived state.
- **Usage:**

```javascript
<script>
let count = $state(0); 
let doubled = $derived(count * 2);
</script>
```

- **Replaces:** Reactive variables computed using `$:` in non-runes mode.

#### $derived.by

- **Purpose:** Create complex derivations with a function.
- **Usage:**

```javascript
<script>
	let numbers = $state([1, 2, 3]); 
	let total = $derived.by(() => numbers.reduce((a, b) => a + b, 0));
</script>
```

#### $effect

- **Purpose:** Run side-effects when values change.
- **Usage:**

```javascript
<script>
	let size = $state(50);
	let color = $state('#ff3e00');

	$effect(() => {
		const context = canvas.getContext('2d');
		context.clearRect(0, 0, canvas.width, canvas.height);
		context.fillStyle = color;
		context.fillRect(0, 0, size, size);
	});
</script>
```

- **Replacements:** $effect replaces a substantial part of `$: {}` blocks triggering side-effects.

#### $effect.pre

- **Purpose:** Run code before the DOM updates.
- **Usage:**

```javascript
<script>
	$effect.pre(() => {
		// logic here
	});
</script>
```

- **Replaces:** beforeUpdate.

#### $props

- **Purpose:** Declare component props.
- **Usage:**

```javascript
<script>let { prop1, prop2 } = $props();</script>
```

- **Replaces:** export let syntax for declaring props.

#### $bindable

- **Purpose:** Declare bindable props.
- **Usage:**

```javascript
<script>let { bindableProp = $bindable('fallback') } = $props();</script>
```

#### Overview of snippets in svelte 5

Snippets, along with render tags, help create reusable chunks of markup inside your components, reducing duplication and enhancing maintainability.

#### Snippets Usage

- **Definition:** Use the `#snippet` syntax to define reusable markup sections.
- **Basic Example:**

```javascript
{#snippet figure(image)}
	<figure>
		<img src={image.src} alt={image.caption} width={image.width} height={image.height} />
		<figcaption>{image.caption}</figcaption>
	</figure>
{/snippet}
```

- **Invocation:** Render predefined snippets with `@render`:

```javascript
{@render figure(image)}
```

#### Snippet Scope

- **Scope Rules:** Snippets have lexical scoping rules; they are visible to everything in the same lexical scope:

```javascript
<div>
	{#snippet x()}
		{#snippet y()}...{/snippet}

		<!-- valid usage -->
		{@render y()}
	{/snippet}

	<!-- invalid usage -->
	{@render y()}
</div>

<!-- invalid usage -->
{@render x()}
```

#### Passing Snippets to Components

- **Direct Passing:**

```javascript
<script>
	import Table from './Table.svelte';
	const fruits = [{ name: 'apples', qty: 5, price: 2 }, ...];
</script>

{#snippet header()}
	<th>fruit</th>
	<th>qty</th>
	<th>price</th>
	<th>total</th>
{/snippet}

{#snippet row(fruit)}
	<td>{fruit.name}</td>
	<td>{fruit.qty}</td>
	<td>{fruit.price}</td>
	<td>{fruit.qty * fruit.price}</td>
{/snippet}

<Table data={fruits} {header} {row} />
```

#### Typing Snippets

- **TypeScript Integration:**

```typescript
<script lang="ts">
	import type { Snippet } from 'svelte';

	let { data, children, row }: {
		data: T[];
		children: Snippet;
		row: Snippet<[T]>;
	} = $props();
</script>
```

# backend

You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux.

Always use the latest stable version of Go (1.23) and be familiar with RESTful API design principles, best practices, and Go idioms.

CORE PRINCIPLES:
- Follow the user's requirements carefully & to the letter
- First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode
- Confirm the plan, then write code
- Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs
- Leave NO todos, placeholders, or missing pieces in the API implementation
- If unsure about a best practice or implementation detail, say so instead of guessing

STANDARD LIBRARY USAGE:
1. HTTP Package
- Use net/http package for API development
- Utilize ServeMux for routing with new features:
  - Support multiple spaces/tabs after method names in patterns
  - Use wildcard matching and regex support
- Implement proper HTTP method handlers
- Use appropriate status codes
- Format JSON responses correctly

2. Cookie Handling (New in 1.23)
- Use Cookie.Quoted field for preserving double quotes
- Implement Request.CookiesNamed for multiple cookies
- Support Cookie.Partitioned attribute
- Use ParseCookie/ParseSetCookie functions appropriately

3. Iterator Support (New in 1.23)
- Use the iter package for user-defined iterators
- Implement iterator functions matching patterns:
  func(func() bool)
  func(func(K) bool)
  func(func(K, V) bool)
- Leverage slices package iterator functions:
  - All() for indexes and values
  - Values() for elements
  - Backward() for reverse iteration
  - Collect() for gathering values
  - AppendSeq() for appending values
  - Sorted/SortedFunc/SortedStableFunc for sorted collections

4. Maps Package (New in 1.23)
- Use maps package iterator functions:
  - All() for key-value pairs
  - Keys() for map keys
  - Values() for map values
  - Insert() for adding pairs
  - Collect() for gathering into maps

5. Value Management (New in 1.23)
- Use unique package for value canonicalization
- Apply Handle[T] for efficient comparisons
- Consider structs package for memory layout control
- Use HostLayout when interfacing with platform APIs

ERROR HANDLING AND LOGGING:
- Implement proper error handling, including custom error types
- Properly wrap errors from driver.Valuer implementations
- Use structured errors with unwrap support
- Implement proper logging using standard library
- Consider telemetry for monitoring and debugging

PERFORMANCE AND SECURITY:
- Timer Considerations (New in 1.23):
  - Handle unbuffered timer channels (capacity 0)
  - Manage timer garbage collection
  - Use GODEBUG=asynctimerchan=1 if needed
- Utilize Go's built-in concurrency features
- Implement rate limiting
- Implement authentication/authorization
- Apply proper input validation
- Consider performance implications of struct layout

MIDDLEWARE AND CROSS-CUTTING CONCERNS:
- Implement middleware for logging, authentication, etc.
- Consider cross-cutting concerns in API design
- Handle timeouts and cancellation properly

TESTING:
- Provide suggestions for testing endpoints
- Use Go's testing package effectively
- Consider both unit and integration tests

Always prioritize:
1. Security
2. Scalability
3. Maintainability
4. Performance
5. Code readability
css
dockerfile
go
golang
html
java
javascript
jwt
+9 more
YYvanYang/raspberry-dashboard

Used in 1 repository

TypeScript
This is a software project for a payment company. We are using Next.js, Shadcn UI, Tailwind CSS, TypeScript, and Firebase. The idea is that the frontpage can receive leads and we use the back end to manage the leads and to create a CRM. 
Then I want an apply section where the customers can provide all the important information to apply for credit card processing. 
I need you to help me write a script for the Back end Software to manage teh customers. Customers can be a lead, a merchant, . I would like a system like trello to manage the lead and ths status. With ability to send email when changing status. 
The status in a column can be Lead,Phone Calls, Offer Sent,Underwriting, Documents, Approved.
PLease tell me what other features I would want in a crm fr merchant processing.

So I am going to send you a few prompts one by one until we can complete the project together. 


# Code Completeness Rules
CODE_COMPLETENESS:
- Write the complete file content from start to finish without any placeholders or comments about previous content
- Do not use comments like "Rest of code remains the same" or "Code unchanged"
- Do not truncate any files
- Do not use placeholders
- Every file modification must be complete and self-contained
- Never use ellipsis (...) to indicate unchanged code

# UI Framework Rules
UI_COMPONENTS:
Admin Interface (Back Office):
- Use Shadcn UI components exclusively for admin interfaces
- Required Shadcn components:
  - @/components/ui/button
  - @/components/ui/input
  - @/components/ui/form
  - @/components/ui/select
  - @/components/ui/dialog
  - @/components/ui/dropdown-menu
  - @/components/ui/table
  - @/components/ui/tabs
  - @/components/ui/card
  - @/components/ui/toast
  - @/components/ui/switch
- Follow Shadcn component naming conventions
- Use Shadcn theming system for admin interface
- Maintain consistent component styling across admin panels
- Use Shadcn form handling with react-hook-form

Public Website (Front Office):
- Use custom components with Tailwind CSS
- Always make the web pages beautiful and use as much effect as possible to improve the user experience
- Implement custom designs for better brand identity
- Use custom animations and transitions
- Maintain unique visual identity separate from admin interface

# Component Documentation
DOCUMENTATION:
- Add JSDoc comments for component props
- Document component usage patterns
- Include example usage in comments
- Document any complex logic or business rules
- Add TODO comments for future improvements

# File Structure
FILE_STRUCTURE:
Admin Components:
- Place in src/components/admin/
- Use Shadcn UI components
- Follow consistent layout patterns
- Implement proper loading states
- Use proper error boundaries

Public Components:
- Place in src/components/
- Use custom Tailwind components
- Implement unique designs
- Focus on performance and accessibility
- Use proper SEO practices

# Code Generation Rules
CODE_GENERATION:
- Generate complete files without truncation
- Include all imports and exports
- Include all type definitions
- Include all necessary comments
- Include all error handling
- Include all loading states
- Never use placeholder comments

File Structure:
```
└── 📁wikipayit
    └── 📁.bolt
        └── config.json
        └── prompt
    └── 📁src
        └── 📁assets
            └── 📁models
                └── credit-card.mtl
                └── credit-card.obj
            └── 📁textures
                └── gradient.png
            └── authorize.png.webp
            └── particles.json
        └── 📁components
            └── 📁admin
                └── AdminLayout.tsx
                └── SortableSection.tsx
                └── SuperAdmin.tsx
                └── WebsiteManagement.tsx
            └── 📁auth
                └── LoginModal.tsx
            └── 📁icons
                └── AuthorizeNetLogo.tsx
            └── 📁layouts
                └── MainLayout.tsx
            └── 📁ui
                └── navigation-menu.tsx
                └── switch.tsx
            └── ACHSection.tsx
            └── Authorize.svg
            └── ChargebackSection.tsx
            └── ContactForm.tsx
            └── EntrepreneurSection.tsx
            └── Footer.tsx
            └── GatewaySection.tsx
            └── Header.tsx
            └── HeroSection.tsx
            └── HighRiskSection.tsx
            └── IndustriesSection.tsx
            └── POSSection.tsx
            └── PricingSection.tsx
            └── TestimonialCard.tsx
            └── TestimonialsSection.tsx
        └── 📁config
        └── 📁contexts
            └── AuthContext.tsx
        └── 📁hooks
            └── useToast.tsx
        └── 📁lib
            └── firebase.ts
            └── utils.ts
        └── 📁pages
            └── HomePage.tsx
            └── LoginPage.tsx
        └── 📁public
        └── 📁services
            └── websiteService.ts
        └── .DS_Store
        └── App.tsx
        └── index.css
        └── main.tsx
        └── vite-env.d.ts
    └── .cursorrules
    └── .DS_Store
    └── .env
    └── .gitignore
    └── eslint.config.js
    └── index.html
    └── package-lock.json
    └── package.json
    └── postcss.config.js
    └── robots.txt
    └── tailwind.config.js
    └── tsconfig.app.json
    └── tsconfig.json
    └── tsconfig.node.json
    └── vite.config.ts
```
css
eslint
firebase
golang
html
javascript
next.js
react
+5 more

First seen in:

mserralta01/wikipayit

Used in 1 repository