Jehlani Luciano Logo

Rules

Rules I use in cursor. This will be updated regularly.

Guidelines for defining and using Astro Actions for server communication.

astro
## Astro Actions Guidelines

1.  Purpose: Actions provide a type-safe way to define and call server-side functions (backend logic) from client-side code or HTML forms, simplifying data validation, fetching, and error handling compared to manual API endpoints for specific tasks like form submissions or mutations.

2.  Definition (`src/actions/index.ts`):

    - Create `src/actions/index.ts`.
    - Export a `server` object containing your actions.
    - Define each action using `defineAction` imported from `astro:actions`.

    ```typescript
    // src/actions/index.ts
    import { defineAction, z } from "astro:actions"; // z also available from 'astro:schema'

    export const server = {
      // Example action
      likePost: defineAction({
        // Optional: Define input schema using Zod for automatic validation
        input: z.object({
          postId: z.string(),
        }),
        // Handler function runs on the server
        handler: async (input, context) => {
          // input is validated based on the schema
          // context provides APIContext (locals, cookies, request, etc.)
          console.log(`Liking post ${input.postId}`);
          // Check authorization using context.locals, context.cookies etc.
          if (!context.locals.user) {
            throw new ActionError({
              code: "UNAUTHORIZED",
              message: "Must be logged in.",
            });
          }
          try {
            // ... perform database update or other server logic ...
            return { success: true, postId: input.postId };
          } catch (e) {
            console.error(e);
            throw new ActionError({
              code: "INTERNAL_SERVER_ERROR",
              message: "Failed to like post.",
            });
          }
        },
      }),
      // Add other actions...
    };
    ```

3.  Calling Actions (Client-Side):

    - Import the `actions` object from `astro:actions`.
    - Call actions as async functions: `const result = await actions.actionName(input);`.
    - Works within `<script>` tags in `.astro` files or inside UI framework components.

    ```javascript
    import { actions } from "astro:actions";

    async function handleLike(postId) {
      const { data, error } = await actions.likePost({ postId });
      if (error) {
        console.error("Action failed:", error.message, "Code:", error.code);
        // Handle specific error codes like error.code === 'UNAUTHORIZED'
      } else {
        console.log("Action succeeded:", data);
      }
    }
    ```

4.  Return Value (`{ data, error }`):

    - Actions _always_ return an object with either a `data` property (on success) or an `error` property (on failure).
    - `data`: The JSON-serializable value returned by the `handler`.
    - `error`: An `ActionError` instance containing:
      - `code`: A standardized error code string (e.g., `VALIDATION_ERROR`, `UNAUTHORIZED`, `INTERNAL_SERVER_ERROR`, `NOT_FOUND`).
      - `message`: A description of the error.
      - `fields` (for `VALIDATION_ERROR`): An object detailing validation errors per input field.

5.  Input Validation:

    - Defining an `input` schema with Zod in `defineAction` enables automatic validation.
    - Works for both JSON payloads (from client-side calls) and `FormData` (from HTML forms).
    - If validation fails, the action call returns an `error` with `code: 'VALIDATION_ERROR'` and details in `error.fields`.

6.  HTML Form Integration:

    - Use an action directly in a `<form>`'s `action` attribute. Import the specific action and use `action={actions.actionName}`.
    - Method must be `POST`. Astro handles sending `FormData`.
    - Access the result on the _next_ page load (after submission/redirect) using `Astro.getActionResult(actions.actionName)` in the page's frontmatter script. This returns the same `{ data, error }` structure or `undefined` if the action wasn't the last one run for that page load.
    - Use this result to display success/error messages or validation feedback (`result.error?.fields`).
    - For more complex state persistence across redirects (avoiding browser resubmission warnings), use middleware with `getActionContext` and session storage (see advanced docs).

7.  Security:

    - Actions create public endpoints under `/_actions/actionName`.
    - Crucially, implement authorization checks within each action's `handler` using `context.locals`, cookies, etc. Throw an `ActionError({ code: 'UNAUTHORIZED' })` if the user is not permitted.
    - Optionally, gate access to actions more broadly using middleware and `getActionContext` from `astro:actions`, but per-action checks in the handler are still recommended for fine-grained control.

8.  Server-Side Calling:
    - Call actions from `.astro` frontmatter using `Astro.callAction(actions.actionName, input)`.
    - Call actions from endpoints or middleware using `context.callAction(actions.actionName, input)`.
    - Returns the same `{ data, error }` structure. Useful for reusing action logic on the server.

Reference: [Astro Actions Docs](mdc:https:/docs.astro.build/en/guides/actions)

Guidelines for using Astro DB for database management in Astro projects.

astro
## Astro DB Guidelines

1.  Purpose: Astro DB provides a fully managed SQL database solution built on libSQL, integrated with the Astro ecosystem. It simplifies database configuration, local development, and deployment.

2.  Installation: Add Astro DB to your project using the Astro CLI:

    ```bash
    npx astro add db
    ```

3.  Configuration (`db/config.ts`):

    - Define database tables within the `db/config.ts` file using `defineDb` and `defineTable` imported from `astro:db`.
    - Columns: Define table columns using helpers from `astro:db`, specifying the data type (e.g., `column.text()`, `column.number()`, `column.boolean()`, `column.date()`, `column.json()`).
    - Attributes: Configure columns with attributes like `primaryKey`, `unique`, `optional`, `default`, `references`.
    - Relationships: Define foreign key relationships using `column.number({ references: () => OtherTable.columns.id })`.

4.  Local Development:

    - When running `astro dev`, Astro DB automatically creates and manages a local SQLite database file at `.astro/content.db`. No external database or Docker is needed for local development.

5.  Seeding (`db/seed.ts`):

    - Create a `db/seed.ts` file to populate your database with initial data for development.
    - Import `db` and table definitions from `astro:db`.
    - Use `db.insert(MyTable).values([...])` within the default export async function.
    - The seed script runs automatically during `astro dev`.

6.  Querying (`astro:db` & Drizzle ORM):

    - Import the `db` client and table definitions from the `astro:db` module in your `.astro` components or API endpoints.
    - Astro DB uses Drizzle ORM for querying.
    - Common Operations:
      - Select: `await db.select().from(MyTable).where(...)`
      - Insert: `await db.insert(MyTable).values({ ... })`
      - Update: `await db.update(MyTable).set({ ... }).where(...)`
      - Delete: `await db.delete(MyTable).where(...)`
    - Filtering: Import and use Drizzle operators (`eq`, `gt`, `lt`, `like`, `inArray`, etc.) from `astro:db` within `.where()` clauses.
    - Relationships defined in the schema can be queried.
    - Use `db.batch([...])` for atomic transactions.

7.  Production Deployment:

    - Connect to a remote libSQL-compatible database (e.g., Turso).
    - Configure connection using environment variables:
      - `ASTRO_DB_REMOTE_URL`: The URL of your remote database.
      - `ASTRO_DB_AUTH_TOKEN`: The authentication token for the remote database.

8.  Pushing Schema Changes (`astro db push`):

    - Apply schema changes defined in `db/config.ts` to your database.
    - `astro db push`: Updates the local development database.
    - `astro db push --remote`: Updates the configured remote production database.
    - The command checks for potential data loss and prevents destructive changes by default.
    - Force Reset: Use `astro db push --remote --force-reset` to destroy and recreate the remote database schema according to `db/config.ts`. This causes data loss and should be used with extreme caution.
    - Renaming Tables: Requires a safe, multi-step migration process using the `deprecated: true` flag (see docs for details) to avoid data loss.

9.  Executing Scripts (`astro db execute`):

    - Run a `.ts` script file containing `astro:db` queries against a database.
    - Useful for data migrations or seeding production data.
    - `astro db execute path/to/script.ts --remote`: Executes the script against the remote database.

10. Integrations:
    - Astro integrations can define their own DB tables and seed data using the `astro:db:setup` hook and the `extendDb()` method.
    - Use `defineDbIntegration()` and `asDrizzleTable()` helpers for type safety within integrations.

Reference: [Astro DB Docs](https://docs.astro.build/en/guides/astro-db/)

Guidelines for implementing authentication in Astro, focusing on the Clerk integration.

astro
## Astro Authentication Guidelines (Focus: Clerk)

1.  Overview: Astro does not have built-in authentication. Integration with third-party services is required. Popular options include Clerk, Auth.js, Lucia, and Better Auth. This guide focuses on Clerk.

2.  Clerk Integration (`@clerk/astro`):

    - Purpose: Provides a complete suite for user authentication and management, including pre-built UI components, APIs, and admin dashboards. Offers an official SDK for Astro.
    - Installation:
      - Install the official Clerk SDK:
        ```bash
        npm install @clerk/astro
        # or pnpm add @clerk/astro / yarn add @clerk/astro
        ```
    - Configuration:
      - Requires a Clerk account and project setup.
      - Follow the official Clerk Astro Quickstart guide for detailed instructions. This typically involves:
        - Setting up environment variables with your Clerk API keys (Publishable Key, Secret Key).
        - Configuring Clerk middleware in `src/middleware.ts`.
    - Client-Side Usage (UI Components):
      - Import Clerk components from `@clerk/astro/components` into your `.astro` files.
      - Use components like `<SignedIn>`, `<SignedOut>`, `<UserButton>`, and `<SignInButton>` to conditionally render UI elements based on the user's authentication status.
        ```astro
        ---
        import Layout from 'src/layouts/Base.astro';
        import { SignedIn, SignedOut, UserButton, SignInButton } from '@clerk/astro/components';
        ---
        <Layout>
          <header>
            <SignedIn>
              <UserButton afterSignOutUrl="/" />
            </SignedIn>
            <SignedOut>
              <SignInButton />
            </SignedOut>
          </header>
          <main>
            <!-- Page Content -->
          </main>
        </Layout>
        ```
    - Server-Side Usage (Middleware for Route Protection):

      - Import `clerkMiddleware` and `createRouteMatcher` from `@clerk/astro/server` in `src/middleware.ts`.
      - Define which routes require authentication using `createRouteMatcher`.
      - Use `clerkMiddleware` to check the user's auth state (`auth().userId`) and redirect unauthenticated users attempting to access protected routes (e.g., using `auth().redirectToSignIn()`).

        ```typescript
        // src/middleware.ts
        import {
          clerkMiddleware,
          createRouteMatcher,
        } from "@clerk/astro/server";

        // Define protected routes
        const isProtectedRoute = createRouteMatcher([
          "/dashboard(.*)", // Protects /dashboard and sub-routes
          "/settings",
        ]);

        export const onRequest = clerkMiddleware((auth, context) => {
          // If the route is protected and the user is not logged in...
          if (isProtectedRoute(context.request) && !auth().userId) {
            // Redirect them to the sign-in page
            return auth().redirectToSignIn({
              returnBackUrl: context.request.url,
            });
          }
        });
        ```

3.  Other Options (Briefly):

    - Auth.js (`auth-astro`): Community adapter for the popular Auth.js library. Requires configuration with providers.
    - Lucia: Session-based authentication library; requires setting up APIs and middleware manually.
    - Better Auth: Framework-agnostic library with its own set of helpers and configuration.

4.  Key Considerations for Any Auth Solution:
    - SSR Required: Authentication typically requires Server-Side Rendering (SSR) enabled via an Astro adapter (e.g., Node, Vercel, Netlify, Cloudflare).
    - Middleware: Often used for session management and protecting routes server-side.
    - Environment Variables: API keys and secrets must be stored securely using environment variables (`.env`).

Reference: [Astro Authentication Guide](mdc:https:/docs.astro.build/en/guides/authentication), [Clerk Astro Quickstart](mdc:https:/clerk.com/docs/quickstarts/astro)

Guidelines for preventing redundant code and promoting DRY principles

personal
## Guidelines for Avoiding Code Duplication

1. **DRY Principle (Don't Repeat Yourself):**

   - Write code once and reuse it instead of copying and pasting
   - Extract repeated code into functions, components, or utilities
   - Centralize common logic in shared modules
   - Use inheritance, composition, or mixins where appropriate

2. **Common Duplication Patterns to Avoid:**

   - Repeated validation logic
   - Duplicate UI components with minor variations
   - Copy-pasted utility functions
   - Similar API call handling
   - Redundant data transformation code
   - Repeated configuration settings

3. **Abstraction Strategies:**

   - Create utility functions for common operations
   - Build reusable components with props for variations
   - Use higher-order components or custom hooks for shared behavior
   - Implement services or helpers for repeated business logic
   - Create configuration files for repeated settings

4. **Balance Considerations:**

   - Avoid premature abstraction - don't over-engineer for anticipated duplication
   - Consider the "Rule of Three" - abstract after the third occurrence
   - Balance DRY principles against code readability and simplicity
   - Ensure abstractions actually reduce complexity rather than increasing it

5. **Code Review Focus:**

   - Identify patterns of duplication across the codebase
   - Look for opportunities to consolidate similar code
   - Check for inconsistent implementations of the same functionality
   - Review new code against existing utilities before accepting duplication

6. **Testing Implications:**
   - Consolidated code only needs to be tested once
   - Tests can serve as documentation for reusable code
   - Fewer code paths means more thorough test coverage

By avoiding code duplication, you'll create a more maintainable codebase that's easier to update, has fewer bugs, and promotes consistent behavior across your application.

Bun

Instructions to use bun/bunx instead of npm/npx.

Bun Logobun
# Bun Web Development Guidelines

## General Principles

- Always use `bun` and `bunx` instead of `npm` and `npx` for package management and script execution
- Leverage Bun's built-in bundler, test runner, and TypeScript support when possible
- Use Bun's native APIs for improved performance in web applications

## Package Management

- Use `bun install` for installing dependencies
- Use `bun add [package]` to add new dependencies
- Use `bun remove [package]` to remove dependencies
- Always commit `bun.lockb` to version control

## Scripts & Commands

- Run scripts with `bun run [script]` instead of `npm run [script]`
- Execute packages with `bunx [package]` instead of `npx [package]`
- Use `bun [file.js]` to run JavaScript/TypeScript files directly

## Testing

- Prefer Bun's built-in test runner (`bun test`) over Jest or other test frameworks
- Use `bun test --watch` for development
- Configure tests in `package.json` with the "test" field

## Web Development Features

- Leverage Bun's built-in `.env` support
- Use Bun's native fetch API for improved performance
- Consider Bun's built-in file system APIs for server-side operations
- For production web servers, use `bun --hot` for hot module reloading

## Framework Integration

- When using frameworks like React, Next.js, or Astro, check for Bun-specific optimizations
- Configure your build tools to work optimally with Bun
- Consider using Bun plugins when available

## Performance

- Take advantage of Bun's speed for faster development and build times
- Use Bun's native APIs over Node.js equivalents when possible for better performance
- Consider Bun's optimized SQLite integration for simple database needs

Guidelines for creating consistent, meaningful names in code

personal
## Guidelines for Clear Naming Conventions

1. **Core Principles:**

   - Names should clearly communicate purpose and intent
   - Consistency is key across the entire codebase
   - Be specific rather than generic
   - Prioritize readability over brevity (except for well-understood conventions)
   - Follow established patterns in the language and framework

2. **Variables and Constants:**

   - Use nouns or noun phrases that describe the data they contain
   - Boolean variables should have prefixes like `is`, `has`, or `should`
   - Avoid single-letter variables except for well-established conventions (e.g., `i` for loop indices)
   - Use meaningful, searchable names (avoid ambiguous abbreviations)
   - Constants should be in UPPER_SNAKE_CASE

3. **Functions and Methods:**

   - Use verbs or verb phrases that describe the action performed
   - Start with action words (e.g., `get`, `calculate`, `update`, `is`, `has`)
   - Event handlers should start with `handle` or `on`
   - Callback functions can be named with `cb` suffix when passed as arguments
   - Express what they return or do, not how they work

4. **Components and Classes:**

   - Use PascalCase for component and class names
   - Name components after their primary responsibility
   - Be specific about what they represent
   - Higher-order components can use `with` prefix (e.g., `withAuth`)
   - Custom hooks should start with `use` (e.g., `useFetch`)

5. **Files and Directories:**

   - Use consistent casing (kebab-case for files is common in many projects)
   - Group related files in descriptive directories
   - Index files should export from a logical group
   - Test files should clearly relate to what they're testing

6. **Language-Specific Conventions:**

   - JavaScript/TypeScript: camelCase for variables/functions, PascalCase for classes/components
   - CSS: kebab-case for class names and custom properties
   - HTML: kebab-case for attributes, lowercase for elements

7. **Consistency Rule:**
   - Follow existing patterns in the codebase even if they differ from your preference
   - Document naming conventions to ensure team alignment
   - Use linting tools to enforce consistency

Clear, descriptive names make code self-documenting, reducing the need for comments and making the codebase more maintainable for everyone.

Guidelines for adding meaningful comments to code

personal
## Guidelines for Code Comments

1. **Purpose:** Add comments to explain code functionality, especially for complex logic, non-obvious solutions, or business rules that aren't self-evident from the code itself.

2. **When to Comment:**

   - Comment on **WHY** code is written a certain way, not just WHAT it does
   - Document unexpected behavior or edge cases
   - Explain complex algorithms or business logic
   - Add context to workarounds or temporary solutions
   - Document API integrations and external dependencies

3. **Comment Quality:**

   - Be concise and clear - avoid unnecessary verbosity
   - Keep comments up-to-date when modifying code
   - Use proper grammar and spelling
   - Write comments that add value beyond what the code already communicates

4. **Comment Patterns:**

   - **Function/Method Headers:** Document purpose, parameters, return values, and side effects
   - **Block Comments:** Explain complex sections of code
   - **Inline Comments:** Clarify specific lines when necessary
   - **TODO/FIXME:** Mark areas for future improvement (with specific details)

5. **Avoid Unnecessary Comments:**

   - Don't comment on obvious code
   - Prefer self-documenting code with clear names over excessive comments
   - Remove commented-out code (rely on version control instead)

6. **Documentation Comments:**
   - Use JSDoc, TSDoc, or other documentation formats for public APIs
   - Include examples when they would help understanding

Remember that good comments complement good code - they don't replace the need for readable, well-structured code.

Guidelines for methodically exploring and understanding a codebase before making changes.

personal
## Codebase Exploration Guidelines

1. **Search First Approach:**

   - Search the codebase FIRST to get an understanding of the project structure and where files are located
   - Use grep search or fuzzy file search to locate relevant files and directories
   - Look for common patterns in file organization and naming conventions

2. **Review Project Structure:**

   - Identify key directories: src, components, pages, lib, utils, etc.
   - Understand the relationship between different parts of the codebase
   - Note where configuration files are stored (package.json, tsconfig.json, etc.)

3. **Examine Entry Points:**

   - Find and review main entry files (index.js, main.ts, App.tsx, etc.)
   - Check routing configurations to understand application flow
   - Review import patterns to identify commonly used modules

4. **Understand Conventions:**

   - Note coding styles and patterns used across the project
   - Identify naming conventions for files, components, and functions
   - Review how error handling, data fetching, and state management are implemented

5. **Reference Existing Code:**
   - When implementing new features, find similar existing implementations
   - Use existing patterns and approaches for consistency
   - Reference related components when making changes to maintain uniformity

Guidelines for choosing between Astro and React components

astro
# Astro Component Choice Guidelines (`.astro` vs. React)

## Purpose

This rule guides the decision on when to use native Astro components (`.astro`) versus framework components (specifically React `.jsx`/`.tsx` in this context) within an Astro project. The goal is to leverage Astro's performance benefits while using framework components strategically for interactivity.

## 1. Default to Astro Components (`.astro`)

- **Priority:** Start with Astro components for most UI elements.
- **Use Case:** Ideal for static content, page/component structure, layouts, and presentational elements that do not require client-side JavaScript for state management or complex interactivity.
- **Benefits:**
  - Aligns with Astro's "zero JS by default" philosophy, leading to faster load times.
  - Renders to HTML/CSS only, minimizing client-side footprint.
- **Simple Interactivity:** For basic interactions (e.g., toggling a class), consider using standard `<script>` tags within the `.astro` component before reaching for a framework component.

## 2. Use React Components (`.jsx`/`.tsx`) For Interactivity

- **Use Case:** Choose React components when **client-side JavaScript is necessary** for the component's core functionality.
- **Specific Scenarios:**
  - **State Management:** Components needing to manage internal state (e.g., using `useState`, `useEffect`).
  - **Complex Event Handling:** User interactions tightly coupled with component state or requiring sophisticated logic.
  - **React Ecosystem Integration:** Utilizing React-specific libraries (state managers, hooks) or third-party React component libraries (e.g., Shadcn UI).
  - **Reusing Existing Logic:** Integrating pre-existing React components or hooks.

## 3. Understand the "Island Architecture"

- React components act as "Islands of Interactivity" within your Astro application.
- They are isolated units that Astro hydrates on the client-side using `client:*` directives (e.g., `client:load`, `client:idle`, `client:visible`). This controls _when_ the component's JavaScript is loaded and executed.

## 4. Performance Consideration

- Each React component island adds JavaScript to the client, increasing bundle size and potentially impacting performance compared to a pure `.astro` component.
- Be deliberate: Use React components where their interactive capabilities provide significant value, not just because React is available.

## Example Mindset

- **Site Layout (`src/layouts/MainLayout.astro`):** Use `.astro`. It's structure.
- **Blog Post Content (`src/pages/posts/[slug].astro`):** Use `.astro` (or `.md`/`.mdx` with an `.astro` layout). It's primarily content.
- **Interactive Data Table (`src/components/InteractiveTable.jsx`):** Use React. Needs client-side sorting, filtering, state. Embed with `<InteractiveTable client:visible />`.
- **Simple Button (`src/components/ui/button.tsx` from Shadcn):** Use React (as provided by Shadcn). Although visually simple, it might encapsulate accessibility logic or styles best handled within the React component model. Embed with `<Button client:load />` if needed immediately, or perhaps `client:idle`.

## Code Examples

### ❌ INCORRECT: Using React for static content

```jsx
// Unnecessary React component for static content
// src/components/StaticHero.jsx
import React from "react";

export default function StaticHero() {
  return (
    <div className="py-20 text-center bg-blue-100">
      <h1 className="text-4xl font-bold">Welcome to My Site</h1>
      <p className="mt-4">This content never changes or needs interactivity</p>
    </div>
  );
}
```

```astro
<!-- Using that React component in an Astro page -->
---
import StaticHero from '../components/StaticHero.jsx';
---
<StaticHero client:load />
```

### ✅ CORRECT: Using Astro for static content

```astro
<!-- src/components/StaticHero.astro -->
---
// No props or logic needed
---
<div class="py-20 text-center bg-blue-100">
  <h1 class="text-4xl font-bold">Welcome to My Site</h1>
  <p class="mt-4">This content never changes or needs interactivity</p>
</div>
```

```astro
<!-- Using the Astro component -->
---
import StaticHero from '../components/StaticHero.astro';
---
<StaticHero />
```

### ❌ INCORRECT: Complex script inside Astro component

```astro
<!-- src/components/ComplexForm.astro -->
---
// Import data or props
---
<form class="mt-6 space-y-4">
  <input type="text" id="name" class="border p-2 w-full" />
  <input type="email" id="email" class="border p-2 w-full" />
  <!-- more form fields -->
  <button type="submit" class="bg-blue-500 text-white px-4 py-2">Submit</button>
</form>

<script>
  // Complex form validation with state management
  let errors = {};
  let formData = {};

  function validateName() {
    const nameInput = document.getElementById('name');
    if (nameInput.value.length < 2) {
      errors.name = 'Name is too short';
      showError(nameInput, errors.name);
    } else {
      delete errors.name;
      clearError(nameInput);
    }
    formData.name = nameInput.value;
  }

  // Many more validation functions and state management
  // Getting verbose and hard to maintain
  // ...

  document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault();
    validateForm();
    if (Object.keys(errors).length === 0) {
      submitData(formData);
    }
  });
</script>
```

### ✅ CORRECT: React component for complex interactive form

```tsx
// src/components/ComplexForm.tsx
import { useState } from "react";
import { z } from "zod";

const formSchema = z.object({
  name: z.string().min(2, "Name is too short"),
  email: z.string().email("Invalid email address"),
  // more validations
});

export default function ComplexForm() {
  const [formData, setFormData] = useState({ name: "", email: "" });
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    try {
      formSchema.parse(formData);
      // Submit data
      console.log("Submitting:", formData);
    } catch (error) {
      setErrors(error.flatten().fieldErrors);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="mt-6 space-y-4">
      <div>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
          className="border p-2 w-full"
        />
        {errors.name && <p className="text-red-500 text-sm">{errors.name}</p>}
      </div>

      <div>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          className="border p-2 w-full"
        />
        {errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
      </div>

      <button type="submit" className="bg-blue-500 text-white px-4 py-2">
        Submit
      </button>
    </form>
  );
}
```

```astro
<!-- Using the React form in an Astro page -->
---
import ComplexForm from '../components/ComplexForm.tsx';
---
<ComplexForm client:visible />
```

Guidelines for creating and using Astro components (.astro files).

astro
## Astro Components Guidelines

1.  Definition:

    - Basic building blocks of Astro projects, using the `.astro` file extension.
    - Primarily HTML templating components.
    - No client-side runtime by default: Render to HTML during build (static) or on request (SSR).

2.  Structure: `.astro` files have two parts:

    - Component Script: Enclosed in code fences (`---`). Contains JavaScript/TypeScript that runs only on the server/at build time. Used for imports, fetching data, defining variables, etc. This code is _not_ sent to the client.
    - Component Template: Standard HTML markup outside the code fences. Can include JavaScript expressions (e.g., `{variable}`, `<MyComponent prop={value} />`), Astro directives, and other components. Defines the HTML output.

3.  Props: Pass data from parent to child components.

    - Define props on the child component using `Astro.props`.
    - Use TypeScript `interface Props { ... }` within the script for type-checking.
    - Destructure props: `const { name, count = 0 } = Astro.props;`
    - Pass props as attributes when using the component: `<Greeting name="World" count={5} />`.
    - Attribute names are typically camelCase in the interface/script (e.g., `isActive`) and kebab-case when passed (e.g., `is-active={true}`), though Astro handles various casings.

4.  Slots (`<slot />`): Allow passing HTML content _into_ a component (children).

    - Default Slot: A single `<slot />` renders any child elements passed to the component that don't have a `slot` attribute.
    - Named Slots: Use `<slot name="my-name" />` in the component template. Pass content to it using the `slot="my-name"` attribute on the child element(s) in the parent.
      - Use `<Fragment slot="my-name">...</Fragment>` to pass multiple elements to a named slot without a wrapping `<div>`.
    - Fallback Content: Content placed inside the `<slot>` tag (`<slot>Default text</slot>`) is rendered _only_ if no matching children are passed for that slot.
    - Transferring Slots: Pass slots received by a component down to another component it uses. Use `<slot name="received-name" slot="target-name" />` for named slots or `<slot />` for the default slot.

5.  Interactivity:

    - For client-side JavaScript, use standard HTML `<script>` tags (potentially with `is:inline`) or import UI Framework Components (React, Vue, Svelte, etc.) which become Astro Islands.

6.  `.html` Components:
    - Can be imported and used like `.astro` files.
    - Contain only valid HTML; no frontmatter, server-side imports, or dynamic expressions.
    - `<script>` tags are treated as `is:inline` (not processed/bundled by Vite).
    - Assets referenced must be in the `public/` folder.
    - `<slot>` elements work similarly unless marked `is:inline`.

Reference: [Astro Components Docs](mdc:https:/docs.astro.build/en/basics/astro-components)

Guidelines for using Astro Content Collections

astro
## Guidelines for Astro Content Collections

1.  Purpose: Use Content Collections to organize, query, and type-check sets of related content (e.g., blog posts, projects, products) that share a similar data structure. Collections provide type safety and dedicated APIs.

2.  Location: Store collection content files (Markdown, MDX, JSON, YAML, etc.) in the `src/content/` directory, organized into subdirectories named after each collection (e.g., `src/content/blog/`, `src/content/projects/`). Do NOT place collection content directly in `src/pages/`.

3.  Configuration (`src/content/config.ts`):

    - Define each collection using `defineCollection` imported from `astro:content`.
    - Specify a `type` (`'content'` for Markdown/MDX or `'data'` for JSON/YAML).
    - Define a `schema` using Zod (`z` imported from `astro:content`) to validate the frontmatter or data structure of each entry and provide TypeScript types.
    - Use `reference()` within schemas to link entries between different collections (e.g., linking an author entry to a blog post).

4.  Querying Content:

    - Use `getCollection('collectionName', filterCallback?)` to fetch multiple entries. The filter callback receives `{ id, slug, body, collection, data }`.
    - Use `getEntry('collectionName', 'entryId')` or `getEntryBySlug('collectionName', 'entrySlug')` to fetch a single entry.
    - To fetch referenced entries (defined using `reference()` in the schema), use `getEntry()` or `getEntries()` on the reference object(s) returned in the `data` property of the initial entry.

5.  Rendering Content:

    - For Markdown/MDX entries (`type: 'content'`), import `render` from `astro:content`.
    - Call `const { Content } = await render(entry);` to get a component that renders the entry's main content.
    - Render the component in your template: `<Content />`.

6.  Generating Routes/Pages:

    - Collections do not automatically create pages. You must create dynamic routes in `src/pages/` to display collection entries.
    - Static Sites (Default): Use `getStaticPaths` within a dynamic route file (e.g., `src/pages/blog/[...slug].astro`). Call `getCollection` inside `getStaticPaths`, map the results to return `{ params: { slug: entry.slug }, props: { entry } }`. Use `Astro.props.entry` in the page template.
    - SSR: Inside the dynamic route file, retrieve the `slug` or `id` from `Astro.params`. Use `getEntryBySlug` or `getEntry` to fetch the specific entry needed for the request. Redirect to 404 if the entry isn't found.

7.  When to Use: Ideal for multiple pieces of content sharing a structure, requiring validation, type safety, and benefiting from Astro's content APIs. Suitable for scaling to large amounts of content.

8.  When NOT to Use:
    - Single, unique pages (use standard `.astro` pages in `src/pages/`).
    - Static assets like PDFs or images not processed by Astro (use the `public/` directory).
    - Data requiring real-time updates (collections are typically processed at build time).
    - When a specific SDK for a data source is preferred and doesn't integrate with the Content Layer API.

Reference: [Astro Content Collections Docs](mdc:https:/docs.astro.build/en/guides/content-collections)

Guidelines for using and creating Astro Content Loaders.

astro
## Astro Content Loader API Guidelines

1.  Purpose: Loaders bridge data sources (local files, APIs, CMS, databases) with Astro's Content Collections system. They define _how_ data gets into a collection.

2.  Association: Each content collection defined in `src/content/config.ts` requires a `loader`.

3.  Built-in Loaders:

    - `glob({ pattern, base?, generateId? })`: Loads entries from directories of files (Markdown, MDX, Markdoc, JSON, YAML) based on a glob pattern relative to the `base` path. [Reference](mdc:https:/docs.astro.build/en/reference/content-loader-reference/#glob-loader)
    - `file({ filename, generateId? })`: Loads entries from a single JSON or YAML file. [Reference](mdc:https:/docs.astro.build/en/reference/content-loader-reference/#file-loader)

4.  Custom Loaders: Can be defined inline in `src/content/config.ts` or as reusable "Object Loaders".

5.  Object Loader API: A custom loader is an object with a `name` and a `load` function. [Reference](mdc:https:/docs.astro.build/en/reference/content-loader-reference/#object-loader-api)

    - `name`: `string` - A unique identifier for the loader.
    - `load`: `async (context: LoaderContext) => void` - The core function responsible for fetching, parsing, and storing data.

6.  `LoaderContext` (passed to `load`): Provides tools for the loader. Key properties include:

    - `store`: `DataStore` - Interface to manage entries _within the specific collection_ the loader is assigned to.
    - `logger`: `Logger` - For outputting informational or debug messages during the load process.
    - `parseData`: `async ({ id, data }) => Promise<ParsedData>` - Crucial function. Validates raw fetched data against the collection's Zod schema and parses it into the expected typed format. Must be called before `store.set()`.
    - `generateDigest`: `(data) => string` - Creates a non-cryptographic hash of data, useful for the `digest` property on `DataEntry` to track changes.
    - `watcher`: `FSWatcher | undefined` - In dev mode, provides access to a filesystem watcher to trigger reloads (e.g., when a source file changes).
    - `config`: `AstroConfig` - The resolved Astro project configuration.

7.  `DataStore` API: Methods to interact with the collection's key-value store. [Reference](mdc:https:/docs.astro.build/en/reference/content-loader-reference/#datastore)

    - `set(entry: DataEntry)`: Adds or updates an entry _after_ it has been processed by `parseData`. Uses the `digest` property, if present, to avoid unnecessary updates if content hasn't changed.
    - `get(id: string)`: Retrieves an entry by ID.
    - `delete(id: string)`: Removes an entry.
    - `clear()`: Removes all entries (useful before loading fresh data).
    - `has(id: string)`: Checks if an entry exists.
    - `entries()`, `keys()`, `values()`: Iterate over stored entries.

8.  `DataEntry` Object: The structure representing a single item within the collection store. [Reference](mdc:https:/docs.astro.build/en/reference/content-loader-reference/#dataentry)
    - `id`: `string` (required) - Unique identifier within the collection.
    - `data`: `Record<string, unknown>` (required) - The _parsed_ data conforming to the collection's schema (result of `parseData`).
    - `filePath`: `string | undefined` - Relative path to the source file (if applicable, e.g., for `glob`). Used for resolving assets like images within the entry.
    - `body`: `string | undefined` - Raw, unparsed content body (e.g., Markdown source before rendering).
    - `digest`: `string | undefined` - Content hash generated by `generateDigest` for change detection.
    - `rendered`: `RenderedContent | undefined` - Object containing pre-rendered `html` and `metadata` (like `headings`, `imagePaths`). If present, allows the entry to be rendered using `<Content />` or `render()`.

Reference: [Astro Content Loader API Docs](mdc:https:/docs.astro.build/en/reference/content-loader-reference)

Guidelines for fetching remote data in Astro projects.

astro
## Astro Data Fetching Guidelines

1.  Primary Method: Use the standard global `fetch()` API within the component script (`---` fences) of `.astro` files.

    - Top-level `await` is supported and recommended for cleaner code.

    ```astro
    ---
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    ---
    <div>{data.message}</div>
    ```

2.  Timing of Fetch:

    - Static Site Generation (SSG - Default): `fetch()` calls run at build time. The fetched data is used to generate static HTML. Data is fetched only once during the build process.
    - Server-Side Rendering (SSR / On-Demand): `fetch()` calls run at request time (runtime) whenever the page or component is requested.

3.  Fetching in UI Framework Components:

    - The global `fetch()` is also available within UI framework components (.jsx, .tsx, .svelte, .vue, etc.).
    - If the component is server-rendered (or pre-rendered during build), the fetch behaves similarly to `.astro` files (build time for static, request time for SSR).
    - If the component is client-rendered (`client:*` directive), fetching might occur both on the server (if pre-rendered) and again on the client during hydration, or solely on the client depending on the setup. Be mindful of where and when the fetch executes.

4.  Using Fetched Data:

    - Render the data directly within the Astro component's template (`{data.property}`).
    - Pass the data as props to child components (both `.astro` and UI framework components).

5.  GraphQL:

    - Use `fetch()` with `method: 'POST'`, `headers: { 'Content-Type': 'application/json' }`, and a `body` containing the JSON-stringified GraphQL query and variables.

6.  CMS / API Integration:

    - Fetch data from headless CMSs or APIs within component scripts.
    - Often used in conjunction with dynamic routes (`src/pages/[slug].astro`) to generate pages based on fetched content.

7.  Client-Side Fetching:
    - For data that needs to be fetched or re-fetched _after_ the initial page load (client-side), use standard JavaScript `fetch()` within a `<script>` tag in an `.astro` component or within the logic of a client-rendered UI framework component.

Reference: [Astro Data Fetching Docs](mdc:https:/docs.astro.build/en/guides/data-fetching)

Guidelines for creating API routes and custom endpoints in Astro.

astro
## Astro Endpoints Guidelines

1.  Purpose: Create non-HTML responses like JSON data, RSS feeds, dynamic images, or full API routes.
2.  Location: Place `.js` or `.ts` files inside the `src/pages/` directory.
3.  Routing & Naming:
    - The file path determines the route (e.g., `src/pages/api/users.json.ts` becomes `/api/users.json`).
    - The extension in the filename dictates the output file's extension (e.g., `.json.ts` -> `.json`, `.png.ts` -> `.png`).
4.  Core Structure:

    - Export named functions corresponding to HTTP methods (e.g., `export function GET(...)`, `export function POST(...)`, `export function DELETE(...)`, `export const ALL = (...)`).
    - Use `import type { APIRoute } from 'astro';` for typing these functions (e.g., `export const GET: APIRoute = (...) => { ... }`).
    - Each function receives a context object (similar to `Astro` global) containing `params`, `request`, `cookies`, `redirect`, etc.
    - Functions must return a standard Web `Response` object (e.g., `return new Response(JSON.stringify({ data }), { status: 200, headers: { 'Content-Type': 'application/json' } });`).

5.  Static Endpoints (Default Build Behavior):

    - The `GET` function runs _at build time_ to generate a static file. Other methods (POST, etc.) are not applicable.
    - Dynamic Routes: Use `[param]` syntax in filenames (e.g., `src/pages/users/[id].json.ts`). Requires exporting `getStaticPaths()` to define the paths to pre-render at build time.
    - Context:
      - `params`: Contains parameters defined in `getStaticPaths`.
      - `request`: Limited; primarily `request.url` is useful.

6.  Server Endpoints (API Routes - Requires SSR/Hybrid Mode):

    - Requires `output: 'server'` or `output: 'hybrid'` in `astro.config.mjs`.
    - For hybrid/static sites, opt-out of pre-rendering for the specific endpoint file: `export const prerender = false;`.
    - Functions run _on request_ time (server-side).
    - All HTTP Methods: Supports `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `ALL`, etc. Export functions for the methods you need to handle. Astro calls the matching function based on the incoming request method.
    - `ALL` serves as a fallback for methods without a specific exported function.
    - Dynamic Routes: `params` are available directly from the requested URL (e.g., `Astro.params.id` or `context.params.id`) without needing `getStaticPaths`.
    - Context:
      - `request`: A full standard `Request` object. Access headers (`request.headers.get(...)`), body (`await request.json()`, `await request.formData()`), method (`request.method`), etc.
      - `redirect`: A function `redirect('/new-path', status?)` to perform server-side redirects (similar to `Astro.redirect`).
      - `cookies`: Access/set cookies using `context.cookies.get(...)` and `context.cookies.set(...)`.

7.  Response Object:
    - Use the standard `Response` constructor.
    - Set body, status code (`status`), and headers (`headers`).
    - For binary data (like images), pass an `ArrayBuffer` or `Buffer` as the body and set the correct `Content-Type` header.

Reference: [Astro Endpoints Docs](mdc:https:/docs.astro.build/en/guides/endpoints)

Guidelines for creating components and modules with logically related functionality

personal
## Guidelines for High Cohesion

Cohesion refers to the degree to which elements within a module belong together. High cohesion means that the methods and properties of a class, component, or module are closely related and focused on a single purpose.

1. **Core Principles:**

   - Each module, component, or function should have a single, well-defined purpose
   - Related functionality should be grouped together
   - Unrelated functionality should be separated
   - Elements that change together should stay together
   - Elements that don't change together should be separated

2. **Signs of Good Cohesion:**

   - Clear, focused component and function names that describe a single responsibility
   - Methods in a class that operate on the same data
   - Functions that work toward a common goal
   - Easy-to-write unit tests that don't require excessive mocking
   - Components that can be explained in a single sentence

3. **Types of Cohesion (from highest to lowest):**

   - **Functional Cohesion:** All elements contribute to a single, well-defined task
   - **Sequential Cohesion:** Output from one element serves as input to another
   - **Communicational Cohesion:** Elements operate on the same data
   - **Procedural Cohesion:** Elements follow a specified sequence of execution
   - **Temporal Cohesion:** Elements are related by when they're executed
   - **Logical Cohesion:** Elements perform similar functions but are otherwise unrelated
   - **Coincidental Cohesion:** Elements have no meaningful relationship (avoid this)

4. **Implementation Strategies:**

   - Apply the Single Responsibility Principle
   - Create utility modules that focus on specific domains
   - Use component composition instead of large monolithic components
   - Organize code around business domains or features
   - Extract unrelated functionality into separate modules

5. **Benefits of High Cohesion:**

   - Improved maintainability and readability
   - Better testability
   - Easier debugging
   - Enhanced reusability
   - Simpler code navigation

6. **Practical Applications:**
   - Split large files into smaller, more focused ones
   - Create helper/utility files organized by domain
   - Separate UI, business logic, and data access concerns
   - Group related components in directories with clear purposes
   - Use hooks to extract and isolate related functionality

By maintaining high cohesion throughout your codebase, you create a more organized, maintainable, and understandable system that's easier to extend and modify over time.

Images

Guidelines for using and optimizing images in Astro.

astro
## Astro Images Guidelines

1.  Image Storage:

    - `src/` (Recommended): Place images anywhere inside `src/` (e.g., `src/assets/`). Astro processes, optimizes, and bundles these images. Import them into your files to use.
      ```astro
      ---
      import localImage from '../assets/logo.png';
      ---
      ```
    - `public/`: Place images here if they should _not_ be processed by Astro and need a direct public URL. Reference them using a root-relative path (e.g., `/images/hero.jpg`).
    - Remote: Images hosted externally (CMS, CDN). Reference using their full URL. Remote domains _must_ be authorized in `astro.config.mjs` to be processed by `<Image />` or `<Picture />`.

2.  Using Images in `.astro` Files:

    - `<Image />` Component (from `astro:assets`): For optimized images. Automatically handles resizing, format conversion, and adds performance/accessibility attributes.

      - Required Props: `src`, `alt`, `width`, `height`.
      - `src`: Can be an imported local image object (`import img from '...'`) or an authorized remote URL string.

      ```astro
      ---
      import { Image } from 'astro:assets';
      import localLogo from '../assets/logo.png';
      ---
      <!-- Local Image -->
      <Image src={localLogo} width={300} height={150} alt="Astro Logo" />

      <!-- Remote Image (domain must be authorized) -->
      <Image src="https://example.com/remote.jpg" width={800} height={600} alt="Remote Image" />

      <!-- Public Image (no optimization) -->
      <Image src="/images/public-image.png" width={100} height={100} alt="Public Image" />
      ```

    - `<Picture />` Component (from `astro:assets`): For responsive images, providing different formats and sizes.
      - Required Props: `src`, `alt`, `widths`, `formats`.
      ```astro
      ---
      import { Picture } from 'astro:assets';
      import responsiveImg from '../assets/responsive.jpg';
      ---
      <Picture src={responsiveImg} widths={[200, 400, 800]} formats={['avif', 'webp']} alt="Responsive" />
      ```
    - HTML `<img>` Tag: For basic, unprocessed images.

      - Local Image: Import the image first, then use the `.src` property.
      - Public/Remote Image: Use the direct URL path.

      ```astro
      ---
      import localImage from '../assets/unprocessed.png';
      ---
      <!-- Local Image -->
      <img src={localImage.src} width={localImage.width} height={localImage.height} alt="Unprocessed" />

      <!-- Public Image -->
      <img src="/images/public-raw.jpg" alt="Public Raw" />

      <!-- Remote Image -->
      <img src="https://example.com/raw-remote.gif" alt="Remote Raw" />
      ```

3.  Authorizing Remote Domains: To allow Astro's built-in image service to process remote images used in `<Image />` or `<Picture />`, list the domains or URL patterns in `astro.config.mjs`:

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";

    export default defineConfig({
      image: {
        // Simple domain list
        domains: ["astro.build", "example.com"],
        // Or more complex patterns
        remotePatterns: [{ protocol: "https", hostname: "**.cdn.net" }],
      },
    });
    ```

4.  Images in Markdown (`.md`) and MDX (`.mdx`):

    - Standard Markdown Syntax: `![alt text](mdc:path/to/image.jpg)` works for relative paths (to the Markdown file), paths in `public/`, and remote URLs. Images are _not_ optimized by default with this syntax.
    - MDX: Can additionally use imported images with `<Image />`, `<Picture />`, or `<img>` tags just like in `.astro` files.

5.  Images in Content Collections:

    - Use the `image()` helper from `astro:content` in your collection schema (`z.object({ cover: image() })`).
    - Reference the image file path relative to the content file in the frontmatter (`cover: './cover-image.png'`).
    - The `image()` helper imports and processes the image, returning metadata suitable for the `src` prop of `<Image />` or `getImage()`.

6.  Images in UI Framework Components (React, Vue, etc.):

    - The Astro `<Image />` and `<Picture />` components cannot be used directly _inside_ framework components.
    - Option 1: Pass the rendered `<Image />` from an `.astro` parent component via children or `<slot />`.
    - Option 2: Use the framework's native image tag (e.g., JSX `<img />`). Import the local image within the framework component file to get its properties (`src`, `width`, `height`).

7.  `getImage()` Utility (from `astro:assets`):

    - A function to programmatically generate image metadata (`src`, `attributes`, etc.) based on options.
    - Useful for scenarios where components aren't suitable (e.g., API routes, custom components).

8.  Accessibility (`alt` Text):

    - Required for `<Image />` and `<Picture />`. Provide descriptive text.
    - Use `alt=""` for purely decorative images that don't add information.

9.  Image Service Configuration:
    - Sharp is the default service for optimization (may require manual install: `pnpm add sharp`).
    - Can be configured via `image.service` in `astro.config.mjs`.
    - Use `passthroughImageService()` for environments where Sharp isn't supported (e.g., Cloudflare Pages, Deno). This allows using `<Image />`/`<Picture />` syntax but skips optimization.

Reference: [Astro Images Docs](mdc:https:/docs.astro.build/en/guides/images)

Guidelines for creating and using Astro layout components.

astro
## Astro Layouts Guidelines

1.  Purpose: Layouts are reusable Astro components (`.astro` files) designed to provide a consistent structure for pages, such as defining the overall HTML shell (`<html>`, `<head>`, `<body>`), headers, footers, and navigation.

2.  Core Concept: Layouts are just standard Astro components. They can accept props, import other components (including other layouts), and use slots.

3.  Location: Conventionally placed in the `src/layouts/` directory, but this is not mandatory. They can reside anywhere in `src/`. If placed directly within `src/pages/`, prefix the filename with an underscore (`_`) to prevent it from becoming a route (e.g., `src/pages/_MyLayout.astro`).

4.  Basic Structure: A typical layout component defines the common page elements and uses a `<slot />` component to designate where the unique content of each page should be injected.

    ```astro
    <!-- src/layouts/BaseLayout.astro -->
    ---
    const { pageTitle = 'Default Title' } = Astro.props;
    ---
    <html lang="en">
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width" />
      <title>{pageTitle}</title>
      <link rel="stylesheet" href="/global.css">
    </head>
    <body>
      <header>My Site Header</header>
      <main>
        <slot /> <!-- Page content goes here -->
      </main>
      <footer>My Site Footer</footer>
    </body>
    </html>
    ```

5.  Using Layouts in `.astro` Pages: Import the layout component and wrap the page-specific content within its tags. Pass any required data as props.

    ```astro
    <!-- src/pages/index.astro -->
    ---
    import BaseLayout from '../layouts/BaseLayout.astro';
    ---
    <BaseLayout pageTitle="Home Page">
      <h1>Welcome!</h1>
      <p>This is the home page content.</p>
    </BaseLayout>
    ```

6.  Layouts for Markdown Pages (`.md` files in `src/pages/`):

    - Use the special `layout` frontmatter property within the Markdown file to specify the path to the `.astro` layout component.

      ```markdown
      ---
      layout: ../layouts/BlogPostLayout.astro
      title: "My First Blog Post"
      author: "Jane Doe"
      ---

      This is the content of my post.
      ```

    - The specified layout component automatically receives props derived from the Markdown file:
      - `frontmatter`: An object containing all the YAML frontmatter data.
      - `file`: Absolute path of the Markdown file.
      - `url`: URL pathname of the page.
      - `headings`: An array of heading objects (`{ depth, slug, text }`).
      - `rawContent()`: Function returning the raw Markdown string.
      - `compiledContent()`: Async function returning the compiled HTML string.
    - Use the `MarkdownLayoutProps` type helper from `astro` for TypeScript support in these layouts.

7.  Layouts for MDX Pages (`.mdx` files):

    - You can use the `layout` frontmatter property just like in `.md` files, with the same automatic prop injection.
    - Alternatively, you can import the layout component within the MDX file and wrap the content manually. If you do this, you must pass props explicitly; automatic prop injection does not occur in this case. Remember to include `<meta charset="utf-8">` in your layout when using MDX.

8.  Nesting Layouts: Layouts can import and use other layouts. This is useful for creating variations (e.g., a blog post layout that uses a base site layout). Pass props and slots down through the layers as needed.
    ```astro
    <!-- src/layouts/BlogPostLayout.astro -->
    ---
    import BaseLayout from './BaseLayout.astro';
    const { frontmatter } = Astro.props; // Received from Markdown page
    ---
    <BaseLayout pageTitle={frontmatter.title}>
      <article>
        <h1>{frontmatter.title}</h1>
        <p>By {frontmatter.author}</p>
        <slot /> <!-- Markdown content goes here -->
      </article>
    </BaseLayout>
    ```

Reference: [Astro Layouts Docs](https://docs.astro.build/en/basics/layouts/)

Guidelines for creating independent, flexible components and modules

personal
## Guidelines for Loose Coupling

Coupling refers to the degree of interdependence between software modules. Loose coupling means creating components and modules that are independent of each other, minimizing direct knowledge of each other's internal workings.

1. **Core Principles:**

   - Components should interact through well-defined interfaces, not implementation details
   - Modules should know as little as possible about other modules
   - Changes in one module should rarely force changes in others
   - Dependency direction should flow toward stability
   - Components should be easily substitutable without affecting others

2. **Implementation Strategies:**

   - **Dependency Injection:** Pass dependencies to components rather than having them create their own
   - **Interface Abstraction:** Depend on interfaces or abstract classes rather than concrete implementations
   - **Event-based Communication:** Use events/callbacks for communication between unrelated components
   - **Mediators/Services:** Use intermediate objects to coordinate between components
   - **Pure Functions:** Create functions with explicit inputs and outputs, no side effects

3. **Common Coupling Problems to Avoid:**

   - Direct references to implementation details of other components
   - Shared mutable state between components
   - Long inheritance chains
   - God objects/components that everything depends on
   - Circular dependencies

4. **Practical Applications:**

   - Create custom hooks that encapsulate and abstract complex logic
   - Use context API or state management libraries to avoid prop drilling
   - Build components that receive data via props without knowing their source
   - Design APIs to expose only the minimum necessary functionality
   - Use adapters to interact with third-party libraries

5. **Signs of Good Coupling:**

   - Components can be tested in isolation with minimal mocking
   - New features can be added without modifying existing code
   - Implementation details can change without affecting consumers
   - Components can be reused in different contexts
   - Code is easy to understand without needing to understand the whole system

6. **Benefits of Loose Coupling:**
   - Increased flexibility and adaptability
   - Better testability
   - Easier maintenance
   - Improved parallel development
   - Simplified understanding (each piece can be understood in isolation)

By maintaining loose coupling throughout your codebase, you create a more flexible, maintainable system that can evolve over time with minimal disruption.

Guidelines for keeping code paths simple and testable

personal
## Guidelines for Maintaining Low Cyclomatic Complexity

Cyclomatic complexity is a quantitative measure of the number of linearly independent paths through a program's source code. Lower complexity means more maintainable, testable code.

1. **Understanding Cyclomatic Complexity:**

   - Each decision point (if, while, for, case, &&, ||, ?:) adds to complexity
   - Higher complexity = more possible execution paths = harder to understand and test
   - A general rule: aim to keep the cyclomatic complexity of functions below 10
   - Critical code should have even lower complexity (5-7 range)

2. **Refactoring Techniques:**

   - **Extract Method:** Break complex functions into smaller, focused functions
   - **Replace Conditionals:** Use polymorphism, strategy pattern, or lookup tables
   - **Early Returns:** Handle edge cases early to avoid nested conditionals
   - **Guard Clauses:** Replace nested if structures with sequential validation checks
   - **State Machines:** For complex workflows with many states and transitions

3. **Common Complexity Sources:**

   - Deeply nested control structures
   - Long chains of if-else if-else blocks
   - Complex Boolean expressions with multiple AND/OR operators
   - Switch statements with many cases
   - Exception handling with multiple catch blocks

4. **Practical Implementation:**

   - Configure linting rules to enforce complexity limits (e.g., ESLint's `complexity` rule)
   - Use static analysis tools to identify high-complexity areas
   - Address complexity in code reviews
   - Refactor highest-complexity functions first

5. **Testing Implications:**

   - Lower cyclomatic complexity means fewer test cases needed for full coverage
   - Aim for one test per logical path
   - Complex functions with many branches require exponentially more tests

6. **Trade-offs to Consider:**

   - Sometimes a slightly more complex function is more readable than many tiny functions
   - Performance-critical code might justify higher complexity in limited cases
   - Balance complexity reduction against other design goals

7. **Monitoring Over Time:**
   - Track cyclomatic complexity as a quality metric
   - Address increasing complexity trends early
   - Set team standards for acceptable complexity levels

By maintaining low cyclomatic complexity, you create code that is easier to understand, test, and maintain while reducing the likelihood of introducing bugs.

MDX

Guidelines for using MDX files and components in Astro projects.

astro
## Astro MDX Integration Guidelines

1.  Purpose: Allows using MDX (`.mdx` files) in Astro projects. MDX extends Markdown by allowing JSX expressions, component imports (Astro & UI frameworks), and JavaScript variables directly within content.

2.  Installation: Install using the Astro CLI:

    ```bash
    npx astro add mdx
    # or pnpm add @astrojs/mdx / yarn add @astrojs/mdx
    ```

    This installs the package and adds it to your `astro.config.mjs`.

3.  Usage:

    - Pages: Create `.mdx` files in `src/pages/` just like `.astro` or `.md` files. They will be rendered as pages based on file-based routing.
    - Content Collections: Use `.mdx` files within `src/content/` collections. Query them using `getCollection()` or `getEntryBySlug()`.

4.  Key Features within `.mdx` files:

    - Standard Markdown: All standard Markdown syntax is supported.
    - Frontmatter: Use YAML frontmatter (`---`) just like in `.md` files. Frontmatter variables are accessible via `frontmatter.{variableName}` within the MDX content (after the closing `---`).
    - JSX Expressions: Embed JavaScript expressions directly using curly braces: `<h1>{frontmatter.title}</h1>`, `<p>Calculation: {2 + 2}</p>`.
    - Component Imports: Import Astro (`.astro`) or UI Framework (`.jsx`, `.svelte`, etc.) components using standard `import` statements _below_ the frontmatter.
    - Using Components: Render imported components using JSX syntax: `<MyComponent prop="value" client:load />`. Remember client directives for interactive components.
    - Exporting Variables: Use standard JavaScript `export const myVar = ...;` _below_ the frontmatter to define variables or data within the MDX file. These can be imported by other files.

5.  Rendering MDX Programmatically:

    - When using `getCollection()` or `getEntryBySlug()`, you get access to a `render()` function for the entry.
    - Call `const { Content, headings } = await entry.render();` to get the rendered content.
    - Render the content using the `<Content />` component in an `.astro` file.

6.  Customizing MDX Rendering:

    - `<Content components={...}>`: Pass a `components` prop to the `<Content />` component to override default HTML elements with custom components (e.g., `{ h1: MyCustomHeading }`).
    - Exporting `components` Object: Within an `.mdx` file, `export const components = { h1: MyCustomHeading };` maps Markdown syntax (`# Heading`) directly to your custom component for that file.

7.  Configuration (`astro.config.mjs`): Configure the MDX integration within the `integrations` array.
    - Inheritance: By default (`extendMarkdownConfig: true`), MDX inherits settings from your global `markdown` configuration (e.g., `syntaxHighlight`, `remarkPlugins`, `rehypePlugins`, `gfm`).
    - Overriding: Specify options directly within the `mdx()` config object to override inherited Markdown settings specifically for MDX files (e.g., `mdx({ gfm: false, remarkPlugins: [mdxSpecificPlugin] })`).
    - `extendMarkdownConfig: false`: Set to `false` to completely ignore the global `markdown` config and only use settings defined within `mdx()`.
    - `recmaPlugins`: Add Recma plugins (operate on the JavaScript AST after transformation).
    - `optimize: boolean | { ignoreElementNames?: string[] }`: Experimental optimization for faster builds. May cause issues with custom components passed via the `components` prop unless `ignoreElementNames` is used. Disabled by default.

Reference: [@astrojs/mdx Integration Docs](https://docs.astro.build/en/guides/integrations-guide/mdx/)

Guidelines for organizing code using the Mutually Exclusive, Collectively Exhaustive framework

personal
## MECE Framework Guidelines

The MECE (Mutually Exclusive, Collectively Exhaustive) framework is a principle for organizing code into clear, non-overlapping categories that together cover all necessary functionality.

1. **Mutually Exclusive Organization:**

   - Ensure each component, function, or module has a clearly defined, unique responsibility
   - Avoid functional overlap between different parts of the codebase
   - Create clear boundaries between different concerns
   - Eliminate duplicate or redundant implementations

2. **Collectively Exhaustive Coverage:**

   - Ensure all necessary functionality is accounted for across the codebase
   - Address all requirements and use cases
   - Include proper error handling for all possible scenarios
   - Cover both happy paths and edge cases

3. **Key Categories to Consider:**

   - **Structure:** Code organization, architecture, and patterns
   - **Comprehensibility:** Readability, maintainability, and documentation
   - **Efficiency:** Performance, optimization, and resource usage
   - **Inclusivity:** Accessibility, internationalization, and user experience

4. **Application in Code Architecture:**

   - Break down complex problems into distinct, non-overlapping components
   - Ensure each layer of your application has clear responsibilities (presentation, business logic, data access)
   - Create APIs and interfaces that cover all required functionality without redundancy
   - Organize test cases to be comprehensive without duplication

5. **Benefits:**
   - Reduces cognitive load by clearly separating concerns
   - Facilitates easier maintenance and debugging
   - Improves code reusability and modularity
   - Ensures complete coverage of requirements

By applying MECE principles, your code will be better organized, more maintainable, and with fewer gaps or overlaps in functionality.

Guidelines for using Astro Middleware to intercept requests and responses.

astro
## Astro Middleware Guidelines

1.  Purpose: Middleware allows you to run code before a page or API endpoint is rendered. It can intercept and modify request and response data, enabling dynamic behaviors like authentication, redirects, logging, or HTML rewriting.

2.  Requirement: Middleware functions primarily target on-demand rendered pages (SSR), as they run _at request time_. For pre-rendered static pages, middleware runs _once at build time_. Requires a server adapter to be installed for SSR functionality.

3.  Location: Create a file named `src/middleware.js` or `src/middleware.ts` (or `src/middleware/index.js|ts`).

4.  Structure:

    - Export a named function `onRequest`. This function can be `async`.
    - The function receives two arguments: `context` (an `APIContext`-like object) and `next` (a function).

    ```typescript
    // src/middleware.ts
    import { defineMiddleware } from "astro:middleware";

    export const onRequest = defineMiddleware(async (context, next) => {
      // Code runs before rendering the page/endpoint
      console.log(`Handling request for: ${context.url.pathname}`);

      // Modify context.locals to share data
      context.locals.userRole = "admin"; // Example

      // Proceed to the next middleware or the page render
      const response = await next();

      // Code runs after the page/endpoint has generated a response
      console.log(`Response status: ${response.status}`);

      // Optionally modify the response before sending
      // const html = await response.text();
      // return new Response(html.replace('foo', 'bar'), response);

      return response; // Return the original or modified response
    });
    ```

5.  `context` Object: Provides request information (e.g., `context.request`, `context.url`, `context.cookies`, `context.clientAddress`) and the crucial `context.locals` object.

6.  `context.locals`:

    - An object used to share data between middleware and your pages/endpoints within the same request lifecycle.
    - Populate `context.locals` in middleware (e.g., `context.locals.user = await getUser(...)`).
    - Access shared data in `.astro` files via `Astro.locals` (e.g., `const user = Astro.locals.user;`) or in endpoints via the `context.locals` property.
    - Data persists only for the _current request_.
    - Define the shape of `locals` in `src/env.d.ts` for type safety:
      ```typescript
      // src/env.d.ts
      declare namespace App {
        interface Locals {
          user?: { id: string; email: string };
          // other properties...
        }
      }
      ```

7.  `next()` Function:

    - Calling `await next()` proceeds to the next middleware in the sequence or renders the actual page/endpoint.
    - Crucially, you must `return` the result of `await next()` (or return a new `Response` directly) for the process to continue correctly.
    - `next(newPathOrRequest)`: Can be called with a URL path string, `URL`, or `Request` object to rewrite the request _without_ restarting the middleware chain. Subsequent middleware or the page will receive the rewritten context.

8.  Returning a `Response`: Instead of calling `next()`, middleware can directly return a standard `Response` object (e.g., `return new Response('Unauthorized', { status: 401 })` or `return context.redirect('/login')`). This stops further processing and sends the response immediately.

9.  Chaining Middleware (`sequence`):

    - Import `sequence` from `astro:middleware`.
    - Export `onRequest` as the result of `sequence(middleware1, middleware2, ...)`. Middleware runs in the specified order.

10. Rewriting (`context.rewrite`):

    - Use `return context.rewrite(newPathOrRequest)` to internally forward the request to render a different page/endpoint _without_ changing the browser URL.
    - Important: This _restarts_ the request handling process, meaning _all_ middleware functions (including the one calling `rewrite`) will run again for the rewritten path. Compare this to `next(newPath)`

Guidelines for reducing the mental effort required to understand code

personal
## Guidelines for Minimizing Cognitive Complexity

Cognitive complexity refers to the mental effort required to understand code. Minimizing it makes code more maintainable and reduces the likelihood of bugs.

1. **Function and Component Size:**

   - Keep functions and components small and focused on a single responsibility
   - Aim for functions under 20-30 lines where possible
   - Break large functions into smaller, well-named helper functions
   - Consider the "screen rule" - a function should fit on one screen

2. **Control Flow Simplification:**
   - Limit nesting to 2-3 levels maximum
   - Extract deeply nested code into separate functions
   - Use early returns to handle edge cases at the beginning of functions
   - Replace complex conditionals with guard clauses
   - Consider replacing nested if statements with switch statements or lookup tables
3. **Logical Expression Clarity:**

   - Break complex Boolean expressions into well-named variables
   - Limit logical operators in a single expression (3 or fewer conditions)
   - Use positive conditions instead of negative ones where possible
   - Avoid double negatives

4. **Abstraction and Encapsulation:**

   - Hide implementation details behind clear interfaces
   - Use composition to manage complex objects
   - Create helper functions with descriptive names for complex operations
   - Use meaningful design patterns that solve common problems

5. **State Management:**

   - Minimize the number of state variables in a component
   - Use consistent patterns for state updates
   - Consolidate related state into objects or custom hooks
   - Make state changes predictable and traceable

6. **Readability Techniques:**

   - Use consistent formatting and whitespace
   - Group related code together
   - Add empty lines between logical sections
   - Maintain consistent levels of abstraction within functions

7. **Documentation for Complex Logic:**
   - Add comments explaining WHY for complex algorithms or business rules
   - Document assumptions and edge cases
   - Use meaningful variable names that explain their purpose

By reducing cognitive complexity, you make your code more approachable, easier to debug, and more maintainable in the long term - both for yourself and other developers.

Guidelines for reducing reliance on external libraries and packages

personal
## Guidelines for Minimizing Dependencies

Dependencies are external code packages that your application relies on. While helpful, each dependency increases complexity, security risk, and potential for issues. This guide helps manage them effectively.

1. **Core Principles:**

   - Prefer native language/platform features over third-party libraries
   - Choose dependencies with purpose, not convenience
   - Evaluate each dependency for its necessity, quality, and maintenance burden
   - Understand the full cost of each dependency (size, security, maintenance)
   - Don't reinvent the wheel for complex, specialized functionality

2. **Before Adding a Dependency:**

   - **Necessity Check:** Can this be accomplished with native APIs? Is the functionality essential?
   - **Evaluation Criteria:**
     - Package size and impact on bundle
     - Active maintenance and community support
     - Security history and vulnerability reports
     - Documentation quality and completeness
     - License compatibility
     - Number of sub-dependencies

3. **Implementation Strategies:**

   - Use modern JavaScript/TypeScript features over utility libraries
   - Create focused utility functions instead of importing large libraries
   - Consider copying small, well-tested functions instead of importing an entire library
   - Use browser-native APIs (fetch, localStorage, etc.) when available
   - Implement simple solutions in-house for basic functionality

4. **Managing Existing Dependencies:**

   - Regularly audit dependencies with `npm audit` or similar tools
   - Remove unused dependencies (tools like `depcheck` can help)
   - Keep dependencies updated to secure versions
   - Consider dependency consolidation (use one solution consistently)
   - Document why each non-obvious dependency is needed

5. **Framework-Specific Considerations:**

   - For React, prefer hooks and built-in features over external state management for simpler apps
   - For styling, consider native CSS features before adding styling libraries
   - For UI components, evaluate if building simpler components yourself is more maintainable

6. **Benefits of Dependency Minimization:**

   - Smaller bundle sizes and faster load times
   - Reduced security vulnerabilities
   - Easier upgrades and maintenance
   - Better control over application behavior
   - Simplified debugging and troubleshooting

7. **Balanced Approach:**
   - It's about mindful selection, not avoiding all dependencies
   - For complex, well-established problems, quality libraries often provide better solutions
   - Consider the development time vs. maintenance trade-off

By minimizing dependencies, you create a leaner, more maintainable, and more secure application that you truly understand and control.

Guidelines for enabling and using server-side rendering (SSR) in Astro projects.

astro
## Astro On-Demand Rendering (SSR) Guidelines

1.  Definition: On-demand rendering, or Server-Side Rendering (SSR), generates page HTML on the server _when a request is made_, rather than at build time. This allows for dynamic, personalized content. Astro defaults to static pre-rendering.

2.  Requirement: Server Adapter: To enable any on-demand rendering, you must install and configure a server adapter specific to your deployment environment (e.g., Node.js, Vercel, Netlify, Cloudflare).

    - Use `bunx astro add [adapter-name]` (e.g., `bunx astro add node`) to install and configure automatically.
    - Alternatively, install the package manually and add it to the `adapter` property in `astro.config.mjs`.

3.  Enabling On-Demand Rendering:

    - Per-Page/Endpoint Basis (Hybrid Mode - Default when adapter is added): Add `export const prerender = false;` at the top of the specific `.astro`, `.md`, `.mdx` page or `.js`/`.ts` endpoint file you want to render on demand. All other pages remain static (pre-rendered).
    - Site-Wide Default (`server` Mode): Set `output: 'server'` in `astro.config.mjs`. This makes _all_ pages and endpoints render on demand by default.
      - To make specific pages static in `server` mode, add `export const prerender = true;` to those files.

4.  SSR-Exclusive Features: These are available _only_ for pages/endpoints configured for on-demand rendering:

    - `Astro.request`: Access the full standard `Request` object:
      - `Astro.request.headers`: Read incoming request headers (e.g., cookies, authorization).
      - `Astro.request.method`: Get the HTTP method (GET, POST, etc.).
      - `await Astro.request.formData()` / `await Astro.request.json()`: Read request body (for POST/PUT requests, often in API routes).
    - `Astro.cookies`: Get, set, and delete cookies using the `Astro.cookies` API (`.get()`, `.set()`, `.delete()`, `.has()`).
    - `Astro.response`: Modify the outgoing response:
      - `Astro.response.status`: Set the HTTP status code (e.g., 404, 500).
      - `Astro.response.statusText`: Set the status text message.
      - `Astro.response.headers.set(...)`: Set response headers.
    - Returning `Response` Objects: Directly return a standard `new Response(...)` object from a page or endpoint for full control over the response (e.g., for custom 404s, redirects, API responses). `Astro.redirect()` is a helper for returning redirect responses.
    - Server Endpoints (API Routes): Create `.js`/`.ts` files in `src/pages/` that export functions for HTTP methods (GET, POST, etc.) to handle API requests securely on the server.
    - HTML Streaming: Astro streams HTML content chunk-by-chunk as it's rendered on the server, potentially improving Time To First Byte (TTFB).

5.  When to Use:

    - Pages requiring user authentication or session data.
    - Content that changes frequently and needs to be up-to-the-minute.
    - Personalized pages based on user preferences or location.
    - Handling form submissions server-side.
    - Building API routes.

6.  Recommendation: Start with the default static mode (`output: 'static'`) and opt-in specific pages to SSR (`export const prerender = false;`) unless the vast majority of your site requires dynamic rendering. Static pages are generally more performant and scalable.

Reference: [Astro On-Demand Rendering Docs](mdc:https:/docs.astro.build/en/guides/on-demand-rendering)

Guidelines for using the @astrojs/partytown integration to offload third-party scripts.

astro
## Astro Partytown Integration Guidelines

1.  Purpose: Moves resource-intensive third-party scripts (like analytics, ads, tag managers) off the main browser thread and into a web worker. This improves site performance and responsiveness by preventing these scripts from blocking the main thread.

2.  Installation: Install using the Astro CLI:

    ```bash
    npx astro add partytown
    # or pnpm add @astrojs/partytown / yarn add @astrojs/partytown
    ```

    This installs the package and adds it to your `astro.config.mjs`.

3.  Usage:

    - After installation, identify third-party `<script>` tags in your project (usually in layouts or specific pages).
    - Change the `type` attribute of these scripts from `text/javascript` (or omit it) to `type="text/partytown"`.

    ```html
    <!-- Before -->
    <script src="https://example.com/analytics.js"></script>

    <!-- After -->
    <script
      type="text/partytown"
      src="https://example.com/analytics.js"
    ></script>
    ```

    - Partytown will intercept requests for scripts with this type and run them in the web worker.

4.  Configuration (Optional): Pass a `config` object to the `partytown()` integration in `astro.config.mjs`.

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";
    import partytown from "@astrojs/partytown";

    export default defineConfig({
      integrations: [
        partytown({
          // Partytown config options go here
          config: {
            debug: false, // Example: Disable debug logs
            forward: ["dataLayer.push"], // Example: Forward events
          },
        }),
      ],
    });
    ```

    - `config.debug`: `boolean` - Enables/disables Partytown's detailed console logging. Defaults to `true` in dev/preview, `false` in production.
    - `config.forward`: `string[]` - An array of global variables/functions (as strings) that need to be forwarded from the main thread to the web worker (e.g., `['dataLayer.push']` for Google Tag Manager). Necessary for communication with scripts running in the worker.

5.  Verification: After adding `type="text/partytown"`, use your browser's developer tools (Network tab) to check if requests for these scripts are being handled by the `partytown` proxy.

Reference: [@astrojs/partytown Integration Docs](https://docs.astro.build/en/guides/integrations-guide/partytown/)

Guidelines for using Astro's built-in page prefetching capabilities.

astro
## Astro Prefetching Guidelines

1.  Purpose: Improves perceived performance by prefetching linked pages in the background before the user clicks the link, leading to faster navigation.
2.  Enablement: Opt-in feature. Enable globally in `astro.config.mjs`:

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";

    export default defineConfig({
      prefetch: true, // Can also be an object for detailed config
    });
    ```

3.  Usage on Links: Add the `data-astro-prefetch` attribute to individual `<a>` tags pointing to internal site pages.
    ```html
    <a href="/about" data-astro-prefetch>About Us</a>
    ```
    Prefetching does not work for external links.
4.  Prefetch Strategies: Control _when_ prefetching occurs. Set per-link or via global default.

    - `hover` (Default): Prefetches when the link is hovered over or focused.
    - `tap`: Prefetches just before the user clicks the link.
    - `viewport`: Prefetches links as soon as they enter the viewport.
    - `load`: Prefetches all opted-in links on the page after the initial page load.

    ```html
    <!-- Use a specific strategy -->
    <a href="/contact" data-astro-prefetch="tap">Contact</a>

    <!-- Disable prefetch for a specific link -->
    <a href="/logout" data-astro-prefetch="false">Log Out</a>
    ```

5.  Configuration Object (`astro.config.mjs`): Fine-tune prefetching behavior.

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";

    export default defineConfig({
      prefetch: {
        // Change the default strategy for links with just `data-astro-prefetch`
        defaultStrategy: "viewport",
        // Prefetch ALL links on the page by default, even without the attribute?
        // (Note: This is true by default if View Transitions are enabled)
        prefetchAll: false,
      },
    });
    ```

6.  Programmatic API: Prefetch based on events other than link interactions.

    ```javascript
    import { prefetch } from "astro:prefetch";

    // Call this in a client-side script
    prefetch("/dashboard");

    // Options:
    prefetch("/slow-resource", { ignoreSlowConnection: true });

    // With experimental.clientPrerender enabled:
    // 'immediate' (default), 'eager', 'moderate', 'conservative'
    prefetch("/maybe-needed", { eagerness: "moderate" });
    ```

7.  View Transitions Integration:
    - If View Transitions are enabled on a page, prefetching is enabled automatically with a default config equivalent to `prefetch: { prefetchAll: true }`.
    - You can override this by explicitly setting the `prefetch` config in `astro.config.mjs` (e.g., set `prefetchAll: false` or `prefetch: false`).
8.  Browser Support & Considerations:
    - Uses `<link rel="prefetch">` where supported (Chrome), falls back to `fetch()` (Firefox, Safari).
    - Crucially relies on proper HTTP Caching Headers (especially `ETag`, but also `Cache-Control`/`Expires`) set by the server/host for the target pages. Without correct caching headers, prefetching might fail or be inefficient, especially in Firefox and Safari.
    - Static/prerendered pages often get `ETag` automatically from hosts.
    - SSR pages require manual setting of appropriate cache headers.
    - Respects user's data saver mode and connection speed (defaults to `tap` on slow connections), unless `ignoreSlowConnection: true` is used programmatically.
9.  Migration: The `@astrojs/prefetch` integration is deprecated. Remove it and use the built-in `prefetch` config. Convert `selector` config to `data-astro-prefetch="viewport"` and `intentSelector` to `data-astro-prefetch="hover"` (or just `data-astro-prefetch`).

Reference: [Astro Prefetch Docs](https://docs.astro.build/en/guides/prefetch/)

Guidelines for Astro's file-based routing, dynamic routes, and redirects.

astro
## Astro Routing Guidelines

1.  Core Concept: File-Based Routing

    - Routes are generated based on the file structure within the `src/pages/` directory.
    - `.astro`, `.md`, and `.mdx` files become pages.
    - `src/pages/index.astro` -> `/`
    - `src/pages/about.astro` -> `/about`
    - `src/pages/blog/post.astro` -> `/blog/post`

2.  Navigation

    - Use standard HTML `<a>` tags for linking between pages. No special framework component is required.
    - `<a href="/about">About</a>`
    - `<a href="/blog/latest-post">Blog Post</a>`

3.  Dynamic Routes

    - Use bracket syntax `[param]` for single path segments or spread syntax `[...slug]` for multiple segments.
    - `src/pages/posts/[id].astro` matches `/posts/1`, `/posts/abc`.
    - `src/pages/files/[...path].astro` matches `/files/a/b`, `/files/document.pdf`.
    - Static (SSG - Default):

      - Export an `async function getStaticPaths()` from the dynamic route file.
      - This function must return an array of objects, each defining the `params` for a specific route and optionally `props` to pass to the page.
      - ```javascript
        // src/pages/posts/[id].astro
        export async function getStaticPaths() {
          // Fetch data...
          const posts = [
            { id: "1", title: "First" },
            { id: "2", title: "Second" },
          ];
          return posts.map((post) => ({
            params: { id: post.id },
            props: { post }, // Pass the whole post object as a prop
          }));
        }
        const { post } = Astro.props; // Access props in the template
        ```

    - Server (SSR):

      - Access dynamic parameters directly using `Astro.params`.
      - `getStaticPaths` is not required to define routes but can be used for _prerendering_ specific paths for performance.
      - ```javascript
        // src/pages/users/[userId].astro
        const { userId } = Astro.params;
        // Fetch user data based on userId...
        ```

4.  Redirects

    - Configuration: Define permanent (301) or temporary (302) redirects in `astro.config.mjs`:
      ```javascript
      // astro.config.mjs
      import { defineConfig } from "astro/config";
      export default defineConfig({
        redirects: {
          "/old": "/new", // 301 default
          "/home": { status: 302, destination: "/" },
          "/users/[id]": "/profile/[id]", // Dynamic redirects
        },
      });
      ```
    - Dynamic (in .astro pages/endpoints): Use `return Astro.redirect('/new-path', status);`
      ```javascript
      // src/pages/admin.astro
      if (!isLoggedIn) {
        return Astro.redirect("/login", 307); // Temporary redirect
      }
      ```

5.  Rewrites (SSR Only)

    - Serve content from a different internal path without changing the URL shown to the user.
    - Use `return await Astro.rewrite('/internal/path');` primarily within Middleware.

6.  Route Priority

    - Static routes > Dynamic routes > Rest (...) routes.
    - More specific routes override less specific ones (e.g., `/posts/create` overrides `/posts/[id]`).
    - Endpoints (`.js`/`.ts` files) take precedence over pages (`.astro`/`.md`).
    - File-based routes > Configured redirects.
    - Reserved routes (`/_astro/`, `/_server_islands/`, `/_actions/`) have the highest priority.
    - Alphabetical order is the final tie-breaker.

7.  Pagination

    - Use a dynamic route parameter like `[page]` (e.g., `src/pages/blog/[page].astro`).
    - In `getStaticPaths`, use the `paginate` function provided as an argument:
      ```javascript
      // src/pages/items/[page].astro
      export async function getStaticPaths({ paginate }) {
        const allItems = await fetchItems();
        return paginate(allItems, { pageSize: 10 });
      }
      const { page } = Astro.props; // Access pagination data
      // page.data, page.currentPage, page.url.prev, page.url.next, etc.
      ```
    - Nested Pagination: Group paginated results (e.g., by tag). `getStaticPaths` should return multiple `paginate()` results, passing the grouping parameter via `params`:
      ```javascript
      // src/pages/[tag]/[page].astro
      export function getStaticPaths({ paginate }) {
        // ... fetch posts and tags ...
        return allTags.flatMap((tag) => {
          const taggedPosts = filterPostsByTag(tag);
          return paginate(taggedPosts, {
            params: { tag }, // Crucial for grouping
            pageSize: 5,
          });
        });
      }
      ```

8.  Excluding Pages
    - Prefix filenames or directory names within `src/pages/` with an underscore (`_`) to prevent them from being built as routes (e.g., `_components/`, `_utils.js`, `_draft-page.astro`).

Reference: [Astro Routing Docs](https://docs.astro.build/en/guides/routing/)

RSS

Guidelines for generating an RSS feed in Astro projects using @astrojs/rss.

astro
## Astro RSS Feed Generation Guidelines

1.  Installation: Install the official RSS package:

    ```bash
    npx astro add rss
    # or pnpm add @astrojs/rss / yarn add @astrojs/rss
    ```

2.  Prerequisite: Ensure your site's base URL is configured in `astro.config.mjs` under the `site` property. This is required for generating absolute URLs in the feed.

3.  Create Endpoint: Create a new file in `src/pages/` to serve as your feed endpoint. Use the `.xml.js` or `.xml.ts` extension (e.g., `src/pages/rss.xml.js`). This file will generate the `rss.xml` feed.

4.  Implement Endpoint:

    - Import the `rss` helper from `@astrojs/rss`.
    - Export an async `GET` function.
    - Inside `GET`, call and return the `rss()` function, passing it a configuration object.

5.  `rss()` Configuration Object:

    - `title` (string, required): The title of your RSS feed (e.g., "My Blog").
    - `description` (string, required): A short description of your feed.
    - `site` (string, required): The root URL of your site. Access this via `context.site` inside the `GET` function.
    - `items` (array, required): An array of objects, where each object represents an item (e.g., a blog post) in the feed. See step 6.
    - `customData` (string, optional): Inject arbitrary XML tags into the feed's `<channel>` element (e.g., `<language>en-us</language>`).
    - `stylesheet` (string, optional): Absolute path (from site root) to an XSL stylesheet to format the feed for browser viewing (e.g., `/rss/styles.xsl`).
    - `trailingSlash` (boolean, optional): Defaults to `true`. Set to `false` if your site config uses `trailingSlash: "never"` to ensure link consistency.

6.  Generating Feed `items`:

    - From Content Collections:
      - Use `getCollection('your-collection')`.
      - Map the results, extracting necessary properties for each item object. Required properties are `link` (full URL to the post), `title`, and `pubDate` (JavaScript `Date` object). Optional: `description`, `content`.
    - From Markdown/MDX in `src/pages/`:
      - Use `import.meta.glob()` to get the files.
      - Use the `pagesGlobToRssItems()` helper from `@astrojs/rss` to automatically convert the glob result into the required `items` array format. (Assumes frontmatter contains `title`, `pubDate`, `description`).
    - Item Properties:
      - `link`: Absolute URL to the content item.
      - `title`: Title of the item.
      - `pubDate`: Publication date (`Date` object).
      - `description` (optional): Short summary.
      - `content` (optional): Full HTML content of the item. Must be sanitized using a library like `sanitize-html` before inclusion. For Markdown, render the body to HTML first (e.g., using `markdown-it` or `post.compiledContent()` for glob imports).
      - `customData` (optional): String for custom XML tags within the `<item>`.

7.  Sanitizing HTML Content: If including full post content in the `content` property, always sanitize the generated HTML to prevent cross-site scripting (XSS) vulnerabilities. Use a library like `sanitize-html` and configure allowed tags (e.g., include `<img>` if needed).

8.  Auto-Discovery (Recommended): Add a `<link>` tag to the `<head>` of your site's layout(s) to help browsers and feed readers automatically find the feed:
    ```html
    <link rel="alternate" type="application/rss+xml" title="Your Feed Title"
    href={new URL('/rss.xml', Astro.site)} />
    ```
    (Adjust the `href` if your endpoint file has a different name).

Reference: [Astro RSS Feed Recipe](https://docs.astro.build/en/recipes/rss/)

Guidelines for using client-side JavaScript `<script>` tags and handling events in Astro.

astro
## Astro Scripts and Event Handling Guidelines

1.  Purpose: Add client-side interactivity (event listeners, animations, analytics, etc.) directly within `.astro` components using standard HTML `<script>` tags.

2.  Default Behavior (`<script>` tag):

    - Processed & Bundled: Astro processes scripts by default. It bundles imports (local files, npm modules) and handles TypeScript.
    - Module Scope: Output script uses `type="module"`. This means it's deferred (non-blocking), scoped (doesn't pollute global namespace), and runs after HTML parsing.
    - Deduplication: If a component with a script is used multiple times on a page, the script itself is only included once in the final HTML output.

3.  Opting Out of Processing (`is:inline`):

    - Use the `is:inline` directive on the `<script>` tag (`<script is:inline>`) to prevent Astro from processing it.
    - The script content is rendered _exactly_ as written into the HTML.
    - Imports will _not_ work. TypeScript is _not_ processed.
    - The script will be duplicated if the component is used multiple times.
    - Use this for simple inline scripts or when loading external scripts via `src` that shouldn't be bundled.
    - Note: Adding `type="module"` or most other attributes (except `src`) to a `<script>` tag implicitly applies `is:inline`.

4.  Loading Script Files:

    - Local Scripts (in `src/`): Reference using a relative path in the `src` attribute (`<script src="../scripts/my-script.ts"></script>`). Astro processes, bundles, and optimizes these.
    - External/Public Scripts (in `public/` or CDN): Reference using an absolute path (for `public/`) or full URL. Must use `is:inline` (`<script is:inline src="/scripts/public-script.js"></script>`). Astro does _not_ process these.

5.  Event Handling:

    - Astro uses standard browser APIs. No custom event syntax (like `onClick`).
    - Use `document.addEventListener` or `element.addEventListener` within a `<script>` tag to attach listeners.
    - Use `document.querySelectorAll` to target multiple elements if the script is part of a reusable component.

6.  Custom Elements (Web Components):

    - Define custom element behavior using `class MyElement extends HTMLElement { ... }` and register with `customElements.define('my-element', MyElement)` inside a `<script>` tag.
    - Wrap the component's HTML template in the custom tag (`<my-element>...</my-element>`).
    - Benefits:
      - Encapsulates logic and DOM querying (`this.querySelector` vs. `document.querySelector`).
      - Initialization logic (`connectedCallback`) runs for _each instance_ of the element, even though the defining `<script>` only runs once per page.
    - Recommended for reusable interactive components built solely with vanilla JS.

7.  Passing Data from Server (Frontmatter) to Client (Script):

    - Server-side variables in the `---` script are not directly accessible in client-side `<script>` tags.
    - Use data-\* attributes on HTML elements to store server-side values.
      ```astro
      ---
      const serverMessage = "Hello from server!";
      ---
      <div data-message={serverMessage}>...</div>
      <script>
        const div = document.querySelector('div');
        const clientMessage = div.dataset.message; // "Hello from server!"
        console.log(clientMessage);
      </script>
      ```
    - Custom elements can access these via `this.dataset.attributeName`.

8.  Interaction with UI Frameworks: If a `<script>` needs to interact with elements rendered by a UI framework component (island), consider using Custom Elements, as the framework component might not be hydrated/available when the standard script runs initially.

Reference: [Astro Scripts and Event Handling Docs](https://docs.astro.build/en/guides/client-side-scripts/)

Sentry

Guidelines for integrating Sentry for error tracking and performance monitoring in Astro projects.

astro
## Astro Sentry Integration Guidelines

1.  Purpose: Integrates Sentry's application monitoring and error tracking service into your Astro application. Helps identify, diagnose, and resolve issues in real-time.

2.  Installation: Use the Astro CLI to add the Sentry SDK and integration:

    ```bash
    npx astro add @sentry/astro
    # or pnpm add @sentry/astro / yarn add @sentry/astro
    ```

    This command installs the necessary package (`@sentry/astro`) and adds the integration to your `astro.config.mjs`.

3.  Configuration (`astro.config.mjs`): Configure the Sentry integration within the `integrations` array.

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";
    import sentry from "@sentry/astro";

    export default defineConfig({
      integrations: [
        sentry({
          // Required: Your Sentry project's DSN
          dsn: "YOUR_SENTRY_DSN_HERE", // Find in Project Settings > Client Keys (DSN)

          // Required for Source Map Uploads (readable stack traces)
          sourceMapsUploadOptions: {
            // Required: Your Sentry project name slug
            project: "your-sentry-project-slug", // Find in Project Settings > General Settings

            // Required: Sentry Auth Token (use environment variable)
            authToken: process.env.SENTRY_AUTH_TOKEN, // Create in Org Settings > Auth Tokens
          },

          // Optional: Add other Sentry SDK options here if needed
          // tracesSampleRate: 1.0,
          // profilesSampleRate: 1.0,
        }),
      ],
    });
    ```

4.  Required Credentials:

    - DSN: Found in your Sentry Project Settings > Client Keys (DSN).
    - Project Slug: Found in your Sentry Project Settings > General Settings.
    - Auth Token: Create an auth token in your Sentry Organization Settings > Developer Settings > Auth Tokens. Store this securely, typically as an environment variable (`SENTRY_AUTH_TOKEN`) and reference it via `process.env`. Do _not_ hardcode the token in your config file.

5.  Functionality: Once configured with the DSN and source map options, the SDK automatically:

    - Captures unhandled errors in both server-side (SSR) and client-side code.
    - Sends performance monitoring data (tracing) to Sentry.
    - Uploads source maps during the build (`astro build`) to provide readable stack traces in Sentry.

6.  Testing: To verify the setup, you can temporarily add a button or code snippet to a page that intentionally throws an error:

    ```html
    <button onclick="throw new Error('Sentry Test Error from Astro')">
      Throw test error
    </button>
    ```

    Click the button, then check your Sentry project to see if the error was captured.

7.  Development Tool: Sentry provides the "Spotlight" dev toolbar app for Astro, which shows Sentry errors and traces directly in the browser overlay during local development.

Reference: [Monitor your Astro Site with Sentry Guide](https://docs.astro.build/en/guides/backend/sentry/)

Guidelines for interacting with Shadcn UI components.

shadcn
# Shadcn UI Guidelines

## Context

- Shadcn UI is a collection of reusable components built using Radix UI and Tailwind CSS
- It's not a component library, but a collection of components you copy and paste into your project
- The components are unstyled and customizable
- Shadcn UI now fully supports Tailwind CSS v4 and React 19

## Component Usage

- Install components using the CLI: `bunx shadcn-ui@latest add <component-name>`
- Components should be added to the `components/ui` directory
- Do not modify files in the `components/ui` directory directly - create wrapper components instead
- Always check the documentation before implementing new components: https://ui.shadcn.com/docs

## Styling Guidelines

- Use Tailwind CSS for all component styling
- Follow the project's color theme defined in the CSS using the `@theme` directive (not in `tailwind.config.js`)
- Use the theme's semantic color tokens (e.g., `--color-primary`, `--color-secondary`) rather than raw color values
- Colors now use OKLCH format instead of HSL for better color representation
- For dark mode support, use the built-in `dark:` variant from Tailwind
- Utilize `data-slot` attributes now present on all primitives for targeted styling

## Custom Components

- When extending shadcn components, create wrapper components in separate directories
- Use composition rather than inheritance when building on existing components
- Follow the same naming conventions as shadcn components
- No need to use `forwardRef` with React 19 components
- Use the new `size-*` utility instead of width/height combinations

## Forms

- Use the form components from shadcn with the `react-hook-form` pattern
- Follow the Zod validation pattern for type-safe form validation
- Maintain consistent error handling across all forms

## Best Practices

- Use the `cn()` utility function from `lib/utils` to merge Tailwind classes
- Use `tw-animate-css` instead of the deprecated `tailwindcss-animate`
- Follow accessibility best practices as outlined in the shadcn documentation
- Ensure all interactive components have appropriate keyboard navigation support
- Test components in both light and dark mode
- Use `@import "tailwindcss";` instead of the legacy `@tailwind` directives in CSS

Guidelines for generating a sitemap using the @astrojs/sitemap integration.

astro
## Astro Sitemap Integration Guidelines

1.  Purpose: Automatically generates a `sitemap.xml` file for your Astro project during the build process. Sitemaps help search engines discover and crawl your site's pages more efficiently.

2.  Installation: Install using the Astro CLI:

    ```bash
    npx astro add sitemap
    # or pnpm add @astrojs/sitemap / yarn add @astrojs/sitemap
    ```

    This will install the package and add it to your `astro.config.mjs`.

3.  Prerequisite: You must have the `site` property configured in your `astro.config.mjs` with your website's final production URL.

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";
    import sitemap from "@astrojs/sitemap";

    export default defineConfig({
      site: "https://www.my-awesome-site.dev", // Required!
      integrations: [sitemap()],
    });
    ```

4.  Basic Usage: Once installed and configured with `site`, the integration automatically crawls your statically generated pages and creates `sitemap.xml` (and `sitemap-index.xml` if needed) in the output directory (usually `dist/`) during `astro build`.

5.  Limitations:

    - Does not automatically include routes generated on-demand (SSR routes using `export const prerender = false` or `output: 'server'`). These must be added manually using the `customPages` option if needed.

6.  Configuration Options (Passed to `sitemap()` in `astro.config.mjs`):

    - `filter`: `(pageUrl: string) => boolean` - Function to exclude specific pages based on their URL. Return `false` to exclude.
    - `customPages`: `string[]` - Array of absolute URLs to manually include pages not automatically detected by Astro (e.g., SSR pages, externally hosted pages relevant to the site).
    - `entryLimit`: `number` (default: 45000) - Maximum number of URLs per sitemap file. If exceeded, creates a sitemap index and multiple sitemap files.
    - `changefreq`: `string` - Sets the default `<changefreq>` value for all pages (e.g., `'daily'`, `'weekly'`). Note: Often ignored by search engines.
    - `lastmod`: `Date` - Sets a default `<lastmod>` date for all pages.
    - `priority`: `number` - Sets a default `<priority>` value (0.0 to 1.0) for all pages. Note: Often ignored by search engines.
    - `serialize`: `(item: SitemapItem) => SitemapItem | undefined` - Advanced: Function called for _each_ sitemap entry before writing. Allows modifying properties (`url`, `changefreq`, `lastmod`, `priority`, `links`) or excluding the item (return `undefined`). Useful for setting per-page metadata.
    - `i18n`: `{ defaultLocale: string, locales: Record<string, string> }` - Configures internationalization support, generating `<xhtml:link rel="alternate" ...>` tags for localized versions of pages based on URL structure.
    - `xslURL`: `string` - URL (absolute or relative to `site`) of an XSL stylesheet to format the sitemap for human viewing in browsers.

7.  Sitemap Discovery: While not part of the integration itself, it's recommended to add a link to your sitemap in your `robots.txt` file:
    ```
    Sitemap: https://www.my-awesome-site.dev/sitemap-index.xml
    ```
    (Or `sitemap.xml` if you don't exceed the `entryLimit`).

Reference: [@astrojs/sitemap Integration Docs](mdc:https:/docs.astro.build/en/guides/integrations-guide/sitemap)

Guidelines for optimizing page load performance using Astro's HTML streaming in SSR.

astro
## Astro Streaming Performance Guidelines

1.  Context: This applies when using Astro's Server-Side Rendering (SSR / On-Demand Rendering) capabilities. SSR uses HTML streaming to send content chunks to the browser as they become available.

2.  Problem: Blocking Fetches: If you `await` long-running data fetches (e.g., `await fetch(...)`) in the main page component's frontmatter script (`---`), Astro must wait for _all_ those fetches to complete before it can start sending _any_ HTML to the browser. This blocks rendering and can lead to slower perceived page load times.

3.  Solution 1: Component Refactoring:

    - Identify slow or independent data fetches in your main page/layout component.
    - Move each slow fetch into its own smaller, dedicated `.astro` component.
    - Import and use these new components in your main page template where the data is needed.
    - Benefit: The main page can now stream its initial HTML (like `<head>`, `<body>`, headers) immediately. The smaller components fetch their data in parallel (or sequentially depending on placement), and Astro streams their rendered HTML to the browser as soon as each component's data is ready and it's rendered.

    _Example:_

    ```astro
    <!-- BEFORE: src/pages/index.astro (slow) -->
    ---
    const slowData1 = await fetch('...');
    const slowData2 = await fetch('...');
    ---
    <html>...
      <Part1 data={slowData1} />
      <Part2 data={slowData2} />
    ...</html>

    <!-- AFTER: src/pages/index.astro (faster) -->
    ---
    import FetchPart1 from '../components/FetchPart1.astro';
    import FetchPart2 from '../components/FetchPart2.astro';
    ---
    <html>...
      <FetchPart1 />
      <FetchPart2 />
    ...</html>

    <!-- src/components/FetchPart1.astro -->
    ---
    const slowData1 = await fetch('...');
    ---
    <Part1 data={slowData1} />
    ```

4.  Solution 2: Using Promises Directly in Template:

    - Instead of `await`ing the `fetch` in the script, assign the `Promise` returned by `fetch().then(...)` to a variable.
    - Place the promise variable directly within `{}` in the component template.
    - Benefit: Astro streams the HTML _up to_ the point where the promise is used. It then waits for that specific promise to resolve, streams the resolved value, and continues streaming the rest of the HTML. Fetches placed later in the template don't block earlier content.

    _Example:_

    ```astro
    <!-- src/pages/index.astro -->
    ---
    const dataPromise = fetch('...').then(res => res.json());
    ---
    <html>...
      <p>Content before data...</p>
      <div>{dataPromise.then(data => data.message)}</div>
      <p>Content after data...</p>
    ...</html>
    ```

5.  Goal: Maximize the amount of HTML that can be sent to the browser quickly, unblocking rendering while slower data fetches complete in the background, improving metrics like Time To First Byte (TTFB) and perceived load speed.

Reference: [Using streaming to improve page performance Recipe](https://docs.astro.build/en/recipes/streaming-improve-page-performance/)

SVG

Guidelines for using Astro's experimental SVG components feature.

astro
Rule Name: experimental-svg.mdc
Description: Guidelines for using Astro's experimental SVG components feature.

# Experimental SVG Components Guidelines

1.  **Purpose:** Allows importing local `.svg` files directly as Astro components. The SVG content is inlined into the final HTML output. This feature requires enabling an experimental flag.

2.  **Enablement (`astro.config.mjs`):** Add the `experimental.svg` flag to your configuration file:

    ```javascript
    import { defineConfig } from "astro/config";

    export default defineConfig({
      experimental: {
        svg: true,
      },
    });
    ```

3.  **Usage:** Import the SVG file using a default import and render it like any other Astro component. Note the component capitalization convention.

    ```astro
    ---
    import MyIcon from '../assets/icon.svg';
    import AnotherLogo from '../assets/another-logo.svg';
    ---
    <div>
      <MyIcon />
      <AnotherLogo />
    </div>
    ```

4.  **Passing Attributes:** You can pass standard SVG attributes (e.g., `width`, `height`, `fill`, `class`, `stroke`) as props directly to the imported SVG component. These props will be applied to the root `<svg>` element, overriding any matching attributes present in the original `.svg` file.
    ```astro
    ---
    import Logo from '../assets/logo.svg';
    ---
    <Logo width={64} height={64} fill="currentColor" class="logo-style" />
    ```

Reference: [Astro Experimental SVG Components Docs](mdc:https:/docs.astro.build/en/reference/experimental-flags/svg/)

Guidelines for using Tailwind CSS (v4) in Astro projects.

tailwind
## Guidelines for Tailwind V4

1.  Target Version: Assume Tailwind CSS v4.0 or later for all Tailwind-related tasks (code generation, refactoring, suggestions).
2.  CSS-First Configuration:

    - AVOID generating, modifying, or referencing `tailwind.config.js` or `tailwind.config.ts` for theme customizations (e.g., colors, spacing, fonts, breakpoints).
    - PRIORITIZE defining and extending the theme directly within the main CSS file using the `@theme` directive and native CSS syntax.
    - Utilize CSS custom properties (variables) within `@theme` for defining tokens.
    - Example of correct CSS configuration:

      ```css
      /* src/input.css */
      @import "tailwindcss";

      @theme {
        --color-primary: oklch(65% 0.25 290); /* Define custom color */
        --font-sans: "Inter", sans-serif; /* Override default font */

        /* Extend spacing scale */
        spacing: {
          112: 28rem;
          128: 32rem;
        }

        /* Add custom breakpoints */
        screens: {
          '3xl':'1920px', ;
        }
      }

      /* You can add other custom CSS or layers here */
      ```

3.  Import Method:
    - Ensure Tailwind CSS is imported using the standard CSS `@import "tailwindcss";` directive in the main CSS entry point.
    - REMOVE any legacy `@tailwind base;`, `@tailwind components;`, or `@tailwind utilities;` directives.
4.  Content Configuration:
    - Rely on Tailwind v4's automatic content detection.
    - Do NOT add or suggest configuring the `content` array in `tailwind.config.js`/`.ts` unless addressing a specific, known edge case where automatic detection fails.
5.  Utilize v4 Features:
    - Leverage native CSS variables provided by Tailwind for accessing theme values in custom CSS (e.g., `color: var(--color-primary);`).
    - Employ new v4 utilities and variants where appropriate (e.g., container queries (`@`), `not-*` variant, `@starting-style`, expanded gradient utilities).
    - Use modern CSS functions like `color-mix()` where beneficial.
6.  Browser Compatibility:
    - Acknowledge the modern browser requirements of v4 (Safari 16.4+, Chrome 111+, Firefox 128+).
    - If the user explicitly requires support for older browsers, advise that Tailwind CSS v3.4 might be necessary and explain the limitation.
7.  Migration Tasks:
    - When assisting with migration from v3 to v4, focus on:
      - Replacing `@tailwind` directives with `@import "tailwindcss";`.
      - Translating configurations from `tailwind.config.js`/`.ts` (like `theme`, `extend`) into the `@theme` block in the CSS file.
      - Removing the now-unnecessary `tailwind.config.js`/`.ts` file if it only contained configurations now handled in CSS.

Guidelines and tips for troubleshooting common issues in Astro projects.

astro
## Astro Troubleshooting Guidelines

1.  Debugging with `console.log()`:

    - Logs in the component script (`---` fences) appear in the server terminal.
    - Logs in `<script>` tags (client-side JavaScript) appear in the browser console.
    - Framework components log to the terminal during SSR/build and potentially the browser after hydration (`client:*`).

2.  Debugging with `<Debug />`:

    - Import `{ Debug } from 'astro:components';`
    - Use `<Debug {...Astro.props} {variable1} {variable2} />` in your template to inspect prop/variable values directly in the browser output (during development).

3.  Common Error Messages:

    - `Cannot use import statement outside a module`: Usually means trying to use `import` in a non-module script. Ensure client-side `<script>` tags intended for bundling don't have attributes like `is:inline` that prevent processing, or ensure inline scripts don't use `import`.
    - `document`/`window` is not defined: Accessing browser-specific globals (like `document` or `window`) in server-side code (component script `---`). Wrap such code in client-side `<script>` tags or check `import.meta.env.SSR` conditionally.
    - `Expected a default export`: Typically when importing a component or layout. Ensure the imported file has a `export default ...` statement if required by how you're importing it.
    - `Refused to execute inline script`: Related to Content Security Policy (CSP). Check deployment environment CSP settings if using inline scripts (`is:inline`).

4.  Common Gotchas:

    - Component Not Rendering:
      - Verify the import path is correct.
      - Ensure the component file has the correct extension (`.astro`, `.jsx`, etc.).
      - Check if the component has a default export if needed.
    - Component Not Interactive (UI Frameworks):
      - Missing a `client:*` directive (e.g., `client:load`, `client:visible`). Components render as static HTML by default without hydration.
      - Astro components (`.astro`) are HTML-only templates; use `<script>` tags for client-side interactivity.
    - Cannot find package 'X':
      - Integrations (e.g., `@astrojs/react`) often require installing the underlying framework (`react`, `react-dom`) as a peer dependency. Install them explicitly.
    - Yarn 2+ (Berry) Issues: Set `nodeLinker: "node-modules"` in `.yarnrc.yml` if encountering PnP-related problems.
    - Monorepo Issues: Add Astro-related dependencies used in the root to `vite.ssr.noExternal` in `astro.config.mjs`.
    - Using `<head>` in Components: Avoid placing `<head>` tags directly in regular components. Use a single `<head>` within a layout component for the entire page.
    - Unexpected `<style>` Included: Astro bundles CSS for all imported components in the module graph, even if a component isn't conditionally rendered in the final HTML.

5.  Escaping Special Characters in Markdown: Use HTML entities (e.g., `&lt;` for `<`, `&gt;` for `>`) to display characters that have special meaning in Markdown/HTML.

6.  Creating Minimal Reproductions:

    - When asking for help or reporting bugs, create a small, isolated project demonstrating the issue.
    - Use `astro.new` (StackBlitz) or create a minimal local project and push to GitHub.
    - Include only the code necessary to reproduce the problem.

7.  Getting Help:
    - Astro Discord (`#support` channel).
    - GitHub Issues (check existing issues first, include minimal reproduction).
    - RFC Discussions for potential limitations or feature proposals.

Reference: [Astro Troubleshooting Docs](https://docs.astro.build/en/guides/troubleshooting/)

Guidelines for deploying Astro projects to Vercel using the @astrojs/vercel adapter.

astro
## Astro Vercel Adapter Guidelines

1.  Purpose: Enables deployment of Astro projects to Vercel, specifically required for Server-Side Rendering (SSR / on-demand routes). Also enables Vercel-specific features like Image Optimization and Web Analytics, even for static sites.

2.  Installation: Use the Astro CLI for automatic setup:

    ```bash
    npx astro add vercel
    # or pnpm add @astrojs/vercel / yarn add @astrojs/vercel
    ```

    This installs the adapter and updates `astro.config.mjs`.

3.  Usage:

    - SSR/Hybrid: Required when using `output: 'server'` or `output: 'hybrid'` in `astro.config.mjs` to deploy server-rendered pages or API endpoints to Vercel Functions (Serverless or Edge).
    - Static: Only needed if you want to use Vercel's Web Analytics or Image Optimization features with a statically generated Astro site. Otherwise, no adapter is needed for static deployments.

4.  Configuration Options (Passed to `vercel()` in `astro.config.mjs`):

    - `webAnalytics: { enabled: boolean }`: Enable Vercel Web Analytics. Injects the necessary tracking script. Defaults to `false`.
    - `imageService: boolean`: Enable Vercel's Image Optimization service for images processed by `astro:assets` (`<Image />`, `<Picture />`, `getImage()`). Defaults to `false`. Requires configuration in Vercel project settings.
    - `imagesConfig`: (`VercelImagesConfig`): Passthrough configuration for Vercel's native Image Optimization (domains, sizes, etc.). Use this if _not_ using `imageService: true`.
    - `devImageService: 'sharp' | 'squoosh' | string`: Specify the image service (`sharp` or `squoosh`) to use locally during `astro dev` _only_ when `imageService: true` is enabled. Defaults to `sharp`. Useful if Sharp has installation issues locally.
    - `isr: boolean | { expiration: number, exclude?: (string | RegExp)[], bypassToken?: string }`: Enable Incremental Static Regeneration (ISR) for on-demand pages. Pages are cached after the first request.
      - `expiration`: Cache duration in seconds.
      - `exclude`: Array of paths (strings or RegExps) to _always_ render on-demand (never cache).
      - `bypassToken`: Secret token to trigger on-demand regeneration (used with `exclude`).
    - `includeFiles: string[]`: Array of file paths to force-include in the function bundle.
    - `excludeFiles: string[]`: Array of file paths to explicitly exclude from the function bundle.
    - `maxDuration: number`: Maximum execution time in seconds for Serverless Functions. Subject to Vercel plan limits.
    - `skewProtection: boolean`: Enable Vercel's Skew Protection (requires Pro/Enterprise plan). Defaults to `false`.
    - `edgeMiddleware: boolean`: Deploy Astro middleware (`src/middleware.js/ts`) as a Vercel Edge Function instead of part of the Serverless Function. Allows middleware to run on all requests (including static assets). `context.locals` is passed via headers. Defaults to `false`.

5.  Middleware & Edge: When `edgeMiddleware: true`, middleware runs at the edge. Context data is serialized via JSON and passed in headers to serverless functions handling page rendering. Vercel Edge request context is available via `context.locals.vercel.edge`. Update `src/env.d.ts` with `EdgeLocals` for type safety.

6.  Node.js Version: The adapter relies on specific Node.js versions supported by Vercel. Check Vercel project settings for available versions.

Reference: [@astrojs/vercel Adapter Docs](https://docs.astro.build/en/guides/integrations-guide/vercel/)

Guidelines for implementing page transitions using Astro's View Transitions.

astro
## Astro View Transitions Guidelines

1.  Purpose: Enables smooth, animated transitions between pages without a full browser refresh, mimicking Single-Page Application (SPA) behavior within Astro's Multi-Page App (MPA) architecture. Uses the browser's native View Transitions API where available, with configurable fallbacks.

2.  Enablement: Add the `<ClientRouter />` component from `astro:transitions` to the `<head>` of your page or layout.

    ```astro
    ---
    import { ClientRouter } from 'astro:transitions';
    ---
    <head>
      <title>My Page</title>
      <ClientRouter />
    </head>
    <body>
      <!-- Page content -->
    </body>
    ```

    - Adding it to a shared layout enables site-wide view transitions.
    - Adding it to a single page enables transitions _away_ from that page.

3.  Automatic Prefetching: Adding `<ClientRouter />` automatically enables prefetching with the `prefetch: { prefetchAll: true }` default. Links will be prefetched on hover/focus to speed up transitions. This can be configured/disabled via the `prefetch` setting in `astro.config.mjs`.

4.  Transition Directives: Control how elements participate in transitions. Apply these directives to HTML elements.

    - `transition:name="unique-name"`: Assigns a unique name to an element. If an element with the same name exists on the next page, Astro attempts to animate the transition between them (e.g., morphing).
    - `transition:persist="unique-id" | ComponentName`: Keeps an element or component island persistent across navigation. The element/island must exist on both the source and destination pages with the same `transition:persist` value. Useful for maintaining state in islands (e.g., video players, maps).
    - `transition:animate="animation-name"`: Specifies a built-in or custom animation for an element during the transition.
      - Built-ins: `fade` (default), `slide`, `none`.
      - Custom: Define animations using CSS (see docs).

5.  Router Control (`astro:transitions/client` module):

    - Preventing Client-side Navigation: Add the `data-astro-reload` attribute to an `<a>` tag to force a full page refresh for that link, bypassing the view transition.
    - Triggering Navigation Programmatically: Use `navigate(href, options?)` from `astro:transitions/client` in client-side scripts.
      ```javascript
      import { navigate } from "astro:transitions/client";
      document.getElementById("my-button").onclick = () => {
        navigate("/next-page");
      };
      ```
    - Replacing History: Use `navigate('/next-page', { history: 'replace' })` to replace the current history entry instead of pushing a new one.
    - Forms: View transitions work automatically with standard HTML `<form>` submissions (GET and POST).

6.  Fallback Control: Configure behavior for browsers that don't support the native View Transitions API in `astro.config.mjs`.

    ```javascript
    // astro.config.mjs
    import { defineConfig } from "astro/config";

    export default defineConfig({
      viewTransitions: {
        fallback: "animate", // 'animate' (default, uses Astro's fallback animations) or 'swap' (no animation, just content swap)
      },
    });
    ```

7.  Script Behavior:

    - Standard `<script>` tags (not `type="module"`) in the `<head>` are executed once on initial load and not re-executed on navigation.
    - `<script>` tags in the `<body>` and all `<script type="module">` tags are re-executed after every navigation by default.
    - Add the `data-astro-rerun` attribute to a `<script>` tag to force re-execution even if it normally wouldn't, or to prevent re-execution if it normally would.
    - Scripts marked `is:inline` behave like standard scripts (run once in `<head>`, rerun in `<body>`).

8.  Lifecycle Events: Hook into the navigation process using events dispatched on `document`.

    - `astro:before-preparation`: Before loading starts. Can alter loading or direction.
    - `astro:after-preparation`: After new page content is loaded/parsed, before transition starts.
    - `astro:before-swap`: Just before the new DOM replaces the old one (inside the transition). Can modify `event.newDocument` or provide a custom `event.swap()` implementation.
    - `astro:after-swap`: Immediately after the DOM swap. Useful for restoring state.
    - `astro:page-load`: Fires after navigation is complete and the page is interactive. Runs on initial load and subsequent navigations.

9.  Accessibility:
    - Route Announcement: `<ClientRouter />` automatically announces the new page title (or `<h1>`, or path) to assistive technologies after navigation.
    - Reduced Motion: Respects `prefers-reduced-motion` setting, disabling animations automatically.

Reference: [Astro View Transitions Docs](mdc:https:/docs.astro.build/en/guides/view-transitions)