.cursorrules Python FastAPI copy # Python FastAPI .cursorrules # FastAPI best practices fastapi_best_practices = [ "Use Pydantic models for request and response schemas", "Implement dependency injection for shared resources", "Utilize async/await for non-blocking operations", "Use path operations decorators (@app.get, @app.post, etc.)", "Implement proper error handling with HTTPException", "Use FastAPI's built-in OpenAPI and JSON Schema support", ] # Folder structure folder_structure = """ app/ main.py models/ schemas/ routers/ dependencies/ services/ tests/ """ # Additional instructions additional_instructions = """ 1. Use type hints for all function parameters and return values 2. Implement proper input validation using Pydantic 3. Use FastAPI's background tasks for long-running operations 4. Implement proper CORS handling 5. Use FastAPI's security utilities for authentication 6. Follow PEP 8 style guide for Python code 7. Implement comprehensive unit and integration tests """ --- description: Enforces FastAPI best practices for application code within the 'app' directory, including data validation, dependency injection, and asynchronous operations. globs: app/**/*.* --- - Use Pydantic models for request and response schemas - Implement dependency injection for shared resources - Utilize async/await for non-blocking operations - Use path operations decorators (@app.get, @app.post, etc.) - Implement proper error handling with HTTPException - Use FastAPI's built-in OpenAPI and JSON Schema support --- description: Defines the recommended folder structure for FastAPI projects to maintain organization and separation of concerns within the 'app' directory. globs: app/**/*.* --- - Follow this folder structure: app/ main.py models/ schemas/ routers/ dependencies/ services/ tests/ --- description: Specifies guidelines for the main application file in FastAPI projects, focusing on application initialization and configuration. globs: app/main.py --- - Ensure proper application initialization with FastAPI() - Configure middleware and exception handlers - Define API routes using path operation decorators --- description: Guidelines for defining Pydantic models within the models directory of a FastAPI project to ensure data validation and serialization. globs: app/models/*.py --- - Use Pydantic models for request and response schemas - Define data types using Pydantic fields - Implement validation logic using Pydantic validators --- description: Applies general Python coding standards, including type hinting, input validation with Pydantic, background tasks, CORS handling, security utilities, PEP 8 compliance, and comprehensive testing. globs: **/*.py --- - Use type hints for all function parameters and return values - Implement proper input validation using Pydantic - Use FastAPI's background tasks for long-running operations - Implement proper CORS handling - Use FastAPI's security utilities for authentication - Follow PEP 8 style guide for Python code - Implement comprehensive unit and integration tests Cursor AI by @PatrickJS
.cursorrules Optimize DRY SOLID Principles copy Communication and Problem-Solving: Code Quality and Best Practices: Paradigms and Principles: Semantic Naming and Abstractions: Platform Thinking: Response Format: Handling Uncertainty and Limitations: When outputting code blocks, include a # or // file name comment prior to the block, with a few lines before and after the modification. This helps the user identify where to make changes. Stick to the current architecture choices located in pyproject.toml unless the user suggests a new method or module. If you need clarification on any part of the task, ask for more information before proceeding with the implementation. Cursor AI by @Malcolm Jones (bossjones/Tony Dark)
.cursorrules for Project Context Management copy ## Key Principles - **Code Quality & Style** - Write concise, maintainable, and strongly typed code with accurate TypeScript implementations. - Embrace functional, declarative programming. Avoid OOP and classes. - Limit files to a maximum of 150 lines; refactor into smaller modules if exceeded. - Prefer iteration and modularization over duplication. - Use descriptive, semantic variable names with auxiliary verbs (e.g., `isLoading`, `hasError`). - Use lowercase with dashes for directories and files (e.g., `components/auth-wizard`). - Favor named exports for components. - Adopt RORO (Receive an Object, Return an Object) for function parameters/returns. - Always attain to use DRY (Don't Repeat Yourself) principles. - Conduct regular code reviews and frequent refactoring sessions to ensure consistency and quality. - Check and improve Web Vitals (LCP, CLS, FID) to maintain performance and user experience. - **Create 'Build Notes':** - You must create a 'Build Notes' file for each task group to track the progress of the task group we work on. - **Clarity & Brevity:** Keep notes concise, direct, and focused on the task at hand. - **Logical Naming:** Use a consistent naming convention that ties each notes file to a specific task and date. - **Incremental Updates:** Update notes as plans evolve or tasks are completed. Append rather than overwrite. - **Traceability:** Ensure that each decision or change in approach is recorded and easy to follow. - **Review 'Project Contexts':** - You must review the `projectContext.md` as we need to ensure that the project context is up to date and accurate. - **Stability:** Treat context files as stable references, not daily scratchpads. - **Selective Updates:** Update context files only when there are significant, approved changes to requirements or project scope. - **Accessibility:** Make context files easily understandable and organized so future developers can quickly grasp the project’s core guidance. - **Stack and Framework Conventions** - Target **Next.js 15+** and leverage the App Router, React Server Components (RSC), and SSR capabilities. - Use Zustand for state management in client components when necessary. - Maintain proper Shadcn UI management using `npx shadcn@latest add` for new components. - Follow a mobile-first approach and responsive design patterns. - Emphasize server-side logic, minimizing the usage of `use client` and other client-only APIs. - Structure project as Progressive Web App (PWA) with offline capabilities, app-like experience, and installability across devices. - **Monorepo & Tooling** - If using a monorepo structure, place shared code in a `packages/` directory and app-specific code in `app/`. - Use `Taskfile.yml` commands for development, testing, and deployment tasks. - Keep environment variables and sensitive data outside of code and access them through `.env` files or similar configuration. Below is a structured guideline to provide to the AI development agent, incorporating key principles and detailed rules for maintaining the `/ProjectDocs/Build_Notes/` and `/ProjectDocs/contexts/` directories. --- ### Rules for Build Notes Files 1. **Location & Naming:** - Store all notes files in `/ProjectDocs/Build_Notes/`. - Use a logical, descriptive naming convention, e.g., `build-title_phase-#_task-group-name.md`. - Use the `` to describe the build task. - Use the `` to apply the Phase # to the build task. - Use the `` to describe the task group name. - Example: `supabase-schema-standardization_phase-1_preparation-and-code-analysis.md` - `supabase-schema-standardization` is the build title - `phase-1` is the phase number - `preparation-and-code-analysis` is the task group name 2. **Content Structure:** - Begin with a brief **Task Objective** that summarizes what you aim to achieve. - Provide **Current State Assessment**: a short description of the current state of the project pertaining to the build tasks. - Provide **Future State Goal**: a short description of the future state of the project pertaining to the build tasks. - Follow with a **Implementation Plan**: a numbered list of **steps** containing checklist **tasks** to achieve the future state. - Update the **Implementation Plan** as tasks are completed and line out not applicable tasks. NEVER DELETE TASKS FROM THE PLAN. - If the plan changes or evolves, add new **steps** or **tasks**, rather than overwriting previous content. 3. **When to Update:** - **At Task Start:** Create or open the task-specific notes file and record the initial plan before coding. - **During Task Execution:** Add updates when plans change, difficulties arise, or new insights emerge. - **At Task Completion:** Append a summary of what was done and verify it aligns with the original objective. 4. **Style & Tone:** - Keep notes succinct, on-topic, and free of unrelated commentary. - Maintain a logical sequence so that future readers can understand the decision-making process without confusion. 5. **Completion of Build Notes:** - Once the build notes are complete, move the file to the `/ProjectDocs/Build_Notes/completed/` directory. - If build notes are deprecated and no longer needed, move the file to the `/ProjectDocs/Build_Notes/archived/` directory. --- ### Rules for Context Files 1. **Master Project Context (`projectContext.md`):** - Located in `/ProjectDocs/contexts/`. - Provides the overarching project scope, requirements, and design principles. - Only update this file if there are major changes to the project’s fundamental direction or scope. 2. **Additional Context Files:** - Supplementary files (e.g., `uiContext.md`, `featureAContext.md`) may be created for more detailed specifications on certain functionalities, designs, or areas of the application. - Keep these files stable. Update them only when new, approved changes need to be documented. - Reference these files frequently to ensure development aligns with established guidelines. 3. **Change Management:** - Record any changes to context files within the corresponding build notes file for that task. - Maintain a clear rationale for context changes to preserve transparency and alignment with the core project goals. --- ## Project Structure Adopt a clear, modular directory structure: Cursor AI by @ kryptobaseddev
.cursorrules Basic Htmx copy // HTMX Basic Setup .cursorrules // HTMX best practices const htmxBestPractices = [ "Use hx-get for GET requests", "Implement hx-post for POST requests", "Utilize hx-trigger for custom events", "Use hx-swap to control how content is swapped", "Implement hx-target to specify where to swap content", "Utilize hx-indicator for loading indicators", ]; // Folder structure const folderStructure = ` src/ templates/ static/ css/ js/ app.py `; // Additional instructions const additionalInstructions = ` 1. Use semantic HTML5 elements 2. Implement proper CSRF protection 3. Utilize HTMX extensions when needed 4. Use hx-boost for full page navigation 5. Implement proper error handling 6. Follow progressive enhancement principles 7. Use server-side templating (e.g., Jinja2, Handlebars) `; Cursor AI by @PatrickJS
.cursorrules GitHub Instructions copy Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand." As software developers, understanding how to write clean code that is functional, easy to read, and adheres to best practices helps you create better software consistently. This article discusses what clean code is and why it's essential and provides principles and best practices for writing clean and maintainable code. What Is Clean Code? Clean code is a term used to refer to code that is easy to read, understand, and maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob, who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008. In this book, he presented a set of principles and best practices for writing clean code, such as using meaningful names, short functions, clear comments, and consistent formatting. Ultimately, the goal of clean code is to create software that is not only functional but also readable, maintainable, and efficient throughout its lifecycle. Why Is Clean Code Important? When teams adhere to clean code principles, the code base is easier to read and navigate, which makes it faster for developers to get up to speed and start contributing. Here are some reasons why clean code is essential. Readability and maintenance: Clean code prioritizes clarity, which makes reading, understanding, and modifying code easier. Writing readable code reduces the time required to grasp the code's functionality, leading to faster development times. Team collaboration: Clear and consistent code facilitates communication and cooperation among team members. By adhering to established coding standards and writing readable code, developers easily understand each other's work and collaborate more effectively. Debugging and issue resolution: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues. Improved quality and reliability: Clean code prioritizes following established coding standards and writing well-structured code. This reduces the risk of introducing errors, leading to higher-quality and more reliable software down the line. Now that we understand why clean code is essential, let's delve into some best practices and principles to help you write clean code. Principles of Clean Code Like a beautiful painting needs the right foundation and brushstrokes, well-crafted code requires adherence to specific principles. These principles help developers write code that is clear, concise, and, ultimately, a joy to work with. Let's dive in. 1. Avoid Hard-Coded Numbers Use named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code. Example: The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function. Before: def calculate_discount(price): discount = price * 0.1 # 10% discount return price - discount The improved code replaces the hard-coded number with a named constant TEN_PERCENT_DISCOUNT. The name instantly conveys the meaning of the value, making the code more self-documenting. After: def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discount Also, If the discount rate needs to be changed, it only requires modifying the constant declaration, not searching for multiple instances of the hard-coded number. 2. Use Meaningful and Descriptive Names Choose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.” Example: If we take the code from the previous example, it uses generic names like "price" and "discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be interpreted differently without context. Before: def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discount Instead, you can declare the variables to be more descriptive. After: def calculate_discount(product_price): TEN_PERCENT_DISCOUNT = 0.1 discount_amount = product_price * TEN_PERCENT_DISCOUNT return product_price - discount_amount This improved code uses specific names like "product_price" and "discount_amount," providing a clearer understanding of what the variables represent and how we use them. 3. Use Comments Sparingly, and When You Do, Make Them Meaningful You don't need to comment on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase. Example: Before: def group_users_by_id(user_id): # This function groups users by id # ... complex logic ... # ... more code … The comment about the function is redundant and adds no value. The function name already states that it groups users by id; there's no need for a comment stating the same. Instead, use comments to convey the "why" behind specific actions or explain behaviors. After: def group_users_by_id(user_id): """Groups users by id to a specific category (1-9). Warning: Certain characters might not be handled correctly. Please refer to the documentation for supported formats. Args: user_id (str): The user id to be grouped. Returns: int: The category number (1-9) corresponding to the user id. Raises: ValueError: If the user id is invalid or unsupported. """ # ... complex logic ... # ... more code … This comment provides meaningful information about the function's behavior and explains unusual behavior and potential pitfalls. 4. Write Short Functions That Only Do One Thing Follow the single responsibility principle (SRP), which means that a function should have one purpose and perform it effectively. Functions are more understandable, readable, and maintainable if they only have one job. It also makes testing them very easy. If a function becomes too long or complex, consider breaking it into smaller, more manageable functions. Example: Before: def process_data(data): # ... validate users... # ... calculate values ... # ... format output … This function performs three tasks: validating users, calculating values, and formatting output. If any of these steps fail, the entire function fails, making debugging a complex issue. If we also need to change the logic of one of the tasks, we risk introducing unintended side effects in another task. Instead, try to assign each task a function that does just one thing. After: def validate_user(data): # ... data validation logic ... def calculate_values(data): # ... calculation logic based on validated data ... def format_output(data): # ... format results for display … The improved code separates the tasks into distinct functions. This results in more readable, maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify and modify the specific function responsible for the desired functionality. 5. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or Logic Avoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable. It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it. Example: Before: def calculate_book_price(quantity, price): return quantity * price def calculate_laptop_price(quantity, price): return quantity * price In the above example, both functions calculate the total price using the same formula. This violates the DRY principle. We can fix this by defining a single calculate_product_price function that we use for books and laptops. This reduces code duplication and helps improve the maintenance of the codebase. After: def calculate_product_price(product_quantity, product_price): return product_quantity * product_price 6. Follow Established Code-Writing Standards Know your programming language's conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example, PEP 8 for Python and Google JavaScript Style Guide for JavaScript. Here are some specific examples: Java: Use camelCase for variable, function, and class names. Indent code with four spaces. Put opening braces on the same line. Python: Use snake_case for variable, function, and class names. Use spaces over tabs for indentation. Put opening braces on the same line as the function or class declaration. JavaScript: Use camelCase for variable and function names. Use snake_case for object properties. Indent code with two spaces. Put opening braces on the same line as the function or class declaration. Also, consider extending some of these standards by creating internal coding rules for your organization. This can contain information on creating and naming folders or describing function names within your organization. 7. Encapsulate Nested Conditionals into Functions One way to improve the readability and clarity of functions is to encapsulate nested if/else statements into other functions. Encapsulating such logic into a function with a descriptive name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it easier to reuse, modify, and test the logic without affecting the rest of the function. In the code sample below, the discount logic is nested within the calculate_product_discount function, making it difficult to understand at a glance. Example: Before: def calculate_product_discount(product_price): discount_amount = 0 if product_price > 100: discount_amount = product_price * 0.1 elif price > 50: discount_amount = product_price * 0.05 else: discount_amount = 0 final_product_price = product_price - discount_amount return final_product_price We can clean this code up by separating the nested if/else condition that calculates discount logic into another function called get_discount_rate and then calling the get_discount_rate in the calculate_product_discount function. This makes it easier to read at a glance. The get_discount_rate is now isolated and can be reused by other functions in the codebase. It’s also easier to change, test, and debug it without affecting the calculate_discount function. After: def calculate_discount(product_price): discount_rate = get_discount_rate(product_price) discount_amount = product_price * discount_rate final_product_price = product_price - discount_amount return final_product_price def get_discount_rate(product_price): if product_price > 100: return 0.1 elif product_price > 50: return 0.05 else: return 0 8. Refactor Continuously Regularly review and refactor your code to improve its structure, readability, and maintainability. Consider the readability of your code for the next person who will work on it, and always leave the codebase cleaner than you found it. 9. Use Version Control Version control systems meticulously track every change made to your codebase, enabling you to understand the evolution of your code and revert to previous versions if needed. This creates a safety net for code refactoring and prevents accidental deletions or overwrites. Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your codebase and collaborate effectively with others. Cursor AI by @Jeremy Russell
.cursorrules GitHub Code Quality copy { "rules": [ { "name": "Verify Information", "pattern": "(?i)\\b(assume|assumption|guess|speculate)\\b", "message": "Always verify information before presenting it. Do not make assumptions or speculate without clear evidence." }, { "name": "File-by-File Changes", "pattern": "// MULTI-FILE CHANGE:", "message": "Make changes file by file and give me a chance to spot mistakes" }, { "name": "No Apologies", "pattern": "(?i)\\b(sorry|apologize|apologies)\\b", "message": "Never use apologies" }, { "name": "No Understanding Feedback", "pattern": "(?i)\\b(understand|understood|got it)\\b", "message": "Avoid giving feedback about understanding in comments or documentation" }, { "name": "No Whitespace Suggestions", "pattern": "(?i)\\b(whitespace|indentation|spacing)\\b", "message": "Don't suggest whitespace changes" }, { "name": "No Summaries", "pattern": "(?i)\\b(summary|summarize|overview)\\b", "message": "Don't summarize changes made" }, { "name": "No Inventions", "pattern": "(?i)\\b(suggest|recommendation|propose)\\b", "message": "Don't invent changes other than what's explicitly requested" }, { "name": "No Unnecessary Confirmations", "pattern": "(?i)\\b(make sure|confirm|verify|check)\\b", "message": "Don't ask for confirmation of information already provided in the context" }, { "name": "Preserve Existing Code", "pattern": "(?i)\\b(remove|delete|eliminate|destroy)\\b", "message": "Don't remove unrelated code or functionalities. Pay attention to preserving existing structures." }, { "name": "Single Chunk Edits", "pattern": "(?i)\\b(first|then|next|after that|finally)\\b", "message": "Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file" }, { "name": "No Implementation Checks", "pattern": "(?i)\\b(make sure|verify|check|confirm) (it's|it is|that) (correctly|properly) implemented\\b", "message": "Don't ask the user to verify implementations that are visible in the provided context" }, { "name": "No Unnecessary Updates", "pattern": "(?i)\\b(update|change|modify|alter)\\b.*\\bno changes\\b", "message": "Don't suggest updates or changes to files when there are no actual modifications needed" }, { "name": "Provide Real File Links", "pattern": "(?i)\\b(file|in)\\b.*\\b(x\\.md)\\b", "message": "Always provide links to the real files, not x.md" }, { "name": "No Previous x.md Consideration", "pattern": "(?i)\\b(previous|earlier|last)\\b.*\\bx\\.md\\b", "message": "Do not consider any previous x.md files in your memory. Complain if the contents are the same as previous runs." }, { "name": "No Current Implementation", "pattern": "(?i)\\b(current|existing)\\s+(implementation|code)\\b", "message": "Don't show or discuss the current implementation unless specifically requested" }, { "name": "Check x.md Content", "pattern": "(?i)\\b(file|content|implementation)\\b", "message": "Remember to check the x.md file for the current file contents and implementations" } ] } Cursor AI by @meowso 1
.cursorrules Flutter App Expert Guidelines copy // Flutter App Expert .cursorrules // Flexibility Notice // Note: This is a recommended project structure, but be flexible and adapt to existing project structures. // Do not enforce these structural patterns if the project follows a different organization. // Focus on maintaining consistency with the existing project architecture while applying Flutter best practices. // Flutter Best Practices const flutterBestPractices = [ "Adapt to existing project architecture while maintaining clean code principles", "Use Flutter 3.x features and Material 3 design", "Implement clean architecture with BLoC pattern", "Follow proper state management principles", "Use proper dependency injection", "Implement proper error handling", "Follow platform-specific design guidelines", "Use proper localization techniques", ]; // Project Structure // Note: This is a reference structure. Adapt to the project's existing organization const projectStructure = ` lib/ core/ constants/ theme/ utils/ widgets/ features/ feature_name/ data/ datasources/ models/ repositories/ domain/ entities/ repositories/ usecases/ presentation/ bloc/ pages/ widgets/ l10n/ main.dart test/ unit/ widget/ integration/ `; // Coding Guidelines const codingGuidelines = ` 1. Use proper null safety practices 2. Implement proper error handling with Either type 3. Follow proper naming conventions 4. Use proper widget composition 5. Implement proper routing using GoRouter 6. Use proper form validation 7. Follow proper state management with BLoC 8. Implement proper dependency injection using GetIt 9. Use proper asset management 10. Follow proper testing practices `; // Widget Guidelines const widgetGuidelines = ` 1. Keep widgets small and focused 2. Use const constructors when possible 3. Implement proper widget keys 4. Follow proper layout principles 5. Use proper widget lifecycle methods 6. Implement proper error boundaries 7. Use proper performance optimization techniques 8. Follow proper accessibility guidelines `; // Performance Guidelines const performanceGuidelines = ` 1. Use proper image caching 2. Implement proper list view optimization 3. Use proper build methods optimization 4. Follow proper state management patterns 5. Implement proper memory management 6. Use proper platform channels when needed 7. Follow proper compilation optimization techniques `; // Testing Guidelines const testingTestingGuidelines = ` 1. Write unit tests for business logic 2. Implement widget tests for UI components 3. Use integration tests for feature testing 4. Implement proper mocking strategies 5. Use proper test coverage tools 6. Follow proper test naming conventions 7. Implement proper CI/CD testing `; Cursor AI by @PatrickJS
.cursorrules Cursor AI Next.js 14 Tailwind SEO setup copy # System Prompt: Next.js 14 and Tailwind CSS Code Generation with TypeScript You are an AI assistant specialized in generating TypeScript code for Next.js 14 applications using Tailwind CSS. Your task is to analyze design screenshots and create corresponding TypeScript code that implements the design using Next.js 14 and Tailwind CSS, adhering to the latest best practices and standards. ## Key Requirements: 1. Use the App Router: All components should be created within the `app` directory, following Next.js 14 conventions. 2. Implement Server Components by default: Only use Client Components when absolutely necessary for interactivity or client-side state management. 3. Use modern TypeScript syntax: Employ current function declaration syntax and proper TypeScript typing for all components and functions. 4. Follow responsive design principles: Utilize Tailwind CSS classes to ensure responsiveness across various screen sizes. 5. Adhere to component-based architecture: Create modular, reusable components that align with the provided design sections. 6. Implement efficient data fetching using server components and the `fetch` API with appropriate caching and revalidation strategies. 7. Use Next.js 14's metadata API for SEO optimization. 8. Employ Next.js Image component for optimized image loading. 9. Ensure accessibility by using proper ARIA attributes and semantic HTML. 10. Implement error handling using error boundaries and error.tsx files. 11. Use loading.tsx files for managing loading states. 12. Utilize route handlers (route.ts) for API routes in the App Router. 13. Implement Static Site Generation (SSG) and Server-Side Rendering (SSR) using App Router conventions when appropriate. ## Capabilities: 1. Analyze design screenshots to understand layout, styling, and component structure. 2. Generate TypeScript code for Next.js 14 components, including proper imports and export statements. 3. Implement designs using Tailwind CSS classes for styling. 4. Suggest appropriate Next.js features (e.g., Server Components, Client Components, API routes) based on the requirements. 5. Provide a structured approach to building complex layouts, breaking them down into manageable components. 6. Implement efficient data fetching, caching, and revalidation strategies. 7. Optimize performance using Next.js built-in features and best practices. 8. Integrate SEO best practices and metadata management. ## Guidelines: 1. Always use TypeScript for type safety. Provide appropriate type definitions and interfaces. 2. Utilize Tailwind CSS classes exclusively for styling. Avoid inline styles. 3. Implement components as functional components, using hooks when state management is required. 4. Provide clear, concise comments explaining complex logic or design decisions. 5. Suggest appropriate file structure and naming conventions aligned with Next.js 14 best practices. 6. Assume the user has already set up the Next.js project with Tailwind CSS. 7. Use environment variables for configuration following Next.js conventions. 8. Implement performance optimizations such as code splitting, lazy loading, and parallel data fetching where appropriate. 9. Ensure all components and pages are accessible, following WCAG guidelines. 10. Utilize Next.js 14's built-in caching and revalidation features for optimal performance. 11. When defining React components, avoid unnecessary type annotations and let TypeScript infer types when possible. 12. Use `React.FC` or `React.ReactNode` for explicit typing only when necessary, avoiding `JSX.Element`. 13. Write clean, concise component definitions without redundant type annotations. ## Code Generation Rules: 1. Use the `'use client'` directive only when creating Client Components. 2. Employ the following component definition syntax in .tsx files, allowing TypeScript to infer the return type: ```tsx const ComponentName = () => { // Component logic }; ``` 3. For props, use interface definitions: ```tsx interface ComponentNameProps { // Props definition } const ComponentName = ({ prop1, prop2 }: ComponentNameProps) => { // Component logic }; ``` 4. Use named exports for components in .tsx files: ```tsx export const ComponentName = () => { // Component logic }; ``` 5. For page components, use default exports in .tsx files: ```tsx const Page = () => { // Page component logic }; export default Page; ``` 6. If explicit typing is needed, prefer `React.FC` or `React.ReactNode`: ```tsx import React from 'react'; const ComponentName: React.FC = () => { // Component logic }; // OR const ComponentName = (): React.ReactNode => { // Component logic }; ``` 7. For data fetching in server components (in .tsx files): ```tsx async function getData() { const res = await fetch('', { next: { revalidate: 3600 } }) if (!res.ok) throw new Error('Failed to fetch data') return res.json() } export default async function Page() { const data = await getData() // Render component using data } ``` 8. For metadata (in .tsx files): ```tsx import type { Metadata } from 'next' export const metadata: Metadata = { title: 'Page Title', description: 'Page description', } ``` 9. For error handling (in error.tsx): ```tsx 'use client' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( Cursor AI by @kr3t3n
.cursorrules Code Guidelines copy 1. **Verify Information**: Always verify information before presenting it. Do not make assumptions or speculate without clear evidence. 2. **File-by-File Changes**: Make changes file by file and give me a chance to spot mistakes. 3. **No Apologies**: Never use apologies. 4. **No Understanding Feedback**: Avoid giving feedback about understanding in comments or documentation. 5. **No Whitespace Suggestions**: Don't suggest whitespace changes. 6. **No Summaries**: Don't summarize changes made. 7. **No Inventions**: Don't invent changes other than what's explicitly requested. 8. **No Unnecessary Confirmations**: Don't ask for confirmation of information already provided in the context. 9. **Preserve Existing Code**: Don't remove unrelated code or functionalities. Pay attention to preserving existing structures. 10. **Single Chunk Edits**: Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file. 11. **No Implementation Checks**: Don't ask the user to verify implementations that are visible in the provided context. 12. **No Unnecessary Updates**: Don't suggest updates or changes to files when there are no actual modifications needed. 13. **Provide Real File Links**: Always provide links to the real files, not the context generated file. 14. **No Current Implementation**: Don't show or discuss the current implementation unless specifically requested. 15. **Check Context Generated File Content**: Remember to check the context generated file for the current file contents and implementations. 16. **Use Explicit Variable Names**: Prefer descriptive, explicit variable names over short, ambiguous ones to enhance code readability. 17. **Follow Consistent Coding Style**: Adhere to the existing coding style in the project for consistency. 18. **Prioritize Performance**: When suggesting changes, consider and prioritize code performance where applicable. 19. **Security-First Approach**: Always consider security implications when modifying or suggesting code changes. 20. **Test Coverage**: Suggest or include appropriate unit tests for new or modified code. 21. **Error Handling**: Implement robust error handling and logging where necessary. 22. **Modular Design**: Encourage modular design principles to improve code maintainability and reusability. 23. **Version Compatibility**: Ensure suggested changes are compatible with the project's specified language or framework versions. 24. **Avoid Magic Numbers**: Replace hardcoded values with named constants to improve code clarity and maintainability. 25. **Consider Edge Cases**: When implementing logic, always consider and handle potential edge cases. 26. **Use Assertions**: Include assertions wherever possible to validate assumptions and catch potential errors early. Cursor AI by @Hamza Farhan
.cursorrules ASCII Simulation Game copy you are an expert game designer and game programmer, you will choose the best game design and coding practices for all decisions in this project. The game is based on a 10x10 grid, each square has a 10x10 grid inside of it. There must be random map generation that smartly calculates where resources are located and how the map is generated. The player does not control anything in the game the player is simply an observer, therefore there should be logs for almost everything in the game and it should be turn based. All nations should operate the same, their capabilities should be balanced. The player should be able to see the entire map at once, and the player should be able to see the entire history of the game in the logs. There should be a way to zoom in on a specific square to see more detail. Nations should be able to trade resources with each other. Nations should be able to go to war with each other. Nations should be able to make peace with each other. The time period of the game is constant and there is no technological tree. It takes place in ancient times. nations should spawn a minimum distance away from eachother the entire game should be colored ASCII based in terms of graphics There should be neutral land that can be claimed by any nation. Neutral land should be randomly generated each game. There should be a way to view the current owner of a square. There should be a way to view the current resources of a square. value of resources should be based on their rarity throughout the entire map. nations can use gold to either buy resources or armies. armies are the primary way that nations can expand their territory. there should be no talent tree or technology tree, nations should be balanced without the need for such a tree population should collect in towns and cities roads should connect towns and cities resources are spread throughout nations through roads nations attempt to spread their resources evenly over their territory gold is not omni present and must be transported using roads to the location where it is spent to build armies or develop land oceans should be randomly generated to separate continents rivers should be randomly generated to connect oceans and flow across the map vertically or horizontally rivers are a food source for the land and farms can be built on them mountains should be randomly generated throughout the map mountains should be impassable by armies mines in mountains provide metal at 20% efficiency Nations should expand towards resources that they have a low amount of of and away from resources that they have a high amount of armies should spawn at the town or city that issued the order towns can only spawn a max level 3 army towns have a 3 square radius for gathering resources as towns grow their radius grows, there are 3 levels of towns and cities a Nation's largest city is its capital population can only live in towns and cities resources should be spread throughout the map in a way that encourages nations to expand into new squares armies can travel across oceans at .25x speed armies can travel on rivers to move across the map at 3x speed there is a "battle list" that shows all the battles that have happened and stats about them armies go from level 1 to level 10 based on their funding inner squares can be developed into farms, forests, mines armies require wood, food, and metal to be created. nations must pay upkeep depending on the amount of armies and developed land they have battles are resolved by the difference in army level and a RISK esque dice roll mechanic that is effected by army level armies can build castles that are good defensively and allow for funding of armies armies can be used to conquer squares from other nations armies can be used to defend squares from other nations armies can be used to attack other nations armies can be used to attack neutral squares armies can be used to attack other nations squares armies can be used to attack neutral squares armies can be used to attack other nations squares armies can be used to attack neutral squares nations should start with the same amount of gold and land the map should be color coded to show the owner of the square there should be effects over the screen that mimic a CRT monitor the game should aim to be similar to Conway's Game of Life where the nations are the living organisms. like conway's game of life, nations should be able to "see" eachother and react to eachother like conway's game of life, the nations should be able to "see" the resources and react to them there should be a chart page that tracks just about everything that can be tracked in the game Cursor AI by @haldave159 1
.cursorrules GitHub Instructions