Awesome Cursor Rules Collection

Showing 913-924 of 2626 matches

TypeScript
# Demo: Constructivist Teaching with LLMs

## Project Structure

```text
src/
├── app/                    # Next.js App Router
│   ├── layout.tsx         # Root layout with font configurations
│   ├── page.tsx           # Landing page
│   └── globals.css        # Global styles
├── components/
│   ├── demo/              # Demo-specific components
│   │   ├── Introduction.tsx
│   │   ├── Questions.tsx
│   │   └── Tutorial.tsx
│   └── ui/               # Shared UI components
│       ├── Typography.tsx
│       └── Animations.tsx
├── lib/
│   ├── machines/         # XState machines
│   ├── store/           # Zustand store
│   └── hooks/           # Custom hooks
└── styles/              # Additional style modules
```

## Font Usage

The project uses IBM Plex font family:

```typescript
// In components, use Tailwind classes:
<h1 className="font-serif">    // IBM Plex Serif
<p className="font-sans">      // IBM Plex Sans
<code className="font-mono">   // IBM Plex Mono

// Typography scale examples:
text-base font-serif    // Base serif text
text-lg font-sans      // Larger sans text
text-2xl font-serif    // Large serif headings

// Animation examples:
animate-fade-in       // Fade in animation
animate-fade-out      // Fade out animation
```

## Project Overview

Building a demo for a university booth showcasing how LLMs can be taught to teach using constructivist principles. The demo focuses on teaching mergesort through a constructivist approach, with synthetic student responses generated by another LLM.

## Key Features

1. Interactive onboarding flow with vision questions
2. Typography-focused design using IBM Plex Sans and Serif
3. Smooth animations enhancing typographic elements
4. Dynamic synthetic student responses
5. State machine-driven demo flow

## Technical Stack

- Next.js 15.0.4
- React 19.0.0
- TypeScript 5.7.2
- Tailwind CSS 3.4.16
- XState for state management
- Zustand for global state
- Framer Motion for animations
- IBM Plex fonts

## Architecture Decisions

1. Using XState for demo flow management to handle complex state transitions
2. Typography-first design approach with careful attention to animations
3. Separation of LLM roles (teacher vs. synthetic students)
4. Minimal, focused UI with emphasis on text presentation

## Key Components Structure

- Onboarding flow (welcome, name input)
- Vision questions about teaching LLMs
- Mergesort tutorial demonstration
- Synthetic student response selection
- Typography components with animations

## State Management

1. XState machine handles demo flow
2. Zustand manages global state
3. State includes:
   - Current demo step
   - User responses to vision questions
   - Selected student persona
   - Tutorial progress

## Styling Guidelines

1. Use IBM Plex Sans for UI elements
2. Use IBM Plex Serif for educational content
3. Implement smooth transitions between states
4. Focus on typographic hierarchy and spacing
5. Use animations to enhance text prominence

## Animation Guidelines

1. Subtle text fade-ins and transitions
2. Smooth step transitions
3. Typography-focused motion design
4. No flashy or distracting animations

## Code Organization

- `/app` - Next.js app router structure
- `/components` - Reusable UI components
- `/machines` - XState definitions
- `/store` - Zustand store
- `/styles` - Global styles and typography
- `/lib` - Utilities and hooks

## Testing Considerations

1. State transitions
2. Typography rendering
3. Animation performance
4. LLM response handling

## Performance Guidelines

1. Optimize typography loading
2. Minimize animation impact
3. Efficient state management
4. Responsive design considerations

## Development Priorities

1. Set up typography system
2. Implement state machine
3. Create basic flow
4. Add animations
5. Integrate LLM responses
6. Polish UI/UX

## Accessibility Guidelines

1. Maintain text contrast
2. Ensure keyboard navigation
3. Support screen readers
4. Respect reduced motion preferences

When implementing new features or making changes:

1. Follow typographic principles
2. Maintain clean state transitions
3. Keep animations subtle and purposeful
4. Prioritize readability and clarity
5. Ensure responsive behavior

## Component Organization

1. Page Components
   - Located in `src/app`
   - Use page.tsx for main routes
   - Keep pages thin, delegate to components

2. Demo Components
   - Located in `src/components/demo`
   - Each major demo section has its own component
   - Use composition for complex features

3. UI Components
   - Located in `src/components/ui`
   - Reusable, atomic design principles
   - Consistent typography and animation patterns

4. Typography Components

   ```typescript
   // Example Typography component
   const Heading = ({ children, className }: PropsWithChildren<{ className?: string }>) => (
     <h2 className={clsx(
       "font-serif text-2xl leading-relaxed mb-6",
       "animate-fade-in",
       className
     )}>
       {children}
     </h2>
   );
   ```

5. Animation Components

   ```typescript
   // Example animated text component
   const AnimatedText = ({ children }: PropsWithChildren) => (
     <motion.div
       initial={{ opacity: 0, y: 20 }}
       animate={{ opacity: 1, y: 0 }}
       className="font-sans"
     >
       {children}
     </motion.div>
   );
   ```

## Style Enforcement

- Use TypeScript strictly
- Follow Tailwind class ordering
- Maintain consistent component patterns
- Follow Next.js best practices

## Deno KV: Key/Value database - Deno by Example

> ## Excerpt
>
> In-depth documentation, guides, and reference materials for building secure, high-performance JavaScript and TypeScript applications with Deno

IMPORTANT: PLEASE IGNORE LINTS AND ERRORS IN DENO TYPESCRIPT FILES. THE TYPESCRIPT LANGUAGE SERVER INSERTS ERRORS WHEN IT SHOULD NOT. ONLY THE `deno` SOURCE FOR DIAGNOSTICS IS CORRECT.

```typescript
/**
 * @title Deno KV: Key/Value database
 * @difficulty intermediate
 * @tags cli, deploy
 * @run --unstable-kv <url>
 * @resource {https://docs.deno.com/deploy/kv/manual} Deno KV user guide
 * @resource {https://docs.deno.com/api/deno/~/Deno.Kv} Deno KV Runtime API docs
 * @group Unstable APIs
 *
 * <strong>Warning: This is an unstable API that is subject to change or removal at anytime.</strong><br>Deno KV is a key/value database built in to the Deno runtime, and works with
 * zero configuration on Deno Deploy. It's great for use cases that require fast
 * reads and don't require the query flexibility of a SQL database.
 */

// Open the default database
const kv = await Deno.openKv();

// Define an interface in TypeScript for our data
enum Rank {
  Bronze,
  Silver,
  Gold,
}

interface Player {
  username: string;
  rank: Rank;
}

// Create a few instances for testing
const player1: Player = { username: "carlos", rank: Rank.Bronze };
const player2: Player = { username: "briana", rank: Rank.Silver };
const player3: Player = { username: "alice", rank: Rank.Bronze };

// Store object data in Deno KV using the "set" operation. Keys can be arranged
// hierarchically, not unlike resources in a REST API.
await kv.set(["players", player1.username], player1);
await kv.set(["players", player2.username], player2);
await kv.set(["players", player3.username], player3);

// The "set" operation is used to both create and update data for a given key
player3.rank = Rank.Gold;
await kv.set(["players", player3.username], player3);

// Fetch a single object by key with the "get" operation
const record = await kv.get(["players", "alice"]);
const alice: Player = record.value as Player;
console.log(record.key, record.versionstamp, alice);

// Fetch several objects by key with "getMany"
const [record1, record2] = await kv.getMany([
  ["players", "carlos"],
  ["players", "briana"],
]);
console.log(record1, record2);

// List several records by key prefix - note that results are ordered
// lexicographically, so our players will be fetched in the order
// "alice", "briana", "carlos"
const records = kv.list({ prefix: ["players"] });
const players = [];
for await (const res of records) {
  players.push(res.value as Player);
}
console.log(players);

// Delete a value for a given key
await kv.delete(["players", "carlos"]);

// The Deno.KvU64 object is a wrapper for 64 bit integers (BigInt), so you can
// quickly update very large numbers. Let's add a "score" for alice.
const aliceScoreKey = ["scores", "alice"];
await kv.set(aliceScoreKey, new Deno.KvU64(0n));

// To prepare an atomic transaction to update the score, first we need to
// check if the score has been modified since we read it. We can use the
// versionstamp to check if the value has been modified since we read it.
const aliceScoreEntry = await kv.get<Deno.KvU64>(aliceScoreKey);
const atomicCheck = {
  key: aliceScoreEntry.key,
  versionstamp: aliceScoreEntry.versionstamp,
};

// Add 10 to the player's score in an atomic transaction
const res = await kv.atomic()
  .check(atomicCheck)
  .mutate({
    type: "sum",
    key: aliceScoreKey,
    value: new Deno.KvU64(10n),
  })
  .commit();
// Check if the transaction was successful
if (res.ok) {
  const newScore = (await kv.get<Deno.KvU64>(aliceScoreKey)).value;
  console.log("Alice's new score is:", newScore);
} else {
  console.error("Transaction failed ");
  // Optionally, implement retry logic or handle the conflict
}
```

# AI Tutor Implementation Guide

## Core Teaching Philosophy

1. **Constructivist Approach**
   - Guide discovery rather than direct instruction
   - Build on student's existing understanding
   - Never explain concepts before students have a chance to discover them
   - Use carefully chosen examples to lead to insights
   - Track genuine understanding through milestones

2. **Teaching Persona**
   - Professional but approachable
   - Patient and encouraging
   - Adapts to student's pace
   - Maintains clear direction
   - Shows genuine interest in student's thinking

3. **Session Structure**
   - 30-45 minute interactive experience
   - Progress tracking through milestones
   - Dynamic response generation
   - Guided discovery of merge sort
   - Focus on student-led insights

## Implementation Components

1. **State Management Integration**

   ```typescript
   interface TeachingState {
     currentMilestone: string;
     completedMilestones: string[];
     studentResponses: StudentResponse[];
     currentExample: number[];
     teachingPhase: 'discovery' | 'development' | 'mastery';
   }
   ```

2. **Response Generation**
   - Parse student understanding level
   - Select appropriate next example
   - Generate constructivist questions
   - Validate genuine understanding
   - Track milestone progress

3. **Question Design**

   ```typescript
   interface TeachingQuestion {
     type: 'discovery' | 'verification' | 'extension';
     content: string;
     expectedInsight: string;
     followUp: string[];
     validation: string[];
   }
   ```

## Milestone Framework

1. **Inefficiency Discovery**
   - Guide comparison of sorting approaches
   - Build pattern recognition skills
   - Let students discover computational complexity
   - Use concrete examples with clear patterns
   - Track steps for different input sizes

2. **Divide-and-Conquer Insight**
   - Build from binary search understanding
   - Guide discovery of splitting benefits
   - Use small, tractable examples
   - Compare work before and after splitting
   - Let students propose splitting idea

3. **Merging Development**
   - Start with pre-sorted small arrays
   - Guide systematic comparison discovery
   - Build understanding of merge process
   - Use visual aids for clarity
   - Track development of merging strategy

4. **Recursive Pattern Recognition**
   - Build understanding level by level
   - Guide discovery of repeated patterns
   - Use tree visualization
   - Connect to previous insights
   - Let students discover recursive nature

## Implementation Guidelines

1. **Response Processing**

   ```typescript
   interface StudentResponse {
     content: string;
     type: 'question' | 'observation' | 'attempt';
     relatedMilestone?: string;
     comprehensionIndicators: string[];
   }
   ```

2. **Example Management**

   ```typescript
   interface TeachingExample {
     array: number[];
     complexity: 'basic' | 'intermediate' | 'advanced';
     insights: string[];
     visualAids: boolean;
     scaffolding: string[];
   }
   ```

3. **Visual Components**
   - Array visualization
   - Split step animation
   - Merge operation display
   - Progress tracking
   - Milestone indicators

## Recovery Strategies

1. **Understanding Gaps**
   - Return to last confirmed understanding
   - Use simpler examples
   - Break down concepts
   - Provide targeted practice
   - Build confidence through success

2. **Misconceptions**
   - Address immediately but gently
   - Use counterexamples
   - Guide self-correction
   - Reinforce correct understanding
   - Track resolution

## Response Generation Rules

1. **Question Formation**
   - Never ask yes/no questions
   - Focus on process explanation
   - Encourage prediction
   - Build on previous responses
   - Guide discovery naturally

2. **Feedback Design**

   ```typescript
   interface TeachingFeedback {
     type: 'guidance' | 'validation' | 'correction';
     content: string;
     nextStep: string;
     scaffolding?: string[];
   }
   ```

## Accessibility Implementation

1. **ARIA Landmarks and Roles**

   ```typescript
   // Main tutorial layout
   interface AccessibleLayout {
     regions: {
       navigation: "complementary" | "navigation";
       tutorial: "main";
       responses: "complementary";
     };
     landmarks: {
       milestones: "region";
       chat: "log";
       responses: "form";
     };
   }

   // Example implementation
   <nav role="navigation" aria-label="Learning milestones">
     <MilestonesPanel />
   </nav>
   <main role="main" aria-live="polite">
     <ChatArea />
   </main>
   <aside role="complementary" aria-label="Response options">
     <ResponsePanel />
   </aside>
   ```

2. **Dynamic Content Updates**

   ```typescript
   // Chat message structure
   interface ChatMessage {
     role: "tutor" | "student";
     content: string;
     ariaLabel: string;
     ariaLive: "off" | "polite" | "assertive";
   }

   // Implementation example
   <div 
     role="log" 
     aria-label="Tutorial conversation"
     aria-live="polite"
   >
     {messages.map(message => (
       <div 
         role="article"
         aria-label={`${message.role} message: ${message.ariaLabel}`}
       >
         {message.content}
       </div>
     ))}
   </div>
   ```

3. **Interactive Elements**

   ```typescript
   // Response option component
   interface ResponseOption {
     id: string;
     content: string;
     persona: string;
     ariaPressed?: boolean;
     ariaExpanded?: boolean;
     ariaControls?: string;
   }

   // Implementation example
   <button
     role="button"
     aria-haspopup="dialog"
     aria-expanded={isExpanded}
     aria-pressed={isSelected}
     aria-controls={`response-${id}`}
   >
     <span className="sr-only">{persona} responds:</span>
     {content}
   </button>
   ```

4. **Progress Tracking**

   ```typescript
   // Milestone structure
   interface AccessibleMilestone {
     id: string;
     text: string;
     isComplete: boolean;
     ariaLabel: string;
   }

   // Implementation example
   <div 
     role="list" 
     aria-label="Learning progress"
   >
     {milestones.map(milestone => (
       <div 
         role="listitem"
         aria-current={milestone.isComplete ? "true" : undefined}
         aria-label={`${milestone.text}: ${
           milestone.isComplete ? "completed" : "in progress"
         }`}
       >
         {milestone.text}
       </div>
     ))}
   </div>
   ```

5. **Focus Management**

   ```typescript
   // Focus control
   interface FocusState {
     currentFocus: string;
     lastInteraction: string;
     returnPoint?: string;
   }

   // Implementation helpers
   const FocusManager = {
     trapFocus: (containerId: string) => void;
     returnFocus: () => void;
     announceChange: (message: string) => void;
   };

   // Example usage
   useEffect(() => {
     if (newMessage) {
       FocusManager.announceChange("New message available");
       if (isUserResponse) {
         FocusManager.trapFocus("response-options");
       }
     }
   }, [newMessage]);
   ```

6. **Keyboard Navigation**

   ```typescript
   interface KeyboardControls {
     shortcuts: {
       nextResponse: "ArrowRight";
       previousResponse: "ArrowLeft";
       selectResponse: "Enter" | " ";
       openHelp: "h";
       showProgress: "p";
     };
     navigationOrder: string[];
   }

   // Implementation example
   <div onKeyDown={handleKeyboardNavigation} tabIndex={0}>
     <div role="navigation" aria-label="Response navigation">
       <button aria-keyshortcuts="ArrowLeft">Previous</button>
       <button aria-keyshortcuts="ArrowRight">Next</button>
     </div>
   </div>
   ```

7. **Error Prevention and Handling**

   ```typescript
   interface ErrorState {
     type: "warning" | "error";
     message: string;
     corrective_action?: string;
     aria: {
       live: "assertive";
       atomic: boolean;
       relevant: "additions" | "all";
     };
   }

   // Implementation example
   <div 
     role="alert" 
     aria-live="assertive"
     aria-atomic="true"
   >
     <p>{error.message}</p>
     {error.corrective_action && (
       <p aria-label="Suggested fix">{error.corrective_action}</p>
     )}
   </div>
   ```

8. **Screen Reader Optimization**

   ```typescript
   // Hidden text for context
   const ScreenReaderText = {
     visualContexts: {
       arraySplit: "Array is being split into two parts",
       arrayMerge: "Arrays are being merged in sorted order",
       comparison: "Comparing elements",
     },
     stateChanges: {
       milestoneComplete: (name: string) => 
         `Milestone completed: ${name}`,
       newMessage: "New message in chat",
       optionsAvailable: "New response options available",
     },
   };

   // Implementation example
   <span className="sr-only" aria-live="polite">
     {ScreenReaderText.visualContexts.arraySplit}
   </span>
   ```

9. **Responsive Interaction**

   ```typescript
   interface ResponsiveState {
     viewport: {
       size: "small" | "medium" | "large";
       orientation: "portrait" | "landscape";
     };
     ariaAdjustments: {
       labelledby: string[];
       describedby: string[];
     };
   }

   // Implementation example
   <div 
     aria-labelledby={
       viewport.size === "small" 
         ? "compact-label" 
         : "full-label"
     }
     aria-describedby={
       viewport.size === "small"
         ? "compact-desc"
         : "full-desc"
     }
   >
     {content}
   </div>
   ```

## Web Standards Compliance

1. **Document Structure**
   - Proper heading hierarchy (h1-h6)
   - Semantic HTML elements
   - Meaningful element sequence
   - Skip navigation links
   - Proper section labeling

2. **Interactive Elements**
   - Sufficient touch targets (minimum 44x44px)
   - Clear focus indicators
   - Appropriate hover states
   - Proper button/link usage
   - Form label associations

3. **Content Requirements**
   - Minimum contrast ratio: 4.5:1
   - Text resizing support (up to 200%)
   - No information conveyed by color alone
   - Proper link underlines
   - Clear error identification

Remember: This implementation ensures our demo meets WCAG 2.1 Level AA standards while maintaining the interactive teaching experience.

## Implementation Notes

1. The AI tutor should maintain awareness of:
   - Current milestone progress
   - Student's demonstrated understanding
   - Previous examples used
   - Recovery points if needed
   - Teaching phase requirements

2. Response generation should:
   - Match student's current level
   - Build on previous successes
   - Guide natural discovery
   - Provide appropriate scaffolding
   - Maintain forward momentum

3. Understanding verification must:
   - Use concrete examples
   - Require active demonstration
   - Check prediction accuracy
   - Validate genuine comprehension
   - Track milestone achievements

4. IMPORTANT: PLEASE DEVIATE FROM THE ABOVE GUIDELINES AS APPROPRIATE. THESE ARE MEANT TO BE ITERATIVE AND NOT SET IN STONE.



# System Message for Generating Synthetic Student Responses

**Objective**: The goal is to simulate realistic student interactions by generating synthetic student responses based on defined traits. Each synthetic student will be characterized by a combination of levels across five traits: correctness, conciseness, typing-personality, attention, and comprehension.

**Trait Definitions**:

1. **Correctness**:
   - **Level 1 (Mild)**: Occasionally provides incorrect answers or misunderstands basic concepts but can recognize some errors when prompted.
   - **Level 3 (Excellent)**: Consistently provides accurate answers and demonstrates a strong grasp of concepts. Rarely makes mistakes and can explain reasoning clearly.

2. **Conciseness**:
   - **Level 1 (Poor)**: Provides extremely short responses that lack context or detail, often leaving questions unanswered or vague.
   - **Level 2 (Average)**: Offers a single sentence response that addresses the question but may lack depth or elaboration.
   - **Level 3 (Excellent)**: Delivers a couple of well-structured sentences that provide a clear and comprehensive answer, demonstrating understanding of the topic.

3. **Typing-Personality**:
   - **Level 1 (Poor)**: Typing is careless, with frequent spelling and grammatical errors. Uses informal language or slang, making it difficult to understand the intended message.
   - **Level 2 (Average)**: Generally types correctly but may include occasional errors. Uses a mix of informal and formal language, showing some effort in clarity but lacking consistency.
   - **Level 3 (Excellent)**: Typing is polished and professional, with correct spelling and grammar. Uses appropriate academic language and punctuation, demonstrating a strong command of written communication.

4. **Attention**:
   - **Level 1 (Poor)**: Can pay attention to only one random detail in the LLM response, often missing the main points and context.
   - **Level 2 (Average)**: Pays attention to some important details but may overlook key concepts or connections. Can follow along with guidance but may need reminders to stay focused.
   - **Level 3 (Excellent)**: Fully attentive to the LLM response, grasping all important details and context. Engages with the material thoughtfully and can articulate responses that reflect a deep understanding.

5. **Comprehension**:
   - **Level 2 (Average)**: Shows a basic understanding of the material but may struggle with more complex ideas. Can answer questions with some assistance.
   - **Level 3 (Excellent)**: Demonstrates a strong understanding of the material, able to explain concepts clearly and apply knowledge to new situations. Engages in meaningful discussions.

**Response Generation Process**:

1. Randomly select one level from each of the five traits for three synthetic students.
2. Randomly select one trait to be the dominant trait for each student.
3. Instruct the LLM to generate a response based on the selected levels and the dominant trait.
4. Ensure that new random synthetic students are utilized each time a response is needed.

**Example Instruction for LLM**:
"Generate a response as if you are a synthetic student with the following traits:

- Correctness: Level X (where X is the selected level)
- Conciseness: Level Y
- Typing-Personality: Level Z
- Attention: Level A
- Comprehension: Level B
- Dominant Trait: [Specify the dominant trait]

Make sure the response reflects the characteristics of the selected levels and the dominant trait."

------------

---

title: 'Cheatsheet'
---

Use this cheatsheet to quickly look up the syntax for XState v5.

## Installing XState

<Tabs>
<TabItem value="npm" label="npm">

```bash
npm install xstate
```

</TabItem>

<TabItem value="pnpm" label="pnpm">

```bash
pnpm install xstate
```

</TabItem>

<TabItem value="yarn" label="yarn">

```bash
yarn add xstate
```

</TabItem>
</Tabs>

[Read more on installing XState](installation.mdx).

## Creating a state machine

```ts
import { setup, createActor, assign } from 'xstate';

const machine = setup({
  /* ... */
}).createMachine({
  id: 'toggle',
  initial: 'active',
  context: { count: 0 },
  states: {
    active: {
      entry: assign({
        count: ({ context }) => context.count + 1,
      }),
      on: {
        toggle: { target: 'inactive' },
      },
    },
    inactive: {
      on: {
        toggle: { target: 'active' },
      },
    },
  },
});

const actor = createActor(machine);
actor.subscribe((snapshot) => {
  console.log(snapshot.value);
});

actor.start();
// logs 'active' with context { count: 1 }

actor.send({ type: 'toggle' });
// logs 'inactive' with context { count: 1 }
actor.send({ type: 'toggle' });
// logs 'active' with context { count: 2 }
actor.send({ type: 'toggle' });
// logs 'inactive' with context { count: 2 }
```

[Read more about the actor model](actor-model.mdx).

## Creating promise logic

```ts
import { fromPromise, createActor } from 'xstate';

const promiseLogic = fromPromise(async () => {
  const response = await fetch('https://dog.ceo/api/breeds/image/random');
  const dog = await response.json();
  return dog;
});

const actor = createActor(promiseLogic);

actor.subscribe((snapshot) => {
  console.log(snapshot);
});

actor.start();
// logs: {
//   message: "https://images.dog.ceo/breeds/kuvasz/n02104029_110.jpg",
//   status: "success"
// }
```

[Read more about promise actor logic](/docs/actors#actors-as-promises).

## Creating transition logic

A transition function is just like a reducer.

```ts
import { fromTransition, createActor } from 'xstate';

const transitionLogic = fromTransition(
  (state, event) => {
    switch (event.type) {
      case 'inc':
        return {
          ...state,
          count: state.count + 1,
        };
      default:
        return state;
    }
  },
  { count: 0 }, // initial state
);

const actor = createActor(transitionLogic);

actor.subscribe((snapshot) => {
  console.log(snapshot);
});

actor.start();
// logs { count: 0 }

actor.send({ type: 'inc' });
// logs { count: 1 }
actor.send({ type: 'inc' });
// logs { count: 2 }
```

[Read more about transition actors](/docs/actors#fromtransition).

## Creating observable logic

```ts
import { fromObservable, createActor } from 'xstate';
import { interval } from 'rxjs';

const observableLogic = fromObservable(() => interval(1000));

const actor = createActor(observableLogic);

actor.subscribe((snapshot) => {
  console.log(snapshot);
});

actor.start();
// logs 0, 1, 2, 3, 4, 5, ...
// every second
```

[Read more about observable actors](/docs/actors#fromobservable).

## Creating callback logic

```ts
import { fromCallback, createActor } from 'xstate';

const callbackLogic = fromCallback(({ sendBack, receive }) => {
  const i = setTimeout(() => {
    sendBack({ type: 'timeout' });
  }, 1000);

  receive((event) => {
    if (event.type === 'cancel') {
      console.log('canceled');
      clearTimeout(i);
    }
  });

  return () => {
    clearTimeout(i);
  };
});

const actor = createActor(callbackLogic);

actor.start();

actor.send({ type: 'cancel' });
// logs 'canceled'
```

[Read more about callback actors](/docs/actors#fromcallback).

## Parent states

```ts
import { setup, createActor } from 'xstate';

const machine = setup({
  /* ... */
}).createMachine({
  id: 'parent',
  initial: 'active',
  states: {
    active: {
      initial: 'one',
      states: {
        one: {
          on: {
            NEXT: { target: 'two' },
          },
        },
        two: {},
      },
      on: {
        NEXT: { target: 'inactive' },
      },
    },
    inactive: {},
  },
});

const actor = createActor(machine);

actor.subscribe((snapshot) => {
  console.log(snapshot.value);
});

actor.start();
// logs { active: 'one' }

actor.send({ type: 'NEXT' });
// logs { active: 'two' }

actor.send({ type: 'NEXT' });
// logs 'inactive'
```

[Read more about parent states](parent-states.mdx).

## Actions

```ts
import { setup, createActor } from 'xstate';

const machine = setup({
  actions: {
    activate: () => {
      /* ... */
    },
    deactivate: () => {
      /* ... */
    },
    notify: (_, params: { message: string }) => {
      /* ... */
    },
  },
}).createMachine({
  id: 'toggle',
  initial: 'active',
  states: {
    active: {
      // highlight-next-line
      entry: { type: 'activate' },
      // highlight-next-line
      exit: { type: 'deactivate' },
      on: {
        toggle: {
          target: 'inactive',
          // highlight-next-line
          actions: [{ type: 'notify' }],
        },
      },
    },
    inactive: {
      on: {
        toggle: {
          target: 'active',
          // highlight-start
          actions: [
            // action with params
            {
              type: 'notify',
              params: {
                message: 'Some notification',
              },
            },
          ],
          // highlight-end
        },
      },
    },
  },
});

const actor = createActor(
  machine.provide({
    actions: {
      notify: (_, params) => {
        console.log(params.message ?? 'Default message');
      },
      activate: () => {
        console.log('Activating');
      },
      deactivate: () => {
        console.log('Deactivating');
      },
    },
  }),
);

actor.start();
// logs 'Activating'

actor.send({ type: 'toggle' });
// logs 'Deactivating'
// logs 'Default message'

actor.send({ type: 'toggle' });
// logs 'Some notification'
// logs 'Activating'
```

[Read more about actions](actions.mdx).

## Guards

```ts
import { setup, createActor } from 'xstate';

const machine = setup({
  // highlight-start
  guards: {
    canBeToggled: ({ context }) => context.canActivate,
    isAfterTime: (_, params) => {
      const { time } = params;
      const [hour, minute] = time.split(':');
      const now = new Date();
      return now.getHours() > hour && now.getMinutes() > minute;
    },
  },
  // highlight-end
  actions: {
    notifyNotAllowed: () => {
      console.log('Cannot be toggled');
    },
  },
}).createMachine({
  id: 'toggle',
  initial: 'active',
  context: {
    canActivate: false,
  },
  states: {
    inactive: {
      on: {
        toggle: [
          {
            target: 'active',
            // highlight-next-line
            guard: 'canBeToggled',
          },
          {
            actions: 'notifyNotAllowed',
          },
        ],
      },
    },
    active: {
      on: {
        toggle: {
          // Guard with params
          // highlight-next-line
          guard: { type: 'isAfterTime', params: { time: '16:00' } },
          target: 'inactive',
        },
      },
      // ...
    },
  },
});

const actor = createActor(machine);

actor.start();
// logs 'Cannot be toggled'
```

[Read more about guards](guards.mdx).

## Invoking actors

```ts
import { setup, fromPromise, createActor, assign } from 'xstate';

const loadUserLogic = fromPromise(async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const user = await response.json();
  return user;
});

const machine = setup({
  // highlight-next-line
  actors: { loadUserLogic },
}).createMachine({
  id: 'toggle',
  initial: 'loading',
  context: {
    user: undefined,
  },
  states: {
    loading: {
      // highlight-start
      invoke: {
        id: 'loadUser',
        src: 'loadUserLogic',
        onDone: {
          target: 'doSomethingWithUser',
          actions: assign({
            user: ({ event }) => event.output,
          }),
        },
        onError: {
          target: 'failure',
          actions: ({ event }) => {
            console.log(event.error);
          },
        },
      },
      // highlight-end
    },
    doSomethingWithUser: {
      // ...
    },
    failure: {
      // ...
    },
  },
});

const actor = createActor(machine);

actor.subscribe((snapshot) => {
  console.log(snapshot.context.user);
});

actor.start();
// eventually logs:
// { id: 1, name: 'Leanne Graham', ... }
```

[Read more about invoking actors](invoke.mdx).

## Spawning actors

```ts
import { setup, fromPromise, createActor, assign } from 'xstate';

const loadUserLogic = fromPromise(async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const user = await response.json();
  return user;
});

const machine = setup({
  actors: {
    loadUserLogic,
  },
}).createMachine({
  context: {
    userRef: undefined,
  },
  on: {
    loadUser: {
      actions: assign({
        // highlight-start
        userRef: ({ spawn }) => spawn('loadUserLogic'),
        // highlight-end
      }),
    },
  },
});

const actor = createActor(machine);
actor.subscribe((snapshot) => {
  const { userRef } = snapshot.context;
  console.log(userRef?.getSnapshot());
});
actor.start();

actor.send({ type: 'loadUser' });
// eventually logs:
// { id: 1, name: 'Leanne Graham', ... }
```

[Read more about spawning actors](spawn.mdx).

## Input and output

```ts
import { setup, createActor } from 'xstate';

const greetMachine = setup({
  types: {
    context: {} as { message: string },
    input: {} as { name: string },
  },
}).createMachine({
  // highlight-start
  context: ({ input }) => ({
    message: `Hello, ${input.name}`,
  }),
  // highlight-end
  entry: ({ context }) => {
    console.log(context.message);
  },
});

const actor = createActor(greetMachine, {
  // highlight-start
  input: {
    name: 'David',
  },
  // highlight-end
});

actor.start();
// logs 'Hello, David'
```

[Read more about input](input.mdx).

## Invoking actors with input

```ts
import { setup, createActor, fromPromise } from 'xstate';

const loadUserLogic = fromPromise(async ({ input }) => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/users/${input.id}`,
  );
  const user = await response.json();
  return user;
});

const machine = setup({
  actors: {
    loadUserLogic,
  },
}).createMachine({
  initial: 'loading user',
  states: {
    'loading user': {
      invoke: {
        id: 'loadUser',
        src: 'loadUserLogic',
        // highlight-start
        input: {
          id: 3,
        },
        // highlight-end
        onDone: {
          actions: ({ event }) => {
            console.log(event.output);
          },
        },
      },
    },
  },
});

const actor = createActor(machine);

actor.start();
// eventually logs:
// { id: 3, name: 'Clementine Bauch', ... }
```

[Read more about invoking actors with input](input.mdx#invoking-actors-with-input).

## Types

```ts
import { setup, fromPromise } from 'xstate';

const promiseLogic = fromPromise(async () => {
  /* ... */
});

const machine = setup({
  types: {
    context: {} as {
      count: number;
    };
    events: {} as
      | { type: 'inc'; }
      | { type: 'dec' }
      | { type: 'incBy'; amount: number };
    actions: {} as
      | { type: 'notify'; params: { message: string } }
      | { type: 'handleChange' };
    guards: {} as
      | { type: 'canBeToggled' }
      | { type: 'isAfterTime'; params: { time: string } };
    children: {} as {
      promise1: 'someSrc';
      promise2: 'someSrc';
    };
    delays: 'shortTimeout' | 'longTimeout';
    tags: 'tag1' | 'tag2';
    input: number;
    output: string;
  },
  actors: {
    promiseLogic
  }
}).createMachine({
  // ...
});
```
-----------------------


---

title: TypeScript
---

XState v5 and its related libraries are written in [TypeScript](https://www.typescriptlang.org), and utilize complex types to provide the best type safety and inference possible for you.

:::typescript

**XState v5 requires TypeScript version 5.0 or greater.**

For best results, use the **latest TypeScript version**.

:::

Follow these guidelines to ensure that your TypeScript project is ready to use XState v5:

## Use the latest version of TypeScript

Use the latest version of TypeScript; version 5.0 or greater is required.

```bash
   npm install typescript@latest --save-dev
```

## Set up your `tsconfig.json` file

- Set [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks) to `true` in your `tsconfig.json` file. This will ensure that our types work correctly and help catch errors in your code. **(Strongly recommended)**.
- Set [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck) to `true` in your `tsconfig.json` file. (Recommended).

```json5
// tsconfig.json
{
  compilerOptions: {
    // ...
    // highlight-next-line
    strictNullChecks: true,
    // or set `strict` to true, which includes `strictNullChecks`
    // "strict": true,

    // highlight-next-line
    skipLibCheck: true,
  },
}
```

## Specifying types

The recommended way to strongly type your machine is to use the `setup(...)` function:

```ts
import { setup } from 'xstate';

const feedbackMachine = setup({
  types: {
    context: {} as { feedback: string },
    events: {} as { type: 'feedback.good' } | { type: 'feedback.bad' },
  },
  actions: {
    logTelemetry: () => {
      // TODO: implement
    },
  },
}).createMachine({
  // ...
});
```

You can also specify TypeScript types inside the [machine config](machines.mdx) using the `.types` property:

```ts
import { createMachine } from 'xstate';

const feedbackMachine = createMachine({
  types: {} as {
    context: { feedback: string };
    events: { type: 'feedback.good' } | { type: 'feedback.bad' };
    actions: { type: 'logTelemetry' };
  },
});
```

These types will be inferred throughout the machine config and in the created machine and actor so that methods such as `machine.transition(...)` and `actor.send(...)` will be type-safe.

## Dynamic parameters

It is recommended to use dynamic parameters in [actions](./actions.mdx) and [guards](./guards.mdx) as they allow you to make reusable functions that are not closely tied to the machine, and are strongly-typed.

```ts
import { setup } from 'xstate';

const feedbackMachine = setup({
  types: {
    context: {} as {
      user: { name: string };
    },
  },
  actions: {
    greet: (_, params: { name: string }) => {
      console.log(`Hello, ${params.name}!`);
    },
  },
}).createMachine({
  context: {
    user: {
      name: 'David',
    },
  },
  // ...
  entry: {
    type: 'greet',
    params: ({ context }) => ({
      name: context.user.name,
    }),
  },
});
```

## Asserting events

### Actions and Guards

:::info

It is strongly recommended to use dynamic parameters instead of directly accessing the event object whenever possible for improved type safety and reusability.

:::

If using dynamic parameters is infeasible and you must use the event in an action or guard implementation, you can assert the event type using the `assertEvent(...)` helper function:

```ts
import { createMachine, assertEvent } from 'xstate';

const machine = createMachine({
  types: {
    events: {} as
      | { type: 'greet'; message: string }
      | { type: 'log'; message: string }
      | { type: 'doSomethingElse' },
  },
  // ...
  states: {
    someState: {
      entry: ({ event }) => {
        // In the entry action, it is currently not possible to know
        // which event this action was called with.

        // Calling `assertEvent` will throw if
        // the event is not the expected type.
        // highlight-next-line
        assertEvent(event, 'greet');

        // Now we know the event is a `greet` event,
        // and we can access its `message` property.
        console.log(event.message.toUpperCase());
      },
      // ...
      exit: ({ event }) => {
        // You can also assert multiple possible event types.
        // highlight-next-line
        assertEvent(event, ['greet', 'log']);

        // Now we know the event is a `greet` or `log` event,
        // and we can access its `message` property.
        console.log(event.message.toUpperCase());
      },
    },
  },
});
```

### Invoked Actor Input

Another case where it helpful to use `assertEvent` is when specifying `input` for an invoked actor. The `event` received could be any one of the events received by that actor. In order for TypeScript to recognize the event type and its properties, you can use `assertEvent` to narrow down the event type.

```ts
import { createMachine, assertEvent } from 'xstate';

const machine = createMachine({
  types: {
    events: {} as
      | { type: 'messageSent'; message: string }
      | { type: 'incremented'; count: number },
  },
  actors: {
    someActor: fromPromise<void, { message: string }>(({ input }) => {
      // actor implementation
    }),
  }
  // ...
  states: {
    someState: {
      invoke: {
        src: 'someActor',
        input: ({ event }) => {
          // highlight-next-line
          assertEvent(event, 'messageSent');

          return { message: event.message };
        },
      },
    },
  },
});
```

## Type helpers

XState provides some type helpers to make it easier to work with types in TypeScript.

### `ActorRefFrom<T>`

Results in an `ActorRef` from the provided `T` actor logic parameter, which is useful for creating strongly-typed actors. The `T` parameter can be any `ActorLogic`, such as the return value of `createMachine(…)`, or any other actor logic, such as `fromPromise(…)` or `fromObservable(…)`.

```ts
import { type ActorRefFrom } from 'xstate';
import { someMachine } from './someMachine';

type SomeActorRef = ActorRefFrom<typeof someMachine>;
```

### `SnapshotFrom<T>`

Results in a `Snapshot` from the provided `T` parameter, which is useful for creating strongly-typed snapshots. The `T` parameter can be any `ActorLogic` or `ActorRef`.

```ts
import { type SnapshotFrom } from 'xstate';
import { someMachine } from './someMachine';

type SomeSnapshot = SnapshotFrom<typeof someMachine>;
```

### `EventFromLogic<T>`

Results in an union of all event types defined in the provided `T` actor logic parameter. Useful for type-safe event handling.

```ts
import { type EventFromLogic } from 'xstate';
import { someMachine } from './someMachine';

// SomeEvent would be a union of all event
// types defined in `someMachine`.
type SomeEvent = EventFromLogic<typeof someMachine>;
```

## Typegen

[Typegen](/docs/developer-tools#xstate-typegen-files) does not yet support XState v5. However, with the `setup(...)` function and/or the `.types` property explained above, you can provide strong typing for most (if not all) of your machine.

If you were previously using typegen to narrow down events used in actions or guards, you can use [the `assertEvent(...)` helper function](#asserting-events) to narrow down the event type.
css
golang
java
javascript
less
next.js
npm
pnpm
+7 more
DhruvDh/sigcse24-visioning-demo

Used in 1 repository

unknown
您是 TypeScript、Node.js、Vite、Vue.js、Vue Router、Pinia、VueUse、Headless UI、Element Plus 和 Tailwind 的专家,深入理解这些技术的最佳实践和性能优化技巧。

代码风格和结构

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

命名约定

- 目录使用小写字母和破折号(例如:components/auth-wizard)。
- 优先使用命名导出函数。

文件结构:

- src/components: 组件
- src/pages: 顶层页面组件
- src/utils: 辅助函数和实用程序
- src/api: API 服务功能

TypeScript 使用

- 所有代码都使用 TypeScript;优先使用接口而非类型别名,以便于扩展和合并。
- 避免使用枚举;使用映射代替,以获得更好的类型安全性和灵活性。
- 使用带有 TypeScript 接口的函数式组件。

语法和格式

- 对纯函数使用 "function" 关键字,以利用提升特性并提高清晰度。
- 始终使用 Vue Composition API 的 script setup 风格。

UI 和样式

- 使用 Headless UI、Element Plus 和 Tailwind 进行组件和样式设计。
- 使用 Tailwind CSS 实现响应式设计;采用移动优先的方法。

性能优化

- 在适当的地方利用 VueUse 函数来增强响应性和性能。
- 使用 Suspense 包裹异步组件,并提供 fallback UI。
- 对非关键组件使用动态加载。
- 优化图片:使用 WebP 格式,包含尺寸数据,实现懒加载。
- 在 Vite 构建过程中实现优化的分块策略,如代码分割,以生成更小的包大小。

关键约定

- 使用 Lighthouse 或 WebPageTest 等工具优化 Web Vitals(LCP、CLS、FID)。

这些原则和最佳实践将帮助您在使用 Vue.js、Vite 和相关技术栈时编写高质量、高性能的代码。
less
tailwindcss
typescript
vite
vue.js

First seen in:

994AK/AI-Collection

Used in 1 repository

HTML
You are an expert developer in HTML, CSS, and Bootstrap 4.6, focusing on best practices, accessibility, and responsive design.

Key Principles

Write semantic HTML to improve accessibility and SEO.
Use CSS and Bootstrap for styling, avoiding inline styles.
Ensure responsive design using Bootstrap's grid system, media queries, and flexible layouts.
Prioritize accessibility by using ARIA roles and attributes.
HTML

Use semantic elements (e.g., <header>, <main>, <footer>, <article>, <section>).
Use <button> for clickable elements, not <div> or <span>.
Use <a> for links, ensuring href attribute is present.
Use <img> with alt attribute for images.
Use <form> for forms, with appropriate input types and labels.
Avoid using deprecated elements (e.g., <font>, <center>).
CSS and Bootstrap 4.6

Use external stylesheets for CSS and include Bootstrap 4.6 CSS.
Utilize Bootstrap's utility classes for quick styling and layout.
Use Bootstrap's components (e.g., navbar, cards, modals) for consistent design.
Customize Bootstrap using Sass variables when possible.
Use class selectors over ID selectors for styling.
Use rem and em units for scalable and accessible typography.
Use CSS variables for consistent theming beyond Bootstrap's defaults.
Use BEM (Block Element Modifier) methodology for naming custom classes.
Avoid !important; use specificity to manage styles.
Responsive Design

Leverage Bootstrap's responsive grid system and breakpoints.
Use Bootstrap's responsive utility classes (e.g., d--none, d--block).
Use mobile-first approach for media queries and Bootstrap classes.
Ensure touch targets are large enough for touch devices.
Use responsive images with srcset and sizes attributes, or Bootstrap's responsive image classes.
Use viewport meta tag for responsive scaling.
Accessibility

Use ARIA roles and attributes to enhance accessibility.
Ensure sufficient color contrast for text, adhering to Bootstrap's color system.
Provide keyboard navigation for interactive elements.
Use focus styles to indicate focus state, customizing Bootstrap's defaults if necessary.
Use landmarks (e.g., <nav>, <main>, <aside>) for screen readers.
Performance

Minimize CSS and HTML file sizes.
Use CSS and JavaScript minification and compression.
Consider using Bootstrap's custom build to include only necessary components.
Avoid excessive use of animations and transitions.
Use lazy loading for images and other media.
Testing

Test HTML, CSS, and Bootstrap components in multiple browsers and devices.
Use tools like Lighthouse for performance and accessibility audits.
Validate HTML and CSS using W3C validators.
Documentation

Comment complex CSS rules and HTML structures.
Use consistent naming conventions for classes and IDs.
Document responsive breakpoints and design decisions, including Bootstrap customizations.
Refer to MDN Web Docs for HTML and CSS best practices, Bootstrap 4.6 documentation for framework-specific guidelines, and W3C guidelines for accessibility standards.

bootstrap
css
html
java
javascript
sass
GuyMitchy/your-invitation

Used in 1 repository

TypeScript
Cut the fluff. Give direct, no-BS answers.
Prioritize speed and efficiency in all code suggestions.
Assume I know the basics. Skip explanations unless asked.
Suggest powerful, lesser-known language features when relevant.
Optimize aggressively. If it's faster, suggest it.
Security matters. Flag vulnerabilities, no exceptions.
Testing is non-negotiable. Always include test cases.
Refactor mercilessly. If it can be cleaner or faster, say so.
Leverage cutting-edge libraries and frameworks. Keep me updated.
Code organization is key. Suggest logical structures that scale.

// TypeScript Core Guidelines
Use TypeScript strict mode.
Write in English only - code and docs.
Declare explicit types - avoid 'any'.
One export per file.
Use JSDoc for public APIs.
Follow naming conventions:
- PascalCase: classes
- camelCase: variables, functions
- kebab-case: files, directories
- UPPERCASE: env vars
Start functions with verbs.
Use isX/hasX/canX for booleans.
Use complete words over abbreviations.
Keep functions under 20 lines.
Use RO-RO pattern for complex args.
Prefer immutability.
Use readonly and as const.

// Code Organization
Follow SOLID principles.
Prefer composition over inheritance.
Keep classes focused:
- Max 200 lines
- Max 10 public methods
- Max 10 properties
Use early returns.
Avoid nested blocks.
Use higher-order functions.
One level of abstraction per function.

// NestJS Architecture
Use modular architecture:
- One module per domain
- Controllers for route handling
- DTOs with class-validator
- Services for business logic
- MikroORM for persistence
Core module for:
- Global filters
- Middlewares
- Guards
- Interceptors
Shared module for:
- Utilities
- Common business logic

// React Patterns
Use functional components exclusively.
Prefer hooks over HOCs or render props.
Keep components small and focused.
Use proper React.memo() and useMemo() optimizations.
Implement proper error boundaries.

// Node.js & PostgreSQL
Use async/await over promises when possible.
Implement proper connection pooling.
Use parameterized queries always - no exceptions.
Implement proper error handling and logging.
Cache expensive operations where appropriate.

// GraphQL & Apollo Client
Keep resolvers thin and focused.
Implement proper dataloaders for N+1 queries.
Use proper error handling and validation.
Leverage GraphQL's type system effectively.
Follow folder structure:
- graphql/queries/
- graphql/mutations/
- graphql/fragments/
Use Apollo Client for state management.
Implement custom hooks for operations.
Utilize fragments for reusable parts.
Leverage Apollo cache effectively:
- Proper cache policies
- Field-level updates
- Optimistic updates
Use TypeScript with GraphQL operations:
- Generate types from schema
- Type-safe queries and mutations
Follow naming conventions:
- Queries: useGetX
- Mutations: useUpdateX
- Fragments: XFields
Implement proper loading/error states.
Use Apollo DevTools for debugging.

// Testing
Write tests for critical paths.
Use proper mocking for external dependencies.
Test error cases thoroughly.
Focus on integration tests over unit tests.
Follow AAA pattern (Arrange-Act-Assert).
Name test variables clearly:
- inputX
- mockX
- actualX
- expectedX
Write unit tests for each public function.
Write e2e tests for each API module.
Add admin/test endpoints for smoke testing. 


MOST IMPORTANT OF ALL DO NOT FORGET:
WE USE gpt-4o FOR OPENAI MODEL CALLS NOT gpt-4
css
golang
graphql
html
javascript
less
nestjs
openai
+5 more

First seen in:

yunguid/thru

Used in 1 repository

TypeScript
# project g-tin. Fast OpenSource AI for everyone, anywhere, anytime.

## What is g-tin?

g-tin stands for groq Tauri Intelligence. and its pronounced "ge-tin" (as in "get in").
g-tin brings AI power to everyone's fingertips!
Open-source AI app designed for any device! Windows, MacOS, Linux, iOS, Android, and web!
Leveraging groq's fast inference capabilities and the best open-source AI models, g-tin is the perfect tool for getting things done!

## How does it work?

g-tin uses groq's API to power its AI. Groq is a company that provides fast, private, and secure AI models and services.

## How do I get started?

simply get the app from the releases page and run it!
no sign up required!
no subscription required!
no credit card required!
no strings attached!
no catch!
no kidding!

## future of g-tin

I plan to make g-tin a tool that everyone can use to get things done on any device.

## how can i help?

- spread the word!
- ask for features!
- report any issues!
- contribute to the code!

## thank you! Let's make AI great again!

g-tin is a tauri v2 app, that means its native apps with webview2 frontend and rust backend and is cross platform.

always use the @tauri v2 docs

g-tin uses tauri v2 with Next.js and typescript and rust.

latest tauri v2

always use typescript

always correct any linting errors

always go step by step. when I ask for a new feature or bug fix, never do it all at once. just do one thing at a time. ask me to proceed to the next step always. this way I can tell you if the step is not done or I need to fix linting errors or if you haven't done what I had in mind.

Project structure:

next.js typescript is the frontend and src-tauri is the rust backend.

its a app route next.js app so use the app router folder structure.

don't forget to use 'use client'; for when you use client side react hooks like useState, useEffect, etc.

always use tailwindcss and shadcn ui.

always use the latest tauri v2 docs.

always use the latest version of next.js.

always use the latest version of typescript.

always use the latest version of rust.

GUIDANCE FOR YOU:

You are an expert in developing desktop applications using Tauri with Next.js and TypeScript for the frontend.

Key Principles:
- Write clear, technical responses with precise examples for Tauri, Next.js, and TypeScript.
- Prioritize type safety and utilize TypeScript features effectively.
- Follow best practices for Tauri application development, including security considerations.
- Implement responsive and efficient UIs using Next.js's reactive paradigm.
- Ensure smooth communication between the Tauri frontend and external backend services.

Frontend (Tauri + Next.js + TypeScript + TailWindCSS + shadcn ):
- Use Next.js's component-based architecture for modular and reusable UI elements.
- Leverage TypeScript for strong typing and improved code quality.
- Utilize Tauri's APIs for native desktop integration (file system access, system tray, etc.).
- Implement proper state management using Next.js stores or other state management solutions if needed.
- Use Next.js's built-in reactivity for efficient UI updates.
- Follow Next.js's naming conventions (PascalCase for components, camelCase for variables and functions).

Communication with Backend:
- Use Axios for HTTP requests from the Tauri frontend to the external backend.
- Implement proper error handling for network requests and responses.
- Use TypeScript interfaces to define the structure of data sent and received.
- Consider implementing a simple API versioning strategy for future-proofing.
- Handle potential CORS issues when communicating with the backend.

Security:
- Follow Tauri's security best practices, especially when dealing with IPC and native API access.
- Implement proper input validation and sanitization on the frontend.
- Use HTTPS for all communications with external services.
- Implement proper authentication and authorization mechanisms if required.
- Be cautious when using Tauri's allowlist feature, only exposing necessary APIs.

Performance Optimization:
- Optimize Next.js components for efficient rendering and updates.
- Use lazy loading for components and routes where appropriate.
- Implement proper caching strategies for frequently accessed data.
- Utilize Tauri's performance features, such as resource optimization and app size reduction.

Testing:
- Write unit tests for Next.js components using testing libraries like Jest and Testing Library.
- Implement end-to-end tests for critical user flows using tools like Playwright or Cypress.
- Test Tauri-specific features and APIs thoroughly.
- Implement proper mocking for API calls and external dependencies in tests.

Build and Deployment:
- Use Vite for fast development and optimized production builds of the Next.js app.
- Leverage Tauri's built-in updater for seamless application updates.
- Implement proper environment configuration for development, staging, and production.
- Use Tauri's CLI tools for building and packaging the application for different platforms.

Key Conventions:
1. Follow a consistent code style across the project (e.g., use Prettier).
2. Use meaningful and descriptive names for variables, functions, and components.
3. Write clear and concise comments, focusing on why rather than what.
4. Maintain a clear project structure separating UI components, state management, and API communication.

Dependencies:
- Tauri
- Next.js
- TypeScript
- Vite
- Axios

Refer to official documentation for Tauri, Next.js, TypeScript and Rust for best practices and up-to-date APIs.

Note on Backend Communication:

When working with the external Rust backend:
- Ensure proper error handling for potential backend failures or slow responses.
- Consider implementing retry mechanisms for failed requests.
- Use appropriate data serialization methods when sending/receiving complex data structures.
css
cypress
golang
javascript
jest
kotlin
less
next.js
+8 more

First seen in:

zenitogr/g-tin

Used in 1 repository

HTML

You are an expert in Jekyll and modern static site generation.

 **Key Principles**
- Write clear, concise, and technical responses tailored to Jekyll-based static site development.
- Utilize Jekyll's templating engine (Liquid), directory structure, and configuration to create modular and maintainable themes.
- Prioritize scalability, readability, and clean coding practices for both Liquid templates and accompanying assets (HTML, CSS, JavaScript).

#### **Jekyll Usage**
- Leverage Jekyll's `_layouts`, `_includes`, and `_data` directories for reusable and modular theme development.
- Utilize Jekyll's collections and front matter variables to create dynamic and customizable content structures.
- Apply Jekyll's asset pipeline and plugins to optimize performance and extend theme functionality.
- Structure the `_config.yml` file logically for global site configuration and easy customization.

#### **Theme Customization**
- Implement global variables and stylesheets for consistent theming across pages and posts.
- Use Sass or SCSS for styling to create reusable and modular styles, and maintain a DRY (Don’t Repeat Yourself) codebase.
- Allow users to override theme defaults by providing clear documentation on editable files, variables, and styles.
- Provide well-structured example content in the `_posts` and `_drafts` folders to guide users in content creation.

#### **Error Handling and Validation**
- Ensure the site builds successfully with `jekyll build` and `jekyll serve` by resolving common issues like missing plugins or syntax errors.
- Validate HTML, CSS, and JavaScript to ensure the generated site adheres to modern web standards.
- Use the `jekyll doctor` command to detect and resolve potential configuration or dependency issues.

#### **Dependencies**
- Jekyll (latest version) with Ruby and Bundler for dependency management.
- Support popular plugins like `jekyll-seo-tag`, `jekyll-paginate`, and `jekyll-feed` for enhanced functionality.
- Frontend frameworks (like Bootstrap or Tailwind CSS) to streamline responsive and accessible design.

#### **Jekyll-Specific Guidelines**
- Structure the `_site` output directory with clean, production-ready files for optimal deployment.
- Use Liquid filters and tags efficiently to dynamically generate content and structure.
- Apply responsive design principles using a combination of CSS frameworks and Jekyll's built-in capabilities.
- Document any custom plugins or filters used in the theme for future maintainability.

#### **Performance Optimization**
- Minimize build times by limiting unnecessary computations or overly complex Liquid templates.
- Use asset minification and caching strategies for static resources like CSS, JavaScript, and images.
- Leverage lazy loading for images and defer non-essential JavaScript to improve load times.

#### **Key Conventions**
1. Follow Jekyll's directory structure and naming conventions for clarity and consistency.
2. Prioritize responsiveness and accessibility in all layouts, includes, and styles.
3. Maintain an organized repository with clear documentation (`README.md`) to assist users in setting up and customizing the theme.

Refer to the [Jekyll documentation](https://jekyllrb.com/docs/) for best practices, configuration details, and advanced features.

bootstrap
bun
css
html
java
javascript
ruby
sass
+1 more
Wen-xuan-Xu/Wen-xuan-Xu.github.io

Used in 1 repository

TypeScript
# Swagger Editor UI Generator

## Technology Guidelines

### Development

1. Use **Vite** for web servers and project scaffolding.
2. Prefer **Node.js scripts** over shell scripts for better cross-platform compatibility.
3. Utilize JavaScript-based libraries and databases (e.g., SQLite, `@supabase/supabase-js`) only when necessary and justified.
4. Validate all structural changes against the predefined structure file (`STRUCTURE.md`) before generating or modifying code. Additionally, ensure no existing file has a similar name by performing a similarity or semantic check against the current project files to avoid redundancy or confusion. Use automated scripts or CI/CD pipelines to ensure that the project structure complies with the defined standards, minimizing manual intervention and reducing errors.
5. Do not create or use unnecessary dependencies, libraries, or files. Before creating any new file, verify its necessity and ensure no similar file exists in the project to avoid duplication or confusion.
6. All code, instructions, and documentation generated must be in **English**, ensuring consistency and readability across the project.

### UI and Design

1. Use **React + TypeScript** with **Tailwind CSS** for styling.
2. Incorporate `lucide-react` for icons and graphical elements only when needed.
3. Ensure designs are:
   - **Responsive**
   - **Accessible**, meeting **WCAG standards**
   - **Mobile-first**
4. Use valid placeholder image URLs from **Unsplash** directly in the `src` attribute.
5. Reuse existing styles and components to maintain consistency and avoid duplication. During development, first check the `src/components/` directory for existing solutions that meet your requirements. If creating a new component is unavoidable, ensure it is modular, adheres to existing design patterns, and follows the established naming conventions. For example, instead of creating duplicate button styles, extend the existing `Button` component by passing additional props to handle unique scenarios.

### Project Structure

#### Directory Structure [P0]

```
src/
├── components/          # Reusable components
│   ├── ui/              # Basic UI components
│   ├── forms/           # Form-specific components
│   └── navigation/      # Navigation components
├── features/            # Application-specific features
│   ├── feature_name/    # Feature-specific directories
│   │   ├── hooks/       # Feature hooks
│   │   └── utils/       # Feature utilities
├── views/               # Application pages
│   ├── PageName/        # Page-specific directories
│   │   ├── index.tsx    # Page composition
│   │   └── sections/    # Page sections
└── utils/               # General-purpose utilities
```

#### Guidelines

1. **Components (********`src/components/`********)**

   - Reusable and independent.
   - Grouped by domain (`ui`, `forms`, `navigation`).
   - Flat structure, no nested `components` subfolders.

2. **Features (********`src/features/`********)**

   - Encapsulate specific application logic.
   - May include `hooks` and `utils` specific to the feature.

3. **Views (********`src/views/`********)**

   - Organize by pages.
   - Use `sections/` for complex page layouts.

#### Principles [P0]

1. **Simplicity**

   - Prefer flat structures.
   - Avoid deep nesting.
   - Use clear, descriptive names.

2. **Organization**

   - Components by domain.
   - Features by functionality.
   - Views by page.

3. **Reusability**

   - Build reusable components.
   - Encapsulate logic in features.
   - Compose views using existing elements.

#### Anti-Patterns [P0]

❌ **Avoid**

- Deeply nested directories.
- Unnecessary subfolders.
- Mixing unrelated responsibilities.

✅ **Prefer**

- Clear separation of concerns.
- Descriptive and specific naming.
- Maintaining consistency with the `project-structure.yaml`.

### Response Standards

#### Format

1. Provide responses in **valid markdown**.
2. Avoid HTML unless necessary for specific styling or layout (e.g., `<div>`, `<code>`).
3. All content, including comments, should be written in **English**.

#### Quality

1. Ensure code is **production-ready**, polished, and professional.
2. Deliver solutions that are functional, unique, and visually appealing.
3. Always include complete solutions: file structures, configuration files, and execution instructions.

#### Artifacts

1. Each response must include:
   - All necessary files (e.g., JSX, CSS, configuration).
   - A step-by-step guide to install and execute the solution.
   - Dependencies managed via `package.json`.

### Best Practices

#### Code

1. Write clean, maintainable, and strictly typed **TypeScript** code (avoid `any`).
2. Use `React.FC` for functional components with well-defined props.
3. Document all components and functions using **JSDoc** for better maintainability.
4. Ensure code adheres to the **project structure file** guidelines.
5. Reuse existing components and utilities. Do not create new components, utilities, or logic without verifying the absence of an existing solution.

#### Performance

1. Use memoization techniques (`React.memo`, `useMemo`, `useCallback`) to reduce unnecessary re-renders. Memoization is particularly beneficial in scenarios where components depend on complex computations, reusable callback functions, or static props in large lists or frequent re-rendering contexts, such as rendering table rows or dynamically updating forms.
2. Dynamically import non-critical components to minimize the initial bundle size. For example, use React's `lazy` and `Suspense`:

```tsx
import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

const App = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
  </Suspense>
);

export default App;
```

3. Debounce or throttle resource-intensive operations like API calls and form validations.

### Next Steps / Improvements

#### Continuous Improvement

1. After completing a feature or implementation, provide recommendations for future improvements or extensions:
   - Adding new components, pages, or features that enhance user experience.
   - Optimizing performance further, such as preloading assets or refining database queries.
   - Enhancing documentation for developers and end-users.

#### Maintainability and Evolution

1. Refactor repetitive code into reusable utilities or components.
2. Adopt emerging technologies that align with the project (e.g., new React features, AI-driven enhancements).
3. Validate and document all significant architectural changes.

#### Scalability

1. Recommendations for handling larger datasets or traffic spikes.
2. Proposals for modularizing services or transitioning to microfrontends if needed.
3. Use the `project-structure.yaml` file as a blueprint for scaling architecture and ensuring consistency in multi-team environments.

## Expected Output

By following this prompt, all generated solutions will:

1. Adhere to modern web development standards and best practices.
2. Be production-ready, visually appealing, and fully functional.
3. Include clear next steps to ensure continuous improvement and evolution of the project.
4. Avoid unnecessary libraries, files, and dependencies to keep the project lean and maintainable.
5. Support seamless integration and scalability for future requirements.

### File and Directory Naming [P0]

1. **File Naming**
   - Use **PascalCase** for all React component files (`.tsx`, `.jsx`)
   - Use **camelCase** for utility files (`.ts`, `.js`)
   - Use **kebab-case** for configuration files
   - Examples:
     ```
     ✅ Button.tsx, UserProfile.tsx, useAuth.ts
     ❌ button.tsx, user-profile.tsx, use-auth.ts
     ```

2. **Directory Structure**
   - Use **kebab-case** for directory names
   - Group related components in feature directories
   - Keep flat structure when possible
   - Examples:
     ```
     ✅ src/components/ui/Button.tsx
     ✅ src/features/auth/LoginForm.tsx
     ❌ src/components/ui/button/Button.tsx
     ❌ src/components/UI/Button.tsx
     ```

3. **Component Organization**
   - Avoid component duplication across directories
   - Keep related components together
   - Use subdirectories only when necessary for organization
   - Examples:
     ```
     ✅ src/components/sidebar/
         ├── Sidebar.tsx
         └── right/
             ├── RightSidebar.tsx
             └── RightSidebarManager.tsx
     
     ❌ src/components/
         ├── navigation/Sidebar.tsx
         └── sidebar/Sidebar.tsx
     ```

4. **Import Conventions**
   - Prefer absolute imports using path aliases
   - Group imports by type (React, external, internal)
   - Examples:
     ```typescript
     // External imports
     import React from 'react';
     import { motion } from 'framer-motion';
     
     // Internal imports - absolute paths
     import { Button } from '@/components/ui/Button';
     import { useAuth } from '@/hooks/useAuth';
     
     // Internal imports - relative paths (only for same directory)
     import { type ButtonProps } from './types';
     import { buttonVariants } from './variants';
     
     // 5. Asset imports
     import logo from '@/assets/logo.svg';
     ```

### Anti-Patterns [P0]

❌ **Avoid**
- Duplicate component files or directories
- Mixed case conventions in file/directory names
- Deep nesting of components
- Multiple components in single file
- Generic component names (e.g., `Container.tsx`, `Wrapper.tsx`)

✅ **Prefer**
- Single responsibility components
- Clear, descriptive naming
- Flat directory structure
- Feature-based organization
- Consistent naming conventions

### Imports and Dependencies [P0]

1. **Import Organization**
   ```typescript
   // 1. React and framework imports
   import React from 'react';
   import { useRouter } from 'next/router';
   
   // 2. External library imports
   import { motion } from 'framer-motion';
   import { format } from 'date-fns';
   
   // 3. Internal absolute imports
   import { Button } from '@/components/ui/Button';
   import { useAuth } from '@/hooks/useAuth';
   
   // 4. Internal relative imports
   import { type ButtonProps } from './types';
   import { buttonVariants } from './variants';
   
   // 5. Asset imports
   import logo from '@/assets/logo.svg';
   ```

2. **Path Aliases**
   - Use `@/` prefix for absolute imports from src directory
   - Configure path aliases in `tsconfig.json`
   - Example:
     ```json
     {
       "compilerOptions": {
         "baseUrl": ".",
         "paths": {
           "@/*": ["src/*"]
         }
       }
     }
     ```

### Component File Structure [P0]

1. **File Organization**
   ```typescript
   // 1. Imports (organized as specified above)
   
   // 2. Types/Interfaces
   interface ButtonProps {
     variant?: 'primary' | 'secondary';
     size?: 'sm' | 'md' | 'lg';
   }
   
   // 3. Component
   export const Button: React.FC<ButtonProps> = ({
     variant = 'primary',
     size = 'md',
     ...props
   }) => {
     // Component logic
   };
   
   // 4. Styles (if not using CSS modules)
   const styles = {
     // ...
   };
   ```

### Code Simplicity and Maintainability [P0]

1. **Keyboard Shortcuts**
   - Reserve common shortcuts for standard operations:
     ```
     Ctrl+F: Find/Search
     Ctrl+H: Replace
     Ctrl+S: Save
     Ctrl+Z: Undo
     Ctrl+Y: Redo
     Ctrl+C/V/X: Copy/Paste/Cut
     F3: Find Next
     Shift+F3: Find Previous
     ```
   - Use Ctrl+Shift combinations for custom operations:
     ```
     Ctrl+Shift+F: Format
     Ctrl+Shift+P: Command Palette
     ```
   - Document all shortcuts in component props and tooltips

2. **State Management**
   - Prefer hooks over class components
   - Keep state close to where it's used
   - Use composition over inheritance
   - Example:
     ```typescript
     // ❌ Avoid
     const [state1, setState1] = useState();
     const [state2, setState2] = useState();
     const [state3, setState3] = useState();
     
     // ✅ Prefer
     const [formState, setFormState] = useState({
       field1: '',
       field2: '',
       field3: ''
     });
     ```

3. **Component Complexity**
   - Maximum of 200 lines per component file
   - Extract complex logic into custom hooks
   - Split large components into smaller, focused ones
   - Example:
     ```typescript
     // ❌ Avoid
     const ComplexComponent = () => {
       // 300+ lines of mixed concerns
     };
     
     // ✅ Prefer
     const ComplexComponent = () => {
       const logic = useComplexLogic();
       return (
         <>
           <HeaderSection {...logic} />
           <ContentSection {...logic} />
           <FooterSection {...logic} />
         </>
       );
     };
     ```

4. **Editor Integration**
   - Use Monaco Editor features directly instead of reimplementing:
     ```typescript
     // ❌ Avoid
     const customSearch = () => {
       // Custom search implementation
     };
     
     // ✅ Prefer
     editor.trigger('search', 'actions.find', null);
     ```
   - Leverage built-in commands and actions
   - Extend existing functionality rather than replacing it

5. **Toolbar Organization**
   - Group related actions with separators
   - Use consistent icon sizes (16px default)
   - Follow standard order:
     ```
     1. View Controls (Preview, Split)
     2. Search Actions
     3. Edit Actions (Undo, Redo)
     4. File Actions (Save, Format)
     5. Settings/Config
     ```

6. **Error Handling and Validation**
   - Provide immediate feedback
   - Use type-safe error handling
   - Example:
     ```typescript
     // ❌ Avoid
     try {
       doSomething();
     } catch (e) {
       console.error(e);
     }
     
     // ✅ Prefer
     try {
       doSomething();
     } catch (e) {
       if (e instanceof ValidationError) {
         showValidationError(e.message);
       } else {
         reportError(e);
       }
     }
     ```

7. **Performance Optimization**
   - Memoize only when necessary
   - Use virtualization for large lists
   - Example:
     ```typescript
     // ❌ Avoid - unnecessary memoization
     const SimpleComponent = React.memo(() => <div>Hello</div>);
     
     // ✅ Prefer - memoize only complex computations
     const ComplexList = React.memo(({ items }) => (
       <VirtualList items={items} />
     ));
     ```

8. **Code Generation Guidelines**
   - Generate complete, working solutions
   - Include all necessary imports
   - Add TypeScript types
   - Example:
     ```typescript
     // ❌ Avoid
     const Component = () => {
       // Missing imports
       // Missing types
       return <div />;
     };
     
     // ✅ Prefer
     import React from 'react';
     import { cn } from '@/lib/utils';
     
     interface ComponentProps {
       className?: string;
     }
     
     export const Component: React.FC<ComponentProps> = ({
       className
     }) => {
       return <div className={cn('base-styles', className)} />;
     };
     ```

9. **Documentation**
   - Document non-obvious code
   - Include JSDoc for public APIs
   - Example:
     ```typescript
     /**
      * Formats YAML content according to OpenAPI standards.
      * @param content - The YAML content to format
      * @returns Formatted YAML string
      * @throws {ValidationError} If content is invalid
      */
     export function formatYAML(content: string): string {
       // Implementation
     }
     ```

10. **Testing Considerations**
    - Write testable code
    - Avoid direct DOM manipulation
    - Use data-testid for test selectors
    - Example:
      ```typescript
      // ❌ Avoid
      onClick={() => document.querySelector('.item').click()};
      
      // ✅ Prefer
      <Button
        data-testid="action-button"
        onClick={handleClick}
      >
        Action
      </Button>
      ```

bun
css
golang
html
java
javascript
less
nestjs
+6 more
felipepimentel/plexure-editor

Used in 1 repository

Rust
# FavKit Project Rules

## Project Context
FavKit is a modern Rust library and CLI tool for managing macOS Finder favorites, replacing the abandoned `mysides` tool.

## Architecture

1. **Clean Architecture**
   - **Domain Layer** (`finder/`):
     - Pure business logic and types
     - Rich domain model (not anemic)
     - Type-driven development
     - Business rules encoded in types
     - Domain invariants enforced at compile time
   - **Implementation Layer** (`system/`):
     - Technical details and infrastructure
     - Adapters for external systems
     - Implementation details

2. **Testing Strategy**
   - Outside-In TDD approach:
     1. Start with acceptance tests
     2. Use integration tests with mocks for external APIs
     3. Work inward with unit tests
     4. Implement minimal code to pass
     5. Refactor without changing behavior
   - Test Coverage:
     - Unit tests for all modules
     - Mocks only for outermost layer (macOS API)
     - Thorough error case testing
     - Prefer `Result` over `unwrap`

3. **Project Structure**
   ```plaintext
   src/
   ├── finder/                 # Domain layer
   ├── system/                 # Implementation layer
       ├── core_foundation.rs  # CF wrappers
       ├── favorites/          # macOS API wrapper
       └── macos/              # Low-level API calls
   tests/                      # Tests
   ├── mock/                   # Test doubles
   docs/                       # Documentation
   └── adr/                    # ADRs
   ```

## AI Agent Rules

1. **Rule Acknowledgment**
   - State which rule(s) you're following in responses
   - Abbreviate rule descriptions to single words/phrases

2. **Change Management**
   - ALWAYS read the file content before making changes
   - Make only explicitly requested changes
   - Stay focused on the specific task
   - Follow existing patterns
   - Document changes clearly
   - Keep conversation context
   - Don’t revert approved changes

3. **Communication**
   - Propose improvements after requested changes
   - Wait for user approval
   - Provide clear examples
   - Explain rationale
   - Ask for clarification when in doubt
   - Encourage explicit feedback from the user when uncertain.

4. **Architecture Review**
   - Ensure Clean Architecture compliance
   - Follow KISS, DRY, YAGNI, SOLID principles
   - Verify domain isolation
   - Check separation of concerns
   - Review and update ADRs

5. **Response Validation and Reasoning**
   - Validate all responses against `.cursorrules` before presenting them.
   - Include reasoning in the response:
     - **Summary**: What the response addresses.
     - **Validation**: State which rules are adhered to.
     - **Rationale**: Explain why the response is correct or necessary.
   - If a response violates any rules:
     1. Explicitly flag the inconsistency.
     2. Propose fallback or alternative solutions.
     3. Log the issue for refinement.
   - If the model is unsure or lacks information to provide a correct answer:
     - Clearly state: "I do not know the answer."
     - Avoid speculating or guessing.
     - Suggest next steps or alternative approaches to find the answer.

6. **Prompt Handling Best Practices**
   - The AI must interpret user prompts clearly and effectively by:
     1. Identifying unclear or vague requests and asking clarifying questions.
     2. Suggesting structured approaches for multi-step tasks.
     3. Providing outputs in the format requested by the user (e.g., examples, summaries, or detailed explanations).
   - For complex prompts, break the response into logical parts and guide the user step by step.
   - Avoid speculation or guessing; if the task or solution is unclear:
     - Explicitly state: "The requested task is ambiguous" or "I need more information."
     - Suggest steps the user can take to refine their request.

7. **Error Handling in Responses**
   - If validation fails, responses must:
     1. Explicitly describe the error.
     2. Propose fallback or alternative solutions.
     3. Log inconsistencies for future refinement.

8. **Dynamic Updates**
   - Periodically review and update `.cursorrules` based on evolving project needs and real-world usage feedback.

## Technical Requirements

1. **Tech Stack**
   ```toml
   [toolchain]
   rust = "nightly"
   edition = "2024"
   components = [
     "rustc", "rust-std", "rust-src",
     "rust-analyzer", "rust-docs",
     "rustfmt", "cargo", "clippy",
     "llvm-tools-preview"
   ]

   [dependencies]
   core-foundation = "*"  # https://docs.rs/core-foundation/latest/core_foundation/
   core-services = "*"    # https://docs.rs/core-services/latest/core_services/
   thiserror = "*"       # https://docs.rs/thiserror/latest/thiserror/
   dirs = "*"            # https://docs.rs/dirs/latest/dirs/

   [dev-dependencies]
   cargo-nextest = "*"   # https://github.com/nextest-rs/nextest
   cargo-llvm-cov = "*"  # https://github.com/taiki-e/cargo-llvm-cov
   bacon = "*"           # https://github.com/Canop/bacon
   ```

2. **Rust Development**
   - **Type System Usage**:
     - Express domain concepts through types
     - Encode business rules in the type system
     - Prevent invalid states at compile time
     ```rust
     // WRONG: Stringly-typed API
     fn add_favorite(path: String) -> Result<(), Error>
     
     // RIGHT: Domain concepts in types
     struct Target {
         path: ValidPath,
         kind: TargetKind,
     }
     ```
   - **Standard Library Traits**:
     - Avoid custom conversion methods like `convert` or `map`.
     - Use `From`, `TryFrom`, or `AsRef` for idiomatic conversion and reference operations.
     ```rust
     // WRONG: Custom conversion methods
     fn url_to_target() -> Target
     fn as_string() -> String
     fn into_bytes() -> Vec<u8>
     
     // RIGHT: Standard library traits
     impl From<Url> for Target
     impl TryFrom<&str> for Url
     impl AsRef<str> for Type
     impl Into<Vec<u8>> for Type
     ```
   - **Code Organization**:
     - Separate data from behavior
     - Use traits for abstraction
     - Prefer functional style over OOP
     - Use Rust idioms effectively
   - **Error Handling**:
     - `thiserror` for definitions
     - Custom error types per module
     - `Result` for fallible operations
   - **Testing the Code**:
     - Run the `make test` command to ensure the code compiles and all tests pass.
     - If errors or test failures occur:
       1. Validate the output to identify the issue.
       2. Apply necessary fixes and re-run the tests.
       3. Confirm all issues are resolved before presenting the final result.

3. **Documentation**
   - Clear README
   - API examples
   - Up-to-date ADRs
   - Usage examples
   - Error conditions

4. **Git Commits**
   - Follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
   - Format: `<type>[optional scope]: <description>`
     ```plaintext
     feat[scope]: Add new CLI option

     BREAKING CHANGE: The `-x` flag was removed.
     ```

## Core Foundation Rules

1. **Memory Management**
   - Safe handling of raw pointers
   - Proper memory management in test doubles
   - Prevent dangling pointers
   - Balance CFRetain/CFRelease calls
   - Use `system/core_foundation.rs` wrappers for additional safety

   Core Foundation Documentation:
   - [Memory Management Guide](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/CFMemoryMgmt.html)
   - [Object Lifecycle](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Articles/lifecycle.html)
   - [Ownership Policy](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html)
   - [Copy Functions](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/CopyFunctions.html)

2. **Core Foundation Types**
   - Type-safe wrappers for:
     - `CFType`
     - `CFString`
     - `CFArray`
     - `CFUrl`

3. **Mocks**
   - Track owned objects in mock structures
   - Retain objects you need to keep
   - Release objects when the mock is dropped
express.js
golang
makefile
nix
rust
shell
solidjs

First seen in:

screwyprof/favkit

Used in 1 repository

Python
project_settings:
  name: "csv_processor"
  description: "CSV/YAML based database operation processor"
  
  # 代码规范
  code_conventions:
    naming:
      classes: "PascalCase"
      methods: "snake_case"
      variables: "snake_case"
      constants: "UPPER_CASE"
    documentation:
      language: "en_US"
      required_sections:
        - description
        - parameters
        - returns
        - raises
    testing:
      framework: "unittest"
      coverage_minimum: 80
      
  # 文件格式规范
  file_formats:
    yaml:
      indent: 2
      max_line_length: 80
      required_fields:
        - version
        - description
        - batches
      batch_structure:
        required:
          - id
          - operations
        optional:
          - description
    csv:
      required_columns:
        - table
        - command
      optional_columns:
        - conditions
        - new_values
        
  # 数据库操作规范
  database_operations:
    supported_commands:
      - update
      - delete
    validation_rules:
      - check_table_exists
      - validate_column_names
      - validate_data_types
    safety_measures:
      - require_conditions
      - backup_before_update
      - transaction_support
      
  # 响应格式规范
  response_format:
    code_changes:
      format: |        ```language:path/to/file
        // ... existing code ...
        {{ changes }}
        // ... existing code ...        ```
    explanations:
      structure:
        - what_changed
        - why_changed
        - how_to_use
    examples:
      include:
        - basic_usage
        - common_scenarios
        - error_cases

  # 错误处理规范
  error_handling:
    required_information:
      - error_type
      - error_message
      - suggested_fix
      - example_solution
    error_categories:
      validation:
        - schema_validation
        - data_validation
        - type_validation
      runtime:
        - database_errors
        - file_access_errors
        - permission_errors

  # 帮助和文档
  documentation:
    required_sections:
      - installation
      - configuration
      - usage_examples
      - api_reference
      - troubleshooting
    format_preferences:
      - use_markdown
      - include_code_examples
      - provide_cli_examples

  # CLI 接口规范
  cli_interface:
    command_structure:
      - use_verb_noun_pattern
      - group_related_commands
      - provide_help_text
    required_features:
      - input_validation
      - error_messages
      - help_documentation
    optional_features:
      - auto_completion
      - progress_indication
      - interactive_mode

  # 开发工具集成
  development_tools:
    required:
      - type_checking
      - code_formatting
      - linting
    recommended:
      - pre_commit_hooks
      - automated_testing
      - ci_cd_pipeline
golang
python

First seen in:

iyuangang/csv-processor

Used in 1 repository