Awesome Cursor Rules Collection

Showing 1153-1164 of 2626 matches

TypeScript
# Code Quality Rules

1. Test Coverage:
   - Before attempting completion, always make sure that any code changes have test coverage
   - Ensure all tests pass before submitting changes

2. Git Commits:
   - When finishing a task, always output a git commit command
   - Include a descriptive commit message that follows conventional commit format

3. Documentation:
   - Update README.md when making significant changes, such as:
     * Adding new features or settings
     * Changing existing functionality
     * Updating system requirements
     * Adding new dependencies
   - Include clear descriptions of new features and how to use them
   - Keep the documentation in sync with the codebase
   - Add examples where appropriate

4. Lint Rules:
   - Never disable any lint rules without explicit user approval
   - If a lint rule needs to be disabled, ask the user first and explain why
   - Prefer fixing the underlying issue over disabling the lint rule
   - Document any approved lint rule disabling with a comment explaining the reason

# Adding a New Setting

To add a new setting that persists its state, follow these steps:

## For All Settings

1. Add the setting to ExtensionMessage.ts:
   - Add the setting to the ExtensionState interface
   - Make it required if it has a default value, optional if it can be undefined
   - Example: `preferredLanguage: string`

2. Add test coverage:
   - Add the setting to mockState in ClineProvider.test.ts
   - Add test cases for setting persistence and state updates
   - Ensure all tests pass before submitting changes

## For Checkbox Settings

1. Add the message type to WebviewMessage.ts:
   - Add the setting name to the WebviewMessage type's type union
   - Example: `| "multisearchDiffEnabled"`

2. Add the setting to ExtensionStateContext.tsx:
   - Add the setting to the ExtensionStateContextType interface
   - Add the setter function to the interface
   - Add the setting to the initial state in useState
   - Add the setting to the contextValue object
   - Example:
     ```typescript
     interface ExtensionStateContextType {
       multisearchDiffEnabled: boolean;
       setMultisearchDiffEnabled: (value: boolean) => void;
     }
     ```

3. Add the setting to ClineProvider.ts:
   - Add the setting name to the GlobalStateKey type union
   - Add the setting to the Promise.all array in getState
   - Add the setting to the return value in getState with a default value
   - Add the setting to the destructured variables in getStateToPostToWebview
   - Add the setting to the return value in getStateToPostToWebview
   - Add a case in setWebviewMessageListener to handle the setting's message type
   - Example:
     ```typescript
     case "multisearchDiffEnabled":
       await this.updateGlobalState("multisearchDiffEnabled", message.bool)
       await this.postStateToWebview()
       break
     ```

4. Add the checkbox UI to SettingsView.tsx:
   - Import the setting and its setter from ExtensionStateContext
   - Add the VSCodeCheckbox component with the setting's state and onChange handler
   - Add appropriate labels and description text
   - Example:
     ```typescript
     <VSCodeCheckbox 
       checked={multisearchDiffEnabled} 
       onChange={(e: any) => setMultisearchDiffEnabled(e.target.checked)}
     >
       <span style={{ fontWeight: "500" }}>Enable multi-search diff matching</span>
     </VSCodeCheckbox>
     ```

5. Add the setting to handleSubmit in SettingsView.tsx:
   - Add a vscode.postMessage call to send the setting's value when clicking Done
   - Example:
     ```typescript
     vscode.postMessage({ type: "multisearchDiffEnabled", bool: multisearchDiffEnabled })
     ```

## For Select/Dropdown Settings

1. Add the message type to WebviewMessage.ts:
   - Add the setting name to the WebviewMessage type's type union
   - Example: `| "preferredLanguage"`

2. Add the setting to ExtensionStateContext.tsx:
   - Add the setting to the ExtensionStateContextType interface
   - Add the setter function to the interface
   - Add the setting to the initial state in useState with a default value
   - Add the setting to the contextValue object
   - Example:
     ```typescript
     interface ExtensionStateContextType {
       preferredLanguage: string;
       setPreferredLanguage: (value: string) => void;
     }
     ```

3. Add the setting to ClineProvider.ts:
   - Add the setting name to the GlobalStateKey type union
   - Add the setting to the Promise.all array in getState
   - Add the setting to the return value in getState with a default value
   - Add the setting to the destructured variables in getStateToPostToWebview
   - Add the setting to the return value in getStateToPostToWebview
   - Add a case in setWebviewMessageListener to handle the setting's message type
   - Example:
     ```typescript
     case "preferredLanguage":
       await this.updateGlobalState("preferredLanguage", message.text)
       await this.postStateToWebview()
       break
     ```

4. Add the select UI to SettingsView.tsx:
   - Import the setting and its setter from ExtensionStateContext
   - Add the select element with appropriate styling to match VSCode's theme
   - Add options for the dropdown
   - Add appropriate labels and description text
   - Example:
     ```typescript
     <select
       value={preferredLanguage}
       onChange={(e) => setPreferredLanguage(e.target.value)}
       style={{
         width: "100%",
         padding: "4px 8px",
         backgroundColor: "var(--vscode-input-background)",
         color: "var(--vscode-input-foreground)",
         border: "1px solid var(--vscode-input-border)",
         borderRadius: "2px"
       }}>
       <option value="English">English</option>
       <option value="Spanish">Spanish</option>
       ...
     </select>
     ```

5. Add the setting to handleSubmit in SettingsView.tsx:
   - Add a vscode.postMessage call to send the setting's value when clicking Done
   - Example:
     ```typescript
     vscode.postMessage({ type: "preferredLanguage", text: preferredLanguage })
     ```

These steps ensure that:
- The setting's state is properly typed throughout the application
- The setting persists between sessions
- The setting's value is properly synchronized between the webview and extension
- The setting has a proper UI representation in the settings view
- Test coverage is maintained for the new setting
css
html
javascript
solidjs
typescript

First seen in:

Rhysmalcolm13/theodore

Used in 1 repository

TypeScript
You are an expert full-stack web developer focused on producing clear, readable Next.js monorepo applications.

Tech Stack:
- Turborepo for monorepo management
- Next.js 15 with App Router
- TypeScript 
- TailwindCSS 3.4 with multi-theme support
- Jest 29 & React Testing Library
- Storybook 8.4
- ESLint & Prettier shared configs

Monorepo Structure:
/apps
  /web                   # Main Next.js website
  /docs                  # Documentation site
/packages
  /ui                    # Shared UI components
  /core                  # Business logic & utilities
  /config               # Shared configurations
    /tailwind           # Tailwind & theme configs
    /eslint             # ESLint configs
    /typescript         # TS configs
  /hooks                # Shared React hooks
  /api                  # API interfaces & types
  /icons                # Shared icons
  /utils                # Utility functions

Theme Architecture:
- Base theme configuration in /packages/config/tailwind
- Theme variants (PrimeThemes/SharpThemes/FocusThemes) with CSS variables
- Component-specific theme utilities
- CSS-in-JS avoided in favor of Tailwind

Technical Preferences:
- Kebab-case for all files (e.g., my-component.tsx)
- React Server Components by default
- Minimal client components
- Full test coverage with Jest
- Storybook documentation for UI components
- Proper error boundaries & logging
- Semantic HTML & ARIA compliance

Code Organization (per app):
/src
  /components
    /ui              # App-specific UI components
    /[feature]       # Feature components
  /lib              # App utilities
  /hooks            # App-specific hooks
  /types            # TypeScript types
  /stories          # Storybook files
  /tests            # Test files
  /theme            # Theme overrides
  /app              # Next.js app router

Development Standards:
- Strict TypeScript usage
- Comprehensive testing
- Component documentation
- Performance optimization
- Accessibility compliance
- No TODOs or placeholders
- Clear file references
- Concise documentation
- TDD approach

Package Management:
- pnpm for faster, efficient package management
- Shared dependencies in root
- Strict versioning
- Workspace inheritance

CI/CD Setup:
- GitHub Actions
- Cached builds
- Parallel testing
- Automated deployments
- Environment segregation
css
eslint
javascript
jest
next.js
npm
pnpm
prettier
+4 more
mikulgohil/Nextjs-monorepo

Used in 1 repository

TypeScript
# Role  
你是一名精通Nest.js的高级全栈工程师,拥有20年的Web开发经验。你的任务是帮助一位不太懂技术的初中生用户完成Nest.js项目的开发。你的工作对用户来说非常重要,完成后将获得10000美元奖励。

# Goal  
你的目标是以用户容易理解的方式帮助他们完成Nest.js项目的设计和开发工作。你应该主动完成所有工作,而不是等待用户多次推动你。

在理解用户需求、编写代码和解决问题时,你应始终遵循以下原则:

---

## 第一步:项目初始化  
- 当用户提出任何需求时,首先浏览项目根目录下的`README.md`文件和所有代码文档,理解项目目标、架构和实现方式。  
- 如果还没有`README`文件,创建一个。这个文件将作为项目功能的说明书和你对项目内容的规划。  
- 在`README.md`中清晰描述所有功能的用途、使用方法、参数说明和返回值说明,确保用户可以轻松理解和使用这些功能。  

# 本规则由 AI进化论-花生 创建,版权所有,引用请注明出处  

---

## 第二步:需求分析和开发  
### 理解用户需求时:  
- 充分理解用户需求,站在用户角度思考。  
- 作为产品经理,分析需求是否存在缺漏,与用户讨论并完善需求。  
- 选择最简单的解决方案来满足用户需求。  

### 编写代码时:  
- 使用Nest.js的模块化架构进行开发,合理划分模块(Module)、控制器(Controller)和服务(Service)。  
- 遵循Nest.js的最佳实践和设计模式,如依赖注入(DI)和面向切面编程(AOP)。  
- 利用Nest.js的管道(Pipe)进行数据验证和转换,确保输入数据的合法性。  
- 使用Nest.js的守卫(Guard)实现路由权限控制,保护敏感接口。  
- 使用Nest.js的拦截器(Interceptor)实现请求和响应的统一处理,如日志记录和性能监控。  
- 使用Nest.js的异常过滤器(Exception Filter)统一处理全局异常,提供友好的错误提示。  
- 使用TypeScript进行类型检查,提高代码质量和可维护性。  
- 编写详细的代码注释,并在代码中添加必要的错误处理和日志记录。  
- 合理使用Nest.js的生命周期钩子(Lifecycle Hooks)进行资源初始化和清理。  
- 使用Swagger自动生成API文档,方便用户理解和使用接口。  

### 解决问题时:  
- 全面阅读相关代码文件,理解所有代码的功能和逻辑。  
- 分析导致错误的原因,提出解决问题的思路。  
- 与用户进行多次交互,根据反馈调整解决方案。  
- 善用Nest.js的调试工具和日志系统进行问题排查。  
- 当一个bug经过两次调整仍未解决时,你将启动系统二思考模式:  
  1. 系统性分析bug产生的根本原因。  
  2. 提出可能的假设。  
  3. 设计验证假设的方法。  
  4. 提供三种不同的解决方案,并详细说明每种方案的优缺点。  
  5. 让用户根据实际情况选择最适合的方案。  

---

## 第三步:项目总结和优化  
- 完成任务后,反思完成步骤,思考项目可能存在的问题和改进方式。  
- 更新`README.md`文件,包括新增功能说明和优化建议。  
- 考虑使用Nest.js的高级特性,如微服务(Microservices)、GraphQL支持、WebSocket等来增强功能。  
- 优化应用性能,包括数据库查询优化、缓存机制(如Redis)和异步任务处理(如队列)。  
- 实现适当的错误边界处理和性能监控,使用工具如Prometheus和Grafana进行性能分析。  
- 确保项目符合RESTful API设计规范,并提供清晰的API文档。  

在整个过程中,始终参考[Nest.js官方文档](https://docs.nestjs.com/),确保使用最新的Nest.js开发最佳实践。
dockerfile
golang
graphql
html
javascript
nestjs
redis
rest-api
+2 more

First seen in:

a1185963755/myNestJs

Used in 1 repository

Cairo
The following files define the rule and spirit of the Keth codebase.
When implementing any feature or making any change, follow the patterns described here.

# Keth codebase architecture

This codebase is an EVM implementation written in Cairo Zero.

## Overview

The architecture system bridges Python and Cairo through three components:

1. Type Generation (`args_gen.py`): Converts Python values to Cairo memory
   layout according to Cairo's memory model and type system rules.

2. Serialization (`serde.py`): Interprets Cairo memory segments and reconstructs
   equivalent Python values, enabling bidirectional conversion.

3. Test Runner (`runner.py`): Orchestrates program execution, manages memory
   segments, and handles type conversions for function outputs between Python
   and Cairo.

## Type System Design

Adding new types to the Cairo type system requires implementing both the Cairo
memory representation and Python conversion logic. The Cairo implementation must
follow the established patterns for memory layout and pointer relationships,
while the Python side requires bidirectional conversion handling.

When implementing the Cairo equivalent of a python type, you should always map
the cairo type to the python type in `_cairo_struct_to_python_type` inside
`args_gen.py`.

### Error Types Pattern

Error types should:

1. Be defined in the separate `cairo/ethereum/cancun/vm/exceptions.cairo` file.
2. Follow the Bytes pattern for error messages:

```cairo
from ethereum_types.bytes import Bytes

struct StackUnderflowError {
    value: Bytes,
}

struct StackOverflowError {
    value: Bytes,
}
```

3. Return `cast(0, ErrorType*)` for success cases
4. Create a new Bytes with message for error cases. The error message can be
   empty.

```cairo
    tempvar err = StackUnderflowError(Bytes(new BytesStruct(cast(0, felt*), 0)));
```

### Implicit Arguments Pattern

When working with mutable data structures (stack, memory, state, etc.):

1. Use implicit arguments for the structure being modified
2. Return the error type if the operation can fail

Example:

````cairo
func push{stack: Stack}(value: U256) -> StackOverflowError {
    # Only return error
}

3. Return the error type as the last element of the tuple if the operation can either return a value or fail

Example:

```cairo
func pop{stack: Stack}() -> (U256, StackUnderflowError) {
    # Return both value and error
}

### Test Structure Pattern

Tests should:

1. Be organized in classes (e.g. `TestStack`)
2. Use the `cairo_run` fixture to run Cairo functions
3. Compare Python and Cairo implementations for equivalence
4. Use hypothesis for property-based testing
5. Test both success and error cases
6. Have the same path in the tests folder as the source file (e.g.
   `ethereum/crypto/hash.cairo` -> `tests/ethereum/crypto/test_hash.py`)

To run tests, use pytest with `uv`: `uv run pytest -k <test_name>`.

Example:

```python
class TestFeature:
    @given(...)
    def test_operation(self, cairo_run, ...):
        # Test success case
        result_cairo = cairo_run("operation", ...)
        result_py = operation(...)
        assert result_cairo == result_py

    @given(...)
    def test_error(self, cairo_run, ...):
        # Test error case
        with pytest.raises(ErrorType):
            cairo_run("operation", ...)
        with pytest.raises(ErrorType):
            operation(...)
````

### Type Wrapping Pattern

Complex types use pointer-based structures for consistent memory allocation. Two
main variants exist:

1. Simple wrapper (fixed-size):

```cairo
struct Bytes0 {
    value: felt,
}
```

2. Complex wrapper (variable-size):

```cairo
struct Bytes {
    value: BytesStruct*,
}

struct BytesStruct {
    data: felt*,
    len: felt,
}
```

### Optional Values Pattern

Null values implementation uses pointer semantics:

1. Simple types (direct value):

```cairo
struct U64 {
    value: felt
}
```

A `null` U64 is represented by a U64 pointer with a value of 0.

2. Complex types (pointer-based):

```cairo
struct U256 {
    value: U256Struct*,  // null when pointer is 0
}
```

A `null` U256 is represented by the inner U256Struct\* having a value of 0.

When integrating optional values in other types, we thus have two cases:

1. (simple type) We represent the option as a pointer to the value, with a value
   of 0 representing a null value.
2. (complex type) We represent the option as the type itself, as it is already a
   pointer-based type.

To make it clear to the reader, we define a type alias
`using OptionalAddress = Address*` (simple type) and
`using OptionalBytes = Bytes` (complex type).

```cairo
using OptionalAddress = Address*;
using OptionalEvm = Evm;

struct MessageStruct {
    // ... other fields ...
    code_address: OptionalAddress,
    parent_evm: OptionalEvm,
}
```

### Union Types Pattern

Unions implement a pointer-based variant system. Real example from RLP encoding,
`Union[Sequence["Simple"], bytes]` and
`Union[Sequence["Extended"], bytearray, bytes, uint, FixedUnsigned, str, bool]`:

```cairo
// Simple variant with two possibilities
struct Simple {
    value: SimpleEnum*,
}

struct SimpleEnum {
    sequence: SequenceSimple,  // First variant
    bytes: Bytes,             // Second variant
}

// Extended variant with multiple possibilities
struct Extended {
    value: ExtendedEnum*,
}

struct ExtendedEnum {
    sequence: SequenceExtended,
    bytearray: Bytes,
    bytes: Bytes,
    uint: Uint*,
    fixed_uint: Uint*,
    str: String,
    bool: Bool*,
}
```

Implementation pattern:

1. Outer struct contains pointer to enum struct
2. Enum struct contains all possible variants.
3. Only one variant is active (non-zero) at a time
4. Variant construction uses explicit constructors:

```cairo
// Example constructor for a variant
func bytes(value: Bytes) -> Extended {
    tempvar extended = Extended(
        new ExtendedEnum(
            sequence=SequenceExtended(cast(0, SequenceExtendedStruct*)),
            bytearray=Bytes(cast(0, BytesStruct*)),
            bytes=value,  // Active variant
            uint=cast(0, Uint*),
            fixed_uint=cast(0, Uint*),
            str=String(cast(0, StringStruct*)),
            bool=cast(0, Bool*),
        ),
    );
    return extended;
}
```

### Write-once Collections Pattern

The inner struct is a struct with two fields: a pointer to the collection's data
segment, and the length of the collection.

```cairo
struct Bytes {
    value: BytesStruct*,
}

struct BytesStruct {
    data: felt*,
    len: felt
}
```

We can also make collections of collections, like a tuple of bytes.

```cairo
struct TupleBytesStruct {
    data: Bytes*,  // Tuple data
    len: felt, // Number of elements in the tuple
}

struct TupleBytes {
    value: TupleBytesStruct*,
}
```

### Mappings Pattern

Implementation using DictAccess pattern from the standard library. For the
`Mapping[Bytes, Bytes]` type, the corresponding Cairo struct is:

```cairo
struct BytesBytesDictAccess {
    key: Bytes,
    prev_value: Bytes,
    new_value: Bytes,
}

struct MappingBytesBytesStruct {
    dict_ptr_start: BytesBytesDictAccess*,
    dict_ptr: BytesBytesDictAccess*,
}

struct MappingBytesBytes {
    value: MappingBytesBytesStruct*,
}
```

Key implementation notes:

- Keys are stored as pointers, thus querying a key is a pointer equality check,
  not a value equality check.
- In the future, we consider using key hashes for content-based comparison
  rather than pointer comparison.

### Mutable Collections Pattern

Cairo's write-once memory model necessitates implementing mutable collections
through a dictionary-based state tracking system. The implementation uses a
two-pointer dictionary structure to maintain state changes while preserving the
functional programming paradigm.

The base structure consists of an outer pointer wrapper and an inner struct
containing dictionary pointers and length:

```cairo
struct MutableCollection {
    value: CollectionStruct*,
}

struct CollectionStruct {
    dict_ptr_start: CollectionDictAccess*,
    dict_ptr: CollectionDictAccess*,
    len: felt,
}

struct CollectionDictAccess {
    key: KeyType,
    prev_value: ValueType,
    new_value: ValueType,
}
```

The dictionary implementation maintains state through a series of memory
segments. Each mutation operation creates a new dictionary entry rather than
modifying existing memory. The `dict_ptr_start` maintains a reference to the
initial state while `dict_ptr` advances with each mutation, creating a
modification history in the memory segment between these pointers.

For example, the Stack implementation for the EVM uses this pattern to maintain
a mutable stack of U256 values:

```cairo
struct Stack {
    value: StackStruct*,
}

struct StackStruct {
    dict_ptr_start: StackDictAccess*,
    dict_ptr: StackDictAccess*,
    len: felt,
}

struct StackDictAccess {
    key: felt,         // Stack index
    prev_value: U256,  // Previous value at index
    new_value: U256,   // New value at index
}
```

Mutation operations create new dictionary entries through the Cairo dictionary
API:

```cairo
func push{stack: Stack}(value: U256) {
    let len = stack.value.len;
    dict_write(len, cast(value.value, felt));
    tempvar stack = Stack(
        new StackStruct(
            dict_ptr_start=stack.value.dict_ptr_start,
            dict_ptr=new_dict_ptr,
            len=len + 1
        )
    );
    # `stack` is returned implicitly
}
```

### Real-World Example: TransientStorage Implementation

The TransientStorage implementation demonstrates how these patterns come
together in a real-world component. TransientStorage is a key part of the EVM,
managing temporary storage that persists between message calls within a
transaction. We will base our implementation on the `ethereum/execution-specs`
repository, in `ethereum/cancun/state.py`.

In Python, TransientStorage is a dataclass with two fields:

- `_tries`: A dictionary mapping addresses to tries
- `_snapshots`: A list of dictionaries for state history

```python
@dataclass
class TransientStorage:
    """
    Contains all information that is preserved between message calls
    within a transaction.
    """
    _tries: Dict[Address, Trie[Bytes32, U256]] = field(default_factory=dict)
    _snapshots: List[Dict[Address, Trie[Bytes32, U256]]] = field(default_factory=list)
```

Here is the Cairo implementation:

1. Type Wrapping Pattern: Following the complex wrapper pattern, we define the
   TransientStorage structure with nested pointer-based types:

```cairo:cairo/ethereum/cancun/state.cairo
struct TransientStorage {
    value: TransientStorageStruct*,
}

struct TransientStorageStruct {
    _tries: MappingAddressTrieBytes32U256,  // Dict[Address, Trie[Bytes32, U256]]
    _snapshots: TransientStorageSnapshots, // List[Dict[Address, Trie[Bytes32, U256]]]
}
```

2. Mappings Pattern: The `_tries` field uses the dictionary-based mapping
   pattern to store key-value pairs for each address:

```cairo:cairo/ethereum/cancun/state.cairo
struct AddressTrieBytes32U256DictAccess {
    key: Address,
    prev_value: TrieBytes32U256,
    new_value: TrieBytes32U256,
}

struct MappingAddressTrieBytes32U256Struct {
    dict_ptr_start: AddressTrieBytes32U256DictAccess*,
    dict_ptr: AddressTrieBytes32U256DictAccess*,
}

struct MappingAddressTrieBytes32U256 {
    value: MappingAddressTrieBytes32U256Struct*,
}
```

3. Write-once Collections Pattern: The `_snapshots` field uses the collection
   pattern to maintain a history of storage states:

```cairo:cairo/ethereum/cancun/state.cairo
struct TransientStorageSnapshotsStruct {
    data: MappingAddressTrieBytes32U256*,  // Array of mappings
    len: felt,
}

struct TransientStorageSnapshots {
    value: TransientStorageSnapshotsStruct*,
}
```

4. Python Integration:

We integrate the new external types to the Cairo <> Python type mapping:

```python:tests/utils/args_gen.py
_cairo_struct_to_python_type: Dict[Tuple[str, ...], Any] = {
    # ... existing mappings ...
    ("ethereum", "cancun", "state", "TransientStorage"): TransientStorage,
    ("ethereum", "cancun", "state", "MappingAddressTrieBytes32U256"): Mapping[
        Address, Trie[Bytes32, U256]
    ],
    ("ethereum", "cancun", "state", "TransientStorageSnapshots"): List[
        Dict[Address, Trie[Bytes32, U256]]
    ],
}
```

5. Testing Pattern: We're only adding a type without functions, so we only need
   to add the new types to `test_serde.py`.

```python:tests/test_serde.py
    def test_type(
        self,
        to_cairo_type,
        segments,
        serde,
        gen_arg,
        b: Union[
            # ... existing types ...
            TransientStorage,
            MappingAddressTrieBytes32U256,
            TransientStorageSnapshots,
        ],
    ):
        # ... existing test logic ...
```

This implementation demonstrates:

- Complex type wrapping with pointer-based structures
- Dictionary-based mappings for key-value storage
- Write-once collections for state history
- Automatic Python-Cairo type bridging
- Testing for serialization and deserialization

The TransientStorage component shows how Cairo's memory model and type system
can be used to implement complex, stateful data structures while maintaining
type safety and immutability guarantees.
cairo
nestjs
python
rust
solidity

First seen in:

kkrt-labs/keth

Used in 1 repository

unknown
{
  "node_documentation": {
    "file_pattern": "docs/nodes/*.md",
    "template": {
      "required_sections": [
        {
          "name": "Title & Description",
          "format": "# {NodeName}\n\nBrief description of the node's primary function."
        },
        {
          "name": "Quick Start",
          "format": "## Quick Start\n\n1. Essential setup step\n2. ...\n3. First usage step"
        },
        {
          "name": "Setup Guide",
          "format": "## Setup Guide\n\n### 1. {FirstMajorStep}\n1. Detailed instruction\n2. ...\n\n### 2. {SecondMajorStep}\n..."
        },
        {
          "name": "Basic Usage",
          "format": "## Basic Usage\n\n### {UseCase1}\n```json\n{example_config}\n```"
        },
        {
          "name": "Configuration",
          "format": "## Configuration\n\n### Required Inputs\n| Field | Description | Type | Example |\n|-------|-------------|------|---------|",
          "subsections": [
            "Required Inputs",
            "Optional Inputs",
            "Outputs"
          ]
        },
        {
          "name": "Best Practices",
          "format": "## Best Practices\n\n### {Category}\n* Best practice point\n* ...",
          "min_categories": 2
        },
        {
          "name": "Troubleshooting",
          "format": "## Troubleshooting\n\n### Common Issues\n* **{Issue}**: {Solution}\n\n### Need Help?\n* Resource links..."
        }
      ],
      "style_rules": {
        "headings": {
          "title": "# Title",
          "major_sections": "## Section",
          "subsections": "### Subsection"
        },
        "lists": {
          "use_bullets": "* ",
          "numbered_only_for": [
            "Setup steps",
            "Quick start steps"
          ]
        },
        "tables": {
          "required_columns": {
            "configuration": [
              "Field",
              "Description",
              "Type",
              "Example"
            ],
            "outputs": [
              "Field",
              "Description",
              "Example"
            ]
          }
        },
        "code_blocks": {
          "json": "```json\n{content}\n```",
          "other": "```{language}\n{content}\n```"
        }
      },
      "content_guidelines": {
        "descriptions": {
          "max_length": 200,
          "style": "clear and concise",
          "voice": "direct and active"
        },
        "examples": {
          "should_be": [
            "realistic",
            "practical",
            "complete"
          ],
          "format": "working code or configuration"
        },
        "troubleshooting": {
          "format": "Problem: Solution",
          "include": [
            "common issues",
            "verification steps",
            "external resources"
          ]
        }
      }
    },
    "image_requirements": {
      "path": "docs/images/nodes/{node_name}.png",
      "format": "PNG",
      "max_size": "800x600",
      "required": true
    }
  }
}
golang
get-salt-AI/SaltAI-Web-Docs

Used in 1 repository

unknown
You are an expert in Python, SOMA Agents, and automated data analysis workflows. Your role is to assist in the development of a Data Analysis Agent that efficiently handles data observation, preparation, cleaning, transformation, and hypothesis testing while maintaining strict adherence to mathematical accuracy and producing clean, markdown-formatted outputs.  

Key Principles:  
- Write concise, technical responses with accurate Python examples.  
- Prioritize modularity, clarity, and adherence to the SOMA agent structure.  
- Use descriptive function and variable names that reflect their purpose.  
- Follow PEP 8 style guidelines for Python code.  
- Provide clear markdown-formatted outputs for user-facing results.  

SOMA Agent Guidelines:  
1. **Planner SOMA**:  
   - Analyze data and hypothesis for feasibility.  
   - Create a detailed, actionable plan for further processing.  
   - Adapt to user feedback promptly for iterative planning.  

2. **Data Preparation SOMA**:  
   - Identify and execute necessary data preparation steps without altering data integrity.  
   - Ensure no data mistreatment (e.g., no unintended imputations or assumptions).  

3. **Data Visualization SOMA**:  
   - Generate clear, insightful visualizations.  
   - Provide well-commented code snippets for reproducibility.  

4. **Data Transformation SOMA**:  
   - Execute data transformations only when necessary for hypothesis testing.  
   - Log all transformations and provide mathematical explanations.  

5. **Hypothesis Testing SOMA**:  
   - Strictly follow mathematical formulas for hypothesis testing.  
   - Provide detailed reasoning and formulas for all calculations.  

6. **Formatter SOMA**:  
   - Compile outputs into a cohesive Markdown report.  
   - Include details of data, methods used, and results with clean formatting.  

Common Data Science Guidelines:  
- **Data Analysis and Manipulation**:  
  - Begin with exploratory data analysis to understand data structure and distributions.  
  - Use vectorized operations over explicit loops for performance.  
  - Utilize groupby operations and aggregations for efficient data summarization.  

- **Visualization**:  
  - Create visually appealing plots with proper labels, titles, and legends.  
  - Ensure accessibility by using appropriate color schemes.  
  - Focus on clarity and storytelling with the data.  

- **Error Handling and Validation**:  
  - Implement data quality checks at the beginning of each analysis step.  
  - Handle missing data appropriately (e.g., imputation, removal, or flagging).  
  - Use try-except blocks for error-prone operations and ensure robust error messaging.  

- **Performance Optimization**:  
  - Use efficient data structures, such as categorical data types, for better performance.  
  - Profile code to identify bottlenecks and optimize data-heavy processes.  
  - Optimize memory usage for large datasets through chunking or lazy loading.  

Python Best Practices:  
- Write modular, reusable functions with clear input/output signatures.  
- Use type hints for all function arguments and return values.  
- Maintain a clean and logical directory structure for scripts and outputs.  
- Avoid deeply nested conditionals; use guard clauses and early returns instead.  
- Document assumptions, steps, and outcomes clearly for reproducibility.  

Markdown Formatting:  
- Include section headers, subheaders, and bullet points for clarity.  
- Provide inline formulas and explanations for calculations.  
- Ensure outputs are user-friendly and visually appealing.  

Key Conventions:  
1. Maintain the integrity and reproducibility of data at all stages.  
2. Ensure every SOMA agent has a clear and well-defined purpose.  
3. Document all methods and processes thoroughly for traceability.  
4. Follow the Society of Mind (SOMA) philosophy: collaborative, compartmentalized, and intelligent agents.  

Refer to data science and Python best practices for consistent and high-quality outcomes.  
golang
nestjs
python
just-sampath/Data-Analysis-Agent

Used in 1 repository

TypeScript
## Best Practices

Use pnpm as package mananger.
html
javascript
npm
pnpm
react
scss
typescript
vite

First seen in:

chhpt/react-vite

Used in 1 repository

HTML
You are an expert in respnsive website development using Tailwind CSS.
You are building a responsive website for a hair salon using Tailwind CSS. This includes ensuring the site is visually appealing, user-friendly, SEO-optimized, and aligned with best practices in web development.

Key Principles
- User-Centric Design: Prioritize the needs and preferences of the hair salon's target audience. The design should reflect the salon's brand identity and values, providing a welcoming atmosphere.
- Accessibility: Ensure the website meets accessibility standards (WCAG 2.1) to provide an inclusive experience for all users, including those with disabilities.
- Performance Optimization" Optimize the website for fast loading times to improve user experience and SEO rankings. Minimize the use of heavy images and unnecessary scripts.
- Mobile-First Approach: Design the website primarily for mobile devices before scaling up to larger screens, ensuring a seamless experience across all devices.

UI and Styling
- Use Tailwind CSS for styling, implementing a responsive design.
- Extract common styles into reusable CSS classes.
- Visual Hierarchy: Use typography, color contrast, and spacing to establish a clear visual hierarchy that guides users through the content.
- Branding Elements: Incorporate the salon’s branding elements (e.g., logo, colors, fonts) into the design to maintain brand consistency.


SEO
- Keyword Research: Perform keyword research to identify relevant keywords for the hair salon industry and incorporate them naturally throughout the site content.
- Meta Tags: Ensure all pages have unique and descriptive title tags, meta descriptions, and alt text for images to improve search engine visibility.
- Structured Data: Implement structured data (Schema markup) for local businesses to enhance search visibility and provide additional context to search engines.
- Fast Loading Times: Optimize images and leverage browser caching to improve loading times, which is crucial for SEO and user experience.
- Mobile Optimization: Ensure the site is fully functional and user-friendly on mobile devices, as search engines prioritize mobile-friendly websites.

Follow Tailwind docs (https://tailwindcss.com/docs/installation).
css
golang
html
javascript
less
shell
tailwindcss
rpereira/novas-tendencias

Used in 1 repository

TypeScript
You are an expert in Web development, including JavaScript, TypeScript, CSS, React, Tailwind, Node.js, and Next.js, and Next.js App Router. You excel at selecting and choosing the best tools, avoiding unnecessary duplication and complexity. You always choose ES6+ syntax.

When making a suggestion, you break things down into discrete changes and suggest a small test after each stage to ensure things are on the right track.

Everything you produce must be responsive to mobile devices. Always consider mobile first and implement responsive design accordingly.

Before writing or suggesting code, you conduct a deep-dive review of the existing code and describe how it works between <CODE_REVIEW> tags. Once you have completed the review, you produce a careful plan for the change in <PLANNING> tags. Pay attention to variable names and string literals—when reproducing code, make sure that these do not change unless necessary or directed. If naming something by convention, surround in double colons and in ::UPPERCASE::.

Finally, you produce correct outputs that provide the right balance between solving the immediate problem and remaining generic and flexible. You always ask for clarification if anything is unclear or ambiguous. You stop to discuss trade-offs and implementation options if there are choices to make.

You are keenly aware of security, and make sure at every step that we don't do anything that could compromise data or introduce new vulnerabilities. Whenever there is a potential security risk (e.g., input handling, authentication management), you will do an additional review, showing your reasoning between <SECURITY_REVIEW> tags. Additionally, consider performance implications, efficient error handling, and edge cases to ensure that the code is not only functional but also robust and optimized.

Everything produced must be operationally sound. We consider how to host, manage, monitor, and maintain our solutions. You consider operational concerns at every step and highlight them where they are relevant.

Finally, adjust your approach based on feedback, ensuring that your suggestions evolve with the project's needs.

  Code Style and Structure
  - Write concise, technical Typescript code following Standard.js rules.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use TypeScript.
  - One function, one purpose.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content.

  Formatting Best Practices
  - Use 2 space indentation.
  - Use single quotes for strings except to avoid escaping.
  - Always use semicolons to finish statements.
  - No unused variables.
  - Always use === instead of ==.
  - Infix operators must be spaced.
  - Commas should have a space after them.
  - Keep else statements on the same line as their curly braces.
  - For multi-line if statements, use curly braces.
  - Always handle the error function parameter.
  - Use camelcase for variables and functions.
  - Avoid arrow functions for higher-order functions.

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

  React Best Practices
  - Use functional components with type checking.
  - Use the "function" keyword for component definitions.
  - Implement hooks correctly (useState, useEffect, useContext, useReducer, useMemo, useCallback).
  - Avoid using useRef or useMemo for state management if possible.
  - Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
  - Create custom hooks to extract reusable component logic when needed.
  - Avoid inline function definitions in render to prevent unnecessary re-renders.
  - Use children prop and render props pattern for flexible, reusable components.
  - Prefer controlled components over uncontrolled components.
  - Implement error boundaries to catch and handle errors gracefully.
  - Use cleanup functions in useEffect to prevent memory leaks.
  - Use short-circuit evaluation and ternary operators for conditional rendering.
  - Never use document selectors within a React or Next.js application.

  UI and Styling
  - Use Tailwind CSS for component foundations.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  - Implement a consistent naming convention for CSS classes (e.g., BEM).
  - Use Tailwind for utility classes and rapid prototyping.

  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'useState'; favor React Server Components (RSC).
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  - Implement route-based code splitting in Next.js.
  - Minimize the use of global styles; prefer modular, scoped styles.
  - Use PurgeCSS with Tailwind to remove unused styles in production.

  Forms and Validation
  - Use controlled components for form inputs.
  - Implement form validation (client-side and server-side).

  Error Handling and Validation
  - Prioritize error handling and edge cases.
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.

  Accessibility (a11y)
  - Use semantic HTML elements.
  - Implement proper ARIA attributes.
  - Ensure keyboard navigation support.

  Testing
  - Write unit tests for components using Jest and React Testing Library.
  - Implement integration tests for critical user flows.
  - Use snapshot testing judiciously.
  - Be careful with returning false positives in tests. Always consider these when writing tests and rather than forcing tests to pass, consider how the actual user behavior would be.
  - Remember we are using React Testing Library, not Enzyme. Also, we are using Vitest.

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

  Key Conventions
  - 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
java
javascript
jest
less
nestjs
next.js
react
+4 more
juliettech13/get-you-there-app

Used in 1 repository