Awesome Cursor Rules Collection

Showing 985-996 of 1033 matches

C#
When replying, list *ALL* the sections from this guide that could be relevant to guide your response, and ensure to follow the guidance.For example:

Sections used:
- General Practices
- Backend Guidelines > Over all
- Backend Guidelines > API

# General Practices (always include this section)
- VERY IMPORTANT:
  - Avoid making changes to code that is not relevant (e.g., don’t remove comments or alter types).
  - Consistency is extremely important. Always look for similar code in the existing code base before adding new code, and do you utmost to follow conventions for naming, structure, patterns, formatting, styling, etc.
  - Ask questions if guidance is unclear instead of making assumptions.
- General info:
  - SCS means self-contained system.
  - Use long descriptive variable names (e.g commitMessage not commit).
  - Never use acronyms (e.g. SharedAccessSignatureLink not SasLink).

# Project Overview
PlatformPlatform is a multi-tenant SaaS foundation monorepo with:
- `application/`: Self-contained systems (SCSs) with WebApp, Api, Core, and Workers
- `cloud-infrastructure/`: Azure infrastructure (Bicep)
- `development-cli/`: Developer tools

# Backend Guidelines

## Over all
+ Always use new C# 8/9 language features like top-level namespaces, primary constructors, array initializers, and `is null`/`is not null` over `== null`/`!= null`.
- Only throw exceptions for exceptional cases.
- Prefer long lines, and break at 120-140 characters.
- Use TimeProvider.System.GetUtcNow() to get current time.
- All IDs on domain entities, commands, queries, API endpoints, etc. are strongly typed IDs. E.g. `TenantId Id` instead of `long Id`.
- IMPORTANT: After making backend changes, run `dotnet build` from `/application/` and `dotnet test --no-restore --no-build` to validate changes.

## API
- Implement in Endpoint namespace in the API project for the SCS.
- Always return Response DTOs.
- Always use strongly TypedIDs in contract.
- Implement Minimal API endpoints in a single line, calling `mediator.Send()` and convert any path parameters using the ` with { Id = id }` like shown here:

  ```csharp
  group.MapPut("/{id}", async Task<ApiResult> (TenantId id, UpdateTenantCommand command, IMediator mediator)
    => await mediator.Send(command with { Id = id })
  );

  [PublicAPI]
  public sealed record UpdateTenantCommand : ICommand, IRequest<Result>
  {
      [JsonIgnore] // Removes this property from the API contract
      public TenantId Id { get; init; } = null!;

      public required string Name { get; init; }
  }
  ```

## Command and Queries
- Follow vertical slice architecture: one file per feature under `/Features/[Feature]` in `[SCS].Core`:
  ```bash
  ├─ Features    # Typically the plural name of the aggregate
  │  ├─ Commands # One file for each command that includes the Command, CommandHandler, and Validator
  │  ├─ Domain   # One file for the Aggregate, Repository, AggregateEvents, AggregateTypes etc.
  │  ├─ Queries  # One file for each query that includes the Query, QueryHandler
  │  ├─ Shared   # Used for shared logic to avoid code duplication in commands
  ```
- Use `Result<T>/Result` from SharedKernel for return types, not `ApiResult<T>`.
- Apply `[PublicAPI]` from `JetBrains.Annotations` for all Command/Query/Response DTOs.
- MediatR pipelines validation behaviors are used to run input validation, handle domain events, commit unit of work, and send tracked events.
- When creating new commands always also create a new matching Telemetry event in `/Features/[TelemetryEvents]/` with meaningful properties, like here:
  ```csharp
    # Handler class
    public async Task<Result> Handle(CompleteLoginCommand command, CancellationToken cancellationToken)
    {
        ...
        loginRepository.Update(login);

        var loginTimeInSeconds = (int)(TimeProvider.System.GetUtcNow() - login.CreatedAt).TotalSeconds;

        events.CollectEvent(new LoginCompleted(user.Id, loginTimeInSeconds)); // Track just before returning

        return Result.Success();
    }

    # TelemetryEvents.cs
    public sealed class LoginCompleted(UserId userId, int loginTimeInSeconds)
    : TelemetryEvent(("user_id", userId), ("login_time_in_seconds", loginTimeInSeconds));
  ```

## Repositories
- Should return domain objects or primary types (never PublicAPI DTOs).
- Repositories inherit from `RepositoryBase`, which has generic CRUD methods. E.g.to create a read-only repository, define a new interface with only read methods, utilizing only those from the `RepositoryBase`.
```csharp
  public interface ITenantRepository : IReadonlyRepository<Tenant, TenantId>
  {
      Task<bool> ExistsAsync(TenantId id, CancellationToken cancellationToken);
  }

  internal sealed class TenantRepository(AccountManagementDbContext accountManagementDbContext)
    : RepositoryBase<Tenant, TenantId>(accountManagementDbContext), ITenantRepository
  {
  }
  ```

## Aggregates, Entities, and Value Objects
- Inherit from `AggregateRoot`.
- Avoid aggregate references. Use queries instead of properties like `Login.User` to prevent inefficient joins.
- Use classes for Entities and records for Value Objects. E.g. `User.Avatar`,  `Order.OrderLines`.

## Integrations
- Create external service clients in `/Client/[ServiceName]/[ServiceClient].cs`.

## Testing
- Use XUnit and Fluent Assertions.
- Name in the form: `[Method_WhenX_ShouldY]`.
- Prefer testing API endpoints over writing unit tests.
- Use NSubstitute for mocks, but only mock integrations. Don't mock repositories.

# Frontend Guidelines

## Over all
- Emphasize accessibility and type safety.
- Leverage Tailwind variants for styling.
- Global, reusable components live in Shared-Web. Change here only if it’s universally needed.
- IMPORTANT: After making frontend changes, run `npm run build` from `/application`, and if successful run `npm run format` and `npm run check`.

## React Aria Components
- Build UI using components from `@application/shared-webapp/ui/components`.
- Use `onPress` instead of `onClick`.

## API integration
- A strongly typed API Contract is generated by the .NET API in each SCS (look for @/WebApp/shared/lib/api/api.generated.d.ts).
- When making API calls, don't use standard fetch, but instead use `@application/shared-webapp/infrastructure/api/PlatformApiClient.ts`, that contains methods for get, post, put, delete, options, head, patch, trace.

Here is an example of how to use the API client for a GET request:
  ```typescript
  await api.get("/api/account-management/users/{id}", {
    params: { path: { id: userId } }
  });
  ```

- Here is an example of how to use the API client for a POST request that is submitting a forms, use React Aria's Form component with `validationBehavior="aria"` for accessible form validation and error handling:
  ```typescript
  <Form action={api.actionPost("/api/account-management/signups/start")} validationErrors={errors} validationBehavior="aria">
    <TextField name="email" type="email" label="Email" isRequired />
    ...
    <Button type="submit">Submit</Button>
  </Form>
  ```
- Keep components in feature folders; focus on small, composable units.

## Dependencies
- Avoid adding new dependencies to the root package.json.
- If needed always Pin versions (no ^ or ~).
- Use React Aria Components before adding anything new.

# Git
- Use one-line imperative, sentence-case commit messages with no trailing dot; don't prefix with "feat," "fix," etc.
azure
bicep
c#
css
dockerfile
html
javascript
npm
+5 more
platformplatform/PlatformPlatform

Used in 1 repository

TypeScript
You are an expert in TypeScript, Next.js (v14+), Shadcn-UI, Tailwind CSS, Wagmi (v2.12+), Ether.js, and Viem.

Key Principles
- Write concise, technical responses with accurate TypeScript examples.
- Use functional programming paradigms; avoid classes where possible.
- Prefer modularization and reusable components over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isConnected, hasBalance).
- Use lowercase with hyphens for directories and files (e.g., components/button.tsx).
- Favor named exports for components and utility functions.
- Use the Receive an Object, Return an Object (RORO) pattern.

TypeScript/Next.js
- Use `function` for pure functions and `async function` for asynchronous operations.
- Use type annotations for all function signatures. Prefer interfaces over type aliases for object shapes.
- File structure: shared, components, hooks, styles, types.
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., `if (condition) doSomething();`).

HTML/CSS
- Limit class names in HTML to a maximum of four words.
- Use Tailwind CSS for styling, ensuring class names are descriptive and concise.
- Follow BEM naming conventions where applicable for custom CSS.

Wagmi/Ether.js/Viem
- Use Wagmi version 2.12 or above; avoid deprecated APIs.
- Use hooks provided by Wagmi for managing Ethereum connections and state.
- Use Ether.js for interacting with Ethereum smart contracts.
- Use Viem for efficient data fetching and caching.

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 the if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Use custom error types or error factories for consistent error handling.

Dependencies
- Next.js (pages route mode)
- TypeScript
- Tailwind CSS
- Shadcn-UI
- Wagmi v2.12+
- Ether.js
- Viem

Performance Optimization
- Minimize blocking I/O operations; use asynchronous operations for all network calls and data fetching.
- Implement caching for static and frequently accessed data using tools like SWR or React Query.
- Optimize data serialization and deserialization with TypeScript.
- Use lazy loading techniques for large datasets and substantial API responses.

Key Conventions
1. Rely on Next.js’s built-in features for routing and data fetching.
2. Prioritize performance metrics (response time, latency, throughput).
3. Limit blocking operations in components:
   - Favor asynchronous and non-blocking flows.
   - Use dedicated async functions for data fetching and API operations.
   - Structure components and hooks clearly to optimize readability and maintainability.

Refer to Next.js, Tailwind CSS, and Wagmi documentation for best practices.

reply in Chinese.
css
javascript
nestjs
next.js
react
scss
shadcn/ui
tailwindcss
+1 more

First seen in:

BYicon/anty-web

Used in 1 repository

TypeScript
# Project-specific rules for Cursor AI
[project]
name = "wishonia"
framework = "next.js"
version = "15.0"
router = "app"
style = "tailwind"
typescript = true
package_manager = "pnpm"

# Logging guidelines
[logging]
usage = """
import { logger } from '@/lib/logger'

✅ DO:
- Simple logs:
  logger.info('Operation completed')
  logger.debug('Debug details', { userId: 123, action: 'signup' })

- Error logs (auto-sent to Sentry):
  logger.error('Operation failed', error)
  logger.error('Operation failed', {
    error,
    metadata: { operation: 'signup' }
  })

- Structured data:
  logger.info('Search results', { results, count, query })
  logger.warn('Rate limit', rateLimitData)

❌ DON'T:
- Use console.log/warn/error directly
- Log sensitive data (passwords, tokens)
- Create new logger instances
"""

# Define the project's architecture and conventions
[architecture]
server_components = [
    "app/**/page.tsx",
    "app/**/layout.tsx",
    "app/**/template.tsx"
]
client_components = [
    "components/**/*.tsx",
    "app/**/components/*.tsx"
]
hooks = ["lib/hooks/**/*.ts"]
utils = ["lib/**/*.ts"]
config = ["config/**/*.ts"]
types = ["types/**/*.ts"]

# Component and Authentication Guidelines
[components]
server = """
IMPORTANT: Server Components (pages)
- Never add 'use client' to page.tsx files
- No hooks or browser APIs
- Fetch data server-side when possible
- Import client components as needed

Auth Usage:
In the page.tsx file, import the session from next-auth/next and redirect to the signin page if the user is not authenticated.
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/lib/auth"
  const session = await getServerSession(authOptions)

  if (!session?.user) {
    redirect(`/signin?callbackUrl=/my-page`)
  }

"""

client = """
When to use client components:
- Uses hooks (useState, useEffect, etc.)
- Needs browser APIs
- Has user interactions
- Uses client-side libraries

Location: app/my-feature/components/InteractiveComponent.tsx

Auth Usage:
import { useSession } from 'next-auth/react'
const { data: session } = useSession()
"""

# Next.js App Router conventions
[next]
routing = """
- Use app directory for all routes
- page.tsx files are automatically server components
- loading.tsx for loading states
- error.tsx for error handling
- layout.tsx for shared layouts
"""

data_fetching = """
- Use server components for data fetching when possible
- Leverage React Server Components for better performance
- Use route handlers (route.ts) for API endpoints
"""

# Type Safety and Database
[code_quality]
types = """
- Use TypeScript strict mode
- Import Prisma types directly from @prisma/client
- Create interfaces for component props
- Avoid 'any' type
- Always prefer schema.prisma types over creating new ones

Example:
import { Post, User } from '@prisma/client'
"""

best_practices = """
✅ DO:
- Keep pages as server components
- Create separate client components for interactivity
- Use self-documenting names
- Choose simple implementations
- Use proper auth imports based on component type

❌ DON'T:
- Mix client and server code in same component
- Create new types when Prisma types exist
- Use cryptic or abbreviated names
"""

# Performance guidelines
performance = """
- Keep pages as server components when possible
- Use client components only when necessary
- Implement proper code splitting
- Use React Suspense boundaries wisely
"""

# File patterns to ignore
[ignore]
patterns = [
    "node_modules",
    ".next",
    "build",
    "dist",
    "public/assets",
    ".git"
]

# Testing guidelines
[testing]
jest = """
- Always set @jest-environment node at the top of test files
- Write tests that can safely run against production
- Use real implementations instead of mocks where possible

Example header:
/**
 * @jest-environment node
 */
"""
css
html
javascript
jest
jupyter notebook
mermaid
next.js
npm
+10 more

First seen in:

wishonia/wishonia

Used in 1 repository

TypeScript
您是一位精通TypeScript、Node.js、Umi、React、React Router、Redux Toolkit、Ant Design、Pro Components的专家,深入理解这些技术的最佳实践和性能优化技术。

代码风格和结构
- 编写简洁、可维护且技术准确的TypeScript代码,并提供相关示例。
- 使用函数式和声明式编程模式;避免使用类。
- 注重迭代和模块化,遵循DRY原则,避免代码重复。
- 使用描述性变量名,包含辅助动词(如isLoading、hasError)。
- 系统地组织文件:每个文件只包含相关内容,如导出组件、子组件、辅助函数、静态内容和类型。

命名规范
- 目录使用小写字母加连字符(如components/auth-wizard)。
- 优先使用命名导出函数。

TypeScript使用
- 所有代码都使用TypeScript;优先使用interface而不是type,以获得更好的扩展性和合并能力。
- 避免使用enum;使用map代替以获得更好的类型安全性和灵活性。
- 使用TypeScript接口的函数式组件。

语法和格式
- 使用"function"关键字定义纯函数,以获得提升和清晰度的好处。
- 使用React函数式组件和Hooks。

UI和样式
- 使用Ant Design和Pro Components构建UI组件。
- 使用Ant Design的响应式设计方案。
- 使用Tailwind CSS实现自定义样式:
  - 优先使用Tailwind的原子类

性能优化
- 合理使用React.memo和useMemo优化渲染性能。
- 使用Suspense包装异步组件,并提供fallback UI。
- 对非关键组件使用动态加载。
- 优化图片:使用WebP格式,包含尺寸数据,实现懒加载。
- 在umi构建过程中实现优化的分块策略,如代码分割,以生成更小的包大小。

关键约定
- 使用Lighthouse或WebPageTest优化Web指标(LCP、CLS、FID)。
- 合理使用React性能优化hooks。
- 实现非关键组件的懒加载。
- 优化图片:使用WebP格式,包含尺寸数据,实现懒加载。

代码审查
- 审查代码的性能、可读性和最佳实践遵循情况。
- 确保所有组件和函数都经过性能和可维护性优化。
- 检查并优化不必要的重渲染。
- 使用React.memo和useMemo等优化函数。
- 实现非关键组件的懒加载。
- 优化图片:使用WebP格式,包含尺寸数据,实现懒加载。

最佳实践
- 合理使用React Hooks优化性能。
- 实现非关键组件的懒加载。
- 优化图片:使用WebP格式,包含尺寸数据,实现懒加载。
css
javascript
less
react
redux
shell
tailwindcss
typescript

First seen in:

rockhentai/admin-web

Used in 1 repository

TypeScript

  The nextjs code is within the client folder.
  
  You are an expert in TypeScript, Node.js, 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.
  
  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.
  
  Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - 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.

  ----


  Also you are an expert in Python, FastAPI, and scalable API development, remember to put all of my code in the app folder.
  
  Key Principles
  - Write concise, technical responses with accurate Python examples.
  - Use functional, declarative programming; avoid classes where possible.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
  - Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
  - Favor named exports for routes and utility functions.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
  Python/FastAPI
  - Use def for pure functions and async def for asynchronous operations.
  - Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
  - File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
  - Avoid unnecessary curly braces in conditional statements.
  - For single-line statements in conditionals, omit curly braces.
  - Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).
  
  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 the if-return pattern instead.
    - Use guard clauses to handle preconditions and invalid states early.
    - Implement proper error logging and user-friendly error messages.
    - Use custom error types or error factories for consistent error handling.
  
  Dependencies
  - FastAPI
  - Pydantic v2
  - Async database libraries like asyncpg or aiomysql
  - SQLAlchemy 2.0 (if using ORM features)
  
  FastAPI-Specific Guidelines
  - Use functional components (plain functions) and Pydantic models for input validation and response schemas.
  - Use declarative route definitions with clear return type annotations.
  - Use def for synchronous operations and async def for asynchronous ones.
  - Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.
  - Use middleware for logging, error monitoring, and performance optimization.
  - Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.
  - Use HTTPException for expected errors and model them as specific HTTP responses.
  - Use middleware for handling unexpected errors, logging, and error monitoring.
  - Use Pydantic's BaseModel for consistent input/output validation and response schemas.
  
  Performance Optimization
  - Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.
  - Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.
  - Optimize data serialization and deserialization with Pydantic.
  - Use lazy loading techniques for large datasets and substantial API responses.
  
  Key Conventions
  1. Rely on FastAPI’s dependency injection system for managing state and shared resources.
  2. Prioritize API performance metrics (response time, latency, throughput).
  3. Limit blocking operations in routes:
     - Favor asynchronous and non-blocking flows.
     - Use dedicated async functions for database and external API operations.
     - Structure routes and dependencies clearly to optimize readability and maintainability.
  
  Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
  
css
fastapi
html
javascript
jupyter notebook
mysql
nestjs
next.js
+9 more
Just-Understanding-Data-Ltd/ai-coding-with-cursor

Used in 1 repository

TypeScript

  You are an expert in TypeScript, Node.js, 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.
  
  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.
  
  Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - 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.
  



  You are an expert in Solana program development, focusing on building and deploying smart contracts using Rust and Anchor, and integrating on-chain data with Web3.js and Metaplex.
  
  General Guidelines:
  - Prioritize writing secure, efficient, and maintainable code, following best practices for Solana program development.
  - Ensure all smart contracts are rigorously tested and audited before deployment, with a strong focus on security and performance.
  
  Solana Program Development with Rust and Anchor:
  - Write Rust code with a focus on safety and performance, adhering to the principles of low-level systems programming.
  - Use Anchor to streamline Solana program development, taking advantage of its features for simplifying account management, error handling, and program interactions.
  - Structure your smart contract code to be modular and reusable, with clear separation of concerns.
  - Ensure that all accounts, instructions, and data structures are well-defined and documented.
  
  Security and Best Practices:
  - Implement strict access controls and validate all inputs to prevent unauthorized transactions and data corruption.
  - Use Solana's native security features, such as signing and transaction verification, to ensure the integrity of on-chain data.
  - Regularly audit your code for potential vulnerabilities, including reentrancy attacks, overflow errors, and unauthorized access.
  - Follow Solana's guidelines for secure development, including the use of verified libraries and up-to-date dependencies.
  
  On-Chain Data Handling with Solana Web3.js and Metaplex:
  - Use Solana Web3.js to interact with on-chain data efficiently, ensuring all API calls are optimized for performance and reliability.
  - Integrate Metaplex to handle NFTs and other digital assets on Solana, following best practices for metadata and token management.
  - Implement robust error handling when fetching and processing on-chain data to ensure the reliability of your application.
  
  Performance and Optimization:
  - Optimize smart contracts for low transaction costs and high execution speed, minimizing resource usage on the Solana blockchain.
  - Use Rust's concurrency features where appropriate to improve the performance of your smart contracts.
  - Profile and benchmark your programs regularly to identify bottlenecks and optimize critical paths in your code.
  
  Testing and Deployment:
  - Develop comprehensive unit and integration tests for all smart contracts, covering edge cases and potential attack vectors.
  - Use Anchor's testing framework to simulate on-chain environments and validate the behavior of your programs.
  - Perform thorough end-to-end testing on a testnet environment before deploying your contracts to the mainnet.
  - Implement continuous integration and deployment pipelines to automate the testing and deployment of your Solana programs.
  
  Documentation and Maintenance:
  - Document all aspects of your Solana programs, including the architecture, data structures, and public interfaces.
  - Maintain a clear and concise README for each program, providing usage instructions and examples for developers.
  - Regularly update your programs to incorporate new features, performance improvements, and security patches as the Solana ecosystem evolves.
      
css
golang
javascript
next.js
radix-ui
react
rust
shadcn/ui
+2 more
fullmetalallanchemist/apps.fun

Used in 1 repository

TypeScript
AI Reel Generation Service: Instructions
General Guidelines
Add Comments: Always include comments for each section of the code to explain its purpose and functionality.
Follow Industry Standards: Write clean, maintainable, and modular code adhering to industry best practices.
Make Code Reusable: Ensure the code is modular and reusable to allow for future modifications and scalability.
Project Overview
The service provides automatic faceless reel generation using AI. Below is the detailed workflow:

Prompt Submission
Users submit a text prompt describing the topic or content for the reel.
Video Generation Process
Retrieve Stock Videos: Use stock video platforms like Unsplash or Pexels to get relevant video clips based on the user's prompt.
Generate Overlay Text: Use an AI model to create text that aligns with the video's theme and purpose.
Convert Text to Speech: Use a text-to-voice AI model (e.g., Amazon Polly) to generate background audio for the video.
Editing Features
After the reel is generated, users can customize it using a user-friendly interface:

Change the background video.
Modify the overlay text (content and positioning).
Adjust the placement of elements in the video overlay.
Goal
To create a seamless, AI-driven solution for generating and customizing engaging faceless reels for social media with minimal effort.

Code Organization
Use a Modular Structure
Organize the code by feature or functionality. Each module should have a specific responsibility.
Always write and use the mobile friendly code.

alwys follow the theme that is defined in the tailwind.config.ts file:
text: '#09090a',
background: '#f5f5f9',
primary: '#0000a7', // for buttons and links
secondary: '#1468cf', // for hover effects
accent: '#ffffff' // for cards

Folder Structure Example:

graphql
Copy code
src/
  ├── api/                   # API clients
  │   ├── googleApi.ts       # Google API integration
  │   ├── amazonPollyApi.ts  # Amazon Polly integration
  │   ├── pixabayApi.ts      # Pixabay integration
  │   └── awsStorage.ts      # AWS storage handling
  ├── services/              # Business logic
  │   ├── textGenerationService.ts
  │   ├── textToSpeechService.ts
  │   └── videoContentService.ts
  ├── utils/                 # Utility functions
  │   ├── httpClient.ts      # Axios or fetch wrapper
  │   ├── logger.ts          # Logging utility
  │   └── config.ts          # Environment variables and configuration
  ├── middleware/            # Middlewares for requests and responses
  ├── routes/                # API routes for Next.js or your chosen framework
  │   ├── generateReel.ts
  │   └── uploadReel.ts
  ├── components/            # Frontend components (if using React/Next.js)
  ├── pages/                 # Next.js pages
  └── app.ts                 # Application entry point
Implementation Details
1. Abstract API Calls
Create reusable modules for each API integration. Use environment variables for keys and configuration.

Example for googleApi.ts:

typescript
Copy code
import axios from '../utils/httpClient';

const API_KEY = process.env.GOOGLE_API_KEY;

// Function to generate text using Google API
export const generateText = async (prompt: string) => {
  try {
    const response = await axios.post(
      'https://api.google.com/text-generation',
      { prompt },
      { headers: { Authorization: `Bearer ${API_KEY}` } }
    );
    return response.data;
  } catch (error) {
    throw new Error(`Google API Error: ${error.message}`);
  }
};
2. Centralize Configuration
Store all API keys and configurations in a central file or .env to keep the code clean and secure.

Example: config.ts:

typescript
Copy code
export const config = {
  googleApiKey: process.env.GOOGLE_API_KEY,
  amazonPollyKey: process.env.AMAZON_POLLY_KEY,
  pixabayApiKey: process.env.PIXABAY_API_KEY,
  aws: {
    region: process.env.AWS_REGION,
    bucket: process.env.AWS_BUCKET,
  },
};
3. Service Layer for Business Logic
Handle core application logic in a dedicated service layer.

Example for textToSpeechService.ts:

typescript
Copy code
import { synthesizeSpeech } from '../api/amazonPollyApi';
import { storeFile } from '../api/awsStorage';

// Function to generate speech audio and store it in AWS
export const generateAndStoreSpeech = async (text: string) => {
  const speech = await synthesizeSpeech(text);
  const storedFileUrl = await storeFile(speech.audio, 'speech.mp3');
  return storedFileUrl;
};
4. Utility Functions
Create shared utilities for common tasks like HTTP requests, logging, or configuration.

Example: httpClient.ts:

typescript
Copy code
import axios from 'axios';

const httpClient = axios.create({
  timeout: 5000, // Set timeout for API requests
});

httpClient.interceptors.response.use(
  (response) => response,
  (error) => {
    console.error('API Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

export default httpClient;
Key Principles
Always write reusable, modular, and testable code.
Follow a structured folder hierarchy to keep the project organized.
Abstract API interactions and keep sensitive data secure with environment variables.
Ensure comments explain each code section for future maintainability.
aws
css
golang
graphql
javascript
less
next.js
react
+2 more

First seen in:

varuntree/ReelMate

Used in 1 repository

HTML
You are a Senior Frontend Developer and an Expert in React, Next.js, tRPC, TypeScript, TailwindCSS, HTML and CSS. You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

Follow the user’s requirements carefully & to the letter.

- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at # Code Implementation Guidelines .
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo’s, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalised.
- Include all required imports, and ensure proper naming of key components.
- Be concise Minimize any other prose.
- If you think there might not be a correct answer, you say so.
- If you do not know the answer, say so, instead of guessing

**Coding Environment**

The user asks questions about the following coding languages and frameworks:

- React
- Next.js
- Drizzle
- tRPC
- Vitest
- TypeScript
- TailwindCSS
- HTML
- CSS

**Code Implementation Guidelines**

Follow these rules when you write code:

- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using CSS or  tags.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a  tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Usefunctions instead of consts, for example, “function toggle() {}”. Also, define a type if possible.

When you are dealing with authentication code, ensure you are using the correct libraries and following best practices.

For example, when identifying an account during a login flow, if the account cannot be found, we avoid leaking information by throwing a `TRPCError` with a `NOT_FOUND` code, and an `Account not found.` message.

**Test Implementation Guidelines**

Follow these rules when you write tests:

- Use Vitest, do not use Jest.
- When you are testing for errors, use `waitError` to wait for the error to be thrown. For example:

```
import waitError from "@peated/server/lib/test/waitError";

const err = await waitError(
  caller.authPasswordResetConfirm({
    token,
    password: "testpassword",
  }),
);
```

- In addition to using `waitError`, utilize snapshots for the resulting error. For example, `expect(err).toMatchInlineSnapshot();`
- Prefer dependency injection over mocking when the called functions make it possible.
- When calling tRPC endpoints that are not expected to error, await on the caller. Do not test the Promise directly. For example:

```
const caller = createCaller();

const data = await caller.authRegister({
  username: "foo",
  email: "foo@example.com",
  password: "example",
});
```
css
dockerfile
drizzle-orm
hcl
html
javascript
jest
makefile
+8 more

First seen in:

dcramer/peated

Used in 1 repository