Awesome Cursor Rules Collection

Showing 397-408 of 2626 matches

MDX
General Guidelines:
- Be concise and accurate, avoid unnecessary verbosity.
- Suggest solutions the user might not have thought about; anticipate needs.
- Treat the user as an expert; provide answers directly and thoroughly.
- Value good arguments over authority; source is irrelevant unless explicitly asked.
- Discuss safety only when it’s crucial and non-obvious.
- Split responses into multiple messages if the content exceeds length limitations.
- Avoid placeholders, TODOs, or incomplete pieces of code; ensure completeness.
- Fully implement all requested functionality. Verify correctness thoroughly.
- Keep README.md up-to-date with project setup and contribution guidelines.
- Confirm before writing code when clarification is required.
- Flag speculative or predictive content.


Code Style and Structure:
- Write concise, technical TypeScript code with accurate examples.
- Use functions declared with the `function` keyword for pure functions; omit semicolons.
- Follow DRY principles (Don’t Repeat Yourself) and prefer modularization.
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Never use `export default` unless it’s a config file that doesn’t allow named exports.
- One React component per file; break large components into smaller pieces.
- Use `React.memo()` for performance optimization when appropriate.
- Prefer `async/await` over `.then()` for asynchronous operations.
- Always Receive an Object, Return an Object (RORO).
- Handle errors gracefully; if a promise doesn’t throw, append `noError` to the variable name.



Project Structure:
- **Monorepo Layout**:
  - Deployable apps: `apps/*` (e.g., `apps/blog`, `apps/www`, `apps/api`).
  - Shared modules: `packages/*`.
  - Config files and tooling: `tooling/*`.
- **Naming Conventions**:
  - Booleans: Use auxiliary verbs such as `does`, `has`, `is`, `should` (e.g., `isDisabled`, `hasError`).
  - Directories: Use lowercase with dash separators (e.g., `components/auth-wizard`).
  - React component files: Match the component name (e.g., `CopyRight.tsx` for the `CopyRight` component).
  - File extensions: Use `.config.ts`, `.test.ts`, `.context.tsx`, `.type.ts`, `.hook.ts` appropriately.

React and Next.js Guidelines:

- **React Best Practices**:
  - Minimize `use client`, `useEffect`, and `setState` usage.
  - Favor React Server Components (RSC).
  - Wrap client components in `Suspense` with a fallback.
  - Use dynamic imports for non-critical components.
  - Optimize images (WebP format, size data, lazy loading).
  - Implement accessibility features (e.g., `aria-label`, `tabindex`, proper roles).

- **Next.js Best Practices**:
  - Follow Next.js documentation for Data Fetching, Rendering, and Routing.
  - Optimize Web Vitals (LCP, CLS, FID).
  - Use `nuqs` for URL search parameter state management.
  - Sanitize user inputs to prevent XSS attacks.

Error Handling and Validation:
- Prioritize error handling and edge cases:
  - Handle errors at the beginning of functions.
  - Use guard clauses to handle preconditions and invalid states early.
  - Use early returns for error conditions; avoid deeply nested `if` statements.
  - Avoid unnecessary `else` statements; use the `if-return` pattern.
- Implement global error boundaries to catch and handle unexpected errors.
- Log errors consistently and provide user-friendly error messages.
- Consider using custom error types or error factories.
- Add environment variables to `packages/env` for validation.

Styling and Design:
- Use ShadCN UI, Radix, and TailwindCSS for components and styling.
- Implement responsive design with a mobile-first approach.
- Always use Tailwind classes for styling; avoid inline styles or separate CSS files.
- Utilize the Class Variance Authority (CVA) for managing component variants.

Object-Oriented Programming:
- Use `public` modifier for all public methods.
- Use `private` modifier for all private methods, prefixed with an underscore.
- Place getters and setters at the top of the class.
- Use `static` for static methods.
- Use `async` for asynchronous class methods.

Testing:
- Write unit tests for components using `vitest`.
- Implement integration tests for critical user flows.
- Use snapshot testing sparingly.
- Use Playwright for end-to-end (e2e) tests.



Miscellaneous:
- Sanitize content when using `dangerouslySetInnerHTML`; avoid whenever possible.
- Use libraries like `react-intl` or `next-i18next` for internationalization (i18n).
- Follow Taskfile commands for development and deployment tasks.
- Follow WCAG standards for color contrast and readability.
- Comment only when necessary to clarify complex logic; avoid excessive comments.
- Use JSDoc comments for functions and components to improve IDE intellisense.

css
dockerfile
golang
handlebars
hcl
javascript
just
less
+12 more

First seen in:

ashgw/ashgw.me

Used in 1 repository

unknown
// Code Quality and Best Practices

// Clean Code Principles
- Function Design:
  * Single Responsibility
  * Maximum 20 lines per function
  * Maximum 3 parameters
  * Avoid flag parameters
  * Use meaningful names
- Class Design:
  * Follow SOLID principles
  * Prefer composition over inheritance
  * Keep classes focused
  * Implement interfaces
- Code Organization:
  * Group related code
  * Maintain consistent structure
  * Use meaningful file names
  * Keep files under 400 lines

// Design Patterns
- Creational Patterns:
  * Factory Method
  * Abstract Factory
  * Builder
  * Singleton (use sparingly)
  * Dependency Injection
- Structural Patterns:
  * Adapter
  * Bridge
  * Composite
  * Decorator
  * Facade
- Behavioral Patterns:
  * Observer
  * Strategy
  * Command
  * State
  * Template Method

// Code Review Guidelines
- Review Checklist:
  * Code style compliance
  * Test coverage
  * Security considerations
  * Performance impact
  * Documentation
- Review Process:
  * Maximum 400 lines per review
  * Review within 24 hours
  * Address all comments
  * Require two approvals
  * No self-merging

// Documentation Standards
- Code Documentation:
  * JSDoc/TypeDoc for functions
  * Interface documentation
  * Complex logic explanation
  * Example usage
- Project Documentation:
  * README.md structure
  * API documentation
  * Setup instructions
  * Troubleshooting guide
  * Architecture overview

// Performance Optimization
- Code Level:
  * Optimize loops
  * Use appropriate data structures
  * Implement caching
  * Lazy loading
  * Memory management
- Build Level:
  * Code splitting
  * Tree shaking
  * Minification
  * Asset optimization
  * Bundle analysis

// Technical Debt
- Identification:
  * Code complexity metrics
  * Duplicate code
  * Outdated dependencies
  * TODO comments
  * Dead code
- Management:
  * Regular refactoring
  * Debt tracking
  * Priority assessment
  * Impact analysis
  * Resolution planning

// Code Style
- Formatting:
  * Use prettier/black
  * Consistent indentation
  * Line length limits
  * Whitespace rules
- Naming:
  * Clear and descriptive
  * Follow conventions
  * Use domain terminology
  * Avoid abbreviations
- Comments:
  * Explain why, not what
  * Keep updated
  * Remove commented code
  * Document assumptions 
bun
prettier
solidjs
TMHSDigital/CursorRulesFiles

Used in 1 repository

Astro

# Astro SEO-Optimized Blog Post Rules

0. The canonical url for the domain
  - https://cpmcalculator.online/

1. Use descriptive and keyword-rich titles
   - Include target keyword in the title
   - Keep titles under 60 characters for optimal display in search results

2. Optimize meta descriptions
   - Write compelling meta descriptions between 150-160 characters
   - Include target keyword and a call-to-action

3. Utilize header tags (H1, H2, H3) effectively
   - Use only one H1 tag per post (usually the title)
   - Structure content with H2 and H3 tags for readability and SEO

4. Optimize images
   - Use descriptive, keyword-rich file names
   - Add alt text to all images
   - Compress images for faster loading

5. Internal linking
   - Link to relevant internal pages and other blog posts
   - Use descriptive anchor text for links

6. External linking
   - Link to authoritative sources to support your content
   - Open external links in new tabs

7. URL structure
   - Use short, descriptive URLs with keywords
   - Separate words with hyphens

8. Content quality and length
   - Aim for at least 1500 words for in-depth topics
   - Ensure content is original, informative, and valuable to readers

9. Use schema markup
   - Implement appropriate schema for blog posts (e.g., Article, BlogPosting)

10. Optimize for featured snippets
    - Use question-and-answer format where appropriate
    - Provide concise, direct answers to common questions

11. Mobile optimization
    - Ensure blog posts are responsive and mobile-friendly

12. Page speed
    - Optimize images, minify CSS and JavaScript
    - Utilize Astro's built-in performance features

13. Social media optimization
    - Include Open Graph and Twitter Card meta tags
    - Create shareable content with eye-catching visuals

14. Update content regularly
    - Keep blog posts up-to-date with fresh information
    - Consider adding a "Last Updated" date to posts

15. Encourage user engagement
    - Enable comments (if appropriate for your site)
    - Include social sharing buttons

16. Use canonical tags
    - Implement canonical tags to avoid duplicate content issues

17. Implement breadcrumbs
    - Use breadcrumbs for better navigation and SEO

18. Create a sitemap
    - Ensure your blog posts are included in your sitemap.xml

19. Optimize for Core Web Vitals
    - Focus on Largest Contentful Paint, First Input Delay, and Cumulative Layout Shift

20. Use relevant categories and tags
    - Organize content with SEO-friendly categories and tags
astro
css
golang
html
java
javascript
mdx
typescript
laurencetuchin/cpm-calculator-v2

Used in 1 repository

Java
# プロジェクトの指示

あなたは高度な問題解決能力を持つAIアシスタントです。以下の指示に従って、効率的かつ正確にタスクを遂行してください。

まず、ユーザーから受け取った指示を確認します:
<指示>
{{instructions}}
</指示>

この指示を元に、以下のプロセスに従って作業を進めてください:

---

## 1. 指示の分析と計画

このセクションは、後続のプロセス全体を導くものなので、時間をかけてでも、十分に詳細かつ包括的な分析を行ってください。

### タスク分析

- 主要なタスクを簡潔に要約してください。
- 記載された技術スタックを確認し、その制約内での実装方法を検討してください。
  - **※ 技術スタックに記載のバージョンは変更せず、必要があれば必ず承認を得てください。**
- 重要な要件と制約を特定してください。
- 潜在的な課題をリストアップしてください。
- タスク実行のための具体的なステップを詳細に列挙してください。
- それらのステップの最適な実行順序を決定してください。

### 重複実装の防止

実装前に以下の確認を行ってください

- 既存の類似機能の有無
- 同名または類似名の関数やコンポーネント
- 重複するAPIエンドポイント
- 共通化可能な処理の特定

## 2. タスクの実行

- 特定したステップを一つずつ実行してください。
- 各ステップの完了後、簡潔に進捗を報告してください。
- 実装時は以下の点に注意してください
  - 適切なディレクトリ構造の遵守
  - 命名規則の一貫性維持
  - 共通処理の適切な配置

## 3. 品質管理と問題対応

- 各タスクの実行結果を迅速に検証してください。
- エラーや不整合が発生した場合は、以下のプロセスで対応してください
  - 問題の切り分けと原因特定(ログ分析、デバッグ情報の確認)
  - 対策案の作成と実施
  - 修正後の動作検証
  - デバッグログの確認と分析

- 検証結果は以下の形式で記録してください
  - 検証項目と期待される結果
  - 実際の結果と差異
  - 必要な対応策(該当する場合)

## 4. 最終確認

- すべてのタスクが完了したら、成果物全体を評価してください。
- 当初の指示内容との整合性を確認し、必要に応じて調整を行ってください。
- 実装した機能に重複がないことを最終確認してください。

## 5. 結果報告

以下のフォーマットで最終的な結果を報告してください:

```markdown
    # 実行結果報告

    ## 概要

    [全体の要約を簡潔に記述]

    ## 実行ステップ
    1. [ステップ1の説明と結果]
    2. [ステップ2の説明と結果]
    ...

    ## 最終成果物

    [成果物の詳細や、該当する場合はリンクなど]

    ## 課題対応(該当する場合)

    - 発生した問題と対応内容
    - 今後の注意点

    ## 注意点・改善提案

    - [気づいた点や改善提案があれば記述]
```

---

## 重要な注意事項

- 不明点がある場合は、作業開始前に必ず確認を取ってください。
- 重要な判断が必要な場合は、その都度報告し、承認を得てください。
- 予期せぬ問題が発生した場合は、即座に報告し、対応策を提案してください。
- **明示的に指示されていない変更は行わないでください。** 必要と思われる変更がある場合は、まず提案として報告し、承認を得てから実施してください。
- **特に UI/UXデザインの変更(レイアウト、色、フォント、間隔など)は禁止**とし、変更が必要な場合は必ず事前に理由を示し、承認を得てから行ってください。
- **技術スタックに記載のバージョン(APIやフレームワーク、ライブラリ等)を勝手に変更しないでください。** 変更が必要な場合は、その理由を明確にして承認を得るまでは変更を行わないでください。

---

## 技術スタック

### コア技術

- Java: 21
- Spring Boot: 3.2.1
- JUnit Jupiter: (Spring Boot依存バージョン)
- Mockito: 5.11.0

### 開発ツール

- Maven: 3.9.x
- Eclipse: 2024-03
- JaCoCo: 0.8.11

### プロジェクト設定

- Java Compiler: Java 21
- Source Encoding: UTF-8
- Test Thread Count: 8
- Test Fork Count: 2C

---

## プロジェクト構成

以下のディレクトリ構造に従って実装を行ってください:

```bash
directory-operation-parallel-execution-tool/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── kmg/
│   │   │       └── tool/
│   │   │           └── directorytool/
│   │   │               ├── service/      # サービス層
│   │   │               ├── model/        # モデル
│   │   │               └── runner/       # 実行クラス
│   │   └── resources/                    # リソースファイル
│   └── test/
│       ├── java/                         # テストコード
│       │   └── kmg/
│       │       └── tool/
│       │           └── directorytool/
│       │               ├── service/      # サービステスト
│       │               ├── model/        # モデルテスト
│       │               └── runner/       # 実行クラステスト
│       └── resources/                    # テストリソース
├── .settings/                            # Eclipse設定
│   ├── org.eclipse.jdt.core.prefs       # Java開発設定
│   ├── org.eclipse.jdt.ui.prefs         # UI設定
│   └── org.eclipse.core.resources.prefs  # リソース設定
└── pom.xml                              # Mavenプロジェクト設定
```

### 配置ルール

- サービスクラス → `src/main/java/kmg/tool/directorytool/service/`
- モデルクラス → `src/main/java/kmg/tool/directorytool/model/`
- 実行クラス → `src/main/java/kmg/tool/directorytool/runner/`
- テストクラス → 対応する実装クラスと同じパッケージ構成

---

## 共通のコーディングルール

### メソッドの戻り値

- メソッドの戻り値は変数`result`で定義
- メソッドの戻り値の変数は先頭で宣言
- return文は`return result;`に統一

### 処理コメント

- 機能ごと、処理のまとまり単位に`/* コメント */`で記載
- 通常コメントは`//`で記載

### Javadoc

- 修飾子に限らず必須
- Javadocルールに従う

### 早期リターンパターン

- 早期リターンパターンを使用し、不要なネストを避ける

#### 基本的な指示

早期リターンパターンを使用してコードを書いてください。

#### 詳細な指示

コードの可読性を高めるため、以下の方針でコードを書いてください:
    - ネストを減らすため、条件が満たされない場合は早期にreturnする
    - if-elseの代わりに、ガード節(早期リターン)を使用する
    - インデントの深さを最小限に抑える

#### 具体例を含む指示

以下のような形式でコードを書いてください:

```java

// 望ましくない形式:
if (condition) {
    // 処理A
    // 処理B
}

// 望ましい形式:
if (!condition) {
    return result;
}
// 処理A
// 処理B
```

#### メリット

- コードの可読性が向上
- ネストの深さが減少
- 処理の流れが明確になる
- メンテナンス性の向上

#### 使用シーン

- メソッドやフローの入り口でのバリデーション
- 例外的なケースの早期処理
- 条件分岐が多い処理の簡略化

#### コード例

```java
public boolean someMethod(String input) {
    boolean result = false;  // 先頭で戻り値変数を宣言

    // 早期リターン(ガード節)
    if (input == null) {
        return result;
    }

    // メインの処理
    result = true;

    return result;  // 統一された形式でreturn
}
```

## テストのコーディングルール

### テストコードの実装順序

下記の順番で実装してください。

1. 期待値の定義

   - ```/* 期待値の定義 */```のコメントを入れる。
   - ```expected```で始まる期待値を定義する。

2. 準備

    - ```/* 準備 */```のコメントを入れる。
    - テスト対象を行うために準備しておくべき処理。

3. テスト対象の実行

    - ```/* テスト対象の実行 */```のコメントを入れる。
    - テスト対象を実行する。

4. 検証の準備

    - ```/* 検証の準備 */```のコメントを入れる。
    - ```actual```で始まる実際の値を定義する。

5. 検証の実施

    - ```/* 検証の実施 */```のコメントを入れる。
    - ```Assertions.assertTrue```は```actualXXX```と説明を記載する。
    - ```Assertions.assertEquals```は```actualXXX```と説明を記載する。
    - ```Assertions.assertEquals```は```expectedXXX```と```actualXXX```と説明を記載する。

### テストメソッドのアクセス修飾子

- 「testXXX」メソッドのアクセス修飾子を全て「public」にする

### メッセージの検証

- ```Assertions.assertEquals```を使用する
- 1行1行で検証する

#### メッセージの検証のコード例

```java
@Test
public void testMethod() {

    /* 期待値の定義 */
    final String[] expectedOutputLines = {
            "メッセージ1",
            "メッセージ2",
            "メッセージ3",
    };
    /* 準備 */

    /* テスト対象の実行 */

    /* 検証の準備 */
    final String[] actualLogMessages = this.listAppender.list.stream().map(ILoggingEvent::getFormattedMessage)
            .toArray(String[]::new);

    /* 検証の実施 */
    Assertions.assertEquals(expectedOutputLines.length, actualLogMessages.length, "ログメッセージの数が正しいこと");
    for (int i = 0; i < expectedOutputLines.length; i++) {

        final String expectedLine = expectedOutputLines[i];
        Assertions.assertEquals(expectedLine, actualLogMessages[i],
                String.format("出力に「%s」が含まれること", expectedLine));

    }

}
```

---

## 順守

以上の内容を順守し、タスクを遂行してください。
java
spring
KenichiroArai/directory-operation-parallel-execution-tool

Used in 1 repository

TypeScript
# プロジェクトの技術スタック
expertise:
  - React
  - TypeScript
  - Tailwind CSS
  - shadcn/ui
  - Jotai
  - react-router-dom
  - Supabase
  - Farm
  - Bun
  - Biome

# コーディングスタイルとベストプラクティス
coding_guidelines:
  components:
    - "コンポーネントは単一責任の原則に従い、小さく保つこと。"
    - "関数型コンポーネントを使用し、クラスコンポーネントは避けること。"
    - "再利用可能なコンポーネントは適切にモジュール化すること。"
    - "ページコンポーネントはパスカルケースで命名し、末尾にPageを付けること。"
  logic:
    - "ロジックは適切にモジュール化し、再利用可能な関数として定義すること。"
    - "ロジックはコンポーネントから分離し、コンポーネントの責任を減らすこと。"
    - "サービスロジックはservicesディレクトリに配置すること。"
    - "カスタムフックはhooksディレクトリに配置すること。"
  state_management:
    - "状態管理にはJotaiを使用し、必要に応じてatomやatomFamilyを活用すること。"
    - "グローバル状態の使用を最小限に抑え、ローカル状態を優先すること。"
  routing:
    - "ルーティングにはreact-router-domを使用し、動的ルートやネストされたルートを適切に構成すること。"
    - "Lazy Importを積極的に使用し、ページ遷移時のパフォーマンスを向上させること。"
  styling:
    - "スタイリングにはTailwind CSSとshadcn/uiを使用し、統一されたデザインシステムを維持すること。"
    - "レスポンシブデザインを実装し、モバイルファーストのアプローチを採用すること。"
  performance_optimization:
    - "React.memo、useMemo、useCallbackを適切に使用し、不要な再レンダリングを防ぐこと。"
    - "非同期処理やデータフェッチングにはSuspenseやError Boundaryを活用すること。"
  error_handling:
    - "エラーハンドリングを徹底し、ユーザーに適切なフィードバックを提供すること。"
    - "Supabaseからのエラーは適切にキャッチし、ユーザーにわかりやすいメッセージを表示すること。"
  testing:
    - "ユニットテスト、統合テストを実施し、コードの信頼性を確保すること。"
    - "テストには適切なテスティングフレームワークを使用すること。"

# ビルドとランタイム
build_and_runtime:
  - "ビルドツールにはFarmを使用し、効率的なビルドプロセスを確立すること。"
  - "ランタイムおよびパッケージマネージャーにはBunを使用し、依存関係の管理とスクリプトの実行を行うこと。"

# Lintとフォーマッター
lint_and_formatter:
  - "コードの品質と一貫性を保つためにBiomeを使用し、Lintとフォーマットを実施すること。"
  - "コミット前に自動的にLintとフォーマットを適用するためのフックを設定すること。"
bun
css
html
javascript
jotai
plpgsql
react
shadcn/ui
+3 more

First seen in:

otomatty/farm-cms

Used in 1 repository

TypeScript
{
"projectRules": {
"general": {
"documentation": {
"updateOnChat": true,
"mobileFirst": true,
"nextjsStructure": "App Router with React Server Components",
"responsiveBreakpoints": {
"mobile": "max-width: 640px",
"tablet": "641px-1024px",
"desktop": "1025px+"
},
"namingConvention": "[Topic]\_docs.md"
},
"codeStructure": {
"projectStructure": "AI-friendly with clear relationships",
"comments": {
"jsdoc": {
"required": [
"@ai-context",
"@ai-dependencies",
"@ai-relationships"
]
}
},
"principles": [
"DRY",
"Reusable Components"
],
"naming": {
"components": "PascalCase",
"functions": "camelCase",
"variables": "camelCase",
"constants": "UPPER_SNAKE_CASE"
}
}
},
"design": {
"css": {
"approach": "mobile-first",
"units": [
"rem",
"em"
],
"touchElements": {
"minSize": "44x44px"
},
"layout": [
"CSS Grid",
"Flexbox"
],
"accessibility": "WCAG 2.1 AA"
}
},
"components": {
"default": "server components",
"structure": "atomic",
"requirements": {
"errorHandling": true,
"loadingStates": true,
"maxFunctionLines": 30
}
},
"environment": {
"terminal": "Windows Terminal",
"packageManager": "pnpm",
"conventions": "Windows-specific"
},
"documentation": {
"typeDoc": {
"fileRequirements": [
"@module",
"@packageDocumentation"
],
"componentRequirements": [
"@component",
"@props",
"@returns"
],
"functionRequirements": [
"@function",
"@param",
"@returns"
]
},
"codeComments": {
"format": "// [Purpose]: [Explanation]",
"requirements": [
"logic explanation",
"business logic",
"edge cases",
"performance considerations"
]
}
},
"errorHandling": {
"principles": [
"preserve functionality",
"backup before fixes",
"document state",
"targeted fixes",
"verify features",
"protect build process"
],
"workflow": {
"steps": [
"analyze context",
"map impact",
"create strategy",
"document state",
"implement changes",
"verify functionality",
"update docs",
"validate build",
"confirm stability",
"maintain rollback"
]
}
},
"designSystem": {
"requirements": [
"theme tokens",
"spacing system",
"typography system",
"color system",
"responsive design",
"dark mode",
"component patterns"
],
"components": {
"creation": [
"extend base components",
"use theme colors",
"follow typography",
"follow spacing",
"implement variants"
],
"themeIntegration": [
"theme provider wrapper",
"proper hooks usage",
"token consistency",
"override protocols"
]
}
},
"phaseBasedRules": {
"organization": "PHASE_X_docs.md",
"updates": [
"update existing docs",
"group related features",
"maintain organization",
"use navigation aids"
],
"sections": {
"required": [
"Feature overview",
"Technical details",
"Configuration",
"Usage examples",
"Troubleshooting"
],
"optional": [
"Performance considerations",
"Security notes",
"Future improvements"
]
}
},
"versionTracking": {
"format": "## [Feature Name] - [Date]",
"required": [
"version number",
"change description",
"breaking changes",
"migration steps"
]
},
"changeTracking": {
"fileModification": {
"newFiles": [
"document purpose",
"explain addition",
"list dependencies",
"update structure"
],
"modifiedFiles": [
"track changes",
"document impact",
"update docs",
"maintain history"
],
"deletedFiles": [
"document removal reason",
"update docs",
"remove from structure",
"note dependencies"
]
},
"logging": {
"required": [
"date and time",
"modification type",
"purpose",
"impact",
"feature grouping",
"chronological order",
"documentation links",
"version info"
]
}
},
"validation": {
"requirements": [
"documented changes",
"accurate status",
"current diagrams",
"correct features",
"tracked errors",
"validated relationships"
]
}
}
}
css
javascript
next.js
npm
pnpm
react
typescript
T1nker-1220/nichols-wed-blog

Used in 1 repository

Python
# WebScraper Development Guidelines

## Project Overview
WebScraper is a browser automation tool that uses WebSocket communication between a Python backend and a browser extension to enable automated web interactions.

## Critical Requirements

### Extension Requirements
- Content Script MUST be used for page interactions
- Eval MUST be enabled for dynamic script execution
- Content Script should be injected at document_start
- All script execution must happen through the Content Script

### JavaScript Execution via Chrome Extension Guidelines
1. Browser Context Rules:
   - All JS files in `/commands/js` must be pure browser JavaScript
   - No Node.js/CommonJS/ES modules (no require/import/export)
   - No external dependencies that need bundling
   - Code must be self-contained and executable via eval()
   - Return values must be JSON-serializable objects

2. Code Structure:
   - Each file should contain all needed functions
   - Main execution should be at the end of file
   - Use direct return statements (no Promises/async)
   - Avoid global scope pollution
   - Use IIFE if needed for scope isolation

3. Return Format:
   - Return plain objects only
   - No class instances or complex types
   - No DOM elements or functions
   - No circular references
   - Ensure all data is serializable

4. Browser APIs:
   - Only use standard browser APIs
   - No extension-specific APIs in JS files
   - Handle API errors gracefully
   - Fallback for unsupported features
   - Test in isolated context

5. Security Considerations:
   - No sensitive data in returned objects
   - Sanitize all input/output
   - No external script loading
   - No XSS-vulnerable constructs
   - Follow CSP restrictions

### Manifest Requirements
- Maintain the following content_security_policy in manifest.json:
```json
"content_security_policy": {
  "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'",
  "sandbox": "sandbox allow-scripts allow-forms allow-popups allow-modals; script-src 'self' 'unsafe-inline' 'unsafe-eval'; child-src 'self';"
}
```

### Architecture Principles
- Python backend should maintain primary control
- Extension serves as a Remote Access Tool (RAT)
- Maximize control delegation to Python backend
- WebSocket communication should be reliable and secure

### Development Guidelines
1. Iterative Development:
   - Focus on adding features or careful refactoring
   - Complete codebase scan before refactoring
   - Ensure changes maintain existing functionality

2. Code Quality:
   - Follow type-safe practices
   - Maintain proper error handling
   - Keep WebSocket communication robust
   - Document all changes thoroughly

3. Security:
   - Maintain CSP headers for script execution
   - Keep content scripts in isolated world
   - Validate all commands from Python backend

### Agent Responsibilities
1. Proactive Execution:
   - Minimize user intervention
   - Offer to run necessary commands
   - Handle build and testing automatically
   - Provide clear success/failure feedback

2. Code Review:
   - Scan entire codebase before changes
   - Verify manifest.json integrity
   - Check content script functionality
   - Validate WebSocket communication

3. Error Resolution:
   - Address root causes
   - Maintain security requirements
   - Preserve architecture principles
   - Document solutions thoroughly

## Project Setup and Running

### WebScraperExtension Setup
1. Build Requirements:
   - Node.js and Bun package manager
   - TypeScript for type checking
   - Webpack for bundling
   - Tailwind CSS for styling

2. Build Process:
   - Clean dist directory before each build
   - Build content script separately to maintain isolation
   - Copy static assets including manifest.json
   - Verify CSP rules are properly copied

3. Extension Loading:
   - Load as unpacked extension in Chrome/Brave
   - Verify background service worker starts
   - Check content script injection
   - Validate WebSocket connection

4. Common Commands:
```bash
# Clean and build extension
rm -rf dist && mkdir dist && bun run build

# Format code
bun run format

# Run type checking
bun run typecheck
```

### WebScraperPy Setup
1. Environment Setup:
   - Python 3.12+ required
   - Virtual environment recommended
   - uv package manager for dependencies
   - Development mode installation

2. Running Process:
   - Start Python backend first
   - Wait for WebSocket server to start
   - Verify extension connection
   - Handle command execution

3. Testing Flow:
   - Run conversation extraction tests
   - Verify WebSocket communication
   - Check script execution
   - Validate error handling

4. Common Commands:
```bash
# Setup virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install package
uv pip install -e .

# Run tests
python test_conversation.py

# Format code
black . && ruff .
```

### Running Order
1. Build extension:
   ```bash
   cd WebScraperExtension
   bun run build
   ```

2. Load extension in browser:
   - Navigate to chrome://extensions
   - Enable Developer Mode
   - Load unpacked from dist directory

3. Start Python backend:
   ```bash
   cd WebScraperPy
   python example_extension.py
   ```

4. Verify Connection:
   - Check extension background page console
   - Verify WebSocket connection in Python logs
   - Test basic navigation command

## Python Development Rules

### Critical Requirements
- Use Python 3.12+ features
- Maintain async/await patterns
- Handle WebSocket timeouts
- Implement proper error handling

### Code Standards
- Follow PEP 8 style guide
- Use Python typing with all new code
- Document all classes and methods
- Keep WebSocket handlers and browser commands single-purpose
- Maximum line length: 88 characters (black formatter)

#### 2. Project Structure
```
WebScraper/
├── WebScraperPy/           # Python backend
│   ├── webscraper/        
│   │   ├── browser/       # Browser implementations
│   │   ├── core/          # Core interfaces and types
│   │   └── utils/         # Shared utilities
│   ├── tests/             # Test suite
│   └── example_*.py       # Example scripts
│
└── WebScraperExtension/    # Browser extension
    └── src/               # Extension source code
```

### Development Guidelines

#### Python Standards
- Python version: ^3.12
- Use uv for dependency management
- Use websockets for WebSocket communication
- Use pydantic for message validation
- Use loguru for logging
- Follow black formatting rules

#### WebSocket Communication
- All messages must use ExtensionMessage format
- Handle connection errors gracefully
- Implement proper message validation
- Log all WebSocket events for debugging

#### Browser Automation
- Implement commands through ExtensionBrowser class
- Follow the BrowserInterface protocol
- Handle browser capabilities consistently
- Validate all browser commands

#### Error Handling
- Use custom exceptions for WebSocket errors
- Provide context in error messages
- Log connection and command errors
- Handle browser disconnections gracefully

#### Documentation
- Document all message types
- Document browser capabilities
- Provide WebSocket connection examples
- Include browser command examples

#### Environment Configuration
- WebSocket host and port configuration
- Browser extension settings
- Debug mode settings
- Logging configuration

### Development Workflow
1. Use uv for dependency management
2. Test WebSocket communication
3. Validate message formats
4. Format code with black
5. Sort imports with isort
6. Update documentation

### Important Commands
```bash
# Install dependencies
uv pip install -e .

# Run example script
python example_extension.py

# Format code
uv python -m black .
uv python -m isort .

# Lint code
uv python -m flake8
```

bun
css
html
java
javascript
python
rest-api
tailwindcss
+3 more

First seen in:

ronaldeddings/WebScraper

Used in 1 repository