Compare commits
8 Commits
18103372ae
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| fea127635d | |||
|
|
67960174d3 | ||
|
|
1aa871cdf9 | ||
|
|
0dcbb98f4c | ||
|
|
ba1ffed211 | ||
|
|
4702150af1 | ||
| 1e8d6a9b19 | |||
| 071b1f1515 |
205
.agents/skills/drizzle/SKILL.md
Normal file
205
.agents/skills/drizzle/SKILL.md
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
---
|
||||||
|
name: drizzle
|
||||||
|
description: Drizzle ORM schema and database guide. Use when working with database schemas (src/database/schemas/*), defining tables, creating migrations, or database model code. Triggers on Drizzle schema definition, database migrations, or ORM usage questions.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Drizzle ORM Schema Style Guide
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
- Config: `drizzle.config.ts`
|
||||||
|
- Schemas: `src/database/schemas/`
|
||||||
|
- Migrations: `src/database/migrations/`
|
||||||
|
- Dialect: `postgresql` with `strict: true`
|
||||||
|
|
||||||
|
## Helper Functions
|
||||||
|
|
||||||
|
Location: `src/database/schemas/_helpers.ts`
|
||||||
|
|
||||||
|
- `timestamptz(name)`: Timestamp with timezone
|
||||||
|
- `createdAt()`, `updatedAt()`, `accessedAt()`: Standard timestamp columns
|
||||||
|
- `timestamps`: Object with all three for easy spread
|
||||||
|
|
||||||
|
## Naming Conventions
|
||||||
|
|
||||||
|
- **Tables**: Plural snake_case (`users`, `session_groups`)
|
||||||
|
- **Columns**: snake_case (`user_id`, `created_at`)
|
||||||
|
|
||||||
|
## Column Definitions
|
||||||
|
|
||||||
|
### Primary Keys
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
id: text('id')
|
||||||
|
.primaryKey()
|
||||||
|
.$defaultFn(() => idGenerator('agents'))
|
||||||
|
.notNull(),
|
||||||
|
```
|
||||||
|
|
||||||
|
ID prefixes make entity types distinguishable. For internal tables, use `uuid`.
|
||||||
|
|
||||||
|
### Foreign Keys
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
userId: text('user_id')
|
||||||
|
.references(() => users.id, { onDelete: 'cascade' })
|
||||||
|
.notNull(),
|
||||||
|
```
|
||||||
|
|
||||||
|
### Timestamps
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
...timestamps, // Spread from _helpers.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Indexes
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Return array (object style deprecated)
|
||||||
|
(t) => [uniqueIndex('client_id_user_id_unique').on(t.clientId, t.userId)],
|
||||||
|
```
|
||||||
|
|
||||||
|
## Type Inference
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const insertAgentSchema = createInsertSchema(agents);
|
||||||
|
export type NewAgent = typeof agents.$inferInsert;
|
||||||
|
export type AgentItem = typeof agents.$inferSelect;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Pattern
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const agents = pgTable(
|
||||||
|
'agents',
|
||||||
|
{
|
||||||
|
id: text('id')
|
||||||
|
.primaryKey()
|
||||||
|
.$defaultFn(() => idGenerator('agents'))
|
||||||
|
.notNull(),
|
||||||
|
slug: varchar('slug', { length: 100 })
|
||||||
|
.$defaultFn(() => randomSlug(4))
|
||||||
|
.unique(),
|
||||||
|
userId: text('user_id')
|
||||||
|
.references(() => users.id, { onDelete: 'cascade' })
|
||||||
|
.notNull(),
|
||||||
|
clientId: text('client_id'),
|
||||||
|
chatConfig: jsonb('chat_config').$type<LobeAgentChatConfig>(),
|
||||||
|
...timestamps,
|
||||||
|
},
|
||||||
|
(t) => [uniqueIndex('client_id_user_id_unique').on(t.clientId, t.userId)],
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Patterns
|
||||||
|
|
||||||
|
### Junction Tables (Many-to-Many)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const agentsKnowledgeBases = pgTable(
|
||||||
|
'agents_knowledge_bases',
|
||||||
|
{
|
||||||
|
agentId: text('agent_id')
|
||||||
|
.references(() => agents.id, { onDelete: 'cascade' })
|
||||||
|
.notNull(),
|
||||||
|
knowledgeBaseId: text('knowledge_base_id')
|
||||||
|
.references(() => knowledgeBases.id, { onDelete: 'cascade' })
|
||||||
|
.notNull(),
|
||||||
|
userId: text('user_id')
|
||||||
|
.references(() => users.id, { onDelete: 'cascade' })
|
||||||
|
.notNull(),
|
||||||
|
enabled: boolean('enabled').default(true),
|
||||||
|
...timestamps,
|
||||||
|
},
|
||||||
|
(t) => [primaryKey({ columns: [t.agentId, t.knowledgeBaseId] })],
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Query Style
|
||||||
|
|
||||||
|
**Always use `db.select()` builder API. Never use `db.query.*` relational API** (`findMany`, `findFirst`, `with:`).
|
||||||
|
|
||||||
|
The relational API generates complex lateral joins with `json_build_array` that are fragile and hard to debug.
|
||||||
|
|
||||||
|
### Select Single Row
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ Good
|
||||||
|
const [result] = await this.db
|
||||||
|
.select()
|
||||||
|
.from(agents)
|
||||||
|
.where(eq(agents.id, id))
|
||||||
|
.limit(1);
|
||||||
|
return result;
|
||||||
|
|
||||||
|
// ❌ Bad: relational API
|
||||||
|
return this.db.query.agents.findFirst({
|
||||||
|
where: eq(agents.id, id),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Select with JOIN
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ Good: explicit select + leftJoin
|
||||||
|
const rows = await this.db
|
||||||
|
.select({
|
||||||
|
runId: agentEvalRunTopics.runId,
|
||||||
|
score: agentEvalRunTopics.score,
|
||||||
|
testCase: agentEvalTestCases,
|
||||||
|
topic: topics,
|
||||||
|
})
|
||||||
|
.from(agentEvalRunTopics)
|
||||||
|
.leftJoin(agentEvalTestCases, eq(agentEvalRunTopics.testCaseId, agentEvalTestCases.id))
|
||||||
|
.leftJoin(topics, eq(agentEvalRunTopics.topicId, topics.id))
|
||||||
|
.where(eq(agentEvalRunTopics.runId, runId))
|
||||||
|
.orderBy(asc(agentEvalRunTopics.createdAt));
|
||||||
|
|
||||||
|
// ❌ Bad: relational API with `with:`
|
||||||
|
return this.db.query.agentEvalRunTopics.findMany({
|
||||||
|
where: eq(agentEvalRunTopics.runId, runId),
|
||||||
|
with: { testCase: true, topic: true },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Select with Aggregation
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ Good: select + leftJoin + groupBy
|
||||||
|
const rows = await this.db
|
||||||
|
.select({
|
||||||
|
id: agentEvalDatasets.id,
|
||||||
|
name: agentEvalDatasets.name,
|
||||||
|
testCaseCount: count(agentEvalTestCases.id).as('testCaseCount'),
|
||||||
|
})
|
||||||
|
.from(agentEvalDatasets)
|
||||||
|
.leftJoin(agentEvalTestCases, eq(agentEvalDatasets.id, agentEvalTestCases.datasetId))
|
||||||
|
.groupBy(agentEvalDatasets.id);
|
||||||
|
```
|
||||||
|
|
||||||
|
### One-to-Many (Separate Queries)
|
||||||
|
|
||||||
|
When you need a parent record with its children, use two queries instead of relational `with:`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ Good: two simple queries
|
||||||
|
const [dataset] = await this.db
|
||||||
|
.select()
|
||||||
|
.from(agentEvalDatasets)
|
||||||
|
.where(eq(agentEvalDatasets.id, id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!dataset) return undefined;
|
||||||
|
|
||||||
|
const testCases = await this.db
|
||||||
|
.select()
|
||||||
|
.from(agentEvalTestCases)
|
||||||
|
.where(eq(agentEvalTestCases.datasetId, id))
|
||||||
|
.orderBy(asc(agentEvalTestCases.sortOrder));
|
||||||
|
|
||||||
|
return { ...dataset, testCases };
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database Migrations
|
||||||
|
|
||||||
|
See the `db-migrations` skill for the detailed migration guide.
|
||||||
475
.agents/skills/elysiajs/SKILL.md
Normal file
475
.agents/skills/elysiajs/SKILL.md
Normal file
@@ -0,0 +1,475 @@
|
|||||||
|
---
|
||||||
|
name: elysiajs
|
||||||
|
description: Create backend with ElysiaJS, a type-safe, high-performance framework.
|
||||||
|
---
|
||||||
|
|
||||||
|
# ElysiaJS Development Skill
|
||||||
|
|
||||||
|
Always consult [elysiajs.com/llms.txt](https://elysiajs.com/llms.txt) for code examples and latest API.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
ElysiaJS is a TypeScript framework for building Bun-first (but not limited to Bun) type-safe, high-performance backend servers. This skill provides comprehensive guidance for developing with Elysia, including routing, validation, authentication, plugins, integrations, and deployment.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Trigger this skill when the user asks to:
|
||||||
|
- Create or modify ElysiaJS routes, handlers, or servers
|
||||||
|
- Setup validation with TypeBox or other schema libraries (Zod, Valibot)
|
||||||
|
- Implement authentication (JWT, session-based, macros, guards)
|
||||||
|
- Add plugins (CORS, OpenAPI, Static files, JWT)
|
||||||
|
- Integrate with external services (Drizzle ORM, Better Auth, Next.js, Eden Treaty)
|
||||||
|
- Setup WebSocket endpoints for real-time features
|
||||||
|
- Create unit tests for Elysia instances
|
||||||
|
- Deploy Elysia servers to production
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
Quick scaffold:
|
||||||
|
```bash
|
||||||
|
bun create elysia app
|
||||||
|
```
|
||||||
|
|
||||||
|
### Basic Server
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t, status } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', () => 'Hello World')
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
age: t.Number()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/id/:id', ({ params: { id } }) => {
|
||||||
|
if(id > 1_000_000) return status(404, 'Not Found')
|
||||||
|
|
||||||
|
return id
|
||||||
|
}, {
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number({
|
||||||
|
minimum: 1
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: t.Number(),
|
||||||
|
404: t.Literal('Not Found')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
|
### HTTP Methods
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', 'GET')
|
||||||
|
.post('/', 'POST')
|
||||||
|
.put('/', 'PUT')
|
||||||
|
.patch('/', 'PATCH')
|
||||||
|
.delete('/', 'DELETE')
|
||||||
|
.options('/', 'OPTIONS')
|
||||||
|
.head('/', 'HEAD')
|
||||||
|
```
|
||||||
|
|
||||||
|
### Path Parameters
|
||||||
|
```typescript
|
||||||
|
.get('/user/:id', ({ params: { id } }) => id)
|
||||||
|
.get('/post/:id/:slug', ({ params }) => params)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Query Parameters
|
||||||
|
```typescript
|
||||||
|
.get('/search', ({ query }) => query.q)
|
||||||
|
// GET /search?q=elysia → "elysia"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Request Body
|
||||||
|
```typescript
|
||||||
|
.post('/user', ({ body }) => body)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Headers
|
||||||
|
```typescript
|
||||||
|
.get('/', ({ headers }) => headers.authorization)
|
||||||
|
```
|
||||||
|
|
||||||
|
## TypeBox Validation
|
||||||
|
|
||||||
|
### Basic Types
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
age: t.Number(),
|
||||||
|
email: t.String({ format: 'email' }),
|
||||||
|
website: t.Optional(t.String({ format: 'uri' }))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Nested Objects
|
||||||
|
```typescript
|
||||||
|
body: t.Object({
|
||||||
|
user: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
address: t.Object({
|
||||||
|
street: t.String(),
|
||||||
|
city: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Arrays
|
||||||
|
```typescript
|
||||||
|
body: t.Object({
|
||||||
|
tags: t.Array(t.String()),
|
||||||
|
users: t.Array(t.Object({
|
||||||
|
id: t.String(),
|
||||||
|
name: t.String()
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### File Upload
|
||||||
|
```typescript
|
||||||
|
.post('/upload', ({ body }) => body.file, {
|
||||||
|
body: t.Object({
|
||||||
|
file: t.File({
|
||||||
|
type: 'image', // image/* mime types
|
||||||
|
maxSize: '5m' // 5 megabytes
|
||||||
|
}),
|
||||||
|
files: t.Files({ // Multiple files
|
||||||
|
type: ['image/png', 'image/jpeg']
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Response Validation
|
||||||
|
```typescript
|
||||||
|
.get('/user/:id', ({ params: { id } }) => ({
|
||||||
|
id,
|
||||||
|
name: 'John',
|
||||||
|
email: 'john@example.com'
|
||||||
|
}), {
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number()
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
name: t.String(),
|
||||||
|
email: t.String()
|
||||||
|
}),
|
||||||
|
404: t.String()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Standard Schema (Zod, Valibot, ArkType)
|
||||||
|
|
||||||
|
### Zod
|
||||||
|
```typescript
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: z.object({
|
||||||
|
name: z.string(),
|
||||||
|
age: z.number().min(0),
|
||||||
|
email: z.string().email()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.get('/user/:id', ({ params: { id }, status }) => {
|
||||||
|
const user = findUser(id)
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return status(404, 'User not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
return user
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guards (Apply to Multiple Routes)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.guard({
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number()
|
||||||
|
})
|
||||||
|
}, app => app
|
||||||
|
.get('/user/:id', ({ params: { id } }) => id)
|
||||||
|
.delete('/user/:id', ({ params: { id } }) => id)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Macro
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
hi: (word: string) => ({
|
||||||
|
beforeHandle() { console.log(word) }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/', () => 'hi', { hi: 'Elysia' })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Project Structure (Recommended)
|
||||||
|
Elysia takes an unopinionated approach but based on user request. But without any specific preference, we recommend a feature-based and domain driven folder structure where each feature has its own folder containing controllers, services, and models.
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── index.ts # Main server entry
|
||||||
|
├── modules/
|
||||||
|
│ ├── auth/
|
||||||
|
│ │ ├── index.ts # Auth routes (Elysia instance)
|
||||||
|
│ │ ├── service.ts # Business logic
|
||||||
|
│ │ └── model.ts # TypeBox schemas/DTOs
|
||||||
|
│ └── user/
|
||||||
|
│ ├── index.ts
|
||||||
|
│ ├── service.ts
|
||||||
|
│ └── model.ts
|
||||||
|
└── plugins/
|
||||||
|
└── custom.ts
|
||||||
|
|
||||||
|
public/ # Static files (if using static plugin)
|
||||||
|
test/ # Unit tests
|
||||||
|
```
|
||||||
|
|
||||||
|
Each file has its own responsibility as follows:
|
||||||
|
- **Controller (index.ts)**: Handle HTTP routing, request validation, and cookie.
|
||||||
|
- **Service (service.ts)**: Handle business logic, decoupled from Elysia controller if possible.
|
||||||
|
- **Model (model.ts)**: Define the data structure and validation for the request and response.
|
||||||
|
|
||||||
|
## Best Practice
|
||||||
|
Elysia is unopinionated on design pattern, but if not provided, we can relies on MVC pattern pair with feature based folder structure.
|
||||||
|
|
||||||
|
- Controller:
|
||||||
|
- Prefers Elysia as a controller for HTTP dependant controller
|
||||||
|
- For non HTTP dependent, prefers service instead unless explicitly asked
|
||||||
|
- Use `onError` to handle local custom errors
|
||||||
|
- Register Model to Elysia instance via `Elysia.models({ ...models })` and prefix model by namespace `Elysia.prefix('model', 'Namespace.')
|
||||||
|
- Prefers Reference Model by name provided by Elysia instead of using an actual `Model.name`
|
||||||
|
- Service:
|
||||||
|
- Prefers class (or abstract class if possible)
|
||||||
|
- Prefers interface/type derive from `Model`
|
||||||
|
- Return `status` (`import { status } from 'elysia'`) for error
|
||||||
|
- Prefers `return Error` instead of `throw Error`
|
||||||
|
- Models:
|
||||||
|
- Always export validation model and type of validation model
|
||||||
|
- Custom Error should be in contains in Model
|
||||||
|
|
||||||
|
## Elysia Key Concept
|
||||||
|
Elysia has a every important concepts/rules to understand before use.
|
||||||
|
|
||||||
|
## Encapsulation - Isolates by Default
|
||||||
|
|
||||||
|
Lifecycles (hooks, middleware) **don't leak** between instances unless scoped.
|
||||||
|
|
||||||
|
**Scope levels:**
|
||||||
|
- `local` (default) - current instance + descendants
|
||||||
|
- `scoped` - parent + current + descendants
|
||||||
|
- `global` - all instances
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.onBeforeHandle(() => {}) // only local instance
|
||||||
|
.onBeforeHandle({ as: 'global' }, () => {}) // exports to all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Method Chaining - Required for Types
|
||||||
|
|
||||||
|
**Must chain**. Each method returns new type reference.
|
||||||
|
|
||||||
|
❌ Don't:
|
||||||
|
```ts
|
||||||
|
const app = new Elysia()
|
||||||
|
app.state('build', 1) // loses type
|
||||||
|
app.get('/', ({ store }) => store.build) // build doesn't exists
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Do:
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.state('build', 1)
|
||||||
|
.get('/', ({ store }) => store.build)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Explicit Dependencies
|
||||||
|
|
||||||
|
Each instance independent. **Declare what you use.**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const auth = new Elysia()
|
||||||
|
.decorate('Auth', Auth)
|
||||||
|
.model(Auth.models)
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ Auth }) => Auth.getProfile()) // Auth doesn't exists
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(auth) // must declare
|
||||||
|
.get('/', ({ Auth }) => Auth.getProfile())
|
||||||
|
```
|
||||||
|
|
||||||
|
**Global scope when:**
|
||||||
|
- No types added (cors, helmet)
|
||||||
|
- Global lifecycle (logging, tracing)
|
||||||
|
|
||||||
|
**Explicit when:**
|
||||||
|
- Adds types (state, models)
|
||||||
|
- Business logic (auth, db)
|
||||||
|
|
||||||
|
## Deduplication
|
||||||
|
|
||||||
|
Plugins re-execute unless named:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia() // rerun on `.use`
|
||||||
|
new Elysia({ name: 'ip' }) // runs once across all instances
|
||||||
|
```
|
||||||
|
|
||||||
|
## Order Matters
|
||||||
|
|
||||||
|
Events apply to routes **registered after** them.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.onBeforeHandle(() => console.log('1'))
|
||||||
|
.get('/', () => 'hi') // has hook
|
||||||
|
.onBeforeHandle(() => console.log('2')) // doesn't affect '/'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Type Inference
|
||||||
|
|
||||||
|
**Inline functions only** for accurate types.
|
||||||
|
|
||||||
|
For controllers, destructure in inline wrapper:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.post('/', ({ body }) => Controller.greet(body), {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Get type from schema:
|
||||||
|
```ts
|
||||||
|
type MyType = typeof MyType.static
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reference Model
|
||||||
|
Model can be reference by name, especially great for documenting an API
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.model({
|
||||||
|
book: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post('/', ({ body }) => body.name, {
|
||||||
|
body: 'book'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Model can be renamed by using `.prefix` / `.suffix`
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.model({
|
||||||
|
book: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.prefix('model', 'Namespace')
|
||||||
|
.post('/', ({ body }) => body.name, {
|
||||||
|
body: 'Namespace.Book'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Once `prefix`, model name will be capitalized by default.
|
||||||
|
|
||||||
|
## Technical Terms
|
||||||
|
The following are technical terms that is use for Elysia:
|
||||||
|
- `OpenAPI Type Gen` - function name `fromTypes` from `@elysiajs/openapi` for generating OpenAPI from types, see `plugins/openapi.md`
|
||||||
|
- `Eden`, `Eden Treaty` - e2e type safe RPC client for share type from backend to frontend
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
Use the following references as needed.
|
||||||
|
|
||||||
|
It's recommended to checkout `route.md` for as it contains the most important foundation building blocks with examples.
|
||||||
|
|
||||||
|
`plugin.md` and `validation.md` is important as well but can be check as needed.
|
||||||
|
|
||||||
|
### references/
|
||||||
|
Detailed documentation split by topic:
|
||||||
|
- `bun-fullstack-dev-server.md` - Bun Fullstack Dev Server with HMR. React without bundler.
|
||||||
|
- `cookie.md` - Detailed documentation on cookie
|
||||||
|
- `deployment.md` - Production deployment guide / Docker
|
||||||
|
- `eden.md` - e2e type safe RPC client for share type from backend to frontend
|
||||||
|
- `guard.md` - Setting validation/lifecycle all at once
|
||||||
|
- `macro.md` - Compose multiple schema/lifecycle as a reusable Elysia via key-value (recommended for complex setup, eg. authentication, authorization, Role-based Access Check)
|
||||||
|
- `plugin.md` - Decouple part of Elysia into a standalone component
|
||||||
|
- `route.md` - Elysia foundation building block: Routing, Handler and Context
|
||||||
|
- `testing.md` - Unit tests with examples
|
||||||
|
- `validation.md` - Setup input/output validation and list of all custom validation rules
|
||||||
|
- `websocket.md` - Real-time features
|
||||||
|
|
||||||
|
### plugins/
|
||||||
|
Detailed documentation, usage and configuration reference for official Elysia plugin:
|
||||||
|
- `bearer.md` - Add bearer capability to Elysia (`@elysiajs/bearer`)
|
||||||
|
- `cors.md` - Out of box configuration for CORS (`@elysiajs/cors`)
|
||||||
|
- `cron.md` - Run cron job with access to Elysia context (`@elysiajs/cron`)
|
||||||
|
- `graphql-apollo.md` - Integration GraphQL Apollo (`@elysiajs/graphql-apollo`)
|
||||||
|
- `graphql-yoga.md` - Integration with GraphQL Yoga (`@elysiajs/graphql-yoga`)
|
||||||
|
- `html.md` - HTML and JSX plugin setup and usage (`@elysiajs/html`)
|
||||||
|
- `jwt.md` - JWT / JWK plugin (`@elysiajs/jwt`)
|
||||||
|
- `openapi.md` - OpenAPI documentation and OpenAPI Type Gen / OpenAPI from types (`@elysiajs/openapi`)
|
||||||
|
- `opentelemetry.md` - OpenTelemetry, instrumentation, and record span utilities (`@elysiajs/opentelemetry`)
|
||||||
|
- `server-timing.md` - Server Timing metric for debug (`@elysiajs/server-timing`)
|
||||||
|
- `static.md` - Serve static files/folders for Elysia Server (`@elysiajs/static`)
|
||||||
|
|
||||||
|
### integrations/
|
||||||
|
Guide to integrate Elysia with external library/runtime:
|
||||||
|
- `ai-sdk.md` - Using Vercel AI SDK with Elysia
|
||||||
|
- `astro.md` - Elysia in Astro API route
|
||||||
|
- `better-auth.md` - Integrate Elysia with better-auth
|
||||||
|
- `cloudflare-worker.md` - Elysia on Cloudflare Worker adapter
|
||||||
|
- `deno.md` - Elysia on Deno
|
||||||
|
- `drizzle.md` - Integrate Elysia with Drizzle ORM
|
||||||
|
- `expo.md` - Elysia in Expo API route
|
||||||
|
- `nextjs.md` - Elysia in Nextjs API route
|
||||||
|
- `nodejs.md` - Run Elysia on Node.js
|
||||||
|
- `nuxt.md` - Elysia on API route
|
||||||
|
- `prisma.md` - Integrate Elysia with Prisma
|
||||||
|
- `react-email.d` - Create and Send Email with React and Elysia
|
||||||
|
- `sveltekit.md` - Run Elysia on Svelte Kit API route
|
||||||
|
- `tanstack-start.md` - Run Elysia on Tanstack Start / React Query
|
||||||
|
- `vercel.md` - Deploy Elysia to Vercel
|
||||||
|
|
||||||
|
### examples/ (optional)
|
||||||
|
- `basic.ts` - Basic Elysia example
|
||||||
|
- `body-parser.ts` - Custom body parser example via `.onParse`
|
||||||
|
- `complex.ts` - Comprehensive usage of Elysia server
|
||||||
|
- `cookie.ts` - Setting cookie
|
||||||
|
- `error.ts` - Error handling
|
||||||
|
- `file.ts` - Returning local file from server
|
||||||
|
- `guard.ts` - Setting mulitple validation schema and lifecycle
|
||||||
|
- `map-response.ts` - Custom response mapper
|
||||||
|
- `redirect.ts` - Redirect response
|
||||||
|
- `rename.ts` - Rename context's property
|
||||||
|
- `schema.ts` - Setup validation
|
||||||
|
- `state.ts` - Setup global state
|
||||||
|
- `upload-file.ts` - File upload with validation
|
||||||
|
- `websocket.ts` - Web Socket for realtime communication
|
||||||
|
|
||||||
|
### patterns/ (optional)
|
||||||
|
- `patterns/mvc.md` - Detail guideline for using Elysia with MVC patterns
|
||||||
9
.agents/skills/elysiajs/examples/basic.ts
Normal file
9
.agents/skills/elysiajs/examples/basic.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', 'Hello Elysia')
|
||||||
|
.post('/', ({ body: { name } }) => name, {
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
33
.agents/skills/elysiajs/examples/body-parser.ts
Normal file
33
.agents/skills/elysiajs/examples/body-parser.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
// Add custom body parser
|
||||||
|
.onParse(async ({ request, contentType }) => {
|
||||||
|
switch (contentType) {
|
||||||
|
case 'application/Elysia':
|
||||||
|
return request.text()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.post('/', ({ body: { username } }) => `Hi ${username}`, {
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
username: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// Increase id by 1 from body before main handler
|
||||||
|
.post('/transform', ({ body }) => body, {
|
||||||
|
transform: ({ body }) => {
|
||||||
|
body.id = body.id + 1
|
||||||
|
},
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
username: t.String()
|
||||||
|
}),
|
||||||
|
detail: {
|
||||||
|
summary: 'A'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.post('/mirror', ({ body }) => body)
|
||||||
|
.listen(3000)
|
||||||
|
|
||||||
|
console.log('🦊 Elysia is running at :8080')
|
||||||
112
.agents/skills/elysiajs/examples/complex.ts
Normal file
112
.agents/skills/elysiajs/examples/complex.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import { Elysia, t, file } from 'elysia'
|
||||||
|
|
||||||
|
const loggerPlugin = new Elysia()
|
||||||
|
.get('/hi', () => 'Hi')
|
||||||
|
.decorate('log', () => 'A')
|
||||||
|
.decorate('date', () => new Date())
|
||||||
|
.state('fromPlugin', 'From Logger')
|
||||||
|
.use((app) => app.state('abc', 'abc'))
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.onRequest(({ set }) => {
|
||||||
|
set.headers = {
|
||||||
|
'Access-Control-Allow-Origin': '*'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.onError(({ code }) => {
|
||||||
|
if (code === 'NOT_FOUND')
|
||||||
|
return 'Not Found :('
|
||||||
|
})
|
||||||
|
.use(loggerPlugin)
|
||||||
|
.state('build', Date.now())
|
||||||
|
.get('/', 'Elysia')
|
||||||
|
.get('/tako', file('./example/takodachi.png'))
|
||||||
|
.get('/json', () => ({
|
||||||
|
hi: 'world'
|
||||||
|
}))
|
||||||
|
.get('/root/plugin/log', ({ log, store: { build } }) => {
|
||||||
|
log()
|
||||||
|
|
||||||
|
return build
|
||||||
|
})
|
||||||
|
.get('/wildcard/*', () => 'Hi Wildcard')
|
||||||
|
.get('/query', () => 'Elysia', {
|
||||||
|
beforeHandle: ({ query }) => {
|
||||||
|
console.log('Name:', query?.name)
|
||||||
|
|
||||||
|
if (query?.name === 'aom') return 'Hi saltyaom'
|
||||||
|
},
|
||||||
|
query: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post('/json', async ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
additional: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post('/transform-body', async ({ body }) => body, {
|
||||||
|
beforeHandle: (ctx) => {
|
||||||
|
ctx.body = {
|
||||||
|
...ctx.body,
|
||||||
|
additional: 'Elysia'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
additional: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/id/:id', ({ params: { id } }) => id, {
|
||||||
|
transform({ params }) {
|
||||||
|
params.id = +params.id
|
||||||
|
},
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post('/new/:id', async ({ body, params }) => body, {
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number()
|
||||||
|
}),
|
||||||
|
body: t.Object({
|
||||||
|
username: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/trailing-slash', () => 'A')
|
||||||
|
.group('/group', (app) =>
|
||||||
|
app
|
||||||
|
.onBeforeHandle(({ query }) => {
|
||||||
|
if (query?.name === 'aom') return 'Hi saltyaom'
|
||||||
|
})
|
||||||
|
.get('/', () => 'From Group')
|
||||||
|
.get('/hi', () => 'HI GROUP')
|
||||||
|
.get('/elysia', () => 'Welcome to Elysian Realm')
|
||||||
|
.get('/fbk', () => 'FuBuKing')
|
||||||
|
)
|
||||||
|
.get('/response-header', ({ set }) => {
|
||||||
|
set.status = 404
|
||||||
|
set.headers['a'] = 'b'
|
||||||
|
|
||||||
|
return 'A'
|
||||||
|
})
|
||||||
|
.get('/this/is/my/deep/nested/root', () => 'Hi')
|
||||||
|
.get('/build', ({ store: { build } }) => build)
|
||||||
|
.get('/ref', ({ date }) => date())
|
||||||
|
.get('/response', () => new Response('Hi'))
|
||||||
|
.get('/error', () => new Error('Something went wrong'))
|
||||||
|
.get('/401', ({ set }) => {
|
||||||
|
set.status = 401
|
||||||
|
|
||||||
|
return 'Status should be 401'
|
||||||
|
})
|
||||||
|
.get('/timeout', async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||||
|
|
||||||
|
return 'A'
|
||||||
|
})
|
||||||
|
.all('/all', () => 'hi')
|
||||||
|
.listen(8080, ({ hostname, port }) => {
|
||||||
|
console.log(`🦊 Elysia is running at http://${hostname}:${port}`)
|
||||||
|
})
|
||||||
45
.agents/skills/elysiajs/examples/cookie.ts
Normal file
45
.agents/skills/elysiajs/examples/cookie.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia({
|
||||||
|
cookie: {
|
||||||
|
secrets: 'Fischl von Luftschloss Narfidort',
|
||||||
|
sign: ['name']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get(
|
||||||
|
'/council',
|
||||||
|
({ cookie: { council } }) =>
|
||||||
|
(council.value = [
|
||||||
|
{
|
||||||
|
name: 'Rin',
|
||||||
|
affilation: 'Administration'
|
||||||
|
}
|
||||||
|
]),
|
||||||
|
{
|
||||||
|
cookie: t.Cookie({
|
||||||
|
council: t.Array(
|
||||||
|
t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
affilation: t.String()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.get('/create', ({ cookie: { name } }) => (name.value = 'Himari'))
|
||||||
|
.get(
|
||||||
|
'/update',
|
||||||
|
({ cookie: { name } }) => {
|
||||||
|
name.value = 'seminar: Rio'
|
||||||
|
name.value = 'seminar: Himari'
|
||||||
|
name.maxAge = 86400
|
||||||
|
|
||||||
|
return name.value
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cookie: t.Cookie({
|
||||||
|
name: t.Optional(t.String())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
38
.agents/skills/elysiajs/examples/error.ts
Normal file
38
.agents/skills/elysiajs/examples/error.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
class CustomError extends Error {
|
||||||
|
constructor(public name: string) {
|
||||||
|
super(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.error({
|
||||||
|
CUSTOM_ERROR: CustomError
|
||||||
|
})
|
||||||
|
// global handler
|
||||||
|
.onError(({ code, error, status }) => {
|
||||||
|
switch (code) {
|
||||||
|
case "CUSTOM_ERROR":
|
||||||
|
return status(401, { message: error.message })
|
||||||
|
|
||||||
|
case "NOT_FOUND":
|
||||||
|
return "Not found :("
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String(),
|
||||||
|
nested: t.Optional(
|
||||||
|
t.Object({
|
||||||
|
hi: t.String()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
// local handler
|
||||||
|
error({ error }) {
|
||||||
|
console.log(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
10
.agents/skills/elysiajs/examples/file.ts
Normal file
10
.agents/skills/elysiajs/examples/file.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Elysia, file } from 'elysia'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example of handle single static file
|
||||||
|
*
|
||||||
|
* @see https://github.com/elysiajs/elysia-static
|
||||||
|
*/
|
||||||
|
new Elysia()
|
||||||
|
.get('/tako', file('./example/takodachi.png'))
|
||||||
|
.listen(3000)
|
||||||
34
.agents/skills/elysiajs/examples/guard.ts
Normal file
34
.agents/skills/elysiajs/examples/guard.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.state('name', 'salt')
|
||||||
|
.get('/', ({ store: { name } }) => `Hi ${name}`, {
|
||||||
|
query: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// If query 'name' is not preset, skip the whole handler
|
||||||
|
.guard(
|
||||||
|
{
|
||||||
|
query: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
},
|
||||||
|
(app) =>
|
||||||
|
app
|
||||||
|
// Query type is inherited from guard
|
||||||
|
.get('/profile', ({ query }) => `Hi`)
|
||||||
|
// Store is inherited
|
||||||
|
.post('/name', ({ store: { name }, body, query }) => name, {
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number({
|
||||||
|
minimum: 5
|
||||||
|
}),
|
||||||
|
username: t.String(),
|
||||||
|
profile: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
15
.agents/skills/elysiajs/examples/map-response.ts
Normal file
15
.agents/skills/elysiajs/examples/map-response.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
const prettyJson = new Elysia()
|
||||||
|
.mapResponse(({ response }) => {
|
||||||
|
if (response instanceof Object)
|
||||||
|
return new Response(JSON.stringify(response, null, 4))
|
||||||
|
})
|
||||||
|
.as('scoped')
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(prettyJson)
|
||||||
|
.get('/', () => ({
|
||||||
|
hello: 'world'
|
||||||
|
}))
|
||||||
|
.listen(3000)
|
||||||
6
.agents/skills/elysiajs/examples/redirect.ts
Normal file
6
.agents/skills/elysiajs/examples/redirect.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', () => 'Hi')
|
||||||
|
.get('/redirect', ({ redirect }) => redirect('/'))
|
||||||
|
.listen(3000)
|
||||||
32
.agents/skills/elysiajs/examples/rename.ts
Normal file
32
.agents/skills/elysiajs/examples/rename.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
// ? Elysia#83 | Proposal: Standardized way of renaming third party plugin-scoped stuff
|
||||||
|
// this would be a plugin provided by a third party
|
||||||
|
const myPlugin = new Elysia()
|
||||||
|
.decorate('myProperty', 42)
|
||||||
|
.model('salt', t.String())
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(
|
||||||
|
myPlugin
|
||||||
|
// map decorator, rename "myProperty" to "renamedProperty"
|
||||||
|
.decorate(({ myProperty, ...decorators }) => ({
|
||||||
|
renamedProperty: myProperty,
|
||||||
|
...decorators
|
||||||
|
}))
|
||||||
|
// map model, rename "salt" to "pepper"
|
||||||
|
.model(({ salt, ...models }) => ({
|
||||||
|
...models,
|
||||||
|
pepper: t.String()
|
||||||
|
}))
|
||||||
|
// Add prefix
|
||||||
|
.prefix('decorator', 'unstable')
|
||||||
|
)
|
||||||
|
.get(
|
||||||
|
'/mapped',
|
||||||
|
({ unstableRenamedProperty }) => unstableRenamedProperty
|
||||||
|
)
|
||||||
|
.post('/pepper', ({ body }) => body, {
|
||||||
|
body: 'pepper',
|
||||||
|
// response: t.String()
|
||||||
|
})
|
||||||
61
.agents/skills/elysiajs/examples/schema.ts
Normal file
61
.agents/skills/elysiajs/examples/schema.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.model({
|
||||||
|
name: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
}),
|
||||||
|
b: t.Object({
|
||||||
|
response: t.Number()
|
||||||
|
}),
|
||||||
|
authorization: t.Object({
|
||||||
|
authorization: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// Strictly validate response
|
||||||
|
.get('/', () => 'hi')
|
||||||
|
// Strictly validate body and response
|
||||||
|
.post('/', ({ body, query }) => body.id, {
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
username: t.String(),
|
||||||
|
profile: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// Strictly validate query, params, and body
|
||||||
|
.get('/query/:id', ({ query: { name }, params }) => name, {
|
||||||
|
query: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
}),
|
||||||
|
params: t.Object({
|
||||||
|
id: t.String()
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: t.String(),
|
||||||
|
300: t.Object({
|
||||||
|
error: t.String()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.guard(
|
||||||
|
{
|
||||||
|
headers: 'authorization'
|
||||||
|
},
|
||||||
|
(app) =>
|
||||||
|
app
|
||||||
|
.derive(({ headers }) => ({
|
||||||
|
userId: headers.authorization
|
||||||
|
}))
|
||||||
|
.get('/', ({ userId }) => 'A')
|
||||||
|
.post('/id/:id', ({ query, body, params, userId }) => body, {
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number()
|
||||||
|
}),
|
||||||
|
transform({ params }) {
|
||||||
|
params.id = +params.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
6
.agents/skills/elysiajs/examples/state.ts
Normal file
6
.agents/skills/elysiajs/examples/state.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.state('counter', 0)
|
||||||
|
.get('/', ({ store }) => store.counter++)
|
||||||
|
.listen(3000)
|
||||||
20
.agents/skills/elysiajs/examples/upload-file.ts
Normal file
20
.agents/skills/elysiajs/examples/upload-file.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.post('/single', ({ body: { file } }) => file, {
|
||||||
|
body: t.Object({
|
||||||
|
file: t.File({
|
||||||
|
maxSize: '1m'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post(
|
||||||
|
'/multiple',
|
||||||
|
({ body: { files } }) => files.reduce((a, b) => a + b.size, 0),
|
||||||
|
{
|
||||||
|
body: t.Object({
|
||||||
|
files: t.Files()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
25
.agents/skills/elysiajs/examples/websocket.ts
Normal file
25
.agents/skills/elysiajs/examples/websocket.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.state('start', 'here')
|
||||||
|
.ws('/ws', {
|
||||||
|
open(ws) {
|
||||||
|
ws.subscribe('asdf')
|
||||||
|
console.log('Open Connection:', ws.id)
|
||||||
|
},
|
||||||
|
close(ws) {
|
||||||
|
console.log('Closed Connection:', ws.id)
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
ws.publish('asdf', message)
|
||||||
|
ws.send(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get('/publish/:publish', ({ params: { publish: text } }) => {
|
||||||
|
app.server!.publish('asdf', text)
|
||||||
|
|
||||||
|
return text
|
||||||
|
})
|
||||||
|
.listen(3000, (server) => {
|
||||||
|
console.log(`http://${server.hostname}:${server.port}`)
|
||||||
|
})
|
||||||
92
.agents/skills/elysiajs/integrations/ai-sdk.md
Normal file
92
.agents/skills/elysiajs/integrations/ai-sdk.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
# AI SDK Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Seamless integration with Vercel AI SDK via response streaming.
|
||||||
|
|
||||||
|
## Response Streaming
|
||||||
|
Return `ReadableStream` or `Response` directly:
|
||||||
|
```typescript
|
||||||
|
import { streamText } from 'ai'
|
||||||
|
import { openai } from '@ai-sdk/openai'
|
||||||
|
|
||||||
|
new Elysia().get('/', () => {
|
||||||
|
const stream = streamText({
|
||||||
|
model: openai('gpt-5'),
|
||||||
|
system: 'You are Yae Miko from Genshin Impact',
|
||||||
|
prompt: 'Hi! How are you doing?'
|
||||||
|
})
|
||||||
|
|
||||||
|
return stream.textStream // ReadableStream
|
||||||
|
// or
|
||||||
|
return stream.toUIMessageStream() // UI Message Stream
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Elysia auto-handles stream.
|
||||||
|
|
||||||
|
## Server-Sent Events
|
||||||
|
Wrap `ReadableStream` with `sse`:
|
||||||
|
```typescript
|
||||||
|
import { sse } from 'elysia'
|
||||||
|
|
||||||
|
.get('/', () => {
|
||||||
|
const stream = streamText({ /* ... */ })
|
||||||
|
|
||||||
|
return sse(stream.textStream)
|
||||||
|
// or
|
||||||
|
return sse(stream.toUIMessageStream())
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Each chunk → SSE.
|
||||||
|
|
||||||
|
## As Response
|
||||||
|
Return stream directly (no Eden type safety):
|
||||||
|
```typescript
|
||||||
|
.get('/', () => {
|
||||||
|
const stream = streamText({ /* ... */ })
|
||||||
|
|
||||||
|
return stream.toTextStreamResponse()
|
||||||
|
// or
|
||||||
|
return stream.toUIMessageStreamResponse() // Uses SSE
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Manual Streaming
|
||||||
|
Generator function for control:
|
||||||
|
```typescript
|
||||||
|
import { sse } from 'elysia'
|
||||||
|
|
||||||
|
.get('/', async function* () {
|
||||||
|
const stream = streamText({ /* ... */ })
|
||||||
|
|
||||||
|
for await (const data of stream.textStream)
|
||||||
|
yield sse({ data, event: 'message' })
|
||||||
|
|
||||||
|
yield sse({ event: 'done' })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fetch for Unsupported Models
|
||||||
|
Direct fetch with streaming proxy:
|
||||||
|
```typescript
|
||||||
|
.get('/', () => {
|
||||||
|
return fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: 'gpt-5',
|
||||||
|
stream: true,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'You are Yae Miko' },
|
||||||
|
{ role: 'user', content: 'Hi! How are you doing?' }
|
||||||
|
]
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Elysia auto-proxies fetch response with streaming.
|
||||||
59
.agents/skills/elysiajs/integrations/astro.md
Normal file
59
.agents/skills/elysiajs/integrations/astro.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
# Astro Integration - SKILLS.md
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Run Elysia on Astro via Astro Endpoint.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Set output to server:
|
||||||
|
```javascript
|
||||||
|
// astro.config.mjs
|
||||||
|
export default defineConfig({
|
||||||
|
output: 'server'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create `pages/[...slugs].ts`
|
||||||
|
3. Define Elysia server + export handlers:
|
||||||
|
```typescript
|
||||||
|
// pages/[...slugs].ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/api', () => 'hi')
|
||||||
|
.post('/api', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
|
||||||
|
const handle = ({ request }: { request: Request }) => app.handle(request)
|
||||||
|
|
||||||
|
export const GET = handle
|
||||||
|
export const POST = handle
|
||||||
|
```
|
||||||
|
|
||||||
|
WinterCG compliance - works normally.
|
||||||
|
|
||||||
|
Recommended: Run Astro on Bun (Elysia designed for Bun).
|
||||||
|
|
||||||
|
## Prefix for Non-Root
|
||||||
|
If placed in `pages/api/[...slugs].ts`, set prefix:
|
||||||
|
```typescript
|
||||||
|
// pages/api/[...slugs].ts
|
||||||
|
const app = new Elysia({ prefix: '/api' })
|
||||||
|
.get('/', () => 'hi')
|
||||||
|
|
||||||
|
const handle = ({ request }: { request: Request }) => app.handle(request)
|
||||||
|
|
||||||
|
export const GET = handle
|
||||||
|
export const POST = handle
|
||||||
|
```
|
||||||
|
|
||||||
|
Ensures routing works in any location.
|
||||||
|
|
||||||
|
## Benefits
|
||||||
|
Co-location of frontend + backend. End-to-end type safety with Eden.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
117
.agents/skills/elysiajs/integrations/better-auth.md
Normal file
117
.agents/skills/elysiajs/integrations/better-auth.md
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
# Better Auth Integration
|
||||||
|
Elysia + Better Auth integration guide
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Framework-agnostic TypeScript auth/authz. Comprehensive features + plugin ecosystem.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
```typescript
|
||||||
|
import { betterAuth } from 'better-auth'
|
||||||
|
import { Pool } from 'pg'
|
||||||
|
|
||||||
|
export const auth = betterAuth({
|
||||||
|
database: new Pool()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handler Mounting
|
||||||
|
```typescript
|
||||||
|
import { auth } from './auth'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.mount(auth.handler) // http://localhost:3000/api/auth
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom Endpoint
|
||||||
|
```typescript
|
||||||
|
// Mount with prefix
|
||||||
|
.mount('/auth', auth.handler) // http://localhost:3000/auth/api/auth
|
||||||
|
|
||||||
|
// Customize basePath
|
||||||
|
export const auth = betterAuth({
|
||||||
|
basePath: '/api' // http://localhost:3000/auth/api
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Cannot set `basePath` to empty or `/`.
|
||||||
|
|
||||||
|
## OpenAPI Integration
|
||||||
|
Extract docs from Better Auth:
|
||||||
|
```typescript
|
||||||
|
import { openAPI } from 'better-auth/plugins'
|
||||||
|
|
||||||
|
let _schema: ReturnType<typeof auth.api.generateOpenAPISchema>
|
||||||
|
const getSchema = async () => (_schema ??= auth.api.generateOpenAPISchema())
|
||||||
|
|
||||||
|
export const OpenAPI = {
|
||||||
|
getPaths: (prefix = '/auth/api') =>
|
||||||
|
getSchema().then(({ paths }) => {
|
||||||
|
const reference: typeof paths = Object.create(null)
|
||||||
|
|
||||||
|
for (const path of Object.keys(paths)) {
|
||||||
|
const key = prefix + path
|
||||||
|
reference[key] = paths[path]
|
||||||
|
|
||||||
|
for (const method of Object.keys(paths[path])) {
|
||||||
|
const operation = (reference[key] as any)[method]
|
||||||
|
operation.tags = ['Better Auth']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return reference
|
||||||
|
}) as Promise<any>,
|
||||||
|
components: getSchema().then(({ components }) => components) as Promise<any>
|
||||||
|
} as const
|
||||||
|
```
|
||||||
|
|
||||||
|
Apply to Elysia:
|
||||||
|
```typescript
|
||||||
|
new Elysia().use(openapi({
|
||||||
|
documentation: {
|
||||||
|
components: await OpenAPI.components,
|
||||||
|
paths: await OpenAPI.getPaths()
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
## CORS
|
||||||
|
```typescript
|
||||||
|
import { cors } from '@elysiajs/cors'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(cors({
|
||||||
|
origin: 'http://localhost:3001',
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||||
|
credentials: true,
|
||||||
|
allowedHeaders: ['Content-Type', 'Authorization']
|
||||||
|
}))
|
||||||
|
.mount(auth.handler)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Macro for Auth
|
||||||
|
Use macro + resolve for session/user:
|
||||||
|
```typescript
|
||||||
|
const betterAuth = new Elysia({ name: 'better-auth' })
|
||||||
|
.mount(auth.handler)
|
||||||
|
.macro({
|
||||||
|
auth: {
|
||||||
|
async resolve({ status, request: { headers } }) {
|
||||||
|
const session = await auth.api.getSession({ headers })
|
||||||
|
|
||||||
|
if (!session) return status(401)
|
||||||
|
|
||||||
|
return {
|
||||||
|
user: session.user,
|
||||||
|
session: session.session
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(betterAuth)
|
||||||
|
.get('/user', ({ user }) => user, { auth: true })
|
||||||
|
```
|
||||||
|
|
||||||
|
Access `user` and `session` in all routes.
|
||||||
95
.agents/skills/elysiajs/integrations/cloudflare-worker.md
Normal file
95
.agents/skills/elysiajs/integrations/cloudflare-worker.md
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
|
||||||
|
# Cloudflare Worker Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
**Experimental** Cloudflare Worker adapter for Elysia.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Install Wrangler:
|
||||||
|
```bash
|
||||||
|
wrangler init elysia-on-cloudflare
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Apply adapter + compile:
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker'
|
||||||
|
|
||||||
|
export default new Elysia({
|
||||||
|
adapter: CloudflareAdapter
|
||||||
|
})
|
||||||
|
.get('/', () => 'Hello Cloudflare Worker!')
|
||||||
|
.compile() // Required
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Set compatibility date (min `2025-06-01`):
|
||||||
|
```json
|
||||||
|
// wrangler.json
|
||||||
|
{
|
||||||
|
"name": "elysia-on-cloudflare",
|
||||||
|
"main": "src/index.ts",
|
||||||
|
"compatibility_date": "2025-06-01"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Dev server:
|
||||||
|
```bash
|
||||||
|
wrangler dev
|
||||||
|
# http://localhost:8787
|
||||||
|
```
|
||||||
|
|
||||||
|
No `nodejs_compat` flag needed.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
1. `Elysia.file` + Static Plugin don't work (no `fs` module)
|
||||||
|
2. OpenAPI Type Gen doesn't work (no `fs` module)
|
||||||
|
3. Cannot define Response before server start
|
||||||
|
4. Cannot inline values:
|
||||||
|
```typescript
|
||||||
|
// ❌ Throws error
|
||||||
|
.get('/', 'Hello Elysia')
|
||||||
|
|
||||||
|
// ✅ Works
|
||||||
|
.get('/', () => 'Hello Elysia')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Static Files
|
||||||
|
Use Cloudflare's built-in static serving:
|
||||||
|
```json
|
||||||
|
// wrangler.json
|
||||||
|
{
|
||||||
|
"assets": { "directory": "public" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Structure:
|
||||||
|
```
|
||||||
|
├─ public
|
||||||
|
│ ├─ kyuukurarin.mp4
|
||||||
|
│ └─ static/mika.webp
|
||||||
|
```
|
||||||
|
|
||||||
|
Access:
|
||||||
|
- `http://localhost:8787/kyuukurarin.mp4`
|
||||||
|
- `http://localhost:8787/static/mika.webp`
|
||||||
|
|
||||||
|
## Binding
|
||||||
|
Import env from `cloudflare:workers`:
|
||||||
|
```typescript
|
||||||
|
import { env } from 'cloudflare:workers'
|
||||||
|
|
||||||
|
export default new Elysia({ adapter: CloudflareAdapter })
|
||||||
|
.get('/', () => `Hello ${await env.KV.get('my-key')}`)
|
||||||
|
.compile()
|
||||||
|
```
|
||||||
|
|
||||||
|
## AoT Compilation
|
||||||
|
As of Elysia 1.4.7, AoT works with Cloudflare Worker. Drop `aot: false` flag.
|
||||||
|
|
||||||
|
Cloudflare now supports Function compilation during startup.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
34
.agents/skills/elysiajs/integrations/deno.md
Normal file
34
.agents/skills/elysiajs/integrations/deno.md
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Deno Integration
|
||||||
|
Run Elysia on Deno
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Run Elysia on Deno via Web Standard Request/Response.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
Wrap `Elysia.fetch` in `Deno.serve`:
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', () => 'Hello Elysia')
|
||||||
|
.listen(3000)
|
||||||
|
|
||||||
|
Deno.serve(app.fetch)
|
||||||
|
```
|
||||||
|
|
||||||
|
Run:
|
||||||
|
```bash
|
||||||
|
deno serve --watch src/index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Port Config
|
||||||
|
```typescript
|
||||||
|
Deno.serve(app.fetch) // Default
|
||||||
|
Deno.serve({ port: 8787 }, app.fetch) // Custom port
|
||||||
|
```
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
[Inference] pnpm doesn't auto-install peer deps. Manual install required:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
258
.agents/skills/elysiajs/integrations/drizzle.md
Normal file
258
.agents/skills/elysiajs/integrations/drizzle.md
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
# Drizzle Integration
|
||||||
|
Elysia + Drizzle integration guide
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Headless TypeScript ORM. Convert Drizzle schema → Elysia validation models via `drizzle-typebox`.
|
||||||
|
|
||||||
|
## Flow
|
||||||
|
```
|
||||||
|
Drizzle → drizzle-typebox → Elysia validation → OpenAPI + Eden Treaty
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add drizzle-orm drizzle-typebox
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pin TypeBox Version
|
||||||
|
Prevent Symbol conflicts:
|
||||||
|
```bash
|
||||||
|
grep "@sinclair/typebox" node_modules/elysia/package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Add to `package.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"overrides": {
|
||||||
|
"@sinclair/typebox": "0.32.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Drizzle Schema
|
||||||
|
```typescript
|
||||||
|
// src/database/schema.ts
|
||||||
|
import { pgTable, varchar, timestamp } from 'drizzle-orm/pg-core'
|
||||||
|
import { createId } from '@paralleldrive/cuid2'
|
||||||
|
|
||||||
|
export const user = pgTable('user', {
|
||||||
|
id: varchar('id').$defaultFn(() => createId()).primaryKey(),
|
||||||
|
username: varchar('username').notNull().unique(),
|
||||||
|
password: varchar('password').notNull(),
|
||||||
|
email: varchar('email').notNull().unique(),
|
||||||
|
salt: varchar('salt', { length: 64 }).notNull(),
|
||||||
|
createdAt: timestamp('created_at').defaultNow().notNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
export const table = { user } as const
|
||||||
|
export type Table = typeof table
|
||||||
|
```
|
||||||
|
|
||||||
|
## drizzle-typebox
|
||||||
|
```typescript
|
||||||
|
import { t } from 'elysia'
|
||||||
|
import { createInsertSchema } from 'drizzle-typebox'
|
||||||
|
import { table } from './database/schema'
|
||||||
|
|
||||||
|
const _createUser = createInsertSchema(table.user, {
|
||||||
|
email: t.String({ format: 'email' }) // Replace with Elysia type
|
||||||
|
})
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.post('/sign-up', ({ body }) => {}, {
|
||||||
|
body: t.Omit(_createUser, ['id', 'salt', 'createdAt'])
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Type Instantiation Error
|
||||||
|
**Error**: "Type instantiation is possibly infinite"
|
||||||
|
|
||||||
|
**Cause**: Circular reference when nesting drizzle-typebox into Elysia schema.
|
||||||
|
|
||||||
|
**Fix**: Explicitly define type between them:
|
||||||
|
```typescript
|
||||||
|
// ✅ Works
|
||||||
|
const _createUser = createInsertSchema(table.user, {
|
||||||
|
email: t.String({ format: 'email' })
|
||||||
|
})
|
||||||
|
const createUser = t.Omit(_createUser, ['id', 'salt', 'createdAt'])
|
||||||
|
|
||||||
|
// ❌ Infinite loop
|
||||||
|
const createUser = t.Omit(
|
||||||
|
createInsertSchema(table.user, { email: t.String({ format: 'email' }) }),
|
||||||
|
['id', 'salt', 'createdAt']
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Always declare variable for drizzle-typebox then reference it.
|
||||||
|
|
||||||
|
## Utility Functions
|
||||||
|
Copy as-is for simplified usage:
|
||||||
|
```typescript
|
||||||
|
// src/database/utils.ts
|
||||||
|
/**
|
||||||
|
* @lastModified 2025-02-04
|
||||||
|
* @see https://elysiajs.com/recipe/drizzle.html#utility
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Kind, type TObject } from '@sinclair/typebox'
|
||||||
|
import {
|
||||||
|
createInsertSchema,
|
||||||
|
createSelectSchema,
|
||||||
|
BuildSchema,
|
||||||
|
} from 'drizzle-typebox'
|
||||||
|
|
||||||
|
import { table } from './schema'
|
||||||
|
import type { Table } from 'drizzle-orm'
|
||||||
|
|
||||||
|
type Spread<
|
||||||
|
T extends TObject | Table,
|
||||||
|
Mode extends 'select' | 'insert' | undefined,
|
||||||
|
> =
|
||||||
|
T extends TObject<infer Fields>
|
||||||
|
? {
|
||||||
|
[K in keyof Fields]: Fields[K]
|
||||||
|
}
|
||||||
|
: T extends Table
|
||||||
|
? Mode extends 'select'
|
||||||
|
? BuildSchema<
|
||||||
|
'select',
|
||||||
|
T['_']['columns'],
|
||||||
|
undefined
|
||||||
|
>['properties']
|
||||||
|
: Mode extends 'insert'
|
||||||
|
? BuildSchema<
|
||||||
|
'insert',
|
||||||
|
T['_']['columns'],
|
||||||
|
undefined
|
||||||
|
>['properties']
|
||||||
|
: {}
|
||||||
|
: {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spread a Drizzle schema into a plain object
|
||||||
|
*/
|
||||||
|
export const spread = <
|
||||||
|
T extends TObject | Table,
|
||||||
|
Mode extends 'select' | 'insert' | undefined,
|
||||||
|
>(
|
||||||
|
schema: T,
|
||||||
|
mode?: Mode,
|
||||||
|
): Spread<T, Mode> => {
|
||||||
|
const newSchema: Record<string, unknown> = {}
|
||||||
|
let table
|
||||||
|
|
||||||
|
switch (mode) {
|
||||||
|
case 'insert':
|
||||||
|
case 'select':
|
||||||
|
if (Kind in schema) {
|
||||||
|
table = schema
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
table =
|
||||||
|
mode === 'insert'
|
||||||
|
? createInsertSchema(schema)
|
||||||
|
: createSelectSchema(schema)
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
default:
|
||||||
|
if (!(Kind in schema)) throw new Error('Expect a schema')
|
||||||
|
table = schema
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of Object.keys(table.properties))
|
||||||
|
newSchema[key] = table.properties[key]
|
||||||
|
|
||||||
|
return newSchema as any
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spread a Drizzle Table into a plain object
|
||||||
|
*
|
||||||
|
* If `mode` is 'insert', the schema will be refined for insert
|
||||||
|
* If `mode` is 'select', the schema will be refined for select
|
||||||
|
* If `mode` is undefined, the schema will be spread as is, models will need to be refined manually
|
||||||
|
*/
|
||||||
|
export const spreads = <
|
||||||
|
T extends Record<string, TObject | Table>,
|
||||||
|
Mode extends 'select' | 'insert' | undefined,
|
||||||
|
>(
|
||||||
|
models: T,
|
||||||
|
mode?: Mode,
|
||||||
|
): {
|
||||||
|
[K in keyof T]: Spread<T[K], Mode>
|
||||||
|
} => {
|
||||||
|
const newSchema: Record<string, unknown> = {}
|
||||||
|
const keys = Object.keys(models)
|
||||||
|
|
||||||
|
for (const key of keys) newSchema[key] = spread(models[key], mode)
|
||||||
|
|
||||||
|
return newSchema as any
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
```typescript
|
||||||
|
// ✅ Using spread
|
||||||
|
const user = spread(table.user, 'insert')
|
||||||
|
const createUser = t.Object({
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
password: user.password
|
||||||
|
})
|
||||||
|
|
||||||
|
// ⚠️ Using t.Pick
|
||||||
|
const _createUser = createInsertSchema(table.user)
|
||||||
|
const createUser = t.Pick(_createUser, ['id', 'username', 'password'])
|
||||||
|
```
|
||||||
|
|
||||||
|
## Table Singleton Pattern
|
||||||
|
```typescript
|
||||||
|
// src/database/model.ts
|
||||||
|
import { table } from './schema'
|
||||||
|
import { spreads } from './utils'
|
||||||
|
|
||||||
|
export const db = {
|
||||||
|
insert: spreads({ user: table.user }, 'insert'),
|
||||||
|
select: spreads({ user: table.user }, 'select')
|
||||||
|
} as const
|
||||||
|
```
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
```typescript
|
||||||
|
// src/index.ts
|
||||||
|
import { db } from './database/model'
|
||||||
|
const { user } = db.insert
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.post('/sign-up', ({ body }) => {}, {
|
||||||
|
body: t.Object({
|
||||||
|
id: user.username,
|
||||||
|
username: user.username,
|
||||||
|
password: user.password
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Refinement
|
||||||
|
```typescript
|
||||||
|
// src/database/model.ts
|
||||||
|
import { createInsertSchema, createSelectSchema } from 'drizzle-typebox'
|
||||||
|
|
||||||
|
export const db = {
|
||||||
|
insert: spreads({
|
||||||
|
user: createInsertSchema(table.user, {
|
||||||
|
email: t.String({ format: 'email' })
|
||||||
|
})
|
||||||
|
}, 'insert'),
|
||||||
|
select: spreads({
|
||||||
|
user: createSelectSchema(table.user, {
|
||||||
|
email: t.String({ format: 'email' })
|
||||||
|
})
|
||||||
|
}, 'select')
|
||||||
|
} as const
|
||||||
|
```
|
||||||
|
|
||||||
|
`spread` skips refined schemas.
|
||||||
95
.agents/skills/elysiajs/integrations/expo.md
Normal file
95
.agents/skills/elysiajs/integrations/expo.md
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
# Expo Integration
|
||||||
|
Run Elysia on Expo (React Native)
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Create API routes in Expo app (SDK 50+, App Router v3).
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Create `app/[...slugs]+api.ts`
|
||||||
|
2. Define Elysia server
|
||||||
|
3. Export `Elysia.fetch` as HTTP methods
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/[...slugs]+api.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', 'hello Expo')
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prefix for Non-Root
|
||||||
|
If placed in `app/api/[...slugs]+api.ts`, set prefix:
|
||||||
|
```typescript
|
||||||
|
const app = new Elysia({ prefix: '/api' })
|
||||||
|
.get('/', 'Hello Expo')
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
Ensures routing works in any location.
|
||||||
|
|
||||||
|
## Eden (End-to-End Type Safety)
|
||||||
|
1. Export type:
|
||||||
|
```typescript
|
||||||
|
// app/[...slugs]+api.ts
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', 'Hello Nextjs')
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: treaty.schema('User', { name: 'string' })
|
||||||
|
})
|
||||||
|
|
||||||
|
export type app = typeof app
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create client:
|
||||||
|
```typescript
|
||||||
|
// lib/eden.ts
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import type { app } from '../app/[...slugs]+api'
|
||||||
|
|
||||||
|
export const api = treaty<app>('localhost:3000/api')
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Use in components:
|
||||||
|
```tsx
|
||||||
|
// app/page.tsx
|
||||||
|
import { api } from '../lib/eden'
|
||||||
|
|
||||||
|
export default async function Page() {
|
||||||
|
const message = await api.get()
|
||||||
|
return <h1>Hello, {message}</h1>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
- Deploy as normal Elysia app OR
|
||||||
|
- Use experimental Expo server runtime
|
||||||
|
|
||||||
|
With Expo runtime:
|
||||||
|
```bash
|
||||||
|
expo export
|
||||||
|
# Creates dist/server/_expo/functions/[...slugs]+api.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Edge function, not normal server (no port allocation).
|
||||||
|
|
||||||
|
### Adapters
|
||||||
|
- Express
|
||||||
|
- Netlify
|
||||||
|
- Vercel
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
103
.agents/skills/elysiajs/integrations/nextjs.md
Normal file
103
.agents/skills/elysiajs/integrations/nextjs.md
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
|
||||||
|
# Next.js Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Run Elysia on Next.js App Router.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Create `app/api/[[...slugs]]/route.ts`
|
||||||
|
2. Define Elysia + export handlers:
|
||||||
|
```typescript
|
||||||
|
// app/api/[[...slugs]]/route.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia({ prefix: '/api' })
|
||||||
|
.get('/', 'Hello Nextjs')
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
WinterCG compliance - works as normal Next.js API route.
|
||||||
|
|
||||||
|
## Prefix for Non-Root
|
||||||
|
If placed in `app/user/[[...slugs]]/route.ts`, set prefix:
|
||||||
|
```typescript
|
||||||
|
const app = new Elysia({ prefix: '/user' })
|
||||||
|
.get('/', 'Hello Nextjs')
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
## Eden (End-to-End Type Safety)
|
||||||
|
Isomorphic fetch pattern:
|
||||||
|
- Server: Direct calls (no network)
|
||||||
|
- Client: Network calls
|
||||||
|
|
||||||
|
1. Export type:
|
||||||
|
```typescript
|
||||||
|
// app/api/[[...slugs]]/route.ts
|
||||||
|
export const app = new Elysia({ prefix: '/api' })
|
||||||
|
.get('/', 'Hello Nextjs')
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: treaty.schema('User', { name: 'string' })
|
||||||
|
})
|
||||||
|
|
||||||
|
export type app = typeof app
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create client:
|
||||||
|
```typescript
|
||||||
|
// lib/eden.ts
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import type { app } from '../app/api/[[...slugs]]/route'
|
||||||
|
|
||||||
|
export const api =
|
||||||
|
typeof process !== 'undefined'
|
||||||
|
? treaty(app).api
|
||||||
|
: treaty<typeof app>('localhost:3000').api
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `typeof process` not `typeof window` (window undefined at build time → hydration error).
|
||||||
|
|
||||||
|
3. Use in components:
|
||||||
|
```tsx
|
||||||
|
// app/page.tsx
|
||||||
|
import { api } from '../lib/eden'
|
||||||
|
|
||||||
|
export default async function Page() {
|
||||||
|
const message = await api.get()
|
||||||
|
return <h1>Hello, {message}</h1>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Works with server/client components + ISR.
|
||||||
|
|
||||||
|
## React Query
|
||||||
|
```tsx
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const { data: response } = useQuery({
|
||||||
|
queryKey: ['get'],
|
||||||
|
queryFn: () => getTreaty().get()
|
||||||
|
})
|
||||||
|
|
||||||
|
return response?.data
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Works with all React Query features.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
64
.agents/skills/elysiajs/integrations/nodejs.md
Normal file
64
.agents/skills/elysiajs/integrations/nodejs.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# Node.js Integration
|
||||||
|
Run Elysia on Node.js
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Runtime adapter to run Elysia on Node.js.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add elysia @elysiajs/node
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
Apply node adapter:
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { node } from '@elysiajs/node'
|
||||||
|
|
||||||
|
const app = new Elysia({ adapter: node() })
|
||||||
|
.get('/', () => 'Hello Elysia')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Additional Setup (Recommended)
|
||||||
|
Install `tsx` for hot-reload:
|
||||||
|
```bash
|
||||||
|
bun add -d tsx @types/node typescript
|
||||||
|
```
|
||||||
|
|
||||||
|
Scripts in `package.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"build": "tsc src/index.ts --outDir dist",
|
||||||
|
"start": "NODE_ENV=production node dist/index.js"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **dev**: Hot-reload dev mode
|
||||||
|
- **build**: Production build
|
||||||
|
- **start**: Production server
|
||||||
|
|
||||||
|
Create `tsconfig.json`:
|
||||||
|
```bash
|
||||||
|
tsc --init
|
||||||
|
```
|
||||||
|
|
||||||
|
Update strict mode:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"strict": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Provides hot-reload + JSX support similar to `bun dev`.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
67
.agents/skills/elysiajs/integrations/nuxt.md
Normal file
67
.agents/skills/elysiajs/integrations/nuxt.md
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
# Nuxt Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Community plugin `nuxt-elysia` for Nuxt API routes with Eden Treaty.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add elysia @elysiajs/eden
|
||||||
|
bun add -d nuxt-elysia
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Add to Nuxt config:
|
||||||
|
```typescript
|
||||||
|
export default defineNuxtConfig({
|
||||||
|
modules: ['nuxt-elysia']
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create `api.ts` at project root:
|
||||||
|
```typescript
|
||||||
|
// api.ts
|
||||||
|
export default () => new Elysia()
|
||||||
|
.get('/hello', () => ({ message: 'Hello world!' }))
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Use Eden Treaty:
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<p>{{ data.message }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
const { $api } = useNuxtApp()
|
||||||
|
|
||||||
|
const { data } = await useAsyncData(async () => {
|
||||||
|
const { data, error } = await $api.hello.get()
|
||||||
|
|
||||||
|
if (error) throw new Error('Failed to call API')
|
||||||
|
|
||||||
|
return data
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-setup on Nuxt API route.
|
||||||
|
|
||||||
|
## Prefix
|
||||||
|
Default: `/_api`. Customize:
|
||||||
|
```typescript
|
||||||
|
export default defineNuxtConfig({
|
||||||
|
nuxtElysia: {
|
||||||
|
path: '/api'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Mounts on `/api` instead of `/_api`.
|
||||||
|
|
||||||
|
See [nuxt-elysia](https://github.com/tkesgar/nuxt-elysia) for more config.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
93
.agents/skills/elysiajs/integrations/prisma.md
Normal file
93
.agents/skills/elysiajs/integrations/prisma.md
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
|
||||||
|
# Prisma Integration
|
||||||
|
Elysia + Prisma integration guide
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Type-safe ORM. Generate Elysia validation models from Prisma schema via `prismabox`.
|
||||||
|
|
||||||
|
## Flow
|
||||||
|
```
|
||||||
|
Prisma → prismabox → Elysia validation → OpenAPI + Eden Treaty
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @prisma/client prismabox && \
|
||||||
|
bun add -d prisma
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prisma Schema
|
||||||
|
Add `prismabox` generator:
|
||||||
|
```prisma
|
||||||
|
// prisma/schema.prisma
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client"
|
||||||
|
output = "../generated/prisma"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "sqlite"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
generator prismabox {
|
||||||
|
provider = "prismabox"
|
||||||
|
typeboxImportDependencyName = "elysia"
|
||||||
|
typeboxImportVariableName = "t"
|
||||||
|
inputModel = true
|
||||||
|
output = "../generated/prismabox"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
email String @unique
|
||||||
|
name String?
|
||||||
|
posts Post[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Post {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
title String
|
||||||
|
content String?
|
||||||
|
published Boolean @default(false)
|
||||||
|
author User @relation(fields: [authorId], references: [id])
|
||||||
|
authorId String
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Generates:
|
||||||
|
- `User` → `generated/prismabox/User.ts`
|
||||||
|
- `Post` → `generated/prismabox/Post.ts`
|
||||||
|
|
||||||
|
## Using Generated Models
|
||||||
|
```typescript
|
||||||
|
// src/index.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
import { PrismaClient } from '../generated/prisma'
|
||||||
|
import { UserPlain, UserPlainInputCreate } from '../generated/prismabox/User'
|
||||||
|
|
||||||
|
const prisma = new PrismaClient()
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.put('/', async ({ body }) =>
|
||||||
|
prisma.user.create({ data: body }), {
|
||||||
|
body: UserPlainInputCreate,
|
||||||
|
response: UserPlain
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.get('/id/:id', async ({ params: { id }, status }) => {
|
||||||
|
const user = await prisma.user.findUnique({ where: { id } })
|
||||||
|
|
||||||
|
if (!user) return status(404, 'User not found')
|
||||||
|
|
||||||
|
return user
|
||||||
|
}, {
|
||||||
|
response: {
|
||||||
|
200: UserPlain,
|
||||||
|
404: t.String()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Reuses DB schema in Elysia validation models.
|
||||||
134
.agents/skills/elysiajs/integrations/react-email.md
Normal file
134
.agents/skills/elysiajs/integrations/react-email.md
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
# React Email Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Use React components to create emails. Direct JSX import via Bun.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add -d react-email
|
||||||
|
bun add @react-email/components react react-dom
|
||||||
|
```
|
||||||
|
|
||||||
|
Script in `package.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"email": "email dev --dir src/emails"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Email templates → `src/emails` directory.
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
Add to `tsconfig.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"jsx": "react"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Email Template
|
||||||
|
```tsx
|
||||||
|
// src/emails/otp.tsx
|
||||||
|
import * as React from 'react'
|
||||||
|
import { Tailwind, Section, Text } from '@react-email/components'
|
||||||
|
|
||||||
|
export default function OTPEmail({ otp }: { otp: number }) {
|
||||||
|
return (
|
||||||
|
<Tailwind>
|
||||||
|
<Section className="flex justify-center items-center w-full min-h-screen font-sans">
|
||||||
|
<Section className="flex flex-col items-center w-76 rounded-2xl px-6 py-1 bg-gray-50">
|
||||||
|
<Text className="text-xs font-medium text-violet-500">
|
||||||
|
Verify your Email Address
|
||||||
|
</Text>
|
||||||
|
<Text className="text-gray-500 my-0">
|
||||||
|
Use the following code to verify your email address
|
||||||
|
</Text>
|
||||||
|
<Text className="text-5xl font-bold pt-2">{otp}</Text>
|
||||||
|
<Text className="text-gray-400 font-light text-xs pb-4">
|
||||||
|
This code is valid for 10 minutes
|
||||||
|
</Text>
|
||||||
|
<Text className="text-gray-600 text-xs">
|
||||||
|
Thank you for joining us
|
||||||
|
</Text>
|
||||||
|
</Section>
|
||||||
|
</Section>
|
||||||
|
</Tailwind>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
OTPEmail.PreviewProps = { otp: 123456 }
|
||||||
|
```
|
||||||
|
|
||||||
|
`@react-email/components` → email-client compatible (Gmail, Outlook). Tailwind support.
|
||||||
|
|
||||||
|
`PreviewProps` → playground only.
|
||||||
|
|
||||||
|
## Preview
|
||||||
|
```bash
|
||||||
|
bun email
|
||||||
|
```
|
||||||
|
|
||||||
|
Opens browser with preview.
|
||||||
|
|
||||||
|
## Send Email
|
||||||
|
Render with `react-dom/server`, submit via provider:
|
||||||
|
|
||||||
|
### Nodemailer
|
||||||
|
```typescript
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server'
|
||||||
|
import OTPEmail from './emails/otp'
|
||||||
|
import nodemailer from 'nodemailer'
|
||||||
|
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: 'smtp.gehenna.sh',
|
||||||
|
port: 465,
|
||||||
|
auth: { user: 'makoto', pass: '12345678' }
|
||||||
|
})
|
||||||
|
|
||||||
|
.get('/otp', async ({ body }) => {
|
||||||
|
const otp = ~~(Math.random() * 900_000) + 100_000
|
||||||
|
const html = renderToStaticMarkup(<OTPEmail otp={otp} />)
|
||||||
|
|
||||||
|
await transporter.sendMail({
|
||||||
|
from: '[email protected]',
|
||||||
|
to: body,
|
||||||
|
subject: 'Verify your email address',
|
||||||
|
html
|
||||||
|
})
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
}, {
|
||||||
|
body: t.String({ format: 'email' })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Resend
|
||||||
|
```typescript
|
||||||
|
import OTPEmail from './emails/otp'
|
||||||
|
import Resend from 'resend'
|
||||||
|
|
||||||
|
const resend = new Resend('re_123456789')
|
||||||
|
|
||||||
|
.get('/otp', ({ body }) => {
|
||||||
|
const otp = ~~(Math.random() * 900_000) + 100_000
|
||||||
|
|
||||||
|
await resend.emails.send({
|
||||||
|
from: '[email protected]',
|
||||||
|
to: body,
|
||||||
|
subject: 'Verify your email address',
|
||||||
|
html: <OTPEmail otp={otp} /> // Direct JSX
|
||||||
|
})
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Direct JSX import thanks to Bun.
|
||||||
|
|
||||||
|
Other providers: AWS SES, SendGrid.
|
||||||
|
|
||||||
|
See [React Email Integrations](https://react.email/docs/integrations/overview).
|
||||||
53
.agents/skills/elysiajs/integrations/sveltekit.md
Normal file
53
.agents/skills/elysiajs/integrations/sveltekit.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
|
||||||
|
# SvelteKit Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Run Elysia on SvelteKit server routes.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Create `src/routes/[...slugs]/+server.ts`
|
||||||
|
2. Define Elysia server
|
||||||
|
3. Export fallback handler:
|
||||||
|
```typescript
|
||||||
|
// src/routes/[...slugs]/+server.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', 'hello SvelteKit')
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
|
||||||
|
interface WithRequest {
|
||||||
|
request: Request
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fallback = ({ request }: WithRequest) => app.handle(request)
|
||||||
|
```
|
||||||
|
|
||||||
|
Treat as normal SvelteKit server route.
|
||||||
|
|
||||||
|
## Prefix for Non-Root
|
||||||
|
If placed in `src/routes/api/[...slugs]/+server.ts`, set prefix:
|
||||||
|
```typescript
|
||||||
|
// src/routes/api/[...slugs]/+server.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia({ prefix: '/api' })
|
||||||
|
.get('/', () => 'hi')
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
|
||||||
|
type RequestHandler = (v: { request: Request }) => Response | Promise<Response>
|
||||||
|
|
||||||
|
export const fallback: RequestHandler = ({ request }) => app.handle(request)
|
||||||
|
```
|
||||||
|
|
||||||
|
Ensures routing works in any location.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
87
.agents/skills/elysiajs/integrations/tanstack-start.md
Normal file
87
.agents/skills/elysiajs/integrations/tanstack-start.md
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# Tanstack Start Integration
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Elysia runs inside Tanstack Start server routes.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Create `src/routes/api.$.ts`
|
||||||
|
2. Define Elysia server
|
||||||
|
3. Export handlers in `server.handlers`:
|
||||||
|
```typescript
|
||||||
|
// src/routes/api.$.ts
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { createIsomorphicFn } from '@tanstack/react-start'
|
||||||
|
|
||||||
|
const app = new Elysia({
|
||||||
|
prefix: '/api'
|
||||||
|
}).get('/', 'Hello Elysia!')
|
||||||
|
|
||||||
|
const handle = ({ request }: { request: Request }) => app.fetch(request)
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/api/$')({
|
||||||
|
server: {
|
||||||
|
handlers: {
|
||||||
|
GET: handle,
|
||||||
|
POST: handle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Runs on `/api`. Add methods to `server.handlers` as needed.
|
||||||
|
|
||||||
|
## Eden (End-to-End Type Safety)
|
||||||
|
Isomorphic pattern with `createIsomorphicFn`:
|
||||||
|
```typescript
|
||||||
|
// src/routes/api.$.ts
|
||||||
|
export const getTreaty = createIsomorphicFn()
|
||||||
|
.server(() => treaty(app).api)
|
||||||
|
.client(() => treaty<typeof app>('localhost:3000').api)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Server: Direct call (no HTTP overhead)
|
||||||
|
- Client: HTTP call
|
||||||
|
|
||||||
|
## Loader Data
|
||||||
|
Fetch before render:
|
||||||
|
```tsx
|
||||||
|
// src/routes/index.tsx
|
||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { getTreaty } from './api.$'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/a')({
|
||||||
|
component: App,
|
||||||
|
loader: () => getTreaty().get().then((res) => res.data)
|
||||||
|
})
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const data = Route.useLoaderData()
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Executed server-side during SSR. No HTTP overhead. Type-safe.
|
||||||
|
|
||||||
|
## React Query
|
||||||
|
```tsx
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { getTreaty } from './api.$'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const { data: response } = useQuery({
|
||||||
|
queryKey: ['get'],
|
||||||
|
queryFn: () => getTreaty().get()
|
||||||
|
})
|
||||||
|
|
||||||
|
return response?.data
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Works with all React Query features.
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
55
.agents/skills/elysiajs/integrations/vercel.md
Normal file
55
.agents/skills/elysiajs/integrations/vercel.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
# Vercel Integration
|
||||||
|
Deploy Elysia on Vercel
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Zero-config deployment on Vercel (Bun or Node runtime).
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Create/import Elysia server in `src/index.ts`
|
||||||
|
2. Export as default:
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
export default new Elysia()
|
||||||
|
.get('/', () => 'Hello Vercel Function')
|
||||||
|
.post('/', ({ body }) => body, {
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Develop locally:
|
||||||
|
```bash
|
||||||
|
vc dev
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Deploy:
|
||||||
|
```bash
|
||||||
|
vc deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Node.js Runtime
|
||||||
|
Set in `package.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "elysia-app",
|
||||||
|
"type": "module"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bun Runtime
|
||||||
|
Set in `vercel.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||||
|
"bunVersion": "1.x"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## pnpm
|
||||||
|
Manual install:
|
||||||
|
```bash
|
||||||
|
pnpm add @sinclair/typebox openapi-types
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
Vercel has zero config for Elysia. For additional config, see [Vercel docs](https://vercel.com/docs/frameworks/backend/elysia).
|
||||||
380
.agents/skills/elysiajs/patterns/mvc.md
Normal file
380
.agents/skills/elysiajs/patterns/mvc.md
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
# MVC pattern
|
||||||
|
This file contains a guideline for using Elysia with MVC or Model View Controller patterns
|
||||||
|
|
||||||
|
- Controller:
|
||||||
|
- Prefers Elysia as a controller for HTTP dependant
|
||||||
|
- For non HTTP dependent, prefers service instead unless explicitly asked
|
||||||
|
- Use `onError` to handle local custom errors
|
||||||
|
- Register Model to Elysia instance via `Elysia.models({ ...models })` and prefix model by namespace `Elysia.prefix('model', 'Namespace.')
|
||||||
|
- Prefers Reference Model by name provided by Elysia instead of using an actual `Model.name`
|
||||||
|
- Service:
|
||||||
|
- Prefers class (or abstract class if possible)
|
||||||
|
- Prefers interface/type derive from `Model`
|
||||||
|
- Return `status` (`import { status } from 'elysia'`) for error
|
||||||
|
- Prefers `return Error` instead of `throw Error`
|
||||||
|
- Models:
|
||||||
|
- Always export validation model and type of validation model
|
||||||
|
- Custom Error should be in contains in Model
|
||||||
|
|
||||||
|
## Controller
|
||||||
|
Due to type soundness of Elysia, it's not recommended to use a traditional controller class that is tightly coupled with Elysia's `Context` because:
|
||||||
|
|
||||||
|
1. **Elysia type is complex** and heavily depends on plugin and multiple level of chaining.
|
||||||
|
2. **Hard to type**, Elysia type could change at anytime, especially with decorators, and store
|
||||||
|
3. **Loss of type integrity**, and inconsistency between types and runtime code.
|
||||||
|
|
||||||
|
We recommended one of the following approach to implement a controller in Elysia.
|
||||||
|
1. Use Elysia instance as a controller itself
|
||||||
|
2. Create a controller that is not tied with HTTP request or Elysia.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 1. Elysia instance as a controller
|
||||||
|
> 1 Elysia instance = 1 controller
|
||||||
|
|
||||||
|
Treat an Elysia instance as a controller, and define your routes directly on the Elysia instance.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Do
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { Service } from './service'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ stuff }) => {
|
||||||
|
Service.doStuff(stuff)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
This approach allows Elysia to infer the `Context` type automatically, ensuring type integrity and consistency between types and runtime code.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Don't
|
||||||
|
import { Elysia, t, type Context } from 'elysia'
|
||||||
|
|
||||||
|
abstract class Controller {
|
||||||
|
static root(context: Context) {
|
||||||
|
return Service.doStuff(context.stuff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', Controller.root)
|
||||||
|
```
|
||||||
|
|
||||||
|
This approach makes it hard to type `Context` properly, and may lead to loss of type integrity.
|
||||||
|
|
||||||
|
### 2. Controller without HTTP request
|
||||||
|
If you want to create a controller class, we recommend creating a class that is not tied to HTTP request or Elysia at all.
|
||||||
|
|
||||||
|
This approach allows you to decouple the controller from Elysia, making it easier to test, reuse, and even swap a framework while still follows the MVC pattern.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
abstract class Controller {
|
||||||
|
static doStuff(stuff: string) {
|
||||||
|
return Service.doStuff(stuff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ stuff }) => Controller.doStuff(stuff))
|
||||||
|
```
|
||||||
|
|
||||||
|
Tying the controller to Elysia Context may lead to:
|
||||||
|
1. Loss of type integrity
|
||||||
|
2. Make it harder to test and reuse
|
||||||
|
3. Lead to vendor lock-in
|
||||||
|
|
||||||
|
We recommended to keep the controller decoupled from Elysia as much as possible.
|
||||||
|
|
||||||
|
### Don't: Pass entire `Context` to a controller
|
||||||
|
**Context is a highly dynamic type** that can be inferred from Elysia instance.
|
||||||
|
|
||||||
|
Do not pass an entire `Context` to a controller, instead use object destructuring to extract what you need and pass it to the controller.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { Context } from 'elysia'
|
||||||
|
|
||||||
|
abstract class Controller {
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
// Don't do this
|
||||||
|
static root(context: Context) {
|
||||||
|
return Service.doStuff(context.stuff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This approach makes it hard to type `Context` properly, and may lead to loss of type integrity.
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
If you're using Elysia as a controller, you can test your controller using `handle` to directly call a function (and it's lifecycle)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { Service } from './service'
|
||||||
|
|
||||||
|
import { describe, it, expect } from 'bun:test'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', ({ stuff }) => {
|
||||||
|
Service.doStuff(stuff)
|
||||||
|
|
||||||
|
return 'ok'
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Controller', () => {
|
||||||
|
it('should work', async () => {
|
||||||
|
const response = await app
|
||||||
|
.handle(new Request('http://localhost/'))
|
||||||
|
.then((x) => x.text())
|
||||||
|
|
||||||
|
expect(response).toBe('ok')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
You may find more information about testing in [Unit Test](/patterns/unit-test.html).
|
||||||
|
|
||||||
|
## Service
|
||||||
|
Service is a set of utility/helper functions decoupled as a business logic to use in a module/controller, in our case, an Elysia instance.
|
||||||
|
|
||||||
|
Any technical logic that can be decoupled from controller may live inside a **Service**.
|
||||||
|
|
||||||
|
There are 2 types of service in Elysia:
|
||||||
|
1. Non-request dependent service
|
||||||
|
2. Request dependent service
|
||||||
|
|
||||||
|
### 1. Abstract away Non-request dependent service
|
||||||
|
|
||||||
|
We recommend abstracting a service class/function away from Elysia.
|
||||||
|
|
||||||
|
If the service or function isn't tied to an HTTP request or doesn't access a `Context`, it's recommended to implement it as a static class or function.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
abstract class Service {
|
||||||
|
static fibo(number: number): number {
|
||||||
|
if(number < 2)
|
||||||
|
return number
|
||||||
|
|
||||||
|
return Service.fibo(number - 1) + Service.fibo(number - 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/fibo', ({ body }) => {
|
||||||
|
return Service.fibo(body)
|
||||||
|
}, {
|
||||||
|
body: t.Numeric()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
If your service doesn't need to store a property, you may use `abstract class` and `static` instead to avoid allocating class instance.
|
||||||
|
|
||||||
|
### 2. Request dependent service as Elysia instance
|
||||||
|
|
||||||
|
**If the service is a request-dependent service** or needs to process HTTP requests, we recommend abstracting it as an Elysia instance to ensure type integrity and inference:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
// Do
|
||||||
|
const AuthService = new Elysia({ name: 'Auth.Service' })
|
||||||
|
.macro({
|
||||||
|
isSignIn: {
|
||||||
|
resolve({ cookie, status }) {
|
||||||
|
if (!cookie.session.value) return status(401)
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: cookie.session.value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const UserController = new Elysia()
|
||||||
|
.use(AuthService)
|
||||||
|
.get('/profile', ({ Auth: { user } }) => user, {
|
||||||
|
isSignIn: true
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Do: Decorate only request dependent property
|
||||||
|
|
||||||
|
It's recommended to `decorate` only request-dependent properties, such as `requestIP`, `requestTime`, or `session`.
|
||||||
|
|
||||||
|
Overusing decorators may tie your code to Elysia, making it harder to test and reuse.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.decorate('requestIP', ({ request }) => request.headers.get('x-forwarded-for') || request.ip)
|
||||||
|
.decorate('requestTime', () => Date.now())
|
||||||
|
.decorate('session', ({ cookie }) => cookie.session.value)
|
||||||
|
.get('/', ({ requestIP, requestTime, session }) => {
|
||||||
|
return { requestIP, requestTime, session }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Don't: Pass entire `Context` to a service
|
||||||
|
**Context is a highly dynamic type** that can be inferred from Elysia instance.
|
||||||
|
|
||||||
|
Do not pass an entire `Context` to a service, instead use object destructuring to extract what you need and pass it to the service.
|
||||||
|
```typescript
|
||||||
|
import type { Context } from 'elysia'
|
||||||
|
|
||||||
|
class AuthService {
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
// Don't do this
|
||||||
|
isSignIn({ status, cookie: { session } }: Context) {
|
||||||
|
if (session.value)
|
||||||
|
return status(401)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
As Elysia type is complex, and heavily depends on plugin and multiple level of chaining, it can be challenging to manually type as it's highly dynamic.
|
||||||
|
|
||||||
|
## Model
|
||||||
|
Model or [DTO (Data Transfer Object)](https://en.wikipedia.org/wiki/Data_transfer_object) is handle by [Elysia.t (Validation)](/essential/validation.html#elysia-type).
|
||||||
|
|
||||||
|
Elysia has a validation system built-in which can infers type from your code and validate it at runtime.
|
||||||
|
|
||||||
|
### Do: Use Elysia's validation system
|
||||||
|
|
||||||
|
Elysia strength is prioritizing a single source of truth for both type and runtime validation.
|
||||||
|
|
||||||
|
Instead of declaring an interface, reuse validation's model instead:
|
||||||
|
```typescript twoslash
|
||||||
|
// Do
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const customBody = t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Optional if you want to get the type of the model
|
||||||
|
// Usually if we didn't use the type, as it's already inferred by Elysia
|
||||||
|
type CustomBody = typeof customBody.static
|
||||||
|
|
||||||
|
export { customBody }
|
||||||
|
```
|
||||||
|
|
||||||
|
We can get type of model by using `typeof` with `.static` property from the model.
|
||||||
|
|
||||||
|
Then you can use the `CustomBody` type to infer the type of the request body.
|
||||||
|
|
||||||
|
```typescript twoslash
|
||||||
|
// Do
|
||||||
|
new Elysia()
|
||||||
|
.post('/login', ({ body }) => {
|
||||||
|
return body
|
||||||
|
}, {
|
||||||
|
body: customBody
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Don't: Declare a class instance as a model
|
||||||
|
|
||||||
|
Do not declare a class instance as a model:
|
||||||
|
```typescript
|
||||||
|
// Don't
|
||||||
|
class CustomBody {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
|
||||||
|
constructor(username: string, password: string) {
|
||||||
|
this.username = username
|
||||||
|
this.password = password
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't
|
||||||
|
interface ICustomBody {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Don't: Declare type separate from the model
|
||||||
|
Do not declare a type separate from the model, instead use `typeof` with `.static` property to get the type of the model.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Don't
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const customBody = t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
|
||||||
|
type CustomBody = {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do
|
||||||
|
const customBody = t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
|
||||||
|
type CustomBody = typeof customBody.static
|
||||||
|
```
|
||||||
|
|
||||||
|
### Group
|
||||||
|
You can group multiple models into a single object to make it more organized.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
export const AuthModel = {
|
||||||
|
sign: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const models = AuthModel.models
|
||||||
|
```
|
||||||
|
|
||||||
|
### Model Injection
|
||||||
|
Though this is optional, if you are strictly following MVC pattern, you may want to inject like a service into a controller. We recommended using Elysia reference model
|
||||||
|
|
||||||
|
Using Elysia's model reference
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
const customBody = t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
|
||||||
|
const AuthModel = new Elysia()
|
||||||
|
.model({
|
||||||
|
sign: customBody
|
||||||
|
})
|
||||||
|
|
||||||
|
const models = AuthModel.models
|
||||||
|
|
||||||
|
const UserController = new Elysia({ prefix: '/auth' })
|
||||||
|
.use(AuthModel)
|
||||||
|
.prefix('model', 'auth.')
|
||||||
|
.post('/sign-in', async ({ body, cookie: { session } }) => {
|
||||||
|
return true
|
||||||
|
}, {
|
||||||
|
body: 'auth.Sign'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
This approach provide several benefits:
|
||||||
|
1. Allow us to name a model and provide auto-completion.
|
||||||
|
2. Modify schema for later usage, or perform a [remap](/essential/handler.html#remap).
|
||||||
|
3. Show up as "models" in OpenAPI compliance client, eg. OpenAPI.
|
||||||
|
4. Improve TypeScript inference speed as model type will be cached during registration.
|
||||||
30
.agents/skills/elysiajs/plugins/bearer.md
Normal file
30
.agents/skills/elysiajs/plugins/bearer.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Bearer
|
||||||
|
Plugin for Elysia for retrieving the Bearer token.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/bearer
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { bearer } from '@elysiajs/bearer'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(bearer())
|
||||||
|
.get('/sign', ({ bearer }) => bearer, {
|
||||||
|
beforeHandle({ bearer, set, status }) {
|
||||||
|
if (!bearer) {
|
||||||
|
set.headers[
|
||||||
|
'WWW-Authenticate'
|
||||||
|
] = `Bearer realm='sign', error="invalid_request"`
|
||||||
|
|
||||||
|
return status(400, 'Unauthorized')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
This plugin is for retrieving a Bearer token specified in RFC6750
|
||||||
141
.agents/skills/elysiajs/plugins/cors.md
Normal file
141
.agents/skills/elysiajs/plugins/cors.md
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
# CORS
|
||||||
|
|
||||||
|
Plugin for Elysia that adds support for customizing Cross-Origin Resource Sharing behavior.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/cors
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cors } from '@elysiajs/cors'
|
||||||
|
|
||||||
|
new Elysia().use(cors()).listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
This will set Elysia to accept requests from any origin.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### origin
|
||||||
|
|
||||||
|
@default `true`
|
||||||
|
|
||||||
|
Indicates whether the response can be shared with the requesting code from the given origins.
|
||||||
|
|
||||||
|
Value can be one of the following:
|
||||||
|
|
||||||
|
- **string** - Name of origin which will directly assign to Access-Control-Allow-Origin header.
|
||||||
|
- **boolean** - If set to true, Access-Control-Allow-Origin will be set to `*` (any origins)
|
||||||
|
- **RegExp** - Pattern to match request's URL, allowed if matched.
|
||||||
|
- **Function** - Custom logic to allow resource sharing, allow if `true` is returned.
|
||||||
|
- Expected to have the type of:
|
||||||
|
```typescript
|
||||||
|
cors(context: Context) => boolean | void
|
||||||
|
```
|
||||||
|
- **Array<string | RegExp | Function>** - iterate through all cases above in order, allowed if any of the values are `true`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### methods
|
||||||
|
|
||||||
|
@default `*`
|
||||||
|
|
||||||
|
Allowed methods for cross-origin requests by assign `Access-Control-Allow-Methods` header.
|
||||||
|
|
||||||
|
Value can be one of the following:
|
||||||
|
- **undefined | null | ''** - Ignore all methods.
|
||||||
|
- **\*** - Allows all methods.
|
||||||
|
- **string** - Expects either a single method or a comma-delimited string
|
||||||
|
- (eg: `'GET, PUT, POST'`)
|
||||||
|
- **string[]** - Allow multiple HTTP methods.
|
||||||
|
- eg: `['GET', 'PUT', 'POST']`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### allowedHeaders
|
||||||
|
|
||||||
|
@default `*`
|
||||||
|
|
||||||
|
Allowed headers for an incoming request by assign `Access-Control-Allow-Headers` header.
|
||||||
|
|
||||||
|
Value can be one of the following:
|
||||||
|
- **string** - Expects either a single header or a comma-delimited string
|
||||||
|
- eg: `'Content-Type, Authorization'`.
|
||||||
|
- **string[]** - Allow multiple HTTP headers.
|
||||||
|
- eg: `['Content-Type', 'Authorization']`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### exposeHeaders
|
||||||
|
|
||||||
|
@default `*`
|
||||||
|
|
||||||
|
Response CORS with specified headers by sssign Access-Control-Expose-Headers header.
|
||||||
|
|
||||||
|
Value can be one of the following:
|
||||||
|
- **string** - Expects either a single header or a comma-delimited string.
|
||||||
|
- eg: `'Content-Type, X-Powered-By'`.
|
||||||
|
- **string[]** - Allow multiple HTTP headers.
|
||||||
|
- eg: `['Content-Type', 'X-Powered-By']`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### credentials
|
||||||
|
|
||||||
|
@default `true`
|
||||||
|
|
||||||
|
The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to the frontend JavaScript code when the request's credentials mode Request.credentials is `include`.
|
||||||
|
|
||||||
|
Credentials are cookies, authorization headers, or TLS client certificates by assign `Access-Control-Allow-Credentials` header.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### maxAge
|
||||||
|
|
||||||
|
@default `5`
|
||||||
|
|
||||||
|
Indicates how long the results of a preflight request that is the information contained in the `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers` headers) can be cached.
|
||||||
|
|
||||||
|
Assign `Access-Control-Max-Age` header.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### preflight
|
||||||
|
|
||||||
|
The preflight request is a request sent to check if the CORS protocol is understood and if a server is aware of using specific methods and headers.
|
||||||
|
|
||||||
|
Response with **OPTIONS** request with 3 HTTP request headers:
|
||||||
|
- **Access-Control-Request-Method**
|
||||||
|
- **Access-Control-Request-Headers**
|
||||||
|
- **Origin**
|
||||||
|
|
||||||
|
This config indicates if the server should respond to preflight requests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pattern
|
||||||
|
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
## Allow CORS by top-level domain
|
||||||
|
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cors } from '@elysiajs/cors'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
cors({
|
||||||
|
origin: /.*\.saltyaom\.com$/
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get('/', () => 'Hi')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
This will allow requests from top-level domains with `saltyaom.com`
|
||||||
265
.agents/skills/elysiajs/plugins/cron.md
Normal file
265
.agents/skills/elysiajs/plugins/cron.md
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
# Cron Plugin
|
||||||
|
|
||||||
|
This plugin adds support for running cronjob to Elysia server.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/cron
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cron } from '@elysiajs/cron'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(
|
||||||
|
cron({
|
||||||
|
name: 'heartbeat',
|
||||||
|
pattern: '*/10 * * * * *',
|
||||||
|
run() {
|
||||||
|
console.log('Heartbeat')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
The above code will log `heartbeat` every 10 seconds.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### cron
|
||||||
|
|
||||||
|
Create a cronjob for the Elysia server.
|
||||||
|
|
||||||
|
```
|
||||||
|
cron(config: CronConfig, callback: (Instance['store']) => void): this
|
||||||
|
```
|
||||||
|
|
||||||
|
`CronConfig` accepts the parameters specified below:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.name
|
||||||
|
|
||||||
|
Job name to register to `store`.
|
||||||
|
|
||||||
|
This will register the cron instance to `store` with a specified name, which can be used to reference in later processes eg. stop the job.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.pattern
|
||||||
|
|
||||||
|
Time to run the job as specified by cron syntax.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────── second (optional)
|
||||||
|
│ ┌──────────── minute
|
||||||
|
│ │ ┌────────── hour
|
||||||
|
│ │ │ ┌──────── day of the month
|
||||||
|
│ │ │ │ ┌────── month
|
||||||
|
│ │ │ │ │ ┌──── day of week
|
||||||
|
│ │ │ │ │ │
|
||||||
|
* * * * * *
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.timezone
|
||||||
|
Time zone in Europe/Stockholm format
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.startAt
|
||||||
|
Schedule start time for the job
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.stopAt
|
||||||
|
Schedule stop time for the job
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.maxRuns
|
||||||
|
Maximum number of executions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CronConfig.catch
|
||||||
|
Continue execution even if an unhandled error is thrown by a triggered function.
|
||||||
|
|
||||||
|
### CronConfig.interval
|
||||||
|
The minimum interval between executions, in seconds.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CronConfig.Pattern
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pattern
|
||||||
|
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
## Stop cronjob
|
||||||
|
|
||||||
|
You can stop cronjob manually by accessing the cronjob name registered to `store`.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cron } from '@elysiajs/cron'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
cron({
|
||||||
|
name: 'heartbeat',
|
||||||
|
pattern: '*/1 * * * * *',
|
||||||
|
run() {
|
||||||
|
console.log('Heartbeat')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get(
|
||||||
|
'/stop',
|
||||||
|
({
|
||||||
|
store: {
|
||||||
|
cron: { heartbeat }
|
||||||
|
}
|
||||||
|
}) => {
|
||||||
|
heartbeat.stop()
|
||||||
|
|
||||||
|
return 'Stop heartbeat'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Predefined patterns
|
||||||
|
|
||||||
|
You can use predefined patterns from `@elysiajs/cron/schedule`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cron, Patterns } from '@elysiajs/cron'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
cron({
|
||||||
|
name: 'heartbeat',
|
||||||
|
pattern: Patterns.everySecond(),
|
||||||
|
run() {
|
||||||
|
console.log('Heartbeat')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get(
|
||||||
|
'/stop',
|
||||||
|
({
|
||||||
|
store: {
|
||||||
|
cron: { heartbeat }
|
||||||
|
}
|
||||||
|
}) => {
|
||||||
|
heartbeat.stop()
|
||||||
|
|
||||||
|
return 'Stop heartbeat'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Functions
|
||||||
|
|
||||||
|
| Function | Description |
|
||||||
|
| ---------------------------------------- | ----------------------------------------------------- |
|
||||||
|
| `.everySeconds(2)` | Run the task every 2 seconds |
|
||||||
|
| `.everyMinutes(5)` | Run the task every 5 minutes |
|
||||||
|
| `.everyHours(3)` | Run the task every 3 hours |
|
||||||
|
| `.everyHoursAt(3, 15)` | Run the task every 3 hours at 15 minutes |
|
||||||
|
| `.everyDayAt('04:19')` | Run the task every day at 04:19 |
|
||||||
|
| `.everyWeekOn(Patterns.MONDAY, '19:30')` | Run the task every Monday at 19:30 |
|
||||||
|
| `.everyWeekdayAt('17:00')` | Run the task every day from Monday to Friday at 17:00 |
|
||||||
|
| `.everyWeekendAt('11:00')` | Run the task on Saturday and Sunday at 11:00 |
|
||||||
|
|
||||||
|
### Function aliases to constants
|
||||||
|
|
||||||
|
| Function | Constant |
|
||||||
|
| ----------------- | ---------------------------------- |
|
||||||
|
| `.everySecond()` | EVERY_SECOND |
|
||||||
|
| `.everyMinute()` | EVERY_MINUTE |
|
||||||
|
| `.hourly()` | EVERY_HOUR |
|
||||||
|
| `.daily()` | EVERY_DAY_AT_MIDNIGHT |
|
||||||
|
| `.everyWeekday()` | EVERY_WEEKDAY |
|
||||||
|
| `.everyWeekend()` | EVERY_WEEKEND |
|
||||||
|
| `.weekly()` | EVERY_WEEK |
|
||||||
|
| `.monthly()` | EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT |
|
||||||
|
| `.everyQuarter()` | EVERY_QUARTER |
|
||||||
|
| `.yearly()` | EVERY_YEAR |
|
||||||
|
|
||||||
|
### Constants
|
||||||
|
|
||||||
|
| Constant | Pattern |
|
||||||
|
| ---------------------------------------- | -------------------- |
|
||||||
|
| `.EVERY_SECOND` | `* * * * * *` |
|
||||||
|
| `.EVERY_5_SECONDS` | `*/5 * * * * *` |
|
||||||
|
| `.EVERY_10_SECONDS` | `*/10 * * * * *` |
|
||||||
|
| `.EVERY_30_SECONDS` | `*/30 * * * * *` |
|
||||||
|
| `.EVERY_MINUTE` | `*/1 * * * *` |
|
||||||
|
| `.EVERY_5_MINUTES` | `0 */5 * * * *` |
|
||||||
|
| `.EVERY_10_MINUTES` | `0 */10 * * * *` |
|
||||||
|
| `.EVERY_30_MINUTES` | `0 */30 * * * *` |
|
||||||
|
| `.EVERY_HOUR` | `0 0-23/1 * * *` |
|
||||||
|
| `.EVERY_2_HOURS` | `0 0-23/2 * * *` |
|
||||||
|
| `.EVERY_3_HOURS` | `0 0-23/3 * * *` |
|
||||||
|
| `.EVERY_4_HOURS` | `0 0-23/4 * * *` |
|
||||||
|
| `.EVERY_5_HOURS` | `0 0-23/5 * * *` |
|
||||||
|
| `.EVERY_6_HOURS` | `0 0-23/6 * * *` |
|
||||||
|
| `.EVERY_7_HOURS` | `0 0-23/7 * * *` |
|
||||||
|
| `.EVERY_8_HOURS` | `0 0-23/8 * * *` |
|
||||||
|
| `.EVERY_9_HOURS` | `0 0-23/9 * * *` |
|
||||||
|
| `.EVERY_10_HOURS` | `0 0-23/10 * * *` |
|
||||||
|
| `.EVERY_11_HOURS` | `0 0-23/11 * * *` |
|
||||||
|
| `.EVERY_12_HOURS` | `0 0-23/12 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_1AM` | `0 01 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_2AM` | `0 02 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_3AM` | `0 03 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_4AM` | `0 04 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_5AM` | `0 05 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_6AM` | `0 06 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_7AM` | `0 07 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_8AM` | `0 08 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_9AM` | `0 09 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_10AM` | `0 10 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_11AM` | `0 11 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_NOON` | `0 12 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_1PM` | `0 13 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_2PM` | `0 14 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_3PM` | `0 15 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_4PM` | `0 16 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_5PM` | `0 17 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_6PM` | `0 18 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_7PM` | `0 19 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_8PM` | `0 20 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_9PM` | `0 21 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_10PM` | `0 22 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_11PM` | `0 23 * * *` |
|
||||||
|
| `.EVERY_DAY_AT_MIDNIGHT` | `0 0 * * *` |
|
||||||
|
| `.EVERY_WEEK` | `0 0 * * 0` |
|
||||||
|
| `.EVERY_WEEKDAY` | `0 0 * * 1-5` |
|
||||||
|
| `.EVERY_WEEKEND` | `0 0 * * 6,0` |
|
||||||
|
| `.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT` | `0 0 1 * *` |
|
||||||
|
| `.EVERY_1ST_DAY_OF_MONTH_AT_NOON` | `0 12 1 * *` |
|
||||||
|
| `.EVERY_2ND_HOUR` | `0 */2 * * *` |
|
||||||
|
| `.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM` | `0 1-23/2 * * *` |
|
||||||
|
| `.EVERY_2ND_MONTH` | `0 0 1 */2 *` |
|
||||||
|
| `.EVERY_QUARTER` | `0 0 1 */3 *` |
|
||||||
|
| `.EVERY_6_MONTHS` | `0 0 1 */6 *` |
|
||||||
|
| `.EVERY_YEAR` | `0 0 1 1 *` |
|
||||||
|
| `.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM` | `0 */30 9-17 * * *` |
|
||||||
|
| `.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM` | `0 */30 9-18 * * *` |
|
||||||
|
| `.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM` | `0 */30 10-19 * * *` |
|
||||||
90
.agents/skills/elysiajs/plugins/graphql-apollo.md
Normal file
90
.agents/skills/elysiajs/plugins/graphql-apollo.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# GraphQL Apollo
|
||||||
|
|
||||||
|
Plugin for Elysia to use GraphQL Apollo.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add graphql @elysiajs/apollo @apollo/server
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { apollo, gql } from '@elysiajs/apollo'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
apollo({
|
||||||
|
typeDefs: gql`
|
||||||
|
type Book {
|
||||||
|
title: String
|
||||||
|
author: String
|
||||||
|
}
|
||||||
|
|
||||||
|
type Query {
|
||||||
|
books: [Book]
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
resolvers: {
|
||||||
|
Query: {
|
||||||
|
books: () => {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
title: 'Elysia',
|
||||||
|
author: 'saltyAom'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Accessing `/graphql` should show Apollo GraphQL playground work with.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Because Elysia is based on Web Standard Request and Response which is different from Node's `HttpRequest` and `HttpResponse` that Express uses, results in `req, res` being undefined in context.
|
||||||
|
|
||||||
|
Because of this, Elysia replaces both with `context` like route parameters.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
apollo({
|
||||||
|
typeDefs,
|
||||||
|
resolvers,
|
||||||
|
context: async ({ request }) => {
|
||||||
|
const authorization = request.headers.get('Authorization')
|
||||||
|
|
||||||
|
return {
|
||||||
|
authorization
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
This plugin extends Apollo's [ServerRegistration](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#options) (which is `ApolloServer`'s' constructor parameter).
|
||||||
|
|
||||||
|
Below are the extended parameters for configuring Apollo Server with Elysia.
|
||||||
|
|
||||||
|
### path
|
||||||
|
|
||||||
|
@default `"/graphql"`
|
||||||
|
|
||||||
|
Path to expose Apollo Server.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### enablePlayground
|
||||||
|
|
||||||
|
@default `process.env.ENV !== 'production'`
|
||||||
|
|
||||||
|
Determine whether should Apollo should provide Apollo Playground.
|
||||||
87
.agents/skills/elysiajs/plugins/graphql-yoga.md
Normal file
87
.agents/skills/elysiajs/plugins/graphql-yoga.md
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# GraphQL Yoga
|
||||||
|
|
||||||
|
This plugin integrates GraphQL yoga with Elysia
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/graphql-yoga
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { yoga } from '@elysiajs/graphql-yoga'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
yoga({
|
||||||
|
typeDefs: /* GraphQL */ `
|
||||||
|
type Query {
|
||||||
|
hi: String
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
resolvers: {
|
||||||
|
Query: {
|
||||||
|
hi: () => 'Hello from Elysia'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Accessing `/graphql` in the browser (GET request) would show you a GraphiQL instance for the GraphQL-enabled Elysia server.
|
||||||
|
|
||||||
|
optional: you can install a custom version of optional peer dependencies as well:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun add graphql graphql-yoga
|
||||||
|
```
|
||||||
|
|
||||||
|
## Resolver
|
||||||
|
|
||||||
|
Elysia uses Mobius to infer type from **typeDefs** field automatically, allowing you to get full type-safety and auto-complete when typing **resolver** types.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
You can add custom context to the resolver function by adding **context**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { yoga } from '@elysiajs/graphql-yoga'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
yoga({
|
||||||
|
typeDefs: /* GraphQL */ `
|
||||||
|
type Query {
|
||||||
|
hi: String
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
context: {
|
||||||
|
name: 'Mobius'
|
||||||
|
},
|
||||||
|
// If context is a function on this doesn't present
|
||||||
|
// for some reason it won't infer context type
|
||||||
|
useContext(_) {},
|
||||||
|
resolvers: {
|
||||||
|
Query: {
|
||||||
|
hi: async (parent, args, context) => context.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
This plugin extends [GraphQL Yoga's createYoga options, please refer to the GraphQL Yoga documentation](https://the-guild.dev/graphql/yoga-server/docs) with inlining `schema` config to root.
|
||||||
|
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### path
|
||||||
|
|
||||||
|
@default `/graphql`
|
||||||
|
|
||||||
|
Endpoint to expose GraphQL handler
|
||||||
188
.agents/skills/elysiajs/plugins/html.md
Normal file
188
.agents/skills/elysiajs/plugins/html.md
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
# HTML
|
||||||
|
|
||||||
|
Allows you to use JSX and HTML with proper headers and support.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/html
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```tsx twoslash
|
||||||
|
import React from 'react'
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { html, Html } from '@elysiajs/html'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(html())
|
||||||
|
.get(
|
||||||
|
'/html',
|
||||||
|
() => `
|
||||||
|
<html lang='en'>
|
||||||
|
<head>
|
||||||
|
<title>Hello World</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Hello World</h1>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
)
|
||||||
|
.get('/jsx', () => (
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello World</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Hello World</h1>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
))
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
This plugin will automatically add `Content-Type: text/html; charset=utf8` header to the response, add `<!doctype html>`, and convert it into a Response object.
|
||||||
|
|
||||||
|
## JSX
|
||||||
|
Elysia can use JSX
|
||||||
|
|
||||||
|
1. Replace your file that needs to use JSX to end with affix **"x"**:
|
||||||
|
- .js -> .jsx
|
||||||
|
- .ts -> .tsx
|
||||||
|
|
||||||
|
2. Register the TypeScript type by append the following to **tsconfig.json**:
|
||||||
|
```jsonc
|
||||||
|
// tsconfig.json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"jsx": "react",
|
||||||
|
"jsxFactory": "Html.createElement",
|
||||||
|
"jsxFragmentFactory": "Html.Fragment"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Starts using JSX in your file
|
||||||
|
```tsx twoslash
|
||||||
|
import React from 'react'
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { html, Html } from '@elysiajs/html'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(html())
|
||||||
|
.get('/', () => (
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello World</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Hello World</h1>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
))
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
If the error `Cannot find name 'Html'. Did you mean 'html'?` occurs, this import must be added to the JSX template:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Html } from '@elysiajs/html'
|
||||||
|
```
|
||||||
|
|
||||||
|
It is important that it is written in uppercase.
|
||||||
|
|
||||||
|
## XSS
|
||||||
|
|
||||||
|
Elysia HTML is based use of the Kita HTML plugin to detect possible XSS attacks in compile time.
|
||||||
|
|
||||||
|
You can use a dedicated `safe` attribute to sanitize user value to prevent XSS vulnerability.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
import { html, Html } from '@elysiajs/html'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(html())
|
||||||
|
.post(
|
||||||
|
'/',
|
||||||
|
({ body }) => (
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Hello World</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1 safe>{body}</h1>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
),
|
||||||
|
{
|
||||||
|
body: t.String()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
However, when are building a large-scale app, it's best to have a type reminder to detect possible XSS vulnerabilities in your codebase.
|
||||||
|
|
||||||
|
To add a type-safe reminder, please install:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun add @kitajs/ts-html-plugin
|
||||||
|
```
|
||||||
|
|
||||||
|
Then appends the following **tsconfig.json**
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
// tsconfig.json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"jsx": "react",
|
||||||
|
"jsxFactory": "Html.createElement",
|
||||||
|
"jsxFragmentFactory": "Html.Fragment",
|
||||||
|
"plugins": [{ "name": "@kitajs/ts-html-plugin" }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### contentType
|
||||||
|
|
||||||
|
- Type: `string`
|
||||||
|
- Default: `'text/html; charset=utf8'`
|
||||||
|
|
||||||
|
The content-type of the response.
|
||||||
|
|
||||||
|
### autoDetect
|
||||||
|
|
||||||
|
- Type: `boolean`
|
||||||
|
- Default: `true`
|
||||||
|
|
||||||
|
Whether to automatically detect HTML content and set the content-type.
|
||||||
|
|
||||||
|
### autoDoctype
|
||||||
|
|
||||||
|
- Type: `boolean | 'full'`
|
||||||
|
- Default: `true`
|
||||||
|
|
||||||
|
Whether to automatically add `<!doctype html>` to a response starting with `<html>`, if not found.
|
||||||
|
|
||||||
|
Use `full` to also automatically add doctypes on responses returned without this plugin
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// without the plugin
|
||||||
|
app.get('/', () => '<html></html>')
|
||||||
|
|
||||||
|
// With the plugin
|
||||||
|
app.get('/', ({ html }) => html('<html></html>'))
|
||||||
|
```
|
||||||
|
|
||||||
|
### isHtml
|
||||||
|
|
||||||
|
- Type: `(value: string) => boolean`
|
||||||
|
- Default: `isHtml` (exported function)
|
||||||
|
|
||||||
|
The function is used to detect if a string is a html or not. Default implementation if length is greater than 7, starts with `<` and ends with `>`.
|
||||||
|
|
||||||
|
Keep in mind there's no real way to validate HTML, so the default implementation is a best guess.
|
||||||
197
.agents/skills/elysiajs/plugins/jwt.md
Normal file
197
.agents/skills/elysiajs/plugins/jwt.md
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
# JWT Plugin
|
||||||
|
This plugin adds support for using JWT in Elysia handlers.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/jwt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript [cookie]
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { jwt } from '@elysiajs/jwt'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
jwt({
|
||||||
|
name: 'jwt',
|
||||||
|
secret: 'Fischl von Luftschloss Narfidort'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get('/sign/:name', async ({ jwt, params: { name }, cookie: { auth } }) => {
|
||||||
|
const value = await jwt.sign({ name })
|
||||||
|
|
||||||
|
auth.set({
|
||||||
|
value,
|
||||||
|
httpOnly: true,
|
||||||
|
maxAge: 7 * 86400,
|
||||||
|
path: '/profile',
|
||||||
|
})
|
||||||
|
|
||||||
|
return `Sign in as ${value}`
|
||||||
|
})
|
||||||
|
.get('/profile', async ({ jwt, status, cookie: { auth } }) => {
|
||||||
|
const profile = await jwt.verify(auth.value)
|
||||||
|
|
||||||
|
if (!profile)
|
||||||
|
return status(401, 'Unauthorized')
|
||||||
|
|
||||||
|
return `Hello ${profile.name}`
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config
|
||||||
|
This plugin extends config from [jose](https://github.com/panva/jose).
|
||||||
|
|
||||||
|
Below is a config that is accepted by the plugin.
|
||||||
|
|
||||||
|
### name
|
||||||
|
Name to register `jwt` function as.
|
||||||
|
|
||||||
|
For example, `jwt` function will be registered with a custom name.
|
||||||
|
```typescript
|
||||||
|
new Elysia()
|
||||||
|
.use(
|
||||||
|
jwt({
|
||||||
|
name: 'myJWTNamespace',
|
||||||
|
secret: process.env.JWT_SECRETS!
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get('/sign/:name', ({ myJWTNamespace, params }) => {
|
||||||
|
return myJWTNamespace.sign(params)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Because some might need to use multiple `jwt` with different configs in a single server, explicitly registering the JWT function with a different name is needed.
|
||||||
|
|
||||||
|
### secret
|
||||||
|
The private key to sign JWT payload with.
|
||||||
|
|
||||||
|
### schema
|
||||||
|
Type strict validation for JWT payload.
|
||||||
|
|
||||||
|
### alg
|
||||||
|
@default `HS256`
|
||||||
|
|
||||||
|
Signing Algorithm to sign JWT payload with.
|
||||||
|
|
||||||
|
Possible properties for jose are:
|
||||||
|
HS256
|
||||||
|
HS384
|
||||||
|
HS512
|
||||||
|
PS256
|
||||||
|
PS384
|
||||||
|
PS512
|
||||||
|
RS256
|
||||||
|
RS384
|
||||||
|
RS512
|
||||||
|
ES256
|
||||||
|
ES256K
|
||||||
|
ES384
|
||||||
|
ES512
|
||||||
|
EdDSA
|
||||||
|
|
||||||
|
### iss
|
||||||
|
The issuer claim identifies the principal that issued the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1)
|
||||||
|
|
||||||
|
TLDR; is usually (the domain) name of the signer.
|
||||||
|
|
||||||
|
### sub
|
||||||
|
The subject claim identifies the principal that is the subject of the JWT.
|
||||||
|
|
||||||
|
The claims in a JWT are normally statements about the subject as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2)
|
||||||
|
|
||||||
|
### aud
|
||||||
|
The audience claim identifies the recipients that the JWT is intended for.
|
||||||
|
|
||||||
|
Each principal intended to process the JWT MUST identify itself with a value in the audience claim as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3)
|
||||||
|
|
||||||
|
### jti
|
||||||
|
JWT ID claim provides a unique identifier for the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7)
|
||||||
|
|
||||||
|
### nbf
|
||||||
|
The "not before" claim identifies the time before which the JWT must not be accepted for processing as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5)
|
||||||
|
|
||||||
|
### exp
|
||||||
|
The expiration time claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4)
|
||||||
|
|
||||||
|
### iat
|
||||||
|
The "issued at" claim identifies the time at which the JWT was issued.
|
||||||
|
|
||||||
|
This claim can be used to determine the age of the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6)
|
||||||
|
|
||||||
|
### b64
|
||||||
|
This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797).
|
||||||
|
|
||||||
|
### kid
|
||||||
|
A hint indicating which key was used to secure the JWS.
|
||||||
|
|
||||||
|
This parameter allows originators to explicitly signal a change of key to recipients as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.4)
|
||||||
|
|
||||||
|
### x5t
|
||||||
|
(X.509 certificate SHA-1 thumbprint) header parameter is a base64url-encoded SHA-1 digest of the DER encoding of the X.509 certificate [RFC5280](https://www.rfc-editor.org/rfc/rfc5280) corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.7)
|
||||||
|
|
||||||
|
### x5c
|
||||||
|
(X.509 certificate chain) header parameter contains the X.509 public key certificate or certificate chain [RFC5280](https://www.rfc-editor.org/rfc/rfc5280) corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6)
|
||||||
|
|
||||||
|
### x5u
|
||||||
|
(X.509 URL) header parameter is a URI [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) that refers to a resource for the X.509 public key certificate or certificate chain [RFC5280] corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.5)
|
||||||
|
|
||||||
|
### jwk
|
||||||
|
The "jku" (JWK Set URL) Header Parameter is a URI [RFC3986] that refers to a resource for a set of JSON-encoded public keys, one of which corresponds to the key used to digitally sign the JWS.
|
||||||
|
|
||||||
|
The keys MUST be encoded as a JWK Set [JWK] as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.2)
|
||||||
|
|
||||||
|
### typ
|
||||||
|
The `typ` (type) Header Parameter is used by JWS applications to declare the media type [IANA.MediaTypes] of this complete JWS.
|
||||||
|
|
||||||
|
This is intended for use by the application when more than one kind of object could be present in an application data structure that can contain a JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.9)
|
||||||
|
|
||||||
|
### ctr
|
||||||
|
Content-Type parameter is used by JWS applications to declare the media type [IANA.MediaTypes] of the secured content (the payload).
|
||||||
|
|
||||||
|
This is intended for use by the application when more than one kind of object could be present in the JWS Payload as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.9)
|
||||||
|
|
||||||
|
## Handler
|
||||||
|
Below are the value added to the handler.
|
||||||
|
|
||||||
|
### jwt.sign
|
||||||
|
A dynamic object of collection related to use with JWT registered by the JWT plugin.
|
||||||
|
|
||||||
|
Type:
|
||||||
|
```typescript
|
||||||
|
sign: (payload: JWTPayloadSpec): Promise<string>
|
||||||
|
```
|
||||||
|
|
||||||
|
`JWTPayloadSpec` accepts the same value as [JWT config](#config)
|
||||||
|
|
||||||
|
### jwt.verify
|
||||||
|
Verify payload with the provided JWT config
|
||||||
|
|
||||||
|
Type:
|
||||||
|
```typescript
|
||||||
|
verify(payload: string) => Promise<JWTPayloadSpec | false>
|
||||||
|
```
|
||||||
|
|
||||||
|
`JWTPayloadSpec` accepts the same value as [JWT config](#config)
|
||||||
|
|
||||||
|
## Pattern
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
## Set JWT expiration date
|
||||||
|
By default, the config is passed to `setCookie` and inherits its value.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(
|
||||||
|
jwt({
|
||||||
|
name: 'jwt',
|
||||||
|
secret: 'kunikuzushi',
|
||||||
|
exp: '7d'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.get('/sign/:name', async ({ jwt, params }) => jwt.sign(params))
|
||||||
|
```
|
||||||
|
|
||||||
|
This will sign JWT with an expiration date of the next 7 days.
|
||||||
246
.agents/skills/elysiajs/plugins/openapi.md
Normal file
246
.agents/skills/elysiajs/plugins/openapi.md
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
# OpenAPI Plugin
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/openapi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript
|
||||||
|
import { openapi } from '@elysiajs/openapi'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(openapi())
|
||||||
|
.get('/', () => 'hello')
|
||||||
|
```
|
||||||
|
|
||||||
|
Docs at `/openapi`, spec at `/openapi/json`.
|
||||||
|
|
||||||
|
## Detail Object
|
||||||
|
Extends OpenAPI Operation Object:
|
||||||
|
```typescript
|
||||||
|
.get('/', () => 'hello', {
|
||||||
|
detail: {
|
||||||
|
title: 'Hello',
|
||||||
|
description: 'An example route',
|
||||||
|
summary: 'Short summary',
|
||||||
|
deprecated: false,
|
||||||
|
hide: true, // Hide from docs
|
||||||
|
tags: ['App']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Documentation Config
|
||||||
|
```typescript
|
||||||
|
openapi({
|
||||||
|
documentation: {
|
||||||
|
info: {
|
||||||
|
title: 'API',
|
||||||
|
version: '1.0.0'
|
||||||
|
},
|
||||||
|
tags: [
|
||||||
|
{ name: 'App', description: 'General' }
|
||||||
|
],
|
||||||
|
components: {
|
||||||
|
securitySchemes: {
|
||||||
|
bearerAuth: { type: 'http', scheme: 'bearer' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Standard Schema Mapping
|
||||||
|
```typescript
|
||||||
|
mapJsonSchema: {
|
||||||
|
zod: z.toJSONSchema, // Zod 4
|
||||||
|
valibot: toJsonSchema,
|
||||||
|
effect: JSONSchema.make
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Zod 3: `zodToJsonSchema` from `zod-to-json-schema`
|
||||||
|
|
||||||
|
## OpenAPI Type Gen
|
||||||
|
Generate docs from types:
|
||||||
|
```typescript
|
||||||
|
import { fromTypes } from '@elysiajs/openapi'
|
||||||
|
|
||||||
|
export const app = new Elysia()
|
||||||
|
.use(openapi({
|
||||||
|
references: fromTypes()
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production
|
||||||
|
Recommended to generate `.d.ts` file for production when using OpenAPI Type Gen
|
||||||
|
```typescript
|
||||||
|
references: fromTypes(
|
||||||
|
process.env.NODE_ENV === 'production'
|
||||||
|
? 'dist/index.d.ts'
|
||||||
|
: 'src/index.ts'
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Options
|
||||||
|
```typescript
|
||||||
|
fromTypes('src/index.ts', {
|
||||||
|
projectRoot: path.join('..', import.meta.dir),
|
||||||
|
tsconfigPath: 'tsconfig.dts.json'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Caveat: Explicit Types
|
||||||
|
Use `Prettify` helper to inline when type is not showing:
|
||||||
|
```typescript
|
||||||
|
type Prettify<T> = { [K in keyof T]: T[K] } & {}
|
||||||
|
|
||||||
|
function getUser(): Prettify<User> { }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Schema Description
|
||||||
|
```typescript
|
||||||
|
body: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String({
|
||||||
|
minLength: 8,
|
||||||
|
description: 'Password (8+ chars)'
|
||||||
|
})
|
||||||
|
}, {
|
||||||
|
description: 'Expected username and password'
|
||||||
|
}),
|
||||||
|
detail: {
|
||||||
|
summary: 'Sign in user',
|
||||||
|
tags: ['auth']
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Response Headers
|
||||||
|
```typescript
|
||||||
|
import { withHeader } from '@elysiajs/openapi'
|
||||||
|
|
||||||
|
response: withHeader(
|
||||||
|
t.Literal('Hi'),
|
||||||
|
{ 'x-powered-by': t.Literal('Elysia') }
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Annotation only - doesn't enforce. Set headers manually.
|
||||||
|
|
||||||
|
## Tags
|
||||||
|
Define + assign:
|
||||||
|
```typescript
|
||||||
|
.use(openapi({
|
||||||
|
documentation: {
|
||||||
|
tags: [
|
||||||
|
{ name: 'App', description: 'General' },
|
||||||
|
{ name: 'Auth', description: 'Auth' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.get('/', () => 'hello', {
|
||||||
|
detail: { tags: ['App'] }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Instance Tags
|
||||||
|
```typescript
|
||||||
|
new Elysia({ tags: ['user'] })
|
||||||
|
.get('/user', 'user')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reference Models
|
||||||
|
Auto-generates schemas:
|
||||||
|
```typescript
|
||||||
|
.model({
|
||||||
|
User: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
username: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/user', () => ({ id: 1, username: 'x' }), {
|
||||||
|
response: { 200: 'User' },
|
||||||
|
detail: { tags: ['User'] }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guard
|
||||||
|
Apply to instance/group:
|
||||||
|
```typescript
|
||||||
|
.guard({
|
||||||
|
detail: {
|
||||||
|
description: 'Requires auth'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get('/user', 'user')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security
|
||||||
|
```typescript
|
||||||
|
.use(openapi({
|
||||||
|
documentation: {
|
||||||
|
components: {
|
||||||
|
securitySchemes: {
|
||||||
|
bearerAuth: {
|
||||||
|
type: 'http',
|
||||||
|
scheme: 'bearer',
|
||||||
|
bearerFormat: 'JWT'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
new Elysia({
|
||||||
|
prefix: '/address',
|
||||||
|
detail: {
|
||||||
|
security: [{ bearerAuth: [] }]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Secures all routes under prefix.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Below is a config which is accepted by the `openapi({})`
|
||||||
|
|
||||||
|
### enabled
|
||||||
|
@default true
|
||||||
|
Enable/Disable the plugin
|
||||||
|
|
||||||
|
### documentation
|
||||||
|
OpenAPI documentation information
|
||||||
|
@see https://spec.openapis.org/oas/v3.0.3.html
|
||||||
|
|
||||||
|
### exclude
|
||||||
|
Configuration to exclude paths or methods from documentation
|
||||||
|
|
||||||
|
### exclude.methods
|
||||||
|
List of methods to exclude from documentation
|
||||||
|
|
||||||
|
### exclude.paths
|
||||||
|
List of paths to exclude from documentation
|
||||||
|
|
||||||
|
### exclude.staticFile
|
||||||
|
@default true
|
||||||
|
|
||||||
|
Exclude static file routes from documentation
|
||||||
|
|
||||||
|
### exclude.tags
|
||||||
|
List of tags to exclude from documentation
|
||||||
|
|
||||||
|
### mapJsonSchema
|
||||||
|
A custom mapping function from Standard schema to OpenAPI schema
|
||||||
|
|
||||||
|
### path
|
||||||
|
@default '/openapi'
|
||||||
|
The endpoint to expose OpenAPI documentation frontend
|
||||||
|
|
||||||
|
### provider
|
||||||
|
@default 'scalar'
|
||||||
|
|
||||||
|
OpenAPI documentation frontend between:
|
||||||
|
- Scalar
|
||||||
|
- SwaggerUI
|
||||||
|
- null: disable frontend
|
||||||
167
.agents/skills/elysiajs/plugins/opentelemetry.md
Normal file
167
.agents/skills/elysiajs/plugins/opentelemetry.md
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
# OpenTelemetry Plugin - SKILLS.md
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/opentelemetry
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript
|
||||||
|
import { opentelemetry } from '@elysiajs/opentelemetry'
|
||||||
|
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'
|
||||||
|
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(opentelemetry({
|
||||||
|
spanProcessors: [
|
||||||
|
new BatchSpanProcessor(new OTLPTraceExporter())
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-collects spans from OpenTelemetry-compatible libraries. Parent/child spans applied automatically.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Extends OpenTelemetry SDK params:
|
||||||
|
|
||||||
|
- `autoDetectResources` (true) - Auto-detect from env
|
||||||
|
- `contextManager` (AsyncHooksContextManager) - Custom context
|
||||||
|
- `textMapPropagator` (CompositePropagator) - W3C Trace + Baggage
|
||||||
|
- `metricReader` - For MeterProvider
|
||||||
|
- `views` - Histogram bucket config
|
||||||
|
- `instrumentations` (getNodeAutoInstrumentations()) - Metapackage or individual
|
||||||
|
- `resource` - Custom resource
|
||||||
|
- `resourceDetectors` ([envDetector, processDetector, hostDetector]) - Auto-detect needs `autoDetectResources: true`
|
||||||
|
- `sampler` - Custom sampler (default: sample all)
|
||||||
|
- `serviceName` - Namespace identifier
|
||||||
|
- `spanProcessors` - Array for tracer provider
|
||||||
|
- `traceExporter` - Auto-setup OTLP/http/protobuf with BatchSpanProcessor if not set
|
||||||
|
- `spanLimits` - Tracing params
|
||||||
|
|
||||||
|
### Resource Detectors via Env
|
||||||
|
```bash
|
||||||
|
export OTEL_NODE_RESOURCE_DETECTORS="env,host"
|
||||||
|
# Options: env, host, os, process, serviceinstance, all, none
|
||||||
|
```
|
||||||
|
|
||||||
|
## Export to Backends
|
||||||
|
Example - Axiom:
|
||||||
|
```typescript
|
||||||
|
.use(opentelemetry({
|
||||||
|
spanProcessors: [
|
||||||
|
new BatchSpanProcessor(
|
||||||
|
new OTLPTraceExporter({
|
||||||
|
url: 'https://api.axiom.co/v1/traces',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${Bun.env.AXIOM_TOKEN}`,
|
||||||
|
'X-Axiom-Dataset': Bun.env.AXIOM_DATASET
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
## OpenTelemetry SDK
|
||||||
|
Use SDK normally - runs under Elysia's request span, auto-appears in trace.
|
||||||
|
|
||||||
|
## Record Utility
|
||||||
|
Equivalent to `startActiveSpan` - auto-closes + captures exceptions:
|
||||||
|
```typescript
|
||||||
|
import { record } from '@elysiajs/opentelemetry'
|
||||||
|
|
||||||
|
.get('', () => {
|
||||||
|
return record('database.query', () => {
|
||||||
|
return db.query('SELECT * FROM users')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Label for code shown in trace.
|
||||||
|
|
||||||
|
## Function Naming
|
||||||
|
Elysia reads function names as span names:
|
||||||
|
```typescript
|
||||||
|
// ⚠️ Anonymous span
|
||||||
|
.derive(async ({ cookie: { session } }) => {
|
||||||
|
return { user: await getProfile(session) }
|
||||||
|
})
|
||||||
|
|
||||||
|
// ✅ Named span: "getProfile"
|
||||||
|
.derive(async function getProfile({ cookie: { session } }) {
|
||||||
|
return { user: await getProfile(session) }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## getCurrentSpan
|
||||||
|
Get current span outside handler (via AsyncLocalStorage):
|
||||||
|
```typescript
|
||||||
|
import { getCurrentSpan } from '@elysiajs/opentelemetry'
|
||||||
|
|
||||||
|
function utility() {
|
||||||
|
const span = getCurrentSpan()
|
||||||
|
span.setAttributes({ 'custom.attribute': 'value' })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## setAttributes
|
||||||
|
Sugar for `getCurrentSpan().setAttributes`:
|
||||||
|
```typescript
|
||||||
|
import { setAttributes } from '@elysiajs/opentelemetry'
|
||||||
|
|
||||||
|
function utility() {
|
||||||
|
setAttributes({ 'custom.attribute': 'value' })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Instrumentations (Advanced)
|
||||||
|
SDK must run before importing instrumented module.
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
1. Separate file:
|
||||||
|
```typescript
|
||||||
|
// src/instrumentation.ts
|
||||||
|
import { opentelemetry } from '@elysiajs/opentelemetry'
|
||||||
|
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'
|
||||||
|
|
||||||
|
export const instrumentation = opentelemetry({
|
||||||
|
instrumentations: [new PgInstrumentation()]
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Apply:
|
||||||
|
```typescript
|
||||||
|
// src/index.ts
|
||||||
|
import { instrumentation } from './instrumentation'
|
||||||
|
new Elysia().use(instrumentation).listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Preload:
|
||||||
|
```toml
|
||||||
|
# bunfig.toml
|
||||||
|
preload = ["./src/instrumentation.ts"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production Deployment (Advanced)
|
||||||
|
OpenTelemetry monkey-patches `node_modules`. Exclude instrumented libs from bundling:
|
||||||
|
```bash
|
||||||
|
bun build --compile --external pg --outfile server src/index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Package.json:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"dependencies": { "pg": "^8.15.6" },
|
||||||
|
"devDependencies": {
|
||||||
|
"@elysiajs/opentelemetry": "^1.2.0",
|
||||||
|
"@opentelemetry/instrumentation-pg": "^0.52.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Production install:
|
||||||
|
```bash
|
||||||
|
bun install --production
|
||||||
|
```
|
||||||
|
|
||||||
|
Keeps `node_modules` with instrumented libs at runtime.
|
||||||
71
.agents/skills/elysiajs/plugins/server-timing.md
Normal file
71
.agents/skills/elysiajs/plugins/server-timing.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
# Server Timing Plugin
|
||||||
|
This plugin adds support for auditing performance bottlenecks with Server Timing API
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/server-timing
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { serverTiming } from '@elysiajs/server-timing'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(serverTiming())
|
||||||
|
.get('/', () => 'hello')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Server Timing then will append header 'Server-Timing' with log duration, function name, and detail for each life-cycle function.
|
||||||
|
|
||||||
|
To inspect, open browser developer tools > Network > [Request made through Elysia server] > Timing.
|
||||||
|
|
||||||
|
Now you can effortlessly audit the performance bottleneck of your server.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### enabled
|
||||||
|
@default `NODE_ENV !== 'production'`
|
||||||
|
|
||||||
|
Determine whether or not Server Timing should be enabled
|
||||||
|
|
||||||
|
### allow
|
||||||
|
@default `undefined`
|
||||||
|
|
||||||
|
A condition whether server timing should be log
|
||||||
|
|
||||||
|
### trace
|
||||||
|
@default `undefined`
|
||||||
|
|
||||||
|
Allow Server Timing to log specified life-cycle events:
|
||||||
|
|
||||||
|
Trace accepts objects of the following:
|
||||||
|
- request: capture duration from request
|
||||||
|
- parse: capture duration from parse
|
||||||
|
- transform: capture duration from transform
|
||||||
|
- beforeHandle: capture duration from beforeHandle
|
||||||
|
- handle: capture duration from the handle
|
||||||
|
- afterHandle: capture duration from afterHandle
|
||||||
|
- total: capture total duration from start to finish
|
||||||
|
|
||||||
|
## Pattern
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
## Allow Condition
|
||||||
|
You may disable Server Timing on specific routes via `allow` property
|
||||||
|
|
||||||
|
```ts twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { serverTiming } from '@elysiajs/server-timing'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(
|
||||||
|
serverTiming({
|
||||||
|
allow: ({ request }) => {
|
||||||
|
return new URL(request.url).pathname !== '/no-trace'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
```
|
||||||
84
.agents/skills/elysiajs/plugins/static.md
Normal file
84
.agents/skills/elysiajs/plugins/static.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# Static Plugin
|
||||||
|
This plugin can serve static files/folders for Elysia Server
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/static
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript twoslash
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { staticPlugin } from '@elysiajs/static'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(staticPlugin())
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, the static plugin default folder is `public`, and registered with `/public` prefix.
|
||||||
|
|
||||||
|
Suppose your project structure is:
|
||||||
|
```
|
||||||
|
| - src
|
||||||
|
| - index.ts
|
||||||
|
| - public
|
||||||
|
| - takodachi.png
|
||||||
|
| - nested
|
||||||
|
| - takodachi.png
|
||||||
|
```
|
||||||
|
|
||||||
|
The available path will become:
|
||||||
|
- /public/takodachi.png
|
||||||
|
- /public/nested/takodachi.png
|
||||||
|
|
||||||
|
## Config
|
||||||
|
Below is a config which is accepted by the plugin
|
||||||
|
|
||||||
|
### assets
|
||||||
|
@default `"public"`
|
||||||
|
|
||||||
|
Path to the folder to expose as static
|
||||||
|
|
||||||
|
### prefix
|
||||||
|
@default `"/public"`
|
||||||
|
|
||||||
|
Path prefix to register public files
|
||||||
|
|
||||||
|
### ignorePatterns
|
||||||
|
@default `[]`
|
||||||
|
|
||||||
|
List of files to ignore from serving as static files
|
||||||
|
|
||||||
|
### staticLimit
|
||||||
|
@default `1024`
|
||||||
|
|
||||||
|
By default, the static plugin will register paths to the Router with a static name, if the limits are exceeded, paths will be lazily added to the Router to reduce memory usage.
|
||||||
|
Tradeoff memory with performance.
|
||||||
|
|
||||||
|
### alwaysStatic
|
||||||
|
@default `false`
|
||||||
|
|
||||||
|
If set to true, static files path will be registered to Router skipping the `staticLimits`.
|
||||||
|
|
||||||
|
### headers
|
||||||
|
@default `{}`
|
||||||
|
|
||||||
|
Set response headers of files
|
||||||
|
|
||||||
|
### indexHTML
|
||||||
|
@default `false`
|
||||||
|
|
||||||
|
If set to true, the `index.html` file from the static directory will be served for any request that is matching neither a route nor any existing static file.
|
||||||
|
|
||||||
|
## Pattern
|
||||||
|
Below you can find the common patterns to use the plugin.
|
||||||
|
|
||||||
|
## Single file
|
||||||
|
Suppose you want to return just a single file, you can use `file` instead of using the static plugin
|
||||||
|
```typescript
|
||||||
|
import { Elysia, file } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/file', file('public/takodachi.png'))
|
||||||
|
```
|
||||||
129
.agents/skills/elysiajs/references/bun-fullstack-dev-server.md
Normal file
129
.agents/skills/elysiajs/references/bun-fullstack-dev-server.md
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
# Fullstack Dev Server
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Bun 1.3 Fullstack Dev Server with HMR. React without bundler (no Vite/Webpack).
|
||||||
|
|
||||||
|
Example: [elysia-fullstack-example](https://github.com/saltyaom/elysia-fullstack-example)
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Install + use Elysia Static:
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { staticPlugin } from '@elysiajs/static'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(await staticPlugin()) // await required for HMR hooks
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create `public/index.html` + `public/index.tsx`:
|
||||||
|
```html
|
||||||
|
<!-- public/index.html -->
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Elysia React App</title>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="./index.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// public/index.tsx
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [count, setCount] = useState(0)
|
||||||
|
const increase = () => setCount((c) => c + 1)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h2>{count}</h2>
|
||||||
|
<button onClick={increase}>Increase</button>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = createRoot(document.getElementById('root')!)
|
||||||
|
root.render(<App />)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Enable JSX in `tsconfig.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"jsx": "react-jsx"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Navigate to `http://localhost:3000/public`.
|
||||||
|
|
||||||
|
Frontend + backend in single project. No bundler. Works with HMR, Tailwind, Tanstack Query, Eden Treaty, path alias.
|
||||||
|
|
||||||
|
## Custom Prefix
|
||||||
|
```typescript
|
||||||
|
.use(await staticPlugin({ prefix: '/' }))
|
||||||
|
```
|
||||||
|
|
||||||
|
Serves at `/` instead of `/public`.
|
||||||
|
|
||||||
|
## Tailwind CSS
|
||||||
|
1. Install:
|
||||||
|
```bash
|
||||||
|
bun add tailwindcss@4
|
||||||
|
bun add -d bun-plugin-tailwind
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create `bunfig.toml`:
|
||||||
|
```toml
|
||||||
|
[serve.static]
|
||||||
|
plugins = ["bun-plugin-tailwind"]
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Create `public/global.css`:
|
||||||
|
```css
|
||||||
|
@tailwind base;
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Add to HTML or TS:
|
||||||
|
```html
|
||||||
|
<link rel="stylesheet" href="tailwindcss">
|
||||||
|
```
|
||||||
|
Or:
|
||||||
|
```tsx
|
||||||
|
import './global.css'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Path Alias
|
||||||
|
1. Add to `tsconfig.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@public/*": ["public/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Use:
|
||||||
|
```tsx
|
||||||
|
import '@public/global.css'
|
||||||
|
```
|
||||||
|
|
||||||
|
Works out of box.
|
||||||
|
|
||||||
|
## Production Build
|
||||||
|
```bash
|
||||||
|
bun build --compile --target bun --outfile server src/index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Creates single executable `server`. Include `public` folder when running.
|
||||||
187
.agents/skills/elysiajs/references/cookie.md
Normal file
187
.agents/skills/elysiajs/references/cookie.md
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
# Cookie
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Reactive mutable signal for cookie interaction. Auto-encodes/decodes objects.
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
No get/set - direct value access:
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ cookie: { name } }) => {
|
||||||
|
// Get
|
||||||
|
name.value
|
||||||
|
|
||||||
|
// Set
|
||||||
|
name.value = "New Value"
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-encodes/decodes objects. Just works.
|
||||||
|
|
||||||
|
## Reactivity
|
||||||
|
Signal-like approach. Single source of truth. Auto-sets headers, syncs values.
|
||||||
|
|
||||||
|
Cookie jar = Proxy object. Extract value always `Cookie<unknown>`, never `undefined`. Access via `.value`.
|
||||||
|
|
||||||
|
Iterate over cookie jar → only existing cookies.
|
||||||
|
|
||||||
|
## Cookie Attributes
|
||||||
|
|
||||||
|
### Direct Property Assignment
|
||||||
|
```typescript
|
||||||
|
.get('/', ({ cookie: { name } }) => {
|
||||||
|
// Get
|
||||||
|
name.domain
|
||||||
|
|
||||||
|
// Set
|
||||||
|
name.domain = 'millennium.sh'
|
||||||
|
name.httpOnly = true
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### set - Reset All Properties
|
||||||
|
```typescript
|
||||||
|
.get('/', ({ cookie: { name } }) => {
|
||||||
|
name.set({
|
||||||
|
domain: 'millennium.sh',
|
||||||
|
httpOnly: true
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Overwrites all properties.
|
||||||
|
|
||||||
|
### add - Update Specific Properties
|
||||||
|
Like `set` but only overwrites defined properties.
|
||||||
|
|
||||||
|
## Remove Cookie
|
||||||
|
```typescript
|
||||||
|
.get('/', ({ cookie, cookie: { name } }) => {
|
||||||
|
name.remove()
|
||||||
|
// or
|
||||||
|
delete cookie.name
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cookie Schema
|
||||||
|
Strict validation + type inference with `t.Cookie`:
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ cookie: { name } }) => {
|
||||||
|
name.value = {
|
||||||
|
id: 617,
|
||||||
|
name: 'Summoning 101'
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
cookie: t.Cookie({
|
||||||
|
name: t.Object({
|
||||||
|
id: t.Numeric(),
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Nullable Cookie
|
||||||
|
```typescript
|
||||||
|
cookie: t.Cookie({
|
||||||
|
name: t.Optional(
|
||||||
|
t.Object({
|
||||||
|
id: t.Numeric(),
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cookie Signature
|
||||||
|
Cryptographic hash for verification. Prevents malicious modification.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
new Elysia()
|
||||||
|
.get('/', ({ cookie: { profile } }) => {
|
||||||
|
profile.value = { id: 617, name: 'Summoning 101' }
|
||||||
|
}, {
|
||||||
|
cookie: t.Cookie({
|
||||||
|
profile: t.Object({
|
||||||
|
id: t.Numeric(),
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
}, {
|
||||||
|
secrets: 'Fischl von Luftschloss Narfidort',
|
||||||
|
sign: ['profile']
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-signs/unsigns.
|
||||||
|
|
||||||
|
### Global Config
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
cookie: {
|
||||||
|
secrets: 'Fischl von Luftschloss Narfidort',
|
||||||
|
sign: ['profile']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cookie Rotation
|
||||||
|
Auto-handles secret rotation. Old signature verification + new signature signing.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
cookie: {
|
||||||
|
secrets: ['Vengeance will be mine', 'Fischl von Luftschloss Narfidort']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Array = key rotation (retire old, replace with new).
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
### secrets
|
||||||
|
Secret key for signing/unsigning. Array = key rotation.
|
||||||
|
|
||||||
|
### domain
|
||||||
|
Domain Set-Cookie attribute. Default: none (current domain only).
|
||||||
|
|
||||||
|
### encode
|
||||||
|
Function to encode value. Default: `encodeURIComponent`.
|
||||||
|
|
||||||
|
### expires
|
||||||
|
Date for Expires attribute. Default: none (non-persistent, deleted on browser exit).
|
||||||
|
|
||||||
|
If both `expires` and `maxAge` set, `maxAge` takes precedence (spec-compliant clients).
|
||||||
|
|
||||||
|
### httpOnly (false)
|
||||||
|
HttpOnly attribute. If true, JS can't access via `document.cookie`.
|
||||||
|
|
||||||
|
### maxAge (undefined)
|
||||||
|
Seconds for Max-Age attribute. Rounded down to integer.
|
||||||
|
|
||||||
|
If both `expires` and `maxAge` set, `maxAge` takes precedence (spec-compliant clients).
|
||||||
|
|
||||||
|
### path
|
||||||
|
Path attribute. Default: handler path.
|
||||||
|
|
||||||
|
### priority
|
||||||
|
Priority attribute: `low` | `medium` | `high`. Not fully standardized.
|
||||||
|
|
||||||
|
### sameSite
|
||||||
|
SameSite attribute:
|
||||||
|
- `true` = Strict
|
||||||
|
- `false` = not set
|
||||||
|
- `'lax'` = Lax
|
||||||
|
- `'none'` = None (explicit cross-site)
|
||||||
|
- `'strict'` = Strict
|
||||||
|
|
||||||
|
Not fully standardized.
|
||||||
|
|
||||||
|
### secure
|
||||||
|
Secure attribute. If true, only HTTPS. Clients won't send over HTTP.
|
||||||
413
.agents/skills/elysiajs/references/deployment.md
Normal file
413
.agents/skills/elysiajs/references/deployment.md
Normal file
@@ -0,0 +1,413 @@
|
|||||||
|
# Deployment
|
||||||
|
|
||||||
|
## Production Build
|
||||||
|
|
||||||
|
### Compile to Binary (Recommended)
|
||||||
|
```bash
|
||||||
|
bun build \
|
||||||
|
--compile \
|
||||||
|
--minify-whitespace \
|
||||||
|
--minify-syntax \
|
||||||
|
--target bun \
|
||||||
|
--outfile server \
|
||||||
|
src/index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefits:**
|
||||||
|
- No runtime needed on deployment server
|
||||||
|
- Smaller memory footprint (2-3x reduction)
|
||||||
|
- Faster startup
|
||||||
|
- Single portable executable
|
||||||
|
|
||||||
|
**Run the binary:**
|
||||||
|
```bash
|
||||||
|
./server
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compile to JavaScript
|
||||||
|
```bash
|
||||||
|
bun build \
|
||||||
|
--minify-whitespace \
|
||||||
|
--minify-syntax \
|
||||||
|
--outfile ./dist/index.js \
|
||||||
|
src/index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
**Run:**
|
||||||
|
```bash
|
||||||
|
NODE_ENV=production bun ./dist/index.js
|
||||||
|
```
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
### Basic Dockerfile
|
||||||
|
```dockerfile
|
||||||
|
FROM oven/bun:1 AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Cache dependencies
|
||||||
|
COPY package.json bun.lock ./
|
||||||
|
RUN bun install
|
||||||
|
|
||||||
|
COPY ./src ./src
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
RUN bun build \
|
||||||
|
--compile \
|
||||||
|
--minify-whitespace \
|
||||||
|
--minify-syntax \
|
||||||
|
--outfile server \
|
||||||
|
src/index.ts
|
||||||
|
|
||||||
|
FROM gcr.io/distroless/base
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=build /app/server server
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
CMD ["./server"]
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build and Run
|
||||||
|
```bash
|
||||||
|
docker build -t my-elysia-app .
|
||||||
|
docker run -p 3000:3000 my-elysia-app
|
||||||
|
```
|
||||||
|
|
||||||
|
### With Environment Variables
|
||||||
|
```dockerfile
|
||||||
|
FROM gcr.io/distroless/base
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=build /app/server server
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV DATABASE_URL=""
|
||||||
|
ENV JWT_SECRET=""
|
||||||
|
|
||||||
|
CMD ["./server"]
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cluster Mode (Multiple CPU Cores)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/index.ts
|
||||||
|
import cluster from 'node:cluster'
|
||||||
|
import os from 'node:os'
|
||||||
|
import process from 'node:process'
|
||||||
|
|
||||||
|
if (cluster.isPrimary) {
|
||||||
|
for (let i = 0; i < os.availableParallelism(); i++) {
|
||||||
|
cluster.fork()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await import('./server')
|
||||||
|
console.log(`Worker ${process.pid} started`)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/server.ts
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/', () => 'Hello World!')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
### .env File
|
||||||
|
```env
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=3000
|
||||||
|
DATABASE_URL=postgresql://user:password@localhost:5432/db
|
||||||
|
JWT_SECRET=your-secret-key
|
||||||
|
CORS_ORIGIN=https://example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load in App
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/env', () => ({
|
||||||
|
env: process.env.NODE_ENV,
|
||||||
|
port: process.env.PORT
|
||||||
|
}))
|
||||||
|
.listen(parseInt(process.env.PORT || '3000'))
|
||||||
|
```
|
||||||
|
|
||||||
|
## Platform-Specific Deployments
|
||||||
|
|
||||||
|
### Railway
|
||||||
|
```typescript
|
||||||
|
// Railway assigns random PORT via env variable
|
||||||
|
new Elysia()
|
||||||
|
.get('/', () => 'Hello Railway')
|
||||||
|
.listen(process.env.PORT ?? 3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Vercel
|
||||||
|
```typescript
|
||||||
|
// src/index.ts
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
export default new Elysia()
|
||||||
|
.get('/', () => 'Hello Vercel')
|
||||||
|
|
||||||
|
export const GET = app.fetch
|
||||||
|
export const POST = app.fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
// vercel.json
|
||||||
|
{
|
||||||
|
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||||
|
"bunVersion": "1.x"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Cloudflare Workers
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker'
|
||||||
|
|
||||||
|
export default new Elysia({
|
||||||
|
adapter: CloudflareAdapter
|
||||||
|
})
|
||||||
|
.get('/', () => 'Hello Cloudflare!')
|
||||||
|
.compile()
|
||||||
|
```
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# wrangler.toml
|
||||||
|
name = "elysia-app"
|
||||||
|
main = "src/index.ts"
|
||||||
|
compatibility_date = "2025-06-01"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Node.js Adapter
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { node } from '@elysiajs/node'
|
||||||
|
|
||||||
|
const app = new Elysia({ adapter: node() })
|
||||||
|
.get('/', () => 'Hello Node.js')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Optimization
|
||||||
|
|
||||||
|
### Enable AoT Compilation
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
aot: true // Ahead-of-time compilation
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Use Native Static Response
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
nativeStaticResponse: true
|
||||||
|
})
|
||||||
|
.get('/version', 1) // Optimized for Bun.serve.static
|
||||||
|
```
|
||||||
|
|
||||||
|
### Precompile Routes
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
precompile: true // Compile all routes ahead of time
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Health Checks
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
new Elysia()
|
||||||
|
.get('/health', () => ({
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: Date.now()
|
||||||
|
}))
|
||||||
|
.get('/ready', ({ db }) => {
|
||||||
|
// Check database connection
|
||||||
|
const isDbReady = checkDbConnection()
|
||||||
|
|
||||||
|
if (!isDbReady) {
|
||||||
|
return status(503, { status: 'not ready' })
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'ready' }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Graceful Shutdown
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', () => 'Hello')
|
||||||
|
.listen(3000)
|
||||||
|
|
||||||
|
process.on('SIGTERM', () => {
|
||||||
|
console.log('SIGTERM received, shutting down gracefully')
|
||||||
|
app.stop()
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
console.log('SIGINT received, shutting down gracefully')
|
||||||
|
app.stop()
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
### OpenTelemetry
|
||||||
|
```typescript
|
||||||
|
import { opentelemetry } from '@elysiajs/opentelemetry'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(opentelemetry({
|
||||||
|
serviceName: 'my-service',
|
||||||
|
endpoint: 'http://localhost:4318'
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom Logging
|
||||||
|
```typescript
|
||||||
|
.onRequest(({ request }) => {
|
||||||
|
console.log(`[${new Date().toISOString()}] ${request.method} ${request.url}`)
|
||||||
|
})
|
||||||
|
.onAfterResponse(({ request, set }) => {
|
||||||
|
console.log(`[${new Date().toISOString()}] ${request.method} ${request.url} - ${set.status}`)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## SSL/TLS (HTTPS)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, file } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia({
|
||||||
|
serve: {
|
||||||
|
tls: {
|
||||||
|
cert: file('cert.pem'),
|
||||||
|
key: file('key.pem')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get('/', () => 'Hello HTTPS')
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
1. **Always compile to binary for production**
|
||||||
|
- Reduces memory usage
|
||||||
|
- Smaller deployment size
|
||||||
|
- No runtime needed
|
||||||
|
|
||||||
|
2. **Use environment variables**
|
||||||
|
- Never hardcode secrets
|
||||||
|
- Use different configs per environment
|
||||||
|
|
||||||
|
3. **Enable health checks**
|
||||||
|
- Essential for load balancers
|
||||||
|
- K8s/Docker orchestration
|
||||||
|
|
||||||
|
4. **Implement graceful shutdown**
|
||||||
|
- Handle SIGTERM/SIGINT
|
||||||
|
- Close connections properly
|
||||||
|
|
||||||
|
5. **Use cluster mode**
|
||||||
|
- Utilize all CPU cores
|
||||||
|
- Better performance under load
|
||||||
|
|
||||||
|
6. **Monitor your app**
|
||||||
|
- Use OpenTelemetry
|
||||||
|
- Log requests/responses
|
||||||
|
- Track errors
|
||||||
|
|
||||||
|
## Example Production Setup
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/server.ts
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
import { cors } from '@elysiajs/cors'
|
||||||
|
import { opentelemetry } from '@elysiajs/opentelemetry'
|
||||||
|
|
||||||
|
export const app = new Elysia({
|
||||||
|
aot: true,
|
||||||
|
nativeStaticResponse: true
|
||||||
|
})
|
||||||
|
.use(cors({
|
||||||
|
origin: process.env.CORS_ORIGIN || 'http://localhost:3000'
|
||||||
|
}))
|
||||||
|
.use(opentelemetry({
|
||||||
|
serviceName: 'my-service'
|
||||||
|
}))
|
||||||
|
.get('/health', () => ({ status: 'ok' }))
|
||||||
|
.get('/', () => 'Hello Production')
|
||||||
|
.listen(parseInt(process.env.PORT || '3000'))
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
process.on('SIGTERM', () => {
|
||||||
|
app.stop()
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/index.ts (cluster)
|
||||||
|
import cluster from 'node:cluster'
|
||||||
|
import os from 'node:os'
|
||||||
|
|
||||||
|
if (cluster.isPrimary) {
|
||||||
|
for (let i = 0; i < os.availableParallelism(); i++) {
|
||||||
|
cluster.fork()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await import('./server')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
# Dockerfile
|
||||||
|
FROM oven/bun:1 AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json bun.lock ./
|
||||||
|
RUN bun install
|
||||||
|
|
||||||
|
COPY ./src ./src
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
RUN bun build --compile --outfile server src/index.ts
|
||||||
|
|
||||||
|
FROM gcr.io/distroless/base
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=build /app/server server
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
CMD ["./server"]
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
```
|
||||||
158
.agents/skills/elysiajs/references/eden.md
Normal file
158
.agents/skills/elysiajs/references/eden.md
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
# Eden Treaty
|
||||||
|
e2e type safe RPC client for share type from backend to frontend.
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Type-safe object representation for Elysia server. Auto-completion + error handling.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
```bash
|
||||||
|
bun add @elysiajs/eden
|
||||||
|
bun add -d elysia
|
||||||
|
```
|
||||||
|
|
||||||
|
Export Elysia server type:
|
||||||
|
```typescript
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', () => 'Hi Elysia')
|
||||||
|
.get('/id/:id', ({ params: { id } }) => id)
|
||||||
|
.post('/mirror', ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number(),
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
|
||||||
|
export type App = typeof app
|
||||||
|
```
|
||||||
|
|
||||||
|
Consume on client side:
|
||||||
|
```typescript
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import type { App } from './server'
|
||||||
|
|
||||||
|
const client = treaty<App>('localhost:3000')
|
||||||
|
|
||||||
|
// response: Hi Elysia
|
||||||
|
const { data: index } = await client.get()
|
||||||
|
|
||||||
|
// response: 1895
|
||||||
|
const { data: id } = await client.id({ id: 1895 }).get()
|
||||||
|
|
||||||
|
// response: { id: 1895, name: 'Skadi' }
|
||||||
|
const { data: nendoroid } = await client.mirror.post({
|
||||||
|
id: 1895,
|
||||||
|
name: 'Skadi'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Errors & Fixes
|
||||||
|
- **Strict mode**: Enable in tsconfig
|
||||||
|
- **Version mismatch**: `npm why elysia` - must match server/client
|
||||||
|
- **TypeScript**: Min 5.0
|
||||||
|
- **Method chaining**: Required on server
|
||||||
|
- **Bun types**: `bun add -d @types/bun` if using Bun APIs
|
||||||
|
- **Path alias**: Must resolve same on frontend/backend
|
||||||
|
|
||||||
|
### Monorepo Path Alias
|
||||||
|
Must resolve to same file on frontend/backend
|
||||||
|
|
||||||
|
```json
|
||||||
|
// tsconfig.json at root
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@frontend/*": ["./apps/frontend/src/*"],
|
||||||
|
"@backend/*": ["./apps/backend/src/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Syntax Mapping
|
||||||
|
| Path | Method | Treaty |
|
||||||
|
|----------------|--------|-------------------------------|
|
||||||
|
| / | GET | `.get()` |
|
||||||
|
| /hi | GET | `.hi.get()` |
|
||||||
|
| /deep/nested | POST | `.deep.nested.post()` |
|
||||||
|
| /item/:name | GET | `.item({ name: 'x' }).get()` |
|
||||||
|
|
||||||
|
## Parameters
|
||||||
|
|
||||||
|
### With body (POST/PUT/PATCH/DELETE):
|
||||||
|
```typescript
|
||||||
|
.user.post(
|
||||||
|
{ name: 'Elysia' }, // body
|
||||||
|
{ headers: {}, query: {}, fetch: {} } // optional
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### No body (GET/HEAD):
|
||||||
|
```typescript
|
||||||
|
.hello.get({ headers: {}, query: {}, fetch: {} })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Empty body with query/headers:
|
||||||
|
```typescript
|
||||||
|
.user.post(null, { query: { name: 'Ely' } })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fetch options:
|
||||||
|
```typescript
|
||||||
|
.hello.get({ fetch: { signal: controller.signal } })
|
||||||
|
```
|
||||||
|
|
||||||
|
### File upload:
|
||||||
|
```typescript
|
||||||
|
// Accepts: File | File[] | FileList | Blob
|
||||||
|
.image.post({
|
||||||
|
title: 'Title',
|
||||||
|
image: fileInput.files!
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Response
|
||||||
|
```typescript
|
||||||
|
const { data, error, response, status, headers } = await api.user.post({ name: 'x' })
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
switch (error.status) {
|
||||||
|
case 400: throw error.value
|
||||||
|
default: throw error.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// data unwrapped after error handling
|
||||||
|
return data
|
||||||
|
```
|
||||||
|
|
||||||
|
status >= 300 → `data = null`, `error` has value
|
||||||
|
|
||||||
|
## Stream/SSE
|
||||||
|
Interpreted as `AsyncGenerator`:
|
||||||
|
```typescript
|
||||||
|
const { data, error } = await treaty(app).ok.get()
|
||||||
|
if (error) throw error
|
||||||
|
|
||||||
|
for await (const chunk of data) console.log(chunk)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Utility Types
|
||||||
|
```typescript
|
||||||
|
import { Treaty } from '@elysiajs/eden'
|
||||||
|
|
||||||
|
type UserData = Treaty.Data<typeof api.user.post>
|
||||||
|
type UserError = Treaty.Error<typeof api.user.post>
|
||||||
|
```
|
||||||
|
|
||||||
|
## WebSocket
|
||||||
|
```typescript
|
||||||
|
const chat = api.chat.subscribe()
|
||||||
|
|
||||||
|
chat.subscribe((message) => console.log('got', message))
|
||||||
|
chat.on('open', () => chat.send('hello'))
|
||||||
|
|
||||||
|
// Native access: chat.raw
|
||||||
|
```
|
||||||
|
|
||||||
|
`.subscribe()` accepts same params as `get`/`head`
|
||||||
198
.agents/skills/elysiajs/references/lifecycle.md
Normal file
198
.agents/skills/elysiajs/references/lifecycle.md
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
# Lifecycle
|
||||||
|
|
||||||
|
Instead of a sequential process, Elysia's request handling is divided into multiple stages called lifecycle events.
|
||||||
|
|
||||||
|
It's designed to separate the process into distinct phases based on their responsibility without interfering with each others.
|
||||||
|
|
||||||
|
### List of events in order
|
||||||
|
|
||||||
|
1. **request** - early, global
|
||||||
|
2. **parse** - body parsing
|
||||||
|
3. **transform** / **derive** - mutate context pre validation
|
||||||
|
4. **beforeHandle** / **resolve** - auth/guard logic
|
||||||
|
5. **handler** - your business code
|
||||||
|
6. **afterHandle** - tweak response, set headers
|
||||||
|
7. **mapResponse** - turn anything into a proper `Response`
|
||||||
|
8. **onError** - centralized error handling
|
||||||
|
9. **onAfterResponse** - post response/cleanup tasks
|
||||||
|
|
||||||
|
## Request (`onRequest`)
|
||||||
|
|
||||||
|
Runs first for every incoming request.
|
||||||
|
|
||||||
|
- Ideal for **caching, rate limiting, CORS, adding global headers**.
|
||||||
|
- If the hook returns a value, the whole lifecycle stops and that value becomes the response.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().onRequest(({ ip, set }) => {
|
||||||
|
if (blocked(ip)) return (set.status = 429)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Parse (`onParse`)
|
||||||
|
|
||||||
|
_Body parsing stage._
|
||||||
|
|
||||||
|
- Handles `text/plain`, `application/json`, `multipart/form-data`, `application/x www-form-urlencoded` by default.
|
||||||
|
- Use to add **custom parsers** or support extra `Content Type`s.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().onParse(({ request, contentType }) => {
|
||||||
|
if (contentType === 'application/custom') return request.text()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Transform (`onTransform`)
|
||||||
|
|
||||||
|
_Runs **just before validation**; can mutate the request context._
|
||||||
|
|
||||||
|
- Perfect for **type coercion**, trimming strings, or adding temporary fields that validation will use.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().onTransform(({ params }) => {
|
||||||
|
params.id = Number(params.id)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Derive
|
||||||
|
|
||||||
|
_Runs along with `onTransform` **but before validation**; adds per request values to the context._
|
||||||
|
|
||||||
|
- Useful for extracting info from headers, cookies, query, etc., that you want to reuse in handlers.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().derive(({ headers }) => ({
|
||||||
|
bearer: headers.authorization?.replace(/^Bearer /, '')
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Before Handle (`onBeforeHandle`)
|
||||||
|
|
||||||
|
_Executed after validation, right before the route handler._
|
||||||
|
|
||||||
|
- Great for **auth checks, permission gating, custom pre validation logic**.
|
||||||
|
- Returning a value skips the handler.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().get('/', () => 'hi', {
|
||||||
|
beforeHandle({ cookie, status }) {
|
||||||
|
if (!cookie.session) return status(401)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resolve
|
||||||
|
|
||||||
|
_Like `derive` but runs **after validation** along "Before Handle" (so you can rely on validated data)._
|
||||||
|
|
||||||
|
- Usually placed inside a `guard` because it isn't available as a local hook.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().guard(
|
||||||
|
{ headers: t.Object({ authorization: t.String() }) },
|
||||||
|
(app) =>
|
||||||
|
app
|
||||||
|
.resolve(({ headers }) => ({
|
||||||
|
bearer: headers.authorization.split(' ')[1]
|
||||||
|
}))
|
||||||
|
.get('/', ({ bearer }) => bearer)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## After Handle (`onAfterHandle`)
|
||||||
|
|
||||||
|
_Runs after the handler finishes._
|
||||||
|
|
||||||
|
- Can **modify response headers**, wrap the result in a `Response`, or transform the payload.
|
||||||
|
- Returning a value **replaces** the handler’s result, but the next `afterHandle` hooks still run.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().get('/', () => '<h1>Hello</h1>', {
|
||||||
|
afterHandle({ response, set }) {
|
||||||
|
if (isHtml(response)) {
|
||||||
|
set.headers['content-type'] = 'text/html; charset=utf-8'
|
||||||
|
return new Response(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Map Response (`mapResponse`)
|
||||||
|
|
||||||
|
_Runs right after all `afterHandle` hooks; maps **any** value to a Web standard `Response`._
|
||||||
|
|
||||||
|
- Ideal for **compression, custom content type mapping, streaming**.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().mapResponse(({ responseValue, set }) => {
|
||||||
|
const body =
|
||||||
|
typeof responseValue === 'object'
|
||||||
|
? JSON.stringify(responseValue)
|
||||||
|
: String(responseValue ?? '')
|
||||||
|
|
||||||
|
set.headers['content-encoding'] = 'gzip'
|
||||||
|
return new Response(Bun.gzipSync(new TextEncoder().encode(body)), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type':
|
||||||
|
typeof responseValue === 'object'
|
||||||
|
? 'application/json'
|
||||||
|
: 'text/plain'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## On Error (`onError`)
|
||||||
|
|
||||||
|
_Caught whenever an error bubbles up from any lifecycle stage._
|
||||||
|
|
||||||
|
- Use to **customize error messages**, **handle 404**, **log**, or **retry**.
|
||||||
|
- Must be registered **before** the routes it should protect.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().onError(({ code, status }) => {
|
||||||
|
if (code === 'NOT_FOUND') return status(404, 'â“ Not found')
|
||||||
|
return new Response('Oops', { status: 500 })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## After Response (`onAfterResponse`)
|
||||||
|
|
||||||
|
_Runs **after** the response has been sent to the client._
|
||||||
|
|
||||||
|
- Perfect for **logging, metrics, cleanup**.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia().onAfterResponse(() =>
|
||||||
|
console.log('✅ response sent at', Date.now())
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hook Types
|
||||||
|
|
||||||
|
| Type | Scope | How to add |
|
||||||
|
| -------------------- | --------------------------------- | --------------------------------------------------------- |
|
||||||
|
| **Local Hook** | Single route | Inside route options (`afterHandle`, `beforeHandle`, …) |
|
||||||
|
| **Interceptor Hook** | Whole instance (and later routes) | `.onXxx(cb)` or `.use(plugin)` |
|
||||||
|
|
||||||
|
> **Remember:** Hooks only affect routes **defined after** they are registered, except `onRequest` which is global because it runs before route matching.
|
||||||
83
.agents/skills/elysiajs/references/macro.md
Normal file
83
.agents/skills/elysiajs/references/macro.md
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
# Macro
|
||||||
|
|
||||||
|
Composable Elysia function for controlling lifecycle/schema/context with full type safety. Available in hook after definition control by key-value label.
|
||||||
|
|
||||||
|
## Basic Pattern
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
hi: (word: string) => ({
|
||||||
|
beforeHandle() { console.log(word) }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/', () => 'hi', { hi: 'Elysia' })
|
||||||
|
```
|
||||||
|
|
||||||
|
## Property Shorthand
|
||||||
|
Object → function accepting boolean:
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
// These equivalent:
|
||||||
|
isAuth: { resolve: () => ({ user: 'saltyaom' }) },
|
||||||
|
isAuth(enabled: boolean) { if(enabled) return { resolve() {...} } }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
Return `status`, don't throw:
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
auth: {
|
||||||
|
resolve({ headers }) {
|
||||||
|
if(!headers.authorization) return status(401, 'Unauthorized')
|
||||||
|
return { user: 'SaltyAom' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Resolve - Add Context Props
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
user: (enabled: true) => ({
|
||||||
|
resolve: () => ({ user: 'Pardofelis' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/', ({ user }) => user, { user: true })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Named Macro for Type Inference
|
||||||
|
TypeScript limitation workaround:
|
||||||
|
```typescript
|
||||||
|
.macro('user', { resolve: () => ({ user: 'lilith' }) })
|
||||||
|
.macro('user2', { user: true, resolve: ({ user }) => {} })
|
||||||
|
```
|
||||||
|
|
||||||
|
## Schema
|
||||||
|
Auto-validates, infers types, stacks with other schemas:
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
withFriends: {
|
||||||
|
body: t.Object({ friends: t.Tuple([...]) })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Use named single macro for lifecycle type inference within same macro.
|
||||||
|
|
||||||
|
## Extension
|
||||||
|
Stack macros:
|
||||||
|
```typescript
|
||||||
|
.macro({
|
||||||
|
sartre: { body: t.Object({...}) },
|
||||||
|
fouco: { body: t.Object({...}) },
|
||||||
|
lilith: { fouco: true, sartre: true, body: t.Object({...}) }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deduplication
|
||||||
|
Auto-dedupes by property value. Custom seed:
|
||||||
|
```typescript
|
||||||
|
.macro({ sartre: (role: string) => ({ seed: role, ... }) })
|
||||||
|
```
|
||||||
|
|
||||||
|
Max stack: 16 (prevents infinite loops)
|
||||||
207
.agents/skills/elysiajs/references/plugin.md
Normal file
207
.agents/skills/elysiajs/references/plugin.md
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
# Plugins
|
||||||
|
|
||||||
|
## Plugin = Decoupled Elysia Instance
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const plugin = new Elysia()
|
||||||
|
.decorate('plugin', 'hi')
|
||||||
|
.get('/plugin', ({ plugin }) => plugin)
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(plugin) // inherit properties
|
||||||
|
.get('/', ({ plugin }) => plugin)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inherits**: state, decorate
|
||||||
|
**Does NOT inherit**: lifecycle (isolated by default)
|
||||||
|
|
||||||
|
## Dependency
|
||||||
|
|
||||||
|
Each instance runs independently like microservice. **Must explicitly declare dependencies**.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const auth = new Elysia()
|
||||||
|
.decorate('Auth', Auth)
|
||||||
|
|
||||||
|
// ❌ Missing dependency
|
||||||
|
const main = new Elysia()
|
||||||
|
.get('/', ({ Auth }) => Auth.getProfile())
|
||||||
|
|
||||||
|
// ✅ Declare dependency
|
||||||
|
const main = new Elysia()
|
||||||
|
.use(auth) // required for Auth
|
||||||
|
.get('/', ({ Auth }) => Auth.getProfile())
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deduplication
|
||||||
|
|
||||||
|
**Every plugin re-executes by default**. Use `name` + optional `seed` to deduplicate:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const ip = new Elysia({ name: 'ip' }) // unique identifier
|
||||||
|
.derive({ as: 'global' }, ({ server, request }) => ({
|
||||||
|
ip: server?.requestIP(request)
|
||||||
|
}))
|
||||||
|
|
||||||
|
const router1 = new Elysia().use(ip)
|
||||||
|
const router2 = new Elysia().use(ip)
|
||||||
|
const server = new Elysia().use(router1).use(router2)
|
||||||
|
// `ip` only executes once due to deduplication
|
||||||
|
```
|
||||||
|
|
||||||
|
## Global vs Explicit Dependency
|
||||||
|
|
||||||
|
**Global plugin** (rare, apply everywhere):
|
||||||
|
- Doesn't add types - cors, compress, helmet
|
||||||
|
- Global lifecycle no instance controls - tracing, logging
|
||||||
|
- Examples: OpenAPI docs, OpenTelemetry, logging
|
||||||
|
|
||||||
|
**Explicit dependency** (default, recommended):
|
||||||
|
- Adds types - macro, state, model
|
||||||
|
- Business logic instances interact with - Auth, DB
|
||||||
|
- Examples: state management, ORM, auth, features
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
**Lifecycle isolated by default**. Must specify scope to export.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// ❌ NOT inherited by app
|
||||||
|
const profile = new Elysia()
|
||||||
|
.onBeforeHandle(({ cookie }) => throwIfNotSignIn(cookie))
|
||||||
|
.get('/profile', () => 'Hi')
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(profile)
|
||||||
|
.patch('/rename', ({ body }) => updateProfile(body)) // No sign-in check
|
||||||
|
|
||||||
|
// ✅ Exported to app
|
||||||
|
const profile = new Elysia()
|
||||||
|
.onBeforeHandle({ as: 'global' }, ({ cookie }) => throwIfNotSignIn(cookie))
|
||||||
|
.get('/profile', () => 'Hi')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scope Levels
|
||||||
|
|
||||||
|
1. **local** (default) - current + descendants only
|
||||||
|
2. **scoped** - parent + current + descendants
|
||||||
|
3. **global** - all instances (all parents, current, descendants)
|
||||||
|
|
||||||
|
Example with `.onBeforeHandle({ as: 'local' }, ...)`:
|
||||||
|
|
||||||
|
| type | child | current | parent | main |
|
||||||
|
|------|-------|---------|--------|------|
|
||||||
|
| local | ✅ | ✅ | ❌ | ❌ |
|
||||||
|
| scoped | ✅ | ✅ | ✅ | ❌ |
|
||||||
|
| global | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Instance factory with config
|
||||||
|
const version = (v = 1) => new Elysia()
|
||||||
|
.get('/version', v)
|
||||||
|
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(version(1))
|
||||||
|
```
|
||||||
|
|
||||||
|
## Functional Callback (not recommended)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Harder to handle scope/encapsulation
|
||||||
|
const plugin = (app: Elysia) => app
|
||||||
|
.state('counter', 0)
|
||||||
|
.get('/plugin', () => 'Hi')
|
||||||
|
|
||||||
|
// Prefer new instance (better type inference, no perf diff)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guard (Apply to Multiple Routes)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.guard(
|
||||||
|
{ body: t.Object({ username: t.String(), password: t.String() }) },
|
||||||
|
(app) =>
|
||||||
|
app.post('/sign-up', ({ body }) => signUp(body))
|
||||||
|
.post('/sign-in', ({ body }) => signIn(body))
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Grouped guard** (merge group + guard):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.group(
|
||||||
|
'/v1',
|
||||||
|
{ body: t.Literal('Rikuhachima Aru') }, // guard here
|
||||||
|
(app) => app.post('/student', ({ body }) => body)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scope Casting
|
||||||
|
|
||||||
|
**3 methods to apply hook to parent**:
|
||||||
|
|
||||||
|
1. **Inline as** (single hook):
|
||||||
|
```ts
|
||||||
|
.derive({ as: 'scoped' }, () => ({ hi: 'ok' }))
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Guard as** (multiple hooks, no derive/resolve):
|
||||||
|
```ts
|
||||||
|
.guard({
|
||||||
|
as: 'scoped',
|
||||||
|
response: t.String(),
|
||||||
|
beforeHandle() { console.log('ok') }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Instance as** (all hooks + schema):
|
||||||
|
```ts
|
||||||
|
const plugin = new Elysia()
|
||||||
|
.derive(() => ({ hi: 'ok' }))
|
||||||
|
.get('/child', ({ hi }) => hi)
|
||||||
|
.as('scoped') // lift scope up
|
||||||
|
```
|
||||||
|
|
||||||
|
`.as()` lifts scope: local → scoped → global
|
||||||
|
|
||||||
|
## Lazy Load
|
||||||
|
|
||||||
|
**Deferred module** (async plugin, non-blocking startup):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// plugin.ts
|
||||||
|
export const loadStatic = async (app: Elysia) => {
|
||||||
|
const files = await loadAllFiles()
|
||||||
|
files.forEach((asset) => app.get(asset, file(asset)))
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
// main.ts
|
||||||
|
const app = new Elysia().use(loadStatic)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Lazy-load module** (dynamic import):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const app = new Elysia()
|
||||||
|
.use(import('./plugin')) // loaded after startup
|
||||||
|
```
|
||||||
|
|
||||||
|
**Testing** (wait for modules):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
await app.modules // ensure all deferred/lazy modules loaded
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
[Inference] Based on docs patterns:
|
||||||
|
- Use inline values for static resources (performance optimization)
|
||||||
|
- Group routes by prefix for organization
|
||||||
|
- Extend context minimally (separation of concerns)
|
||||||
|
- Use `status()` over `set.status` for type safety
|
||||||
|
- Prefer `resolve()` over `derive()` when type integrity matters
|
||||||
|
- Plugins isolated by default (must declare scope explicitly)
|
||||||
|
- Use `name` for deduplication when plugin used multiple times
|
||||||
|
- Prefer explicit dependency over global (better modularity/tracking)
|
||||||
331
.agents/skills/elysiajs/references/route.md
Normal file
331
.agents/skills/elysiajs/references/route.md
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
# ElysiaJS: Routing, Handlers & Context
|
||||||
|
|
||||||
|
## Routing
|
||||||
|
|
||||||
|
### Path Types
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.get('/static', 'static path') // exact match
|
||||||
|
.get('/id/:id', 'dynamic path') // captures segment
|
||||||
|
.get('/id/*', 'wildcard path') // captures rest
|
||||||
|
```
|
||||||
|
|
||||||
|
**Path Priority**: static > dynamic > wildcard
|
||||||
|
|
||||||
|
### Dynamic Paths
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.get('/id/:id', ({ params: { id } }) => id)
|
||||||
|
.get('/id/:id/:name', ({ params: { id, name } }) => id + ' ' + name)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Optional params**: `.get('/id/:id?', ...)`
|
||||||
|
|
||||||
|
### HTTP Verbs
|
||||||
|
|
||||||
|
- `.get()` - retrieve data
|
||||||
|
- `.post()` - submit/create
|
||||||
|
- `.put()` - replace
|
||||||
|
- `.patch()` - partial update
|
||||||
|
- `.delete()` - remove
|
||||||
|
- `.all()` - any method
|
||||||
|
- `.route(method, path, handler)` - custom verb
|
||||||
|
|
||||||
|
### Grouping Routes
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.group('/user', { body: t.Literal('auth') }, (app) =>
|
||||||
|
app.post('/sign-in', ...)
|
||||||
|
.post('/sign-up', ...)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Or use prefix in constructor
|
||||||
|
new Elysia({ prefix: '/user' })
|
||||||
|
.post('/sign-in', ...)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handlers
|
||||||
|
|
||||||
|
### Handler = function accepting HTTP request, returning response
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Inline value (compiled ahead, optimized)
|
||||||
|
.get('/', 'Hello Elysia')
|
||||||
|
.get('/video', file('video.mp4'))
|
||||||
|
|
||||||
|
// Function handler
|
||||||
|
.get('/', () => 'hello')
|
||||||
|
.get('/', ({ params, query, body }) => {...})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Context Properties
|
||||||
|
|
||||||
|
- `body` - HTTP message/form/file
|
||||||
|
- `query` - query string as object
|
||||||
|
- `params` - path parameters
|
||||||
|
- `headers` - HTTP headers
|
||||||
|
- `cookie` - mutable signal for cookies
|
||||||
|
- `store` - global mutable state
|
||||||
|
- `request` - Web Standard Request
|
||||||
|
- `server` - Bun server instance
|
||||||
|
- `path` - request pathname
|
||||||
|
|
||||||
|
### Context Utilities
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { redirect, form } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia().get('/', ({ status, set, form }) => {
|
||||||
|
// Status code (type-safe)
|
||||||
|
status(418, "I'm a teapot")
|
||||||
|
|
||||||
|
// Set response props
|
||||||
|
set.headers['x-custom'] = 'value'
|
||||||
|
set.status = 418 // legacy, no type inference
|
||||||
|
|
||||||
|
// Redirect
|
||||||
|
return redirect('https://...', 302)
|
||||||
|
|
||||||
|
// Cookies (mutable signal, no get/set)
|
||||||
|
cookie.name.value // get
|
||||||
|
cookie.name.value = 'new' // set
|
||||||
|
|
||||||
|
// FormData response
|
||||||
|
return form({ name: 'Party', images: [file('a.jpg')] })
|
||||||
|
|
||||||
|
// Single file
|
||||||
|
return file('document.pdf')
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Streaming
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.get('/stream', function* () {
|
||||||
|
yield 1
|
||||||
|
yield 2
|
||||||
|
yield 3
|
||||||
|
})
|
||||||
|
// Server-Sent Events
|
||||||
|
.get('/sse', function* () {
|
||||||
|
yield sse('hello')
|
||||||
|
yield sse({ event: 'msg', data: {...} })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: Headers only settable before first yield
|
||||||
|
|
||||||
|
**Conditional stream**: returning without yield converts to normal response
|
||||||
|
|
||||||
|
## Context Extension
|
||||||
|
|
||||||
|
[Inference] Extend when property is:
|
||||||
|
|
||||||
|
- Global mutable (use `state`)
|
||||||
|
- Request/response related (use `decorate`)
|
||||||
|
- Derived from existing props (use `derive`/`resolve`)
|
||||||
|
|
||||||
|
### state() - Global Mutable
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
`.state('version', 1)
|
||||||
|
.get('/', ({ store: { version } }) => version)
|
||||||
|
// Multiple
|
||||||
|
.state({ counter: 0, visits: 0 })
|
||||||
|
|
||||||
|
// Remap (create new from existing)
|
||||||
|
.state(({ version, ...store }) => ({
|
||||||
|
...store,
|
||||||
|
apiVersion: version
|
||||||
|
}))
|
||||||
|
````
|
||||||
|
|
||||||
|
**Gotcha**: Use reference not value
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
// ✅ Correct
|
||||||
|
.get('/', ({ store }) => store.counter++)
|
||||||
|
|
||||||
|
// ❌ Wrong - loses reference
|
||||||
|
.get('/', ({ store: { counter } }) => counter++)
|
||||||
|
```
|
||||||
|
|
||||||
|
### decorate() - Additional Context Props
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.decorate('logger', new Logger())
|
||||||
|
.get('/', ({ logger }) => logger.log('hi'))
|
||||||
|
|
||||||
|
// Multiple
|
||||||
|
.decorate({ logger: new Logger(), db: connection })
|
||||||
|
```
|
||||||
|
|
||||||
|
**When**: constant/readonly values, classes with internal state, singletons
|
||||||
|
|
||||||
|
### derive() - Create from Existing (Transform Lifecycle)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.derive(({ headers }) => ({
|
||||||
|
bearer: headers.authorization?.startsWith('Bearer ')
|
||||||
|
? headers.authorization.slice(7)
|
||||||
|
: null
|
||||||
|
}))
|
||||||
|
.get('/', ({ bearer }) => bearer)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Timing**: runs at transform (before validation)
|
||||||
|
**Type safety**: request props typed as `unknown`
|
||||||
|
|
||||||
|
### resolve() - Type-Safe Derive (beforeHandle Lifecycle)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.guard({
|
||||||
|
headers: t.Object({
|
||||||
|
bearer: t.String({ pattern: '^Bearer .+$' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.resolve(({ headers }) => ({
|
||||||
|
bearer: headers.bearer.slice(7) // typed correctly
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Timing**: runs at beforeHandle (after validation)
|
||||||
|
**Type safety**: request props fully typed
|
||||||
|
|
||||||
|
### Error from derive/resolve
|
||||||
|
|
||||||
|
```ts
|
||||||
|
new Elysia()
|
||||||
|
.derive(({ headers, status }) => {
|
||||||
|
if (!headers.authorization) return status(400)
|
||||||
|
return { bearer: ... }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns early if error returned
|
||||||
|
|
||||||
|
## Patterns
|
||||||
|
|
||||||
|
### Affix (Bulk Remap)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const plugin = new Elysia({ name: 'setup' }).decorate({
|
||||||
|
argon: 'a',
|
||||||
|
boron: 'b'
|
||||||
|
})
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.use(plugin)
|
||||||
|
.prefix('decorator', 'setup') // setupArgon, setupBoron
|
||||||
|
.prefix('all', 'setup') // remap everything
|
||||||
|
```
|
||||||
|
|
||||||
|
### Assignment Patterns
|
||||||
|
|
||||||
|
1. **key-value**: `.state('key', value)`
|
||||||
|
2. **object**: `.state({ k1: v1, k2: v2 })`
|
||||||
|
3. **remap**: `.state(({old}) => ({new}))`
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const app = new Elysia().get('/', 'hi')
|
||||||
|
|
||||||
|
// Programmatic test
|
||||||
|
app.handle(new Request('http://localhost/'))
|
||||||
|
```
|
||||||
|
|
||||||
|
## To Throw or Return
|
||||||
|
|
||||||
|
Most of an error handling in Elysia can be done by throwing an error and will be handle in `onError`.
|
||||||
|
|
||||||
|
But for `status` it can be a little bit confusing, since it can be used both as a return value or throw an error.
|
||||||
|
|
||||||
|
It could either be **return** or **throw** based on your specific needs.
|
||||||
|
|
||||||
|
- If an `status` is **throw**, it will be caught by `onError` middleware.
|
||||||
|
- If an `status` is **return**, it will be **NOT** caught by `onError` middleware.
|
||||||
|
|
||||||
|
See the following code:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, file } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.onError(({ code, error, path }) => {
|
||||||
|
if (code === 418) return 'caught'
|
||||||
|
})
|
||||||
|
.get('/throw', ({ status }) => {
|
||||||
|
// This will be caught by onError
|
||||||
|
throw status(418)
|
||||||
|
})
|
||||||
|
.get('/return', ({ status }) => {
|
||||||
|
// This will NOT be caught by onError
|
||||||
|
return status(418)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## To Throw or Return
|
||||||
|
|
||||||
|
Elysia provide a `status` function for returning HTTP status code, prefers over `set.status`.
|
||||||
|
|
||||||
|
`status` can be import from Elysia but preferably extract from route handler Context for type safety.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { Elysia, status } from 'elysia'
|
||||||
|
|
||||||
|
function doThing() {
|
||||||
|
if (Math.random() > 0.33) return status(418, "I'm a teapot")
|
||||||
|
}
|
||||||
|
|
||||||
|
new Elysia().get('/', ({ status }) => {
|
||||||
|
if (Math.random() > 0.33) return status(418)
|
||||||
|
|
||||||
|
return 'ok'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Error Handling in Elysia can be done by throwing an error and will be handle in `onError`.
|
||||||
|
|
||||||
|
Status could either be **return** or **throw** based on your specific needs.
|
||||||
|
|
||||||
|
- If an `status` is **throw**, it will be caught by `onError` middleware.
|
||||||
|
- If an `status` is **return**, it will be **NOT** caught by `onError` middleware.
|
||||||
|
|
||||||
|
See the following code:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, file } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.onError(({ code, error, path }) => {
|
||||||
|
if (code === 418) return 'caught'
|
||||||
|
})
|
||||||
|
.get('/throw', ({ status }) => {
|
||||||
|
// This will be caught by onError
|
||||||
|
throw status(418)
|
||||||
|
})
|
||||||
|
.get('/return', ({ status }) => {
|
||||||
|
// This will NOT be caught by onError
|
||||||
|
return status(418)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
[Inference] Based on docs patterns:
|
||||||
|
|
||||||
|
- Use inline values for static resources (performance optimization)
|
||||||
|
- Group routes by prefix for organization
|
||||||
|
- Extend context minimally (separation of concerns)
|
||||||
|
- Use `status()` over `set.status` for type safety
|
||||||
|
- Prefer `resolve()` over `derive()` when type integrity matters
|
||||||
385
.agents/skills/elysiajs/references/testing.md
Normal file
385
.agents/skills/elysiajs/references/testing.md
Normal file
@@ -0,0 +1,385 @@
|
|||||||
|
# Unit Testing
|
||||||
|
|
||||||
|
## Basic Test Setup
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
```bash
|
||||||
|
bun add -d @elysiajs/eden
|
||||||
|
```
|
||||||
|
|
||||||
|
### Basic Test
|
||||||
|
```typescript
|
||||||
|
// test/app.test.ts
|
||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
describe('Elysia App', () => {
|
||||||
|
it('should return hello world', async () => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/', () => 'Hello World')
|
||||||
|
|
||||||
|
const res = await app.handle(
|
||||||
|
new Request('http://localhost/')
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.text()).toBe('Hello World')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Routes
|
||||||
|
|
||||||
|
### GET Request
|
||||||
|
```typescript
|
||||||
|
it('should get user by id', async () => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/user/:id', ({ params: { id } }) => ({
|
||||||
|
id,
|
||||||
|
name: 'John Doe'
|
||||||
|
}))
|
||||||
|
|
||||||
|
const res = await app.handle(
|
||||||
|
new Request('http://localhost/user/123')
|
||||||
|
)
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(data).toEqual({
|
||||||
|
id: '123',
|
||||||
|
name: 'John Doe'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### POST Request
|
||||||
|
```typescript
|
||||||
|
it('should create user', async () => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.post('/user', ({ body }) => body)
|
||||||
|
|
||||||
|
const res = await app.handle(
|
||||||
|
new Request('http://localhost/user', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: 'Jane Doe',
|
||||||
|
email: 'jane@example.com'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(data.name).toBe('Jane Doe')
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Module/Plugin
|
||||||
|
|
||||||
|
### Module Structure
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── modules/
|
||||||
|
│ └── auth/
|
||||||
|
│ ├── index.ts # Elysia instance
|
||||||
|
│ ├── service.ts
|
||||||
|
│ └── model.ts
|
||||||
|
└── index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Auth Module
|
||||||
|
```typescript
|
||||||
|
// src/modules/auth/index.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
export const authModule = new Elysia({ prefix: '/auth' })
|
||||||
|
.post('/login', ({ body, cookie: { session } }) => {
|
||||||
|
if (body.username === 'admin' && body.password === 'password') {
|
||||||
|
session.value = 'valid-session'
|
||||||
|
return { success: true }
|
||||||
|
}
|
||||||
|
return { success: false }
|
||||||
|
}, {
|
||||||
|
body: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/profile', ({ cookie: { session }, status }) => {
|
||||||
|
if (!session.value) {
|
||||||
|
return status(401, { error: 'Unauthorized' })
|
||||||
|
}
|
||||||
|
return { username: 'admin' }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Auth Module Test
|
||||||
|
```typescript
|
||||||
|
// test/auth.test.ts
|
||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import { authModule } from '../src/modules/auth'
|
||||||
|
|
||||||
|
describe('Auth Module', () => {
|
||||||
|
it('should login successfully', async () => {
|
||||||
|
const res = await authModule.handle(
|
||||||
|
new Request('http://localhost/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: 'admin',
|
||||||
|
password: 'password'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(data.success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should reject invalid credentials', async () => {
|
||||||
|
const res = await authModule.handle(
|
||||||
|
new Request('http://localhost/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: 'wrong',
|
||||||
|
password: 'wrong'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
expect(data.success).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return 401 for unauthenticated profile request', async () => {
|
||||||
|
const res = await authModule.handle(
|
||||||
|
new Request('http://localhost/auth/profile')
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.status).toBe(401)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Eden Treaty Testing
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
```typescript
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import { app } from '../src/modules/auth'
|
||||||
|
|
||||||
|
const api = treaty(app)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Eden Tests
|
||||||
|
```typescript
|
||||||
|
describe('Auth Module with Eden', () => {
|
||||||
|
it('should login with Eden', async () => {
|
||||||
|
const { data, error } = await api.auth.login.post({
|
||||||
|
username: 'admin',
|
||||||
|
password: 'password'
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(error).toBeNull()
|
||||||
|
expect(data?.success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should get profile with Eden', async () => {
|
||||||
|
// First login
|
||||||
|
await api.auth.login.post({
|
||||||
|
username: 'admin',
|
||||||
|
password: 'password'
|
||||||
|
})
|
||||||
|
|
||||||
|
// Then get profile
|
||||||
|
const { data, error } = await api.auth.profile.get()
|
||||||
|
|
||||||
|
expect(error).toBeNull()
|
||||||
|
expect(data?.username).toBe('admin')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Mocking Dependencies
|
||||||
|
|
||||||
|
### With Decorators
|
||||||
|
```typescript
|
||||||
|
// app.ts
|
||||||
|
export const app = new Elysia()
|
||||||
|
.decorate('db', realDatabase)
|
||||||
|
.get('/users', ({ db }) => db.getUsers())
|
||||||
|
|
||||||
|
// test
|
||||||
|
import { app } from '../src/app'
|
||||||
|
|
||||||
|
describe('App with mocked DB', () => {
|
||||||
|
it('should use mock database', async () => {
|
||||||
|
const mockDb = {
|
||||||
|
getUsers: () => [{ id: 1, name: 'Test User' }]
|
||||||
|
}
|
||||||
|
|
||||||
|
const testApp = app.decorate('db', mockDb)
|
||||||
|
|
||||||
|
const res = await testApp.handle(
|
||||||
|
new Request('http://localhost/users')
|
||||||
|
)
|
||||||
|
|
||||||
|
const data = await res.json()
|
||||||
|
expect(data).toEqual([{ id: 1, name: 'Test User' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing with Headers
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
it('should require authorization', async () => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.get('/protected', ({ headers, status }) => {
|
||||||
|
if (!headers.authorization) {
|
||||||
|
return status(401)
|
||||||
|
}
|
||||||
|
return { data: 'secret' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await app.handle(
|
||||||
|
new Request('http://localhost/protected', {
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer token123'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Validation
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
it('should validate request body', async () => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.post('/user', ({ body }) => body, {
|
||||||
|
body: t.Object({
|
||||||
|
name: t.String(),
|
||||||
|
age: t.Number({ minimum: 0 })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Valid request
|
||||||
|
const validRes = await app.handle(
|
||||||
|
new Request('http://localhost/user', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: 'John',
|
||||||
|
age: 25
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(validRes.status).toBe(200)
|
||||||
|
|
||||||
|
// Invalid request (negative age)
|
||||||
|
const invalidRes = await app.handle(
|
||||||
|
new Request('http://localhost/user', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: 'John',
|
||||||
|
age: -5
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(invalidRes.status).toBe(400)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing WebSocket
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
it('should handle websocket connection', (done) => {
|
||||||
|
const app = new Elysia()
|
||||||
|
.ws('/chat', {
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send('Echo: ' + message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const ws = new WebSocket('ws://localhost:3000/chat')
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
ws.send('Hello')
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
expect(event.data).toBe('Echo: Hello')
|
||||||
|
ws.close()
|
||||||
|
done()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Complete Example
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/modules/auth/index.ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
export const authModule = new Elysia({ prefix: '/auth' })
|
||||||
|
.post('/login', ({ body, cookie: { session } }) => {
|
||||||
|
if (body.username === 'admin' && body.password === 'password') {
|
||||||
|
session.value = 'valid-session'
|
||||||
|
return { success: true }
|
||||||
|
}
|
||||||
|
return { success: false }
|
||||||
|
}, {
|
||||||
|
body: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/profile', ({ cookie: { session }, status }) => {
|
||||||
|
if (!session.value) {
|
||||||
|
return status(401)
|
||||||
|
}
|
||||||
|
return { username: 'admin' }
|
||||||
|
})
|
||||||
|
|
||||||
|
// test/auth.test.ts
|
||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import { authModule } from '../src/modules/auth'
|
||||||
|
|
||||||
|
const api = treaty(authModule)
|
||||||
|
|
||||||
|
describe('Auth Module', () => {
|
||||||
|
it('should login successfully', async () => {
|
||||||
|
const { data, error } = await api.auth.login.post({
|
||||||
|
username: 'admin',
|
||||||
|
password: 'password'
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(error).toBeNull()
|
||||||
|
expect(data?.success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return 401 for unauthorized access', async () => {
|
||||||
|
const { error } = await api.auth.profile.get()
|
||||||
|
|
||||||
|
expect(error?.status).toBe(401)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
491
.agents/skills/elysiajs/references/validation.md
Normal file
491
.agents/skills/elysiajs/references/validation.md
Normal file
@@ -0,0 +1,491 @@
|
|||||||
|
# Validation Schema - SKILLS.md
|
||||||
|
|
||||||
|
## What It Is
|
||||||
|
Runtime validation + type inference + OpenAPI schema from single source. TypeBox-based with Standard Schema support.
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/id/:id', ({ params: { id } }) => id, {
|
||||||
|
params: t.Object({ id: t.Number({ minimum: 1 }) }),
|
||||||
|
response: {
|
||||||
|
200: t.Number(),
|
||||||
|
404: t.Literal('Not Found')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Schema Types
|
||||||
|
Third parameter of HTTP method:
|
||||||
|
- **body** - HTTP message
|
||||||
|
- **query** - URL query params
|
||||||
|
- **params** - Path params
|
||||||
|
- **headers** - Request headers
|
||||||
|
- **cookie** - Request cookies
|
||||||
|
- **response** - Response (per status)
|
||||||
|
|
||||||
|
## Standard Schema Support
|
||||||
|
Use Zod, Valibot, ArkType, Effect, Yup, Joi:
|
||||||
|
```typescript
|
||||||
|
import { z } from 'zod'
|
||||||
|
import * as v from 'valibot'
|
||||||
|
|
||||||
|
.get('/', ({ params, query }) => params.id, {
|
||||||
|
params: z.object({ id: z.coerce.number() }),
|
||||||
|
query: v.object({ name: v.literal('Lilith') })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Mix validators in same handler.
|
||||||
|
|
||||||
|
## Body
|
||||||
|
```typescript
|
||||||
|
body: t.Object({ name: t.String() })
|
||||||
|
```
|
||||||
|
|
||||||
|
GET/HEAD: body-parser disabled by default (RFC2616).
|
||||||
|
|
||||||
|
### File Upload
|
||||||
|
```typescript
|
||||||
|
body: t.Object({
|
||||||
|
file: t.File({ format: 'image/*' }),
|
||||||
|
multipleFiles: t.Files()
|
||||||
|
})
|
||||||
|
// Auto-assumes multipart/form-data
|
||||||
|
```
|
||||||
|
|
||||||
|
### File (Standard Schema)
|
||||||
|
```typescript
|
||||||
|
import { fileType } from 'elysia'
|
||||||
|
|
||||||
|
body: z.object({
|
||||||
|
file: z.file().refine((file) => fileType(file, 'image/jpeg'))
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `fileType` for security (validates magic number, not just MIME).
|
||||||
|
|
||||||
|
## Query
|
||||||
|
```typescript
|
||||||
|
query: t.Object({ name: t.String() })
|
||||||
|
// /?name=Elysia
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-coerces to specified type.
|
||||||
|
|
||||||
|
### Arrays
|
||||||
|
```typescript
|
||||||
|
query: t.Object({ name: t.Array(t.String()) })
|
||||||
|
```
|
||||||
|
|
||||||
|
Formats supported:
|
||||||
|
- **nuqs**: `?name=a,b,c` (comma delimiter)
|
||||||
|
- **HTML form**: `?name=a&name=b&name=c` (multiple keys)
|
||||||
|
|
||||||
|
## Params
|
||||||
|
```typescript
|
||||||
|
params: t.Object({ id: t.Number() })
|
||||||
|
// /id/1
|
||||||
|
```
|
||||||
|
|
||||||
|
Auto-inferred as string if schema not provided.
|
||||||
|
|
||||||
|
## Headers
|
||||||
|
```typescript
|
||||||
|
headers: t.Object({ authorization: t.String() })
|
||||||
|
```
|
||||||
|
|
||||||
|
`additionalProperties: true` by default. Always lowercase keys.
|
||||||
|
|
||||||
|
## Cookie
|
||||||
|
```typescript
|
||||||
|
cookie: t.Cookie({
|
||||||
|
name: t.String()
|
||||||
|
}, {
|
||||||
|
secure: true,
|
||||||
|
httpOnly: true
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Or use `t.Object`. `additionalProperties: true` by default.
|
||||||
|
|
||||||
|
## Response
|
||||||
|
```typescript
|
||||||
|
response: t.Object({ name: t.String() })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Per Status
|
||||||
|
```typescript
|
||||||
|
response: {
|
||||||
|
200: t.Object({ name: t.String() }),
|
||||||
|
400: t.Object({ error: t.String() })
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
### Inline Error Property
|
||||||
|
```typescript
|
||||||
|
body: t.Object({
|
||||||
|
x: t.Number({ error: 'x must be number' })
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Or function:
|
||||||
|
```typescript
|
||||||
|
x: t.Number({
|
||||||
|
error({ errors, type, validation, value }) {
|
||||||
|
return 'Expected x to be number'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### onError Hook
|
||||||
|
```typescript
|
||||||
|
.onError(({ code, error }) => {
|
||||||
|
if (code === 'VALIDATION')
|
||||||
|
return error.message // or error.all[0].message
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`error.all` - list all error causes. `error.all.find(x => x.path === '/name')` - find specific field.
|
||||||
|
|
||||||
|
## Reference Models
|
||||||
|
Name + reuse models:
|
||||||
|
```typescript
|
||||||
|
.model({
|
||||||
|
sign: t.Object({
|
||||||
|
username: t.String(),
|
||||||
|
password: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.post('/sign-in', ({ body }) => body, {
|
||||||
|
body: 'sign',
|
||||||
|
response: 'sign'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Extract to plugin:
|
||||||
|
```typescript
|
||||||
|
// auth.model.ts
|
||||||
|
export const authModel = new Elysia().model({ sign: t.Object({...}) })
|
||||||
|
|
||||||
|
// main.ts
|
||||||
|
new Elysia().use(authModel).post('/', ..., { body: 'sign' })
|
||||||
|
```
|
||||||
|
|
||||||
|
### Naming Convention
|
||||||
|
Prevent duplicates with namespaces:
|
||||||
|
```typescript
|
||||||
|
.model({
|
||||||
|
'auth.admin': t.Object({...}),
|
||||||
|
'auth.user': t.Object({...})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Or use `prefix` / `suffix` to rename models in current instance
|
||||||
|
```typescript
|
||||||
|
.model({ sign: t.Object({...}) })
|
||||||
|
.prefix('model', 'auth')
|
||||||
|
.post('/', () => '', {
|
||||||
|
body: 'auth.User'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Models with `prefix` will be capitalized.
|
||||||
|
|
||||||
|
## TypeScript Types
|
||||||
|
```typescript
|
||||||
|
const MyType = t.Object({ hello: t.Literal('Elysia') })
|
||||||
|
type MyType = typeof MyType.static
|
||||||
|
```
|
||||||
|
|
||||||
|
Single schema → runtime validation + coercion + TypeScript type + OpenAPI.
|
||||||
|
|
||||||
|
## Guard
|
||||||
|
Apply schema to multiple handlers. Affects all handlers after definition.
|
||||||
|
|
||||||
|
### Basic Usage
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.get('/none', ({ query }) => 'hi')
|
||||||
|
.guard({
|
||||||
|
query: t.Object({
|
||||||
|
name: t.String()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.get('/query', ({ query }) => query)
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
Ensures `query.name` string required for all handlers after guard.
|
||||||
|
|
||||||
|
### Behavior
|
||||||
|
| Path | Response |
|
||||||
|
|---------------|----------|
|
||||||
|
| /none | hi |
|
||||||
|
| /none?name=a | hi |
|
||||||
|
| /query | error |
|
||||||
|
| /query?name=a | a |
|
||||||
|
|
||||||
|
### Precedence
|
||||||
|
- Multiple global schemas: latest wins
|
||||||
|
- Global vs local: local wins
|
||||||
|
|
||||||
|
### Schema Types
|
||||||
|
|
||||||
|
1. override (default)
|
||||||
|
Latest schema overrides collided schema.
|
||||||
|
```typescript
|
||||||
|
.guard({ query: t.Object({ name: t.String() }) })
|
||||||
|
.guard({ query: t.Object({ id: t.Number() }) })
|
||||||
|
// Only id required, name overridden
|
||||||
|
```
|
||||||
|
|
||||||
|
2. standalone
|
||||||
|
Both schemas run independently. Both validated.
|
||||||
|
```typescript
|
||||||
|
.guard({ query: t.Object({ name: t.String() }) }, { type: 'standalone' })
|
||||||
|
.guard({ query: t.Object({ id: t.Number() }) }, { type: 'standalone' })
|
||||||
|
// Both name AND id required
|
||||||
|
```
|
||||||
|
|
||||||
|
# Typebox Validation (Elysia.t)
|
||||||
|
|
||||||
|
Elysia.t = TypeBox with server-side pre-configuration + HTTP-specific types
|
||||||
|
|
||||||
|
**TypeBox API mirrors TypeScript syntax** but provides runtime validation
|
||||||
|
|
||||||
|
## Basic Types
|
||||||
|
|
||||||
|
| TypeBox | TypeScript | Example Value |
|
||||||
|
|---------|------------|---------------|
|
||||||
|
| `t.String()` | `string` | `"hello"` |
|
||||||
|
| `t.Number()` | `number` | `42` |
|
||||||
|
| `t.Boolean()` | `boolean` | `true` |
|
||||||
|
| `t.Array(t.Number())` | `number[]` | `[1, 2, 3]` |
|
||||||
|
| `t.Object({ x: t.Number() })` | `{ x: number }` | `{ x: 10 }` |
|
||||||
|
| `t.Null()` | `null` | `null` |
|
||||||
|
| `t.Literal(42)` | `42` | `42` |
|
||||||
|
|
||||||
|
## Attributes (JSON Schema 7)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Email format
|
||||||
|
t.String({ format: 'email' })
|
||||||
|
|
||||||
|
// Number constraints
|
||||||
|
t.Number({ minimum: 10, maximum: 100 })
|
||||||
|
|
||||||
|
// Array constraints
|
||||||
|
t.Array(t.Number(), {
|
||||||
|
minItems: 1, // min items
|
||||||
|
maxItems: 5 // max items
|
||||||
|
})
|
||||||
|
|
||||||
|
// Object - allow extra properties
|
||||||
|
t.Object(
|
||||||
|
{ x: t.Number() },
|
||||||
|
{ additionalProperties: true } // default: false
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Patterns
|
||||||
|
|
||||||
|
### Union (Multiple Types)
|
||||||
|
```ts
|
||||||
|
t.Union([t.String(), t.Number()])
|
||||||
|
// type: string | number
|
||||||
|
// values: "Hello" or 123
|
||||||
|
```
|
||||||
|
|
||||||
|
### Optional (Field Optional)
|
||||||
|
```ts
|
||||||
|
t.Object({
|
||||||
|
x: t.Number(),
|
||||||
|
y: t.Optional(t.Number()) // can be undefined
|
||||||
|
})
|
||||||
|
// type: { x: number, y?: number }
|
||||||
|
// value: { x: 123 } or { x: 123, y: 456 }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Partial (All Fields Optional)
|
||||||
|
```ts
|
||||||
|
t.Partial(t.Object({
|
||||||
|
x: t.Number(),
|
||||||
|
y: t.Number()
|
||||||
|
}))
|
||||||
|
// type: { x?: number, y?: number }
|
||||||
|
// value: {} or { y: 123 } or { x: 1, y: 2 }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Elysia-Specific Types
|
||||||
|
|
||||||
|
### UnionEnum (One of Values)
|
||||||
|
```ts
|
||||||
|
t.UnionEnum(['rapi', 'anis', 1, true, false])
|
||||||
|
```
|
||||||
|
|
||||||
|
### File (Single File Upload)
|
||||||
|
```ts
|
||||||
|
t.File({
|
||||||
|
type: 'image', // or ['image', 'video']
|
||||||
|
minSize: '1k', // 1024 bytes
|
||||||
|
maxSize: '5m' // 5242880 bytes
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**File unit suffixes**:
|
||||||
|
- `m` = MegaByte (1048576 bytes)
|
||||||
|
- `k` = KiloByte (1024 bytes)
|
||||||
|
|
||||||
|
### Files (Multiple Files)
|
||||||
|
```ts
|
||||||
|
t.Files() // extends File + array
|
||||||
|
```
|
||||||
|
|
||||||
|
### Cookie (Cookie Jar)
|
||||||
|
```ts
|
||||||
|
t.Cookie({
|
||||||
|
name: t.String()
|
||||||
|
}, {
|
||||||
|
secrets: 'secret-key' // or ['key1', 'key2'] for rotation
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Nullable (Allow null)
|
||||||
|
```ts
|
||||||
|
t.Nullable(t.String())
|
||||||
|
// type: string | null
|
||||||
|
```
|
||||||
|
|
||||||
|
### MaybeEmpty (Allow null + undefined)
|
||||||
|
```ts
|
||||||
|
t.MaybeEmpty(t.String())
|
||||||
|
// type: string | null | undefined
|
||||||
|
```
|
||||||
|
|
||||||
|
### Form (FormData Validation)
|
||||||
|
```ts
|
||||||
|
t.Form({
|
||||||
|
someValue: t.File()
|
||||||
|
})
|
||||||
|
// Syntax sugar for t.Object with FormData support
|
||||||
|
```
|
||||||
|
|
||||||
|
### UInt8Array (Buffer → Uint8Array)
|
||||||
|
```ts
|
||||||
|
t.UInt8Array()
|
||||||
|
// For binary file uploads with arrayBuffer parser
|
||||||
|
```
|
||||||
|
|
||||||
|
### ArrayBuffer (Buffer → ArrayBuffer)
|
||||||
|
```ts
|
||||||
|
t.ArrayBuffer()
|
||||||
|
// For binary file uploads with arrayBuffer parser
|
||||||
|
```
|
||||||
|
|
||||||
|
### ObjectString (String → Object)
|
||||||
|
```ts
|
||||||
|
t.ObjectString()
|
||||||
|
// Accepts: '{"x":1}' → parses to { x: 1 }
|
||||||
|
// Use in: query string, headers, FormData
|
||||||
|
```
|
||||||
|
|
||||||
|
### BooleanString (String → Boolean)
|
||||||
|
```ts
|
||||||
|
t.BooleanString()
|
||||||
|
// Accepts: 'true'/'false' → parses to boolean
|
||||||
|
// Use in: query string, headers, FormData
|
||||||
|
```
|
||||||
|
|
||||||
|
### Numeric (String/Number → Number)
|
||||||
|
```ts
|
||||||
|
t.Numeric()
|
||||||
|
// Accepts: '123' or 123 → transforms to 123
|
||||||
|
// Use in: path params, query string
|
||||||
|
```
|
||||||
|
|
||||||
|
## Elysia Behavior Differences from TypeBox
|
||||||
|
|
||||||
|
### 1. Optional Behavior
|
||||||
|
|
||||||
|
In Elysia, `t.Optional` makes **entire route parameter** optional (not object field):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.get('/optional', ({ query }) => query, {
|
||||||
|
query: t.Optional( // makes query itself optional
|
||||||
|
t.Object({ name: t.String() })
|
||||||
|
)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**Different from TypeBox**: TypeBox uses Optional for object fields only
|
||||||
|
|
||||||
|
### 2. Number → Numeric Auto-Conversion
|
||||||
|
|
||||||
|
**Route schema only** (not nested objects):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.get('/:id', ({ id }) => id, {
|
||||||
|
params: t.Object({
|
||||||
|
id: t.Number() // ✅ Auto-converts to t.Numeric()
|
||||||
|
}),
|
||||||
|
body: t.Object({
|
||||||
|
id: t.Number() // ❌ NOT converted (stays t.Number())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Outside route schema
|
||||||
|
t.Number() // ❌ NOT converted
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why**: HTTP headers/query/params always strings. Auto-conversion parses numeric strings.
|
||||||
|
|
||||||
|
### 3. Boolean → BooleanString Auto-Conversion
|
||||||
|
|
||||||
|
Same as Number → Numeric:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
.get('/:active', ({ active }) => active, {
|
||||||
|
params: t.Object({
|
||||||
|
active: t.Boolean() // ✅ Auto-converts to t.BooleanString()
|
||||||
|
}),
|
||||||
|
body: t.Object({
|
||||||
|
active: t.Boolean() // ❌ NOT converted
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage Pattern
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.post('/', ({ body }) => `Hello ${body}`, {
|
||||||
|
body: t.String() // validates body is string
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Validation flow**:
|
||||||
|
1. Request arrives
|
||||||
|
2. Schema validates against HTTP body/params/query/headers
|
||||||
|
3. If valid → handler executes
|
||||||
|
4. If invalid → Error Life Cycle
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
[Inference] Based on docs:
|
||||||
|
- TypeBox mirrors TypeScript but adds runtime validation
|
||||||
|
- Elysia.t extends TypeBox with HTTP-specific types
|
||||||
|
- Auto-conversion (Number→Numeric, Boolean→BooleanString) only for route schemas
|
||||||
|
- Use `t.Optional` for optional route params (different from TypeBox behavior)
|
||||||
|
- File validation supports unit suffixes ('1k', '5m')
|
||||||
|
- ObjectString/BooleanString for parsing strings in query/headers
|
||||||
|
- Cookie supports key rotation with array of secrets
|
||||||
250
.agents/skills/elysiajs/references/websocket.md
Normal file
250
.agents/skills/elysiajs/references/websocket.md
Normal file
@@ -0,0 +1,250 @@
|
|||||||
|
# WebSocket
|
||||||
|
|
||||||
|
## Basic WebSocket
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia } from 'elysia'
|
||||||
|
|
||||||
|
new Elysia()
|
||||||
|
.ws('/chat', {
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send(message) // Echo back
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.listen(3000)
|
||||||
|
```
|
||||||
|
|
||||||
|
## With Validation
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Elysia, t } from 'elysia'
|
||||||
|
|
||||||
|
.ws('/chat', {
|
||||||
|
body: t.Object({
|
||||||
|
message: t.String(),
|
||||||
|
username: t.String()
|
||||||
|
}),
|
||||||
|
response: t.Object({
|
||||||
|
message: t.String(),
|
||||||
|
timestamp: t.Number()
|
||||||
|
}),
|
||||||
|
message(ws, body) {
|
||||||
|
ws.send({
|
||||||
|
message: body.message,
|
||||||
|
timestamp: Date.now()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Lifecycle Events
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.ws('/chat', {
|
||||||
|
open(ws) {
|
||||||
|
console.log('Client connected')
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
console.log('Received:', message)
|
||||||
|
ws.send('Echo: ' + message)
|
||||||
|
},
|
||||||
|
close(ws) {
|
||||||
|
console.log('Client disconnected')
|
||||||
|
},
|
||||||
|
error(ws, error) {
|
||||||
|
console.error('Error:', error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Broadcasting
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const connections = new Set<any>()
|
||||||
|
|
||||||
|
.ws('/chat', {
|
||||||
|
open(ws) {
|
||||||
|
connections.add(ws)
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
// Broadcast to all connected clients
|
||||||
|
for (const client of connections) {
|
||||||
|
client.send(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
close(ws) {
|
||||||
|
connections.delete(ws)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## With Authentication
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.ws('/chat', {
|
||||||
|
beforeHandle({ headers, status }) {
|
||||||
|
const token = headers.authorization?.replace('Bearer ', '')
|
||||||
|
if (!verifyToken(token)) {
|
||||||
|
return status(401)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Room-Based Chat
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const rooms = new Map<string, Set<any>>()
|
||||||
|
|
||||||
|
.ws('/chat/:room', {
|
||||||
|
open(ws) {
|
||||||
|
const room = ws.data.params.room
|
||||||
|
if (!rooms.has(room)) {
|
||||||
|
rooms.set(room, new Set())
|
||||||
|
}
|
||||||
|
rooms.get(room)!.add(ws)
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
const room = ws.data.params.room
|
||||||
|
const clients = rooms.get(room)
|
||||||
|
|
||||||
|
if (clients) {
|
||||||
|
for (const client of clients) {
|
||||||
|
client.send(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
close(ws) {
|
||||||
|
const room = ws.data.params.room
|
||||||
|
const clients = rooms.get(room)
|
||||||
|
|
||||||
|
if (clients) {
|
||||||
|
clients.delete(ws)
|
||||||
|
if (clients.size === 0) {
|
||||||
|
rooms.delete(room)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## With State/Context
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.ws('/chat', {
|
||||||
|
open(ws) {
|
||||||
|
ws.data.userId = generateUserId()
|
||||||
|
ws.data.joinedAt = Date.now()
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
const response = {
|
||||||
|
userId: ws.data.userId,
|
||||||
|
message,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}
|
||||||
|
ws.send(response)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Client Usage (Browser)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const ws = new WebSocket('ws://localhost:3000/chat')
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
console.log('Connected')
|
||||||
|
ws.send('Hello Server!')
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
console.log('Received:', event.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onerror = (error) => {
|
||||||
|
console.error('Error:', error)
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
console.log('Disconnected')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Eden Treaty WebSocket
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Server
|
||||||
|
export const app = new Elysia()
|
||||||
|
.ws('/chat', {
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export type App = typeof app
|
||||||
|
|
||||||
|
// Client
|
||||||
|
import { treaty } from '@elysiajs/eden'
|
||||||
|
import type { App } from './server'
|
||||||
|
|
||||||
|
const api = treaty<App>('localhost:3000')
|
||||||
|
const chat = api.chat.subscribe()
|
||||||
|
|
||||||
|
chat.subscribe((message) => {
|
||||||
|
console.log('Received:', message)
|
||||||
|
})
|
||||||
|
|
||||||
|
chat.send('Hello!')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Headers in WebSocket
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.ws('/chat', {
|
||||||
|
header: t.Object({
|
||||||
|
authorization: t.String()
|
||||||
|
}),
|
||||||
|
beforeHandle({ headers, status }) {
|
||||||
|
const token = headers.authorization?.replace('Bearer ', '')
|
||||||
|
if (!token) return status(401)
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Query Parameters
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
.ws('/chat', {
|
||||||
|
query: t.Object({
|
||||||
|
username: t.String()
|
||||||
|
}),
|
||||||
|
message(ws, message) {
|
||||||
|
const username = ws.data.query.username
|
||||||
|
ws.send(`${username}: ${message}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Client
|
||||||
|
const ws = new WebSocket('ws://localhost:3000/chat?username=john')
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compression
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
new Elysia({
|
||||||
|
websocket: {
|
||||||
|
perMessageDeflate: true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ws('/chat', {
|
||||||
|
message(ws, message) {
|
||||||
|
ws.send(message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
143
.agents/skills/find-skills/SKILL.md
Normal file
143
.agents/skills/find-skills/SKILL.md
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
---
|
||||||
|
name: find-skills
|
||||||
|
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Find Skills
|
||||||
|
|
||||||
|
This skill helps you discover and install skills from the open agent skills ecosystem.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when the user:
|
||||||
|
|
||||||
|
- Asks "how do I do X" where X might be a common task with an existing skill
|
||||||
|
- Says "find a skill for X" or "is there a skill for X"
|
||||||
|
- Asks "can you do X" where X is a specialized capability
|
||||||
|
- Expresses interest in extending agent capabilities
|
||||||
|
- Wants to search for tools, templates, or workflows
|
||||||
|
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
|
||||||
|
|
||||||
|
## What is the Skills CLI?
|
||||||
|
|
||||||
|
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
|
||||||
|
|
||||||
|
**Key commands:**
|
||||||
|
|
||||||
|
- `npx skills find [query]` - Search for skills interactively or by keyword
|
||||||
|
- `npx skills add <package>` - Install a skill from GitHub or other sources
|
||||||
|
- `npx skills check` - Check for skill updates
|
||||||
|
- `npx skills update` - Update all installed skills
|
||||||
|
|
||||||
|
**Browse skills at:** https://skills.sh/
|
||||||
|
|
||||||
|
## How to Help Users Find Skills
|
||||||
|
|
||||||
|
### Step 1: Understand What They Need
|
||||||
|
|
||||||
|
When a user asks for help with something, identify:
|
||||||
|
|
||||||
|
1. The domain (e.g., React, testing, design, deployment)
|
||||||
|
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
|
||||||
|
3. Whether this is a common enough task that a skill likely exists
|
||||||
|
|
||||||
|
### Step 2: Check the Leaderboard First
|
||||||
|
|
||||||
|
Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options.
|
||||||
|
|
||||||
|
For example, top skills for web development include:
|
||||||
|
|
||||||
|
- `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each)
|
||||||
|
- `anthropics/skills` — Frontend design, document processing (100K+ installs)
|
||||||
|
|
||||||
|
### Step 3: Search for Skills
|
||||||
|
|
||||||
|
If the leaderboard doesn't cover the user's need, run the find command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx skills find [query]
|
||||||
|
```
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
- User asks "how do I make my React app faster?" → `npx skills find react performance`
|
||||||
|
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
|
||||||
|
- User asks "I need to create a changelog" → `npx skills find changelog`
|
||||||
|
|
||||||
|
### Step 4: Verify Quality Before Recommending
|
||||||
|
|
||||||
|
**Do not recommend a skill based solely on search results.** Always verify:
|
||||||
|
|
||||||
|
1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100.
|
||||||
|
2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors.
|
||||||
|
3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism.
|
||||||
|
|
||||||
|
### Step 5: Present Options to the User
|
||||||
|
|
||||||
|
When you find relevant skills, present them to the user with:
|
||||||
|
|
||||||
|
1. The skill name and what it does
|
||||||
|
2. The install count and source
|
||||||
|
3. The install command they can run
|
||||||
|
4. A link to learn more at skills.sh
|
||||||
|
|
||||||
|
Example response:
|
||||||
|
|
||||||
|
```
|
||||||
|
I found a skill that might help! The "react-best-practices" skill provides
|
||||||
|
React and Next.js performance optimization guidelines from Vercel Engineering.
|
||||||
|
(185K installs)
|
||||||
|
|
||||||
|
To install it:
|
||||||
|
npx skills add vercel-labs/agent-skills@react-best-practices
|
||||||
|
|
||||||
|
Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 6: Offer to Install
|
||||||
|
|
||||||
|
If the user wants to proceed, you can install the skill for them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx skills add <owner/repo@skill> -g -y
|
||||||
|
```
|
||||||
|
|
||||||
|
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
|
||||||
|
|
||||||
|
## Common Skill Categories
|
||||||
|
|
||||||
|
When searching, consider these common categories:
|
||||||
|
|
||||||
|
| Category | Example Queries |
|
||||||
|
| --------------- | ---------------------------------------- |
|
||||||
|
| Web Development | react, nextjs, typescript, css, tailwind |
|
||||||
|
| Testing | testing, jest, playwright, e2e |
|
||||||
|
| DevOps | deploy, docker, kubernetes, ci-cd |
|
||||||
|
| Documentation | docs, readme, changelog, api-docs |
|
||||||
|
| Code Quality | review, lint, refactor, best-practices |
|
||||||
|
| Design | ui, ux, design-system, accessibility |
|
||||||
|
| Productivity | workflow, automation, git |
|
||||||
|
|
||||||
|
## Tips for Effective Searches
|
||||||
|
|
||||||
|
1. **Use specific keywords**: "react testing" is better than just "testing"
|
||||||
|
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
|
||||||
|
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
|
||||||
|
|
||||||
|
## When No Skills Are Found
|
||||||
|
|
||||||
|
If no relevant skills exist:
|
||||||
|
|
||||||
|
1. Acknowledge that no existing skill was found
|
||||||
|
2. Offer to help with the task directly using your general capabilities
|
||||||
|
3. Suggest the user could create their own skill with `npx skills init`
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```
|
||||||
|
I searched for skills related to "xyz" but didn't find any matches.
|
||||||
|
I can still help you with this task directly! Would you like me to proceed?
|
||||||
|
|
||||||
|
If this is something you do often, you could create your own skill:
|
||||||
|
npx skills init my-xyz-skill
|
||||||
|
```
|
||||||
177
.agents/skills/frontend-design/LICENSE.txt
Normal file
177
.agents/skills/frontend-design/LICENSE.txt
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
45
.agents/skills/frontend-design/SKILL.md
Normal file
45
.agents/skills/frontend-design/SKILL.md
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
name: frontend-design
|
||||||
|
description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
|
||||||
|
license: Complete terms in LICENSE.txt
|
||||||
|
---
|
||||||
|
|
||||||
|
This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.
|
||||||
|
|
||||||
|
The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints.
|
||||||
|
|
||||||
|
## Design Thinking
|
||||||
|
|
||||||
|
Before coding, understand the context and commit to a BOLD aesthetic direction:
|
||||||
|
|
||||||
|
- **Purpose**: What problem does this interface solve? Who uses it?
|
||||||
|
- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction.
|
||||||
|
- **Constraints**: Technical requirements (framework, performance, accessibility).
|
||||||
|
- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember?
|
||||||
|
|
||||||
|
**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity.
|
||||||
|
|
||||||
|
Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:
|
||||||
|
|
||||||
|
- Production-grade and functional
|
||||||
|
- Visually striking and memorable
|
||||||
|
- Cohesive with a clear aesthetic point-of-view
|
||||||
|
- Meticulously refined in every detail
|
||||||
|
|
||||||
|
## Frontend Aesthetics Guidelines
|
||||||
|
|
||||||
|
Focus on:
|
||||||
|
|
||||||
|
- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font.
|
||||||
|
- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
|
||||||
|
- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise.
|
||||||
|
- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
|
||||||
|
- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.
|
||||||
|
|
||||||
|
NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character.
|
||||||
|
|
||||||
|
Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.
|
||||||
|
|
||||||
|
**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
|
||||||
|
|
||||||
|
Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.
|
||||||
615
.agents/skills/kiranism-shadcn-dashboard/SKILL.md
Normal file
615
.agents/skills/kiranism-shadcn-dashboard/SKILL.md
Normal file
@@ -0,0 +1,615 @@
|
|||||||
|
---
|
||||||
|
name: kiranism-shadcn-dashboard
|
||||||
|
description: |
|
||||||
|
Guide for building features, pages, tables, forms, themes, and navigation in this Next.js 16 shadcn dashboard template. Use this skill whenever the user wants to add a new page, create a feature module, build a data table, add a form, configure navigation items, add a theme, set up RBAC access control, or work with the dashboard's patterns and conventions. Also triggers when adding routes under /dashboard, working with Clerk auth/orgs/billing, creating mock APIs, or modifying the sidebar. Even if the user doesn't mention "dashboard" explicitly — if they're adding UI, pages, or features to this project, use this skill.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dashboard Development Guide
|
||||||
|
|
||||||
|
This skill encodes the exact patterns and conventions used in this Next.js 16 + shadcn/ui admin dashboard template.
|
||||||
|
|
||||||
|
## Quick Reference: What Goes Where
|
||||||
|
|
||||||
|
| Task | Location |
|
||||||
|
| --------------------- | --------------------------------------- |
|
||||||
|
| New page | `src/app/dashboard/<name>/page.tsx` |
|
||||||
|
| New feature module | `src/features/<name>/` |
|
||||||
|
| Feature components | `src/features/<name>/components/` |
|
||||||
|
| API types | `src/features/<name>/api/types.ts` |
|
||||||
|
| Service layer | `src/features/<name>/api/service.ts` |
|
||||||
|
| Query options | `src/features/<name>/api/queries.ts` |
|
||||||
|
| Mutation options | `src/features/<name>/api/mutations.ts` |
|
||||||
|
| Zod schemas | `src/features/<name>/schemas/<name>.ts` |
|
||||||
|
| Filter/select options | `src/features/<name>/constants/` |
|
||||||
|
| Nav config | `src/config/nav-config.ts` |
|
||||||
|
| Types | `src/types/index.ts` |
|
||||||
|
| Mock data | `src/constants/mock-api-<name>.ts` |
|
||||||
|
| Search params | `src/lib/searchparams.ts` |
|
||||||
|
| Query client | `src/lib/query-client.ts` |
|
||||||
|
| Theme CSS | `src/styles/themes/<name>.css` |
|
||||||
|
| Theme registry | `src/components/themes/theme.config.ts` |
|
||||||
|
| Custom hook | `src/hooks/` |
|
||||||
|
| Icons registry | `src/components/icons.tsx` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a New Feature (End-to-End)
|
||||||
|
|
||||||
|
When a user asks to add a feature (e.g., "add an orders page"), follow these steps in order. Each step below shows the minimal pattern — see reference files for full templates.
|
||||||
|
|
||||||
|
### Step 1: Mock API (`src/constants/mock-api-<name>.ts`)
|
||||||
|
|
||||||
|
See [references/mock-api-guide.md](references/mock-api-guide.md) for the complete template. Key structure:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { faker } from '@faker-js/faker';
|
||||||
|
import { matchSorter } from 'match-sorter';
|
||||||
|
import { delay } from './mock-api';
|
||||||
|
|
||||||
|
export type Order = {
|
||||||
|
id: number;
|
||||||
|
customer: string;
|
||||||
|
status: string;
|
||||||
|
total: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fakeOrders = {
|
||||||
|
records: [] as Order[],
|
||||||
|
initialize() {
|
||||||
|
/* generate with faker */
|
||||||
|
},
|
||||||
|
async getOrders({ page, limit, search, sort }) {
|
||||||
|
/* filter, sort, paginate, return { items, total_items } */
|
||||||
|
},
|
||||||
|
async getOrderById(id: number) {
|
||||||
|
/* find by id */
|
||||||
|
},
|
||||||
|
async createOrder(data) {
|
||||||
|
/* push to records */
|
||||||
|
},
|
||||||
|
async updateOrder(id, data) {
|
||||||
|
/* merge into record */
|
||||||
|
},
|
||||||
|
async deleteOrder(id) {
|
||||||
|
/* filter out */
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fakeOrders.initialize();
|
||||||
|
```
|
||||||
|
|
||||||
|
Every method should call `await delay(800)` to simulate network latency. Use `matchSorter` for search. Return `{ items, total_items }` from list methods.
|
||||||
|
|
||||||
|
### Step 2: API Layer (`src/features/<name>/api/`)
|
||||||
|
|
||||||
|
Each feature has 4 API files: **types** → **service** → **queries** → **mutations**.
|
||||||
|
|
||||||
|
**Types** (`api/types.ts`) — re-export the entity type from mock API, plus filter/response/payload types:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export type { Order } from '@/constants/mock-api-orders';
|
||||||
|
export type OrderFilters = { page?: number; limit?: number; search?: string; sort?: string };
|
||||||
|
export type OrdersResponse = { items: Order[]; total_items: number };
|
||||||
|
export type OrderMutationPayload = { customer: string; status: string; total: number };
|
||||||
|
```
|
||||||
|
|
||||||
|
**Service** (`api/service.ts`) — data access layer. One exported function per operation:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { fakeOrders } from '@/constants/mock-api-orders';
|
||||||
|
import type { OrderFilters, OrdersResponse, OrderMutationPayload } from './types';
|
||||||
|
|
||||||
|
export async function getOrders(filters: OrderFilters): Promise<OrdersResponse> {
|
||||||
|
return fakeOrders.getOrders(filters);
|
||||||
|
}
|
||||||
|
export async function getOrderById(id: number) {
|
||||||
|
return fakeOrders.getOrderById(id);
|
||||||
|
}
|
||||||
|
export async function createOrder(data: OrderMutationPayload) {
|
||||||
|
return fakeOrders.createOrder(data);
|
||||||
|
}
|
||||||
|
export async function updateOrder(id: number, data: OrderMutationPayload) {
|
||||||
|
return fakeOrders.updateOrder(id, data);
|
||||||
|
}
|
||||||
|
export async function deleteOrder(id: number) {
|
||||||
|
return fakeOrders.deleteOrder(id);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Queries** (`api/queries.ts`) — query key factory + query options:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { queryOptions } from '@tanstack/react-query';
|
||||||
|
import { getOrders, getOrderById } from './service';
|
||||||
|
import type { Order, OrderFilters } from './types';
|
||||||
|
|
||||||
|
export type { Order };
|
||||||
|
|
||||||
|
export const orderKeys = {
|
||||||
|
all: ['orders'] as const,
|
||||||
|
list: (filters: OrderFilters) => [...orderKeys.all, 'list', filters] as const,
|
||||||
|
detail: (id: number) => [...orderKeys.all, 'detail', id] as const
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ordersQueryOptions = (filters: OrderFilters) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: orderKeys.list(filters),
|
||||||
|
queryFn: () => getOrders(filters)
|
||||||
|
});
|
||||||
|
|
||||||
|
export const orderByIdOptions = (id: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: orderKeys.detail(id),
|
||||||
|
queryFn: () => getOrderById(id)
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Mutations** (`api/mutations.ts`) — use `mutationOptions` + `getQueryClient()` (not custom hooks with `useQueryClient()`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { mutationOptions } from '@tanstack/react-query';
|
||||||
|
import { getQueryClient } from '@/lib/query-client';
|
||||||
|
import { createOrder, updateOrder, deleteOrder } from './service';
|
||||||
|
import { orderKeys } from './queries';
|
||||||
|
import type { OrderMutationPayload } from './types';
|
||||||
|
|
||||||
|
export const createOrderMutation = mutationOptions({
|
||||||
|
mutationFn: (data: OrderMutationPayload) => createOrder(data),
|
||||||
|
onSuccess: () => {
|
||||||
|
getQueryClient().invalidateQueries({ queryKey: orderKeys.all });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateOrderMutation = mutationOptions({
|
||||||
|
mutationFn: ({ id, values }: { id: number; values: OrderMutationPayload }) =>
|
||||||
|
updateOrder(id, values),
|
||||||
|
onSuccess: () => {
|
||||||
|
getQueryClient().invalidateQueries({ queryKey: orderKeys.all });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const deleteOrderMutation = mutationOptions({
|
||||||
|
mutationFn: (id: number) => deleteOrder(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
getQueryClient().invalidateQueries({ queryKey: orderKeys.all });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
`mutationOptions` is the right abstraction because it works outside React (event handlers, tests, utilities), composes via spread at the call site, and uses `getQueryClient()` which handles both SSR (fresh per request) and client (singleton) correctly. See [references/query-abstractions.md](references/query-abstractions.md) for the full rationale.
|
||||||
|
|
||||||
|
### Step 3: Zod Schema (`src/features/<name>/schemas/<name>.ts`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const orderSchema = z.object({
|
||||||
|
customer: z.string().min(2, 'Customer name must be at least 2 characters'),
|
||||||
|
status: z.string().min(1, 'Please select a status'),
|
||||||
|
total: z.number({ message: 'Total is required' })
|
||||||
|
});
|
||||||
|
|
||||||
|
export type OrderFormValues = z.infer<typeof orderSchema>;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 4: Feature Components
|
||||||
|
|
||||||
|
Create `src/features/<name>/components/` with:
|
||||||
|
|
||||||
|
**Listing page** (server component — `<name>-listing.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
|
||||||
|
import { getQueryClient } from '@/lib/query-client';
|
||||||
|
import { searchParamsCache } from '@/lib/searchparams';
|
||||||
|
import { ordersQueryOptions } from '../api/queries';
|
||||||
|
import { OrderTable, OrderTableSkeleton } from './orders-table';
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
|
export default function OrderListingPage() {
|
||||||
|
const page = searchParamsCache.get('page');
|
||||||
|
const search = searchParamsCache.get('name');
|
||||||
|
const pageLimit = searchParamsCache.get('perPage');
|
||||||
|
const sort = searchParamsCache.get('sort');
|
||||||
|
|
||||||
|
const filters = {
|
||||||
|
page,
|
||||||
|
limit: pageLimit,
|
||||||
|
...(search && { search }),
|
||||||
|
...(sort && { sort })
|
||||||
|
};
|
||||||
|
|
||||||
|
const queryClient = getQueryClient();
|
||||||
|
void queryClient.prefetchQuery(ordersQueryOptions(filters));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||||
|
<Suspense fallback={<OrderTableSkeleton />}>
|
||||||
|
<OrderTable />
|
||||||
|
</Suspense>
|
||||||
|
</HydrationBoundary>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Table + skeleton** (client component — `orders-table/index.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||||
|
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
|
||||||
|
import { getSortingStateParser } from '@/lib/parsers';
|
||||||
|
import { useDataTable } from '@/hooks/use-data-table';
|
||||||
|
import { DataTable } from '@/components/ui/table/data-table';
|
||||||
|
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
import { ordersQueryOptions } from '../../api/queries';
|
||||||
|
import { columns } from './columns';
|
||||||
|
|
||||||
|
const columnIds = columns.map((c) => c.id).filter(Boolean) as string[];
|
||||||
|
|
||||||
|
export function OrderTable() {
|
||||||
|
const [params] = useQueryStates({
|
||||||
|
page: parseAsInteger.withDefault(1),
|
||||||
|
perPage: parseAsInteger.withDefault(10),
|
||||||
|
name: parseAsString,
|
||||||
|
sort: getSortingStateParser(columnIds).withDefault([])
|
||||||
|
});
|
||||||
|
|
||||||
|
const filters = {
|
||||||
|
page: params.page,
|
||||||
|
limit: params.perPage,
|
||||||
|
...(params.name && { search: params.name }),
|
||||||
|
...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
|
||||||
|
};
|
||||||
|
|
||||||
|
const { data } = useSuspenseQuery(ordersQueryOptions(filters));
|
||||||
|
|
||||||
|
const { table } = useDataTable({
|
||||||
|
data: data.items,
|
||||||
|
columns,
|
||||||
|
pageCount: Math.ceil(data.total_items / params.perPage),
|
||||||
|
shallow: true,
|
||||||
|
debounceMs: 500,
|
||||||
|
initialState: { columnPinning: { right: ['actions'] } }
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DataTable table={table}>
|
||||||
|
<DataTableToolbar table={table} />
|
||||||
|
</DataTable>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OrderTableSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className='space-y-4 p-4'>
|
||||||
|
<Skeleton className='h-10 w-full' />
|
||||||
|
<Skeleton className='h-96 w-full' />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Column definitions** (`orders-table/columns.tsx`):
|
||||||
|
|
||||||
|
Each column needs `id`, `accessorKey` (or `accessorFn`), `header` with `DataTableColumnHeader`, and optionally `meta` for filtering + `enableColumnFilter: true`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export const columns: ColumnDef<Order>[] = [
|
||||||
|
{
|
||||||
|
id: 'customer',
|
||||||
|
accessorKey: 'customer',
|
||||||
|
header: ({ column }) => <DataTableColumnHeader column={column} title='Customer' />,
|
||||||
|
meta: { label: 'Customer', placeholder: 'Search...', variant: 'text', icon: Icons.text },
|
||||||
|
enableColumnFilter: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'status',
|
||||||
|
accessorKey: 'status',
|
||||||
|
header: ({ column }) => <DataTableColumnHeader column={column} title='Status' />,
|
||||||
|
cell: ({ cell }) => (
|
||||||
|
<Badge variant='outline' className='capitalize'>
|
||||||
|
{cell.getValue<string>()}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
enableColumnFilter: true,
|
||||||
|
meta: { label: 'Status', variant: 'multiSelect', options: STATUS_OPTIONS }
|
||||||
|
},
|
||||||
|
{ id: 'actions', cell: ({ row }) => <CellAction data={row.original} /> }
|
||||||
|
];
|
||||||
|
```
|
||||||
|
|
||||||
|
Filter `meta.variant` options: `text`, `number`, `range`, `date`, `dateRange`, `select`, `multiSelect`, `boolean`. For multiSelect, provide `options: { value, label, icon? }[]`.
|
||||||
|
|
||||||
|
**Cell actions** (`orders-table/cell-action.tsx`):
|
||||||
|
|
||||||
|
Pattern: `DropdownMenu` with edit/delete items + `AlertModal` for delete confirmation + `useMutation` for the delete API call.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { deleteOrderMutation } from '../../api/mutations';
|
||||||
|
|
||||||
|
export const CellAction: React.FC<{ data: Order }> = ({ data }) => {
|
||||||
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
...deleteOrderMutation,
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Deleted');
|
||||||
|
setDeleteOpen(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AlertModal
|
||||||
|
isOpen={deleteOpen}
|
||||||
|
onClose={() => setDeleteOpen(false)}
|
||||||
|
onConfirm={() => deleteMutation.mutate(data.id)}
|
||||||
|
loading={deleteMutation.isPending}
|
||||||
|
/>
|
||||||
|
<DropdownMenu modal={false}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant='ghost' className='h-8 w-8 p-0'>
|
||||||
|
<Icons.ellipsis className='h-4 w-4' />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align='end'>
|
||||||
|
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
||||||
|
<DropdownMenuItem onClick={() => router.push(`/dashboard/orders/${data.id}`)}>
|
||||||
|
<Icons.edit className='mr-2 h-4 w-4' /> Edit
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setDeleteOpen(true)}>
|
||||||
|
<Icons.trash className='mr-2 h-4 w-4' /> Delete
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
For **sheet-based editing** (like Users), replace `router.push` with opening a `<FormSheet>` — see the Forms section below.
|
||||||
|
|
||||||
|
### Step 5: Page Route (`src/app/dashboard/<name>/page.tsx`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import PageContainer from '@/components/layout/page-container';
|
||||||
|
import OrderListingPage from '@/features/orders/components/order-listing';
|
||||||
|
import { searchParamsCache } from '@/lib/searchparams';
|
||||||
|
import type { SearchParams } from 'nuqs/server';
|
||||||
|
|
||||||
|
export const metadata = { title: 'Dashboard: Orders' };
|
||||||
|
type PageProps = { searchParams: Promise<SearchParams> };
|
||||||
|
|
||||||
|
export default async function Page(props: PageProps) {
|
||||||
|
const searchParams = await props.searchParams;
|
||||||
|
searchParamsCache.parse(searchParams);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageContainer
|
||||||
|
scrollable={false}
|
||||||
|
pageTitle='Orders'
|
||||||
|
pageDescription='Manage your orders.'
|
||||||
|
pageHeaderAction={/* Add button — Link or SheetTrigger */}
|
||||||
|
>
|
||||||
|
<OrderListingPage />
|
||||||
|
</PageContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**PageContainer props**: `scrollable`, `pageTitle`, `pageDescription`, `pageHeaderAction` (React node for the top-right button), `infoContent` (help sidebar), `access` + `accessFallback` (RBAC gating).
|
||||||
|
|
||||||
|
**Detail/Edit page** (`src/app/dashboard/<name>/[id]/page.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import PageContainer from '@/components/layout/page-container';
|
||||||
|
import OrderViewPage from '@/features/orders/components/order-view-page';
|
||||||
|
|
||||||
|
export const metadata = { title: 'Dashboard: Order Details' };
|
||||||
|
type PageProps = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
export default async function Page(props: PageProps) {
|
||||||
|
const { id } = await props.params;
|
||||||
|
return (
|
||||||
|
<PageContainer scrollable pageTitle='Order Details'>
|
||||||
|
<OrderViewPage orderId={id} />
|
||||||
|
</PageContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**View page component** (client — handles new vs edit):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
import { orderByIdOptions } from '../api/queries';
|
||||||
|
import OrderForm from './order-form';
|
||||||
|
|
||||||
|
export default function OrderViewPage({ orderId }: { orderId: string }) {
|
||||||
|
if (orderId === 'new') return <OrderForm initialData={null} pageTitle='Create Order' />;
|
||||||
|
const { data } = useSuspenseQuery(orderByIdOptions(Number(orderId)));
|
||||||
|
if (!data) notFound();
|
||||||
|
return <OrderForm initialData={data} pageTitle='Edit Order' />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 6: Search Params (`src/lib/searchparams.ts`)
|
||||||
|
|
||||||
|
Add any new filter keys. Existing params: `page`, `perPage`, `name`, `gender`, `category`, `role`, `sort`.
|
||||||
|
|
||||||
|
### Step 7: Navigation (`src/config/nav-config.ts`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
{ title: 'Orders', url: '/dashboard/orders', icon: 'product', items: [] }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 8: Icons (`src/components/icons.tsx`)
|
||||||
|
|
||||||
|
To register a new icon, import from `@tabler/icons-react` and add to the `Icons` object:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { IconShoppingCart } from '@tabler/icons-react';
|
||||||
|
export const Icons = { /* ...existing */ cart: IconShoppingCart };
|
||||||
|
```
|
||||||
|
|
||||||
|
Never import `@tabler/icons-react` anywhere else. Always use `Icons.keyName`.
|
||||||
|
|
||||||
|
**Existing icon keys** (partial): `dashboard`, `product`, `kanban`, `chat`, `forms`, `user`, `teams`, `billing`, `settings`, `add`, `edit`, `trash`, `search`, `check`, `close`, `clock`, `ellipsis`, `text`, `calendar`, `upload`, `spinner`, `chevronDown/Left/Right/Up`, `sun`, `moon`, `palette`, `pro`, `workspace`, `notification`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Forms
|
||||||
|
|
||||||
|
Forms use **TanStack Form + Zod** with `useAppForm` + `useFormFields<T>()` and `useMutation` for submission. See [references/forms-guide.md](references/forms-guide.md) for all field types, validation strategies, multi-step forms, and advanced patterns.
|
||||||
|
|
||||||
|
### Page Form (Create/Edit on a dedicated route)
|
||||||
|
|
||||||
|
The full pattern is shown in Steps 1-4 above. The key structure:
|
||||||
|
|
||||||
|
1. **Schema** — Zod schema + inferred type in `schemas/<name>.ts`
|
||||||
|
2. **Form component** — `useAppForm({ defaultValues, validators: { onSubmit: schema }, onSubmit })` + `useFormFields<T>()` for typed fields
|
||||||
|
3. **Mutations** — `useMutation({ ...createOrderMutation, onSuccess: () => { toast(); router.push() } })`, spread shared mutation options from `api/mutations.ts` and layer on UI callbacks
|
||||||
|
4. **View page** — client component that checks `id === 'new'` for create vs `useSuspenseQuery(byIdOptions)` for edit
|
||||||
|
|
||||||
|
### Sheet Form (Inline create/edit in a side panel)
|
||||||
|
|
||||||
|
For features where a separate page is overkill (like Users). The sheet manages open state; the form uses a `form` attribute to connect to the sheet footer's submit button.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||||
|
|
||||||
|
export function OrderFormSheet({
|
||||||
|
order,
|
||||||
|
open,
|
||||||
|
onOpenChange
|
||||||
|
}: {
|
||||||
|
order?: Order;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const isEdit = !!order;
|
||||||
|
const mutation = useMutation({
|
||||||
|
...(isEdit ? updateOrderMutation : createOrderMutation),
|
||||||
|
onSuccess: () => {
|
||||||
|
onOpenChange(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const form = useAppForm({
|
||||||
|
defaultValues: { customer: order?.customer ?? '' /* ... */ } as OrderFormValues,
|
||||||
|
validators: { onSubmit: orderSchema },
|
||||||
|
onSubmit: async ({ value }) => {
|
||||||
|
await mutation.mutateAsync(value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const { FormTextField, FormSelectField } = useFormFields<OrderFormValues>();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||||
|
<SheetContent className='flex flex-col'>
|
||||||
|
<SheetHeader>
|
||||||
|
<SheetTitle>{isEdit ? 'Edit' : 'New'} Order</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
<div className='flex-1 overflow-auto'>
|
||||||
|
<form.AppForm>
|
||||||
|
<form.Form id='order-sheet-form' className='space-y-4'>
|
||||||
|
<FormTextField name='customer' label='Customer' required />
|
||||||
|
<FormSelectField name='status' label='Status' required options={STATUS_OPTIONS} />
|
||||||
|
</form.Form>
|
||||||
|
</form.AppForm>
|
||||||
|
</div>
|
||||||
|
<SheetFooter>
|
||||||
|
<Button variant='outline' onClick={() => onOpenChange(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type='submit' form='order-sheet-form' disabled={mutation.isPending}>
|
||||||
|
{mutation.isPending ? 'Saving...' : isEdit ? 'Update' : 'Create'}
|
||||||
|
</Button>
|
||||||
|
</SheetFooter>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For cell actions, add `const [editOpen, setEditOpen] = useState(false)` and render `<OrderFormSheet order={data} open={editOpen} onOpenChange={setEditOpen} />` with a `<DropdownMenuItem onClick={() => setEditOpen(true)}>`. For the page header "Add" button, create a trigger component that manages `open` state and renders the sheet.
|
||||||
|
|
||||||
|
**Available field components** from `useFormFields<T>()`: `FormTextField`, `FormTextareaField`, `FormSelectField`, `FormCheckboxField`, `FormSwitchField`, `FormRadioGroupField`, `FormSliderField`, `FormFileUploadField`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data Fetching with React Query
|
||||||
|
|
||||||
|
The pattern is: server prefetch → HydrationBoundary → client useSuspenseQuery.
|
||||||
|
|
||||||
|
1. **Server**: `void queryClient.prefetchQuery(options)` — fire-and-forget during SSR streaming
|
||||||
|
2. **Client**: `useSuspenseQuery(options)` — picks up dehydrated data, suspends until resolved
|
||||||
|
3. **HydrationBoundary + dehydrate**: bridges server cache → client cache
|
||||||
|
4. **Suspense fallback**: skeleton shown while data streams
|
||||||
|
|
||||||
|
**Why `useSuspenseQuery` not `useQuery`:** `useQuery` doesn't integrate with Suspense — it shows loading even when data is prefetched. `useSuspenseQuery` picks up the dehydrated pending query. Once cached (within `staleTime: 60s`), subsequent visits are instant.
|
||||||
|
|
||||||
|
**Mutations** use `mutationOptions` + `getQueryClient()` in `mutations.ts`, composed via spread at the call site:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// In mutations.ts — shared config
|
||||||
|
export const createOrderMutation = mutationOptions({
|
||||||
|
mutationFn: (data) => createOrder(data),
|
||||||
|
onSuccess: () => {
|
||||||
|
getQueryClient().invalidateQueries({ queryKey: orderKeys.all });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// In component — spread + layer UI callbacks
|
||||||
|
const mutation = useMutation({
|
||||||
|
...createOrderMutation,
|
||||||
|
onSuccess: () => toast.success('Created')
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
See [references/query-abstractions.md](references/query-abstractions.md) for why `mutationOptions`/`queryOptions` are the right abstraction over custom hooks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Navigation & RBAC
|
||||||
|
|
||||||
|
Configure in `src/config/nav-config.ts`. Items are filtered client-side in `src/hooks/use-nav.ts` using Clerk.
|
||||||
|
|
||||||
|
**Access control properties** on nav items:
|
||||||
|
|
||||||
|
- `requireOrg: boolean` — requires active Clerk organization
|
||||||
|
- `permission: string` — requires specific Clerk permission
|
||||||
|
- `role: string` — requires specific Clerk role
|
||||||
|
- `plan: string` — requires subscription plan (server-side)
|
||||||
|
- `feature: string` — requires feature flag (server-side)
|
||||||
|
|
||||||
|
Items without `access` are visible to everyone. All client-side checks are synchronous — no loading states.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Themes
|
||||||
|
|
||||||
|
See [references/theming-guide.md](references/theming-guide.md) for the complete guide. Quick steps:
|
||||||
|
|
||||||
|
1. Create `src/styles/themes/<name>.css` with OKLCH color tokens + `@theme inline` block
|
||||||
|
2. Import in `src/styles/theme.css`
|
||||||
|
3. Register in `THEMES` array in `src/components/themes/theme.config.ts`
|
||||||
|
4. (Optional) Add Google Fonts in `src/components/themes/font.config.ts`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Code Conventions
|
||||||
|
|
||||||
|
- **`cn()`** for class merging — never concatenate className strings
|
||||||
|
- **Server components by default** — only add `'use client'` when needed
|
||||||
|
- **React Query** — `void prefetchQuery()` on server + `useSuspenseQuery` on client
|
||||||
|
- **API layer** — `types.ts` → `service.ts` → `queries.ts` → `mutations.ts` per feature; `queryOptions`/`mutationOptions` as base abstractions (not custom hooks); `getQueryClient()` in mutations (not `useQueryClient()`); key factories (`entityKeys.all/list/detail`); components never import mock APIs directly
|
||||||
|
- **nuqs** — `searchParamsCache` on server, `useQueryStates` on client with `shallow: true`
|
||||||
|
- **Icons** — only from `@/components/icons`, never from `@tabler/icons-react` directly
|
||||||
|
- **Forms** — `useAppForm` + `useFormFields<T>()` from `@/components/ui/tanstack-form`
|
||||||
|
- **Page headers** — `PageContainer` props, never import `<Heading>` manually
|
||||||
|
- **Sort parser** — use `getSortingStateParser` from `@/lib/parsers` (same parser as `useDataTable`)
|
||||||
|
- **Formatting** — single quotes, JSX single quotes, no trailing comma, 2-space indent
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
# Charts & Analytics Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Overview Architecture](#overview-architecture)
|
||||||
|
2. [Parallel Routes Pattern](#parallel-routes-pattern)
|
||||||
|
3. [Chart Components](#chart-components)
|
||||||
|
4. [Stats Cards](#stats-cards)
|
||||||
|
5. [Skeleton Loading](#skeleton-loading)
|
||||||
|
6. [Adding a New Chart Section](#adding-a-new-chart-section)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview Architecture
|
||||||
|
|
||||||
|
The analytics dashboard at `/dashboard/overview` uses **Next.js parallel routes** to load multiple chart sections independently. Each chart slot streams in as its data becomes ready — no waterfall, no blocking.
|
||||||
|
|
||||||
|
**File structure:**
|
||||||
|
|
||||||
|
```
|
||||||
|
src/app/dashboard/overview/
|
||||||
|
├── layout.tsx # Composes all slots into a grid
|
||||||
|
├── @area_stats/
|
||||||
|
│ ├── page.tsx # Async server component (fetches data)
|
||||||
|
│ ├── loading.tsx # Skeleton shown while streaming
|
||||||
|
│ └── error.tsx # Error boundary if fetch fails
|
||||||
|
├── @bar_stats/
|
||||||
|
│ ├── page.tsx
|
||||||
|
│ ├── loading.tsx
|
||||||
|
│ └── error.tsx
|
||||||
|
├── @pie_stats/
|
||||||
|
│ ├── page.tsx
|
||||||
|
│ ├── loading.tsx
|
||||||
|
│ └── error.tsx
|
||||||
|
└── @sales/
|
||||||
|
├── page.tsx
|
||||||
|
├── loading.tsx
|
||||||
|
└── error.tsx
|
||||||
|
|
||||||
|
src/features/overview/components/
|
||||||
|
├── area-graph.tsx # Client chart component
|
||||||
|
├── area-graph-skeleton.tsx # Matching skeleton
|
||||||
|
├── bar-graph.tsx
|
||||||
|
├── bar-graph-skeleton.tsx
|
||||||
|
├── pie-graph.tsx
|
||||||
|
├── pie-graph-skeleton.tsx
|
||||||
|
├── recent-sales.tsx
|
||||||
|
└── recent-sales-skeleton.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Parallel Routes Pattern
|
||||||
|
|
||||||
|
### Layout (`layout.tsx`)
|
||||||
|
|
||||||
|
The layout receives each parallel route as a prop and arranges them in a grid:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default function OverviewLayout({
|
||||||
|
sales,
|
||||||
|
pie_stats,
|
||||||
|
bar_stats,
|
||||||
|
area_stats
|
||||||
|
}: {
|
||||||
|
sales: React.ReactNode;
|
||||||
|
pie_stats: React.ReactNode;
|
||||||
|
bar_stats: React.ReactNode;
|
||||||
|
area_stats: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<PageContainer pageTitle='Dashboard' pageDescription='Overview analytics.'>
|
||||||
|
{/* Stats cards row */}
|
||||||
|
<div className='grid gap-4 md:grid-cols-2 lg:grid-cols-4'>
|
||||||
|
<Card>
|
||||||
|
<CardHeader className='flex flex-row items-center justify-between pb-2'>
|
||||||
|
<CardTitle className='text-sm font-medium'>Total Revenue</CardTitle>
|
||||||
|
<Icons.billing className='h-4 w-4 text-muted-foreground' />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className='text-2xl font-bold'>$45,231.89</div>
|
||||||
|
<p className='text-xs text-muted-foreground'>+20.1% from last month</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
{/* ...more stat cards */}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Charts grid — each slot loads independently */}
|
||||||
|
<div className='grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-7'>
|
||||||
|
<div className='col-span-4'>{area_stats}</div>
|
||||||
|
<div className='col-span-3'>{sales}</div>
|
||||||
|
<div className='col-span-4'>{bar_stats}</div>
|
||||||
|
<div className='col-span-3'>{pie_stats}</div>
|
||||||
|
</div>
|
||||||
|
</PageContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Slot Page (`@area_stats/page.tsx`)
|
||||||
|
|
||||||
|
Each slot is an async server component that fetches data then renders the chart:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { delay } from '@/constants/mock-api';
|
||||||
|
import { AreaGraph } from '@/features/overview/components/area-graph';
|
||||||
|
|
||||||
|
export default async function AreaStatsPage() {
|
||||||
|
await delay(2000); // Simulates API fetch
|
||||||
|
return <AreaGraph />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Slot Loading (`@area_stats/loading.tsx`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { AreaGraphSkeleton } from '@/features/overview/components/area-graph-skeleton';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <AreaGraphSkeleton />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Slot Error (`@area_stats/error.tsx`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||||
|
import { Icons } from '@/components/icons';
|
||||||
|
|
||||||
|
export default function AreaStatsError({ error }: { error: Error }) {
|
||||||
|
return (
|
||||||
|
<Alert variant='destructive'>
|
||||||
|
<Icons.alertCircle className='h-4 w-4' />
|
||||||
|
<AlertTitle>Error</AlertTitle>
|
||||||
|
<AlertDescription>Failed to load area stats: {error.message}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each slot can fail independently without affecting others.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart Components
|
||||||
|
|
||||||
|
All chart components are `'use client'` and use **Recharts** wrapped in shadcn's `ChartContainer`.
|
||||||
|
|
||||||
|
### Chart Config
|
||||||
|
|
||||||
|
Every chart defines a config object mapping data keys to labels and theme colors:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import {
|
||||||
|
type ChartConfig,
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent
|
||||||
|
} from '@/components/ui/chart';
|
||||||
|
|
||||||
|
const chartConfig = {
|
||||||
|
desktop: { label: 'Desktop', color: 'var(--chart-1)' },
|
||||||
|
mobile: { label: 'Mobile', color: 'var(--chart-2)' }
|
||||||
|
} satisfies ChartConfig;
|
||||||
|
```
|
||||||
|
|
||||||
|
Theme colors `--chart-1` through `--chart-5` are defined in each theme's CSS file and automatically adapt to light/dark mode.
|
||||||
|
|
||||||
|
### Area Chart Example
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { Area, AreaChart, CartesianGrid, XAxis } from 'recharts';
|
||||||
|
import {
|
||||||
|
type ChartConfig,
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent
|
||||||
|
} from '@/components/ui/chart';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Icons } from '@/components/icons';
|
||||||
|
|
||||||
|
const chartData = [
|
||||||
|
{ month: 'January', desktop: 186, mobile: 80 },
|
||||||
|
{ month: 'February', desktop: 305, mobile: 200 }
|
||||||
|
// ...more months
|
||||||
|
];
|
||||||
|
|
||||||
|
const chartConfig = {
|
||||||
|
desktop: { label: 'Desktop', color: 'var(--chart-1)' },
|
||||||
|
mobile: { label: 'Mobile', color: 'var(--chart-2)' }
|
||||||
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
|
export function AreaGraph() {
|
||||||
|
return (
|
||||||
|
<Card className='@container/card'>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Area Chart - Stacked</CardTitle>
|
||||||
|
<Badge variant='outline'>
|
||||||
|
<Icons.trendingUp className='mr-1 h-3 w-3' /> +12.5%
|
||||||
|
</Badge>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ChartContainer config={chartConfig} className='aspect-auto h-[250px] w-full'>
|
||||||
|
<AreaChart data={chartData}>
|
||||||
|
<CartesianGrid vertical={false} />
|
||||||
|
<XAxis
|
||||||
|
dataKey='month'
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
tickFormatter={(value) => value.slice(0, 3)}
|
||||||
|
/>
|
||||||
|
<ChartTooltip content={<ChartTooltipContent indicator='dot' />} />
|
||||||
|
<Area
|
||||||
|
dataKey='mobile'
|
||||||
|
type='natural'
|
||||||
|
fill='var(--color-mobile)'
|
||||||
|
stroke='var(--color-mobile)'
|
||||||
|
stackId='a'
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
dataKey='desktop'
|
||||||
|
type='natural'
|
||||||
|
fill='var(--color-desktop)'
|
||||||
|
stroke='var(--color-desktop)'
|
||||||
|
stackId='a'
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ChartContainer>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bar Chart Pattern
|
||||||
|
|
||||||
|
Same structure, using `BarChart` + `Bar`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<ChartContainer config={chartConfig}>
|
||||||
|
<BarChart data={chartData}>
|
||||||
|
<CartesianGrid vertical={false} />
|
||||||
|
<XAxis dataKey='month' tickLine={false} axisLine={false} />
|
||||||
|
<ChartTooltip content={<ChartTooltipContent />} />
|
||||||
|
<Bar dataKey='desktop' fill='var(--color-desktop)' radius={4} />
|
||||||
|
<Bar dataKey='mobile' fill='var(--color-mobile)' radius={4} />
|
||||||
|
</BarChart>
|
||||||
|
</ChartContainer>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pie/Donut Chart Pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<ChartContainer config={chartConfig}>
|
||||||
|
<PieChart>
|
||||||
|
<ChartTooltip content={<ChartTooltipContent hideLabel />} />
|
||||||
|
<Pie data={chartData} dataKey='visitors' nameKey='browser' innerRadius={30}>
|
||||||
|
<LabelList dataKey='visitors' className='fill-background' />
|
||||||
|
</Pie>
|
||||||
|
</PieChart>
|
||||||
|
</ChartContainer>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stats Cards
|
||||||
|
|
||||||
|
Stats cards are simple server-rendered `Card` components at the top of the layout — no parallel routes needed since they render instantly:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card>
|
||||||
|
<CardHeader className='flex flex-row items-center justify-between space-y-0 pb-2'>
|
||||||
|
<CardTitle className='text-sm font-medium'>Total Revenue</CardTitle>
|
||||||
|
<Icons.billing className='h-4 w-4 text-muted-foreground' />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className='text-2xl font-bold'>$45,231.89</div>
|
||||||
|
<p className='text-xs text-muted-foreground'>+20.1% from last month</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
For dynamic stats that need data fetching, wrap in their own Suspense boundary or parallel route slot.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Skeleton Loading
|
||||||
|
|
||||||
|
Each chart has a matching skeleton component. Pattern:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
|
||||||
|
export function AreaGraphSkeleton() {
|
||||||
|
return (
|
||||||
|
<Card className='@container/card'>
|
||||||
|
<CardHeader>
|
||||||
|
<Skeleton className='h-5 w-[140px]' />
|
||||||
|
<Skeleton className='h-4 w-[80px]' />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Skeleton className='h-[250px] w-full rounded-md' />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Match the skeleton dimensions to the actual chart for smooth visual transitions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a New Chart Section
|
||||||
|
|
||||||
|
To add a new chart (e.g., line chart for user growth):
|
||||||
|
|
||||||
|
### 1. Create the chart component
|
||||||
|
|
||||||
|
`src/features/overview/components/line-graph.tsx`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { Line, LineChart, CartesianGrid, XAxis } from 'recharts';
|
||||||
|
import {
|
||||||
|
type ChartConfig,
|
||||||
|
ChartContainer,
|
||||||
|
ChartTooltip,
|
||||||
|
ChartTooltipContent
|
||||||
|
} from '@/components/ui/chart';
|
||||||
|
|
||||||
|
const chartConfig = {
|
||||||
|
users: { label: 'Users', color: 'var(--chart-3)' }
|
||||||
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
|
const chartData = [
|
||||||
|
/* monthly user data */
|
||||||
|
];
|
||||||
|
|
||||||
|
export function LineGraph() {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>User Growth</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ChartContainer config={chartConfig} className='aspect-auto h-[250px] w-full'>
|
||||||
|
<LineChart data={chartData}>
|
||||||
|
<CartesianGrid vertical={false} />
|
||||||
|
<XAxis dataKey='month' tickLine={false} axisLine={false} />
|
||||||
|
<ChartTooltip content={<ChartTooltipContent />} />
|
||||||
|
<Line dataKey='users' type='monotone' stroke='var(--color-users)' strokeWidth={2} />
|
||||||
|
</LineChart>
|
||||||
|
</ChartContainer>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Create matching skeleton
|
||||||
|
|
||||||
|
`src/features/overview/components/line-graph-skeleton.tsx`
|
||||||
|
|
||||||
|
### 3. Create parallel route slot
|
||||||
|
|
||||||
|
```
|
||||||
|
src/app/dashboard/overview/@line_stats/
|
||||||
|
├── page.tsx → async, fetches data, returns <LineGraph />
|
||||||
|
├── loading.tsx → returns <LineGraphSkeleton />
|
||||||
|
├── error.tsx → error alert
|
||||||
|
└── default.tsx → return null (fallback when route doesn't match)
|
||||||
|
```
|
||||||
|
|
||||||
|
`default.tsx` is required for parallel routes — return `null` or a fallback:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default function Default() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Add slot to layout
|
||||||
|
|
||||||
|
Update `src/app/dashboard/overview/layout.tsx`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default function OverviewLayout({
|
||||||
|
sales,
|
||||||
|
pie_stats,
|
||||||
|
bar_stats,
|
||||||
|
area_stats,
|
||||||
|
line_stats // ← add new slot
|
||||||
|
}: {
|
||||||
|
/* ...types */
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className='grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-7'>
|
||||||
|
{/* existing charts */}
|
||||||
|
<div className='col-span-4'>{line_stats}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Available Recharts Components
|
||||||
|
|
||||||
|
Common chart types to use with `ChartContainer`:
|
||||||
|
|
||||||
|
- `AreaChart` + `Area` — filled area charts (stacked or standalone)
|
||||||
|
- `BarChart` + `Bar` — vertical/horizontal bars
|
||||||
|
- `LineChart` + `Line` — line/trend charts
|
||||||
|
- `PieChart` + `Pie` — pie/donut charts
|
||||||
|
- `RadarChart` + `Radar` — radar/spider charts
|
||||||
|
- `RadialBarChart` + `RadialBar` — radial progress bars
|
||||||
|
|
||||||
|
All support `ChartTooltip`, `ChartLegend`, and theme-aware colors via `var(--chart-N)`.
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
# Forms Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Architecture](#architecture)
|
||||||
|
2. [Field Types](#field-types)
|
||||||
|
3. [Usage Patterns](#usage-patterns)
|
||||||
|
4. [Validation Strategies](#validation-strategies)
|
||||||
|
5. [Sheet/Dialog Forms](#sheetdialog-forms)
|
||||||
|
6. [Multi-Step Forms](#multi-step-forms)
|
||||||
|
7. [Advanced Patterns](#advanced-patterns)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The form system is built on **TanStack Form + Zod** with a composable field layer.
|
||||||
|
|
||||||
|
**Key files:**
|
||||||
|
|
||||||
|
- `src/components/ui/tanstack-form.tsx` — exports `useAppForm`, `useFormFields<T>()`, composed fields
|
||||||
|
- `src/components/ui/form-context.tsx` — contexts, `createFormField`, structural components
|
||||||
|
- `src/components/forms/fields/*.tsx` — 8 field type implementations
|
||||||
|
|
||||||
|
**Key exports:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
|
||||||
|
```
|
||||||
|
|
||||||
|
- `useAppForm(config)` — creates a form instance with `defaultValues`, `validators`, `onSubmit`
|
||||||
|
- `useFormFields<T>()` — returns all 8 typed field components with name autocomplete from `T`
|
||||||
|
- `form.AppForm` — context provider wrapper
|
||||||
|
- `form.Form` — `<form>` element that handles submit
|
||||||
|
- `form.SubmitButton` — auto-disabled when form is invalid or submitting
|
||||||
|
- `form.AppField` — low-level render prop for custom fields
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Field Types
|
||||||
|
|
||||||
|
All fields accept: `name`, `label`, `description`, `required`, `disabled`, `validators`, `listeners`, `className`.
|
||||||
|
|
||||||
|
| Component | Props | Notes |
|
||||||
|
| --------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------- |
|
||||||
|
| `FormTextField` | `type` (text/email/number/password/tel/url), `placeholder`, `min`, `max`, `step`, `maxLength` | For numbers use `type='number'` |
|
||||||
|
| `FormTextareaField` | `placeholder`, `rows`, `maxLength` | Multiline text |
|
||||||
|
| `FormSelectField` | `options: {value, label}[]`, `placeholder` | Single select dropdown |
|
||||||
|
| `FormCheckboxField` | `options?: {value, label}[]` | Single checkbox or multi-checkbox group |
|
||||||
|
| `FormSwitchField` | — | Toggle switch |
|
||||||
|
| `FormRadioGroupField` | `options: {value, label}[]`, `orientation` | Radio button group |
|
||||||
|
| `FormSliderField` | `min`, `max`, `step` | Range slider |
|
||||||
|
| `FormFileUploadField` | `maxSize`, `maxFiles`, `accept` | Drag-and-drop with preview |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Usage Patterns
|
||||||
|
|
||||||
|
### Pattern 1: `useFormFields<T>()` (Recommended)
|
||||||
|
|
||||||
|
Type-safe field components with name autocomplete:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const { FormTextField, FormSelectField } = useFormFields<OrderFormValues>();
|
||||||
|
|
||||||
|
<FormTextField name='customer' label='Customer' required placeholder='Name'
|
||||||
|
validators={{ onBlur: z.string().min(2) }} />
|
||||||
|
|
||||||
|
<FormSelectField name='status' label='Status' required options={STATUS_OPTIONS}
|
||||||
|
validators={{ onBlur: z.string().min(1) }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 2: `form.AppField` render prop
|
||||||
|
|
||||||
|
Full control for custom field rendering:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<form.AppField name='framework'>
|
||||||
|
{(field) => (
|
||||||
|
<field.FieldSet>
|
||||||
|
<field.Field>
|
||||||
|
<field.TextField label='Framework' />
|
||||||
|
</field.Field>
|
||||||
|
<field.FieldError />
|
||||||
|
</field.FieldSet>
|
||||||
|
)}
|
||||||
|
</form.AppField>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 3: Direct import (no type safety)
|
||||||
|
|
||||||
|
For quick prototyping:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { FormTextField } from '@/components/ui/tanstack-form';
|
||||||
|
<FormTextField name='name' label='Name' />;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Validation Strategies
|
||||||
|
|
||||||
|
### Field-level (recommended for UX)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FormTextField
|
||||||
|
name='email'
|
||||||
|
label='Email'
|
||||||
|
validators={{
|
||||||
|
onBlur: z.string().email('Invalid email') // Validates when field loses focus
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Form-level (catch-all on submit)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const form = useAppForm({
|
||||||
|
validators: { onSubmit: orderSchema }, // Validates entire form on submit
|
||||||
|
onSubmit: async ({ value }) => {
|
||||||
|
/* ... */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Async validation (server-side checks)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FormTextField
|
||||||
|
name='username'
|
||||||
|
label='Username'
|
||||||
|
validators={{
|
||||||
|
onChangeAsync: async ({ value }) => {
|
||||||
|
const exists = await checkUsername(value);
|
||||||
|
return exists ? 'Username taken' : undefined;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
asyncDebounceMs={500}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linked field validation
|
||||||
|
|
||||||
|
For dependent fields (e.g., confirm password):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FormTextField
|
||||||
|
name='confirmPassword'
|
||||||
|
label='Confirm Password'
|
||||||
|
validators={{
|
||||||
|
onChangeListenTo: ['password'],
|
||||||
|
onChange: ({ value, fieldApi }) => {
|
||||||
|
const password = fieldApi.form.getFieldValue('password');
|
||||||
|
return value !== password ? 'Passwords must match' : undefined;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sheet/Dialog Forms
|
||||||
|
|
||||||
|
The key pattern for forms inside sheets or dialogs: give the `<form.Form>` an `id`, and use that `id` on the submit button's `form` attribute. This allows the submit button to live outside the form element (e.g., in `SheetFooter`).
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<form.AppForm>
|
||||||
|
<form.Form id='my-sheet-form' className='space-y-4'>
|
||||||
|
{/* fields */}
|
||||||
|
</form.Form>
|
||||||
|
</form.AppForm>;
|
||||||
|
|
||||||
|
{
|
||||||
|
/* In SheetFooter — button is outside the <form> but still submits it */
|
||||||
|
}
|
||||||
|
<SheetFooter>
|
||||||
|
<Button type='submit' form='my-sheet-form'>
|
||||||
|
Save
|
||||||
|
</Button>
|
||||||
|
</SheetFooter>;
|
||||||
|
```
|
||||||
|
|
||||||
|
On success, call `onOpenChange(false)` to close the sheet and `form.reset()` for create forms.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Multi-Step Forms
|
||||||
|
|
||||||
|
Use `withFieldGroup` + `useAppForm` with `StepButton`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Define field groups for each step
|
||||||
|
const Step1 = withFieldGroup({
|
||||||
|
fields: ['name', 'email'],
|
||||||
|
render: ({ form }) => {
|
||||||
|
const { FormTextField } = useFormFields<FormValues>();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<FormTextField name='name' label='Name' />
|
||||||
|
<FormTextField name='email' label='Email' />
|
||||||
|
<form.StepButton direction='next' label='Next' />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const Step2 = withFieldGroup({
|
||||||
|
fields: ['address', 'city'],
|
||||||
|
render: ({ form }) => {
|
||||||
|
const { FormTextField } = useFormFields<FormValues>();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<FormTextField name='address' label='Address' />
|
||||||
|
<FormTextField name='city' label='City' />
|
||||||
|
<form.StepButton direction='prev' label='Back' />
|
||||||
|
<form.SubmitButton label='Submit' />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Use the `useStepper` hook from `src/hooks/use-stepper.tsx` to manage step state.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Advanced Patterns
|
||||||
|
|
||||||
|
### Nested objects (dot notation)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FormTextField name='address.street' label='Street' />
|
||||||
|
<FormTextField name='address.city' label='City' />
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dynamic array rows
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<form.AppField name='items' mode='array'>
|
||||||
|
{(field) => (
|
||||||
|
<>
|
||||||
|
{field.state.value.map((_, i) => (
|
||||||
|
<form.AppField key={i} name={`items[${i}].name`}>
|
||||||
|
{(subField) => <subField.TextField label={`Item ${i + 1}`} />}
|
||||||
|
</form.AppField>
|
||||||
|
))}
|
||||||
|
<Button onClick={() => field.pushValue({ name: '' })}>Add Row</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</form.AppField>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Side effects with listeners
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FormSelectField
|
||||||
|
name='country'
|
||||||
|
label='Country'
|
||||||
|
options={countryOptions}
|
||||||
|
listeners={{
|
||||||
|
onChange: ({ value }) => {
|
||||||
|
// Reset city when country changes
|
||||||
|
form.setFieldValue('city', '');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom field with `form.AppField`
|
||||||
|
|
||||||
|
For fields not covered by the built-in 8 types:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<form.AppField name='color'>
|
||||||
|
{(field) => (
|
||||||
|
<field.FieldSet>
|
||||||
|
<Label>Pick a color</Label>
|
||||||
|
<field.Field>
|
||||||
|
<input
|
||||||
|
type='color'
|
||||||
|
value={field.state.value}
|
||||||
|
onChange={(e) => field.handleChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
</field.Field>
|
||||||
|
<field.FieldError />
|
||||||
|
</field.FieldSet>
|
||||||
|
)}
|
||||||
|
</form.AppField>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Form-level errors
|
||||||
|
|
||||||
|
Display errors that apply to the whole form (e.g., server errors):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { FormErrors } from '@/components/ui/form-context';
|
||||||
|
|
||||||
|
<form.AppForm>
|
||||||
|
<form.Form>
|
||||||
|
<FormErrors /> {/* Renders form-level validation errors */}
|
||||||
|
{/* fields... */}
|
||||||
|
</form.Form>
|
||||||
|
</form.AppForm>;
|
||||||
|
```
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
# Mock API Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Structure](#structure)
|
||||||
|
2. [Full Template](#full-template)
|
||||||
|
3. [Key Patterns](#key-patterns)
|
||||||
|
4. [Integrating with React Query](#integrating-with-react-query)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
Each mock API file lives in `src/constants/mock-api-<name>.ts` and is a self-contained in-memory database. It uses:
|
||||||
|
|
||||||
|
- **faker** for generating sample data
|
||||||
|
- **match-sorter** for fuzzy search across fields
|
||||||
|
- **delay** (from `./mock-api`) to simulate network latency
|
||||||
|
|
||||||
|
The `delay` function is exported from `src/constants/mock-api.ts`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export async function delay(ms: number) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Full Template
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { faker } from '@faker-js/faker';
|
||||||
|
import { matchSorter } from 'match-sorter';
|
||||||
|
import { delay } from './mock-api';
|
||||||
|
|
||||||
|
// 1. Define the entity type
|
||||||
|
export type Order = {
|
||||||
|
id: number;
|
||||||
|
customer: string;
|
||||||
|
email: string;
|
||||||
|
status: string;
|
||||||
|
total: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Create the fake database object
|
||||||
|
export const fakeOrders = {
|
||||||
|
records: [] as Order[],
|
||||||
|
|
||||||
|
// 3. Initialize with faker data
|
||||||
|
initialize() {
|
||||||
|
const statuses = ['pending', 'processing', 'completed', 'cancelled'];
|
||||||
|
for (let i = 1; i <= 20; i++) {
|
||||||
|
this.records.push({
|
||||||
|
id: i,
|
||||||
|
customer: faker.person.fullName(),
|
||||||
|
email: faker.internet.email(),
|
||||||
|
status: faker.helpers.arrayElement(statuses),
|
||||||
|
total: parseFloat(faker.commerce.price({ min: 10, max: 500 })),
|
||||||
|
created_at: faker.date.between({ from: '2023-01-01', to: Date.now() }).toISOString(),
|
||||||
|
updated_at: faker.date.recent().toISOString()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// 4. Get all with optional search (used internally)
|
||||||
|
async getAll({ search }: { search?: string } = {}) {
|
||||||
|
let items = [...this.records];
|
||||||
|
if (search) {
|
||||||
|
items = matchSorter(items, search, {
|
||||||
|
keys: ['customer', 'email']
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 5. Paginated list with filtering and sorting
|
||||||
|
async getOrders(params: {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
statuses?: string;
|
||||||
|
sort?: string;
|
||||||
|
}) {
|
||||||
|
await delay(800);
|
||||||
|
const { page = 1, limit = 10, search, statuses, sort } = params;
|
||||||
|
|
||||||
|
let items = await this.getAll({ search });
|
||||||
|
|
||||||
|
// Filter by comma-separated values
|
||||||
|
if (statuses) {
|
||||||
|
const statusList = statuses.split('.');
|
||||||
|
items = items.filter((item) => statusList.includes(item.status));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by column
|
||||||
|
if (sort) {
|
||||||
|
const parsedSort = JSON.parse(sort) as { id: string; desc: boolean }[];
|
||||||
|
if (parsedSort.length > 0) {
|
||||||
|
const { id, desc } = parsedSort[0];
|
||||||
|
items.sort((a, b) => {
|
||||||
|
const aVal = a[id as keyof Order];
|
||||||
|
const bVal = b[id as keyof Order];
|
||||||
|
if (aVal < bVal) return desc ? 1 : -1;
|
||||||
|
if (aVal > bVal) return desc ? -1 : 1;
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginate
|
||||||
|
const total_items = items.length;
|
||||||
|
items = items.slice((page - 1) * limit, page * limit);
|
||||||
|
|
||||||
|
return { items, total_items };
|
||||||
|
},
|
||||||
|
|
||||||
|
// 6. Get single record by ID
|
||||||
|
async getOrderById(id: number) {
|
||||||
|
await delay(800);
|
||||||
|
return this.records.find((r) => r.id === id) || null;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 7. Create
|
||||||
|
async createOrder(data: Omit<Order, 'id' | 'created_at' | 'updated_at'>) {
|
||||||
|
await delay(800);
|
||||||
|
const newRecord: Order = {
|
||||||
|
...data,
|
||||||
|
id: this.records.length + 1,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
updated_at: new Date().toISOString()
|
||||||
|
};
|
||||||
|
this.records.push(newRecord);
|
||||||
|
return newRecord;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 8. Update
|
||||||
|
async updateOrder(id: number, data: Partial<Order>) {
|
||||||
|
await delay(800);
|
||||||
|
const idx = this.records.findIndex((r) => r.id === id);
|
||||||
|
if (idx === -1) return null;
|
||||||
|
this.records[idx] = {
|
||||||
|
...this.records[idx],
|
||||||
|
...data,
|
||||||
|
updated_at: new Date().toISOString()
|
||||||
|
};
|
||||||
|
return this.records[idx];
|
||||||
|
},
|
||||||
|
|
||||||
|
// 9. Delete
|
||||||
|
async deleteOrder(id: number) {
|
||||||
|
await delay(800);
|
||||||
|
this.records = this.records.filter((r) => r.id !== id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 10. Auto-initialize on import
|
||||||
|
fakeOrders.initialize();
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Patterns
|
||||||
|
|
||||||
|
### Search with match-sorter
|
||||||
|
|
||||||
|
Always specify which fields to search across:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
matchSorter(items, search, { keys: ['customer', 'email', 'status'] });
|
||||||
|
```
|
||||||
|
|
||||||
|
### Comma-separated filter values
|
||||||
|
|
||||||
|
For multi-select filters (roles, statuses), the URL param uses `.` as delimiter:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
if (statuses) {
|
||||||
|
const list = statuses.split('.');
|
||||||
|
items = items.filter((item) => list.includes(item.status));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Computed column sorting
|
||||||
|
|
||||||
|
When a table has a computed column (e.g., combining first_name + last_name into "name"), handle it in the sort logic:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
if (id === 'name') {
|
||||||
|
const aName = `${a.first_name} ${a.last_name}`;
|
||||||
|
const bName = `${b.first_name} ${b.last_name}`;
|
||||||
|
return desc ? bName.localeCompare(aName) : aName.localeCompare(bName);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Return shape
|
||||||
|
|
||||||
|
List methods must return `{ items, total_items }` (or `{ products, total }` etc. — match the query option expectations). The total is the count **before** pagination, used for `pageCount` calculation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Integrating with the API Layer
|
||||||
|
|
||||||
|
The mock API is only imported in `service.ts`. Queries and components import from the service and types files:
|
||||||
|
|
||||||
|
```
|
||||||
|
mock-api-orders.ts → api/service.ts → api/queries.ts → components
|
||||||
|
(data source) (data access) (key factory + (useSuspenseQuery
|
||||||
|
queryOptions) + useMutation)
|
||||||
|
```
|
||||||
|
|
||||||
|
**service.ts** imports from the mock API:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { fakeOrders } from '@/constants/mock-api-orders';
|
||||||
|
import type { OrderFilters, OrdersResponse } from './types';
|
||||||
|
|
||||||
|
export async function getOrders(filters: OrderFilters): Promise<OrdersResponse> {
|
||||||
|
return fakeOrders.getOrders(filters);
|
||||||
|
}
|
||||||
|
export async function createOrder(data: OrderMutationPayload) {
|
||||||
|
return fakeOrders.createOrder(data);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**queries.ts** imports from service, uses key factories:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { getOrders } from './service';
|
||||||
|
import type { OrderFilters } from './types';
|
||||||
|
|
||||||
|
export const orderKeys = {
|
||||||
|
all: ['orders'] as const,
|
||||||
|
list: (filters: OrderFilters) => [...orderKeys.all, 'list', filters] as const,
|
||||||
|
detail: (id: number) => [...orderKeys.all, 'detail', id] as const
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ordersQueryOptions = (filters: OrderFilters) =>
|
||||||
|
queryOptions({ queryKey: orderKeys.list(filters), queryFn: () => getOrders(filters) });
|
||||||
|
```
|
||||||
|
|
||||||
|
**Mutations** in components use service functions + key factories:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { createOrder } from '../api/service';
|
||||||
|
import { orderKeys } from '../api/queries';
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: (data) => createOrder(data),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: orderKeys.all })
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
# TanStack Query Abstractions (v5)
|
||||||
|
|
||||||
|
The core insight: **`queryOptions` and `mutationOptions` are the right abstraction — not custom hooks.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Query Abstraction
|
||||||
|
|
||||||
|
### The Pattern
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// queries/invoice.ts
|
||||||
|
import { queryOptions } from '@tanstack/react-query';
|
||||||
|
|
||||||
|
export function invoiceOptions(id: number) {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: ['invoice', id],
|
||||||
|
queryFn: () => fetchInvoice(id)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invoiceListOptions(filters: InvoiceFilters) {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: ['invoices', filters],
|
||||||
|
queryFn: () => fetchInvoices(filters),
|
||||||
|
staleTime: 30_000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usage — always compose at the call site
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// basic
|
||||||
|
const { data } = useQuery(invoiceOptions(id));
|
||||||
|
|
||||||
|
// with suspense — same options, different hook
|
||||||
|
const { data } = useSuspenseQuery(invoiceOptions(id));
|
||||||
|
|
||||||
|
// with extra options spread on top — full type inference, no TS pain
|
||||||
|
const { data } = useQuery({
|
||||||
|
...invoiceOptions(id),
|
||||||
|
select: (invoice) => invoice.createdAt, // data infers as string | undefined
|
||||||
|
enabled: !!id
|
||||||
|
});
|
||||||
|
|
||||||
|
// prefetch in a route loader (works outside React — this is why hooks are wrong)
|
||||||
|
await queryClient.prefetchQuery(invoiceOptions(id));
|
||||||
|
|
||||||
|
// read from cache imperatively — queryKey is typed via DataTag symbol
|
||||||
|
const invoice = queryClient.getQueryData(invoiceOptions(id).queryKey);
|
||||||
|
|
||||||
|
// invalidate
|
||||||
|
queryClient.invalidateQueries({ queryKey: invoiceOptions(id).queryKey });
|
||||||
|
```
|
||||||
|
|
||||||
|
### Why NOT a custom hook
|
||||||
|
|
||||||
|
Custom hooks like `useInvoice(id)` have three critical problems:
|
||||||
|
|
||||||
|
1. **Hooks only work in components/hooks** — but queries are now used in route loaders, server prefetching, event handlers, and server components. `queryOptions` is just a plain function — works anywhere.
|
||||||
|
2. **They share logic, not configuration** — what you actually want to share is the `queryKey` + `queryFn` config. Hooks are the wrong primitive for that.
|
||||||
|
3. **They lock you to one hook** — you can't use `useInvoice()` with `useSuspenseQuery`, `useQueries`, or imperative `queryClient` methods.
|
||||||
|
|
||||||
|
### Why NOT `UseQueryOptions` type directly
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// BAD — data becomes unknown
|
||||||
|
function useInvoice(id: number, options?: Partial<UseQueryOptions>) { ... }
|
||||||
|
|
||||||
|
// STILL BAD — select breaks with TS error
|
||||||
|
function useInvoice(id: number, options?: Partial<UseQueryOptions<Invoice>>) { ... }
|
||||||
|
// select: (invoice) => invoice.createdAt
|
||||||
|
// Error: Type 'string' is not assignable to type 'Invoice'
|
||||||
|
```
|
||||||
|
|
||||||
|
`queryOptions` solves this via a `DataTag` symbol on the queryKey — full inference, zero manual generics.
|
||||||
|
|
||||||
|
### Custom hooks are still fine on top
|
||||||
|
|
||||||
|
If a component always uses the same composition, a hook is fine — but build it _on top of_ `queryOptions`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// OK — hook built on queryOptions
|
||||||
|
function useInvoice(id: number) {
|
||||||
|
return useQuery(invoiceOptions(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// OK — hook that adds per-feature defaults
|
||||||
|
function useInvoiceWithSuspense(id: number) {
|
||||||
|
return useSuspenseQuery(invoiceOptions(id));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mutation Abstraction
|
||||||
|
|
||||||
|
### The Pattern
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// mutations/invoice.ts
|
||||||
|
import { mutationOptions } from '@tanstack/react-query';
|
||||||
|
import { getQueryClient } from '@/lib/query-client';
|
||||||
|
|
||||||
|
export const createInvoiceMutation = mutationOptions({
|
||||||
|
mutationFn: (data: CreateInvoiceInput) => createInvoice(data),
|
||||||
|
onSuccess: () => {
|
||||||
|
getQueryClient().invalidateQueries({ queryKey: ['invoices'] });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateInvoiceMutation = mutationOptions({
|
||||||
|
mutationFn: ({ id, ...data }: UpdateInvoiceInput) => updateInvoice(id, data),
|
||||||
|
onSuccess: (updated) => {
|
||||||
|
const qc = getQueryClient();
|
||||||
|
qc.setQueryData(invoiceOptions(updated.id).queryKey, updated);
|
||||||
|
qc.invalidateQueries({ queryKey: ['invoices'] });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note on queryClient**: Import `getQueryClient()` directly — do NOT pass `queryClient` as a function argument. The `getQueryClient()` pattern handles both SSR (fresh per request) and client (singleton) correctly.
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// basic
|
||||||
|
const { mutate } = useMutation(createInvoiceMutation);
|
||||||
|
|
||||||
|
// composed — add per-usage callbacks on top
|
||||||
|
const { mutate } = useMutation({
|
||||||
|
...createInvoiceMutation,
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
// this runs AFTER the shared onSuccess above
|
||||||
|
router.push(`/invoices/${data.id}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rules Summary
|
||||||
|
|
||||||
|
| Rule | Reason |
|
||||||
|
| ------------------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||||
|
| Use `queryOptions()` not custom hooks as the base abstraction | Works everywhere — loaders, server, imperative calls |
|
||||||
|
| Keep options factories lean — no extra config params | Best abstractions are not configurable |
|
||||||
|
| Compose extra options at the call site via spread | Full TS inference without manual generics |
|
||||||
|
| Import `getQueryClient()` in mutation files | Handles SSR/client correctly without prop drilling |
|
||||||
|
| Co-locate `queryKey` inside `queryOptions` | Typed key reuse in `invalidateQueries`, `setQueryData`, `getQueryData` |
|
||||||
|
| Custom hooks are fine — but built ON TOP of `queryOptions` | Hooks for component convenience, `queryOptions` for sharing config |
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# Theme Creation Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Create Theme CSS](#1-create-theme-css)
|
||||||
|
2. [Import Theme](#2-import-theme)
|
||||||
|
3. [Register Theme](#3-register-theme)
|
||||||
|
4. [Add Custom Fonts](#4-add-custom-fonts-optional)
|
||||||
|
5. [Set as Default](#5-set-as-default-optional)
|
||||||
|
6. [Required Tokens](#required-tokens)
|
||||||
|
7. [Color Format Reference](#color-format-reference)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Create Theme CSS
|
||||||
|
|
||||||
|
Create `src/styles/themes/<name>.css`:
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* Light mode */
|
||||||
|
[data-theme='your-theme'] {
|
||||||
|
--background: oklch(1 0 0);
|
||||||
|
--foreground: oklch(0.145 0 0);
|
||||||
|
--card: oklch(...);
|
||||||
|
--card-foreground: oklch(...);
|
||||||
|
--popover: oklch(...);
|
||||||
|
--popover-foreground: oklch(...);
|
||||||
|
--primary: oklch(...);
|
||||||
|
--primary-foreground: oklch(...);
|
||||||
|
--secondary: oklch(...);
|
||||||
|
--secondary-foreground: oklch(...);
|
||||||
|
--muted: oklch(...);
|
||||||
|
--muted-foreground: oklch(...);
|
||||||
|
--accent: oklch(...);
|
||||||
|
--accent-foreground: oklch(...);
|
||||||
|
--destructive: oklch(...);
|
||||||
|
--destructive-foreground: oklch(...);
|
||||||
|
--border: oklch(...);
|
||||||
|
--input: oklch(...);
|
||||||
|
--ring: oklch(...);
|
||||||
|
--chart-1: oklch(...);
|
||||||
|
--chart-2: oklch(...);
|
||||||
|
--chart-3: oklch(...);
|
||||||
|
--chart-4: oklch(...);
|
||||||
|
--chart-5: oklch(...);
|
||||||
|
--sidebar: oklch(...);
|
||||||
|
--sidebar-foreground: oklch(...);
|
||||||
|
--sidebar-primary: oklch(...);
|
||||||
|
--sidebar-primary-foreground: oklch(...);
|
||||||
|
--sidebar-accent: oklch(...);
|
||||||
|
--sidebar-accent-foreground: oklch(...);
|
||||||
|
--sidebar-border: oklch(...);
|
||||||
|
--sidebar-ring: oklch(...);
|
||||||
|
--font-sans: 'Font Name', sans-serif;
|
||||||
|
--font-mono: 'Mono Font', monospace;
|
||||||
|
--radius: 0.5rem;
|
||||||
|
--spacing: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark mode */
|
||||||
|
[data-theme='your-theme'].dark {
|
||||||
|
--background: oklch(0.145 0 0);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
/* ... all tokens with dark values */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tailwind integration (required) */
|
||||||
|
[data-theme='your-theme'] {
|
||||||
|
@theme inline {
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-destructive-foreground: var(--destructive-foreground);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
--font-sans: var(--font-sans);
|
||||||
|
--font-mono: var(--font-mono);
|
||||||
|
--font-serif: var(--font-serif);
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. Import Theme
|
||||||
|
|
||||||
|
Add to `src/styles/theme.css`:
|
||||||
|
|
||||||
|
```css
|
||||||
|
@import './themes/your-theme.css';
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Register Theme
|
||||||
|
|
||||||
|
Add to `THEMES` array in `src/components/themes/theme.config.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
{ name: 'Your Theme', value: 'your-theme' }
|
||||||
|
```
|
||||||
|
|
||||||
|
The `value` must exactly match the `data-theme` attribute in your CSS.
|
||||||
|
|
||||||
|
## 4. Add Custom Fonts (Optional)
|
||||||
|
|
||||||
|
Only if using a Google Font not already loaded.
|
||||||
|
|
||||||
|
In `src/components/themes/font.config.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Your_Font } from 'next/font/google';
|
||||||
|
|
||||||
|
const fontYourName = Your_Font({
|
||||||
|
subsets: ['latin'],
|
||||||
|
weight: ['400', '500', '700'],
|
||||||
|
variable: '--font-your-name'
|
||||||
|
});
|
||||||
|
|
||||||
|
export const fontVariables = cn(
|
||||||
|
// ... existing fonts
|
||||||
|
fontYourName.variable
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
In your theme CSS, use the font's **display name** (not the CSS variable):
|
||||||
|
|
||||||
|
```css
|
||||||
|
--font-sans: 'Your Font', sans-serif;
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Set as Default (Optional)
|
||||||
|
|
||||||
|
In `src/components/themes/theme.config.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const DEFAULT_THEME = 'your-theme';
|
||||||
|
```
|
||||||
|
|
||||||
|
## Required Tokens
|
||||||
|
|
||||||
|
Minimum required: `--background`, `--foreground`, `--card` & `--card-foreground`, `--popover` & `--popover-foreground`, `--primary` & `--primary-foreground`, `--secondary` & `--secondary-foreground`, `--muted` & `--muted-foreground`, `--accent` & `--accent-foreground`, `--destructive` & `--destructive-foreground`, `--border`, `--input`, `--ring`, `--radius`.
|
||||||
|
|
||||||
|
Optional: `--chart-*`, `--sidebar-*`, `--font-*`, `--shadow-*`, `--tracking-normal`, `--spacing`.
|
||||||
|
|
||||||
|
## Color Format Reference
|
||||||
|
|
||||||
|
OKLCH: `oklch(lightness chroma hue)`
|
||||||
|
|
||||||
|
- Lightness: 0-1 (0=black, 1=white)
|
||||||
|
- Chroma: 0+ (0=gray, higher=saturated)
|
||||||
|
- Hue: 0-360 (0=red, 120=green, 240=blue)
|
||||||
|
|
||||||
|
See `src/styles/themes/claude.css` for a complete example.
|
||||||
171
.agents/skills/next-best-practices/SKILL.md
Normal file
171
.agents/skills/next-best-practices/SKILL.md
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
---
|
||||||
|
name: next-best-practices
|
||||||
|
description: Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling
|
||||||
|
user-invocable: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Next.js Best Practices
|
||||||
|
|
||||||
|
Apply these rules when writing or reviewing Next.js code.
|
||||||
|
|
||||||
|
## File Conventions
|
||||||
|
|
||||||
|
See [file-conventions.md](./file-conventions.md) for:
|
||||||
|
|
||||||
|
- Project structure and special files
|
||||||
|
- Route segments (dynamic, catch-all, groups)
|
||||||
|
- Parallel and intercepting routes
|
||||||
|
- Middleware rename in v16 (middleware → proxy)
|
||||||
|
|
||||||
|
## RSC Boundaries
|
||||||
|
|
||||||
|
Detect invalid React Server Component patterns.
|
||||||
|
|
||||||
|
See [rsc-boundaries.md](./rsc-boundaries.md) for:
|
||||||
|
|
||||||
|
- Async client component detection (invalid)
|
||||||
|
- Non-serializable props detection
|
||||||
|
- Server Action exceptions
|
||||||
|
|
||||||
|
## Async Patterns
|
||||||
|
|
||||||
|
Next.js 15+ async API changes.
|
||||||
|
|
||||||
|
See [async-patterns.md](./async-patterns.md) for:
|
||||||
|
|
||||||
|
- Async `params` and `searchParams`
|
||||||
|
- Async `cookies()` and `headers()`
|
||||||
|
- Migration codemod
|
||||||
|
|
||||||
|
## Runtime Selection
|
||||||
|
|
||||||
|
See [runtime-selection.md](./runtime-selection.md) for:
|
||||||
|
|
||||||
|
- Default to Node.js runtime
|
||||||
|
- When Edge runtime is appropriate
|
||||||
|
|
||||||
|
## Directives
|
||||||
|
|
||||||
|
See [directives.md](./directives.md) for:
|
||||||
|
|
||||||
|
- `'use client'`, `'use server'` (React)
|
||||||
|
- `'use cache'` (Next.js)
|
||||||
|
|
||||||
|
## Functions
|
||||||
|
|
||||||
|
See [functions.md](./functions.md) for:
|
||||||
|
|
||||||
|
- Navigation hooks: `useRouter`, `usePathname`, `useSearchParams`, `useParams`
|
||||||
|
- Server functions: `cookies`, `headers`, `draftMode`, `after`
|
||||||
|
- Generate functions: `generateStaticParams`, `generateMetadata`
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
See [error-handling.md](./error-handling.md) for:
|
||||||
|
|
||||||
|
- `error.tsx`, `global-error.tsx`, `not-found.tsx`
|
||||||
|
- `redirect`, `permanentRedirect`, `notFound`
|
||||||
|
- `forbidden`, `unauthorized` (auth errors)
|
||||||
|
- `unstable_rethrow` for catch blocks
|
||||||
|
|
||||||
|
## Data Patterns
|
||||||
|
|
||||||
|
See [data-patterns.md](./data-patterns.md) for:
|
||||||
|
|
||||||
|
- Server Components vs Server Actions vs Route Handlers
|
||||||
|
- Avoiding data waterfalls (`Promise.all`, Suspense, preload)
|
||||||
|
- Client component data fetching
|
||||||
|
|
||||||
|
## Route Handlers
|
||||||
|
|
||||||
|
See [route-handlers.md](./route-handlers.md) for:
|
||||||
|
|
||||||
|
- `route.ts` basics
|
||||||
|
- GET handler conflicts with `page.tsx`
|
||||||
|
- Environment behavior (no React DOM)
|
||||||
|
- When to use vs Server Actions
|
||||||
|
|
||||||
|
## Metadata & OG Images
|
||||||
|
|
||||||
|
See [metadata.md](./metadata.md) for:
|
||||||
|
|
||||||
|
- Static and dynamic metadata
|
||||||
|
- `generateMetadata` function
|
||||||
|
- OG image generation with `next/og`
|
||||||
|
- File-based metadata conventions
|
||||||
|
|
||||||
|
## Image Optimization
|
||||||
|
|
||||||
|
See [image.md](./image.md) for:
|
||||||
|
|
||||||
|
- Always use `next/image` over `<img>`
|
||||||
|
- Remote images configuration
|
||||||
|
- Responsive `sizes` attribute
|
||||||
|
- Blur placeholders
|
||||||
|
- Priority loading for LCP
|
||||||
|
|
||||||
|
## Font Optimization
|
||||||
|
|
||||||
|
See [font.md](./font.md) for:
|
||||||
|
|
||||||
|
- `next/font` setup
|
||||||
|
- Google Fonts, local fonts
|
||||||
|
- Tailwind CSS integration
|
||||||
|
- Preloading subsets
|
||||||
|
|
||||||
|
## Bundling
|
||||||
|
|
||||||
|
See [bundling.md](./bundling.md) for:
|
||||||
|
|
||||||
|
- Server-incompatible packages
|
||||||
|
- CSS imports (not link tags)
|
||||||
|
- Polyfills (already included)
|
||||||
|
- ESM/CommonJS issues
|
||||||
|
- Bundle analysis
|
||||||
|
|
||||||
|
## Scripts
|
||||||
|
|
||||||
|
See [scripts.md](./scripts.md) for:
|
||||||
|
|
||||||
|
- `next/script` vs native script tags
|
||||||
|
- Inline scripts need `id`
|
||||||
|
- Loading strategies
|
||||||
|
- Google Analytics with `@next/third-parties`
|
||||||
|
|
||||||
|
## Hydration Errors
|
||||||
|
|
||||||
|
See [hydration-error.md](./hydration-error.md) for:
|
||||||
|
|
||||||
|
- Common causes (browser APIs, dates, invalid HTML)
|
||||||
|
- Debugging with error overlay
|
||||||
|
- Fixes for each cause
|
||||||
|
|
||||||
|
## Suspense Boundaries
|
||||||
|
|
||||||
|
See [suspense-boundaries.md](./suspense-boundaries.md) for:
|
||||||
|
|
||||||
|
- CSR bailout with `useSearchParams` and `usePathname`
|
||||||
|
- Which hooks require Suspense boundaries
|
||||||
|
|
||||||
|
## Parallel & Intercepting Routes
|
||||||
|
|
||||||
|
See [parallel-routes.md](./parallel-routes.md) for:
|
||||||
|
|
||||||
|
- Modal patterns with `@slot` and `(.)` interceptors
|
||||||
|
- `default.tsx` for fallbacks
|
||||||
|
- Closing modals correctly with `router.back()`
|
||||||
|
|
||||||
|
## Self-Hosting
|
||||||
|
|
||||||
|
See [self-hosting.md](./self-hosting.md) for:
|
||||||
|
|
||||||
|
- `output: 'standalone'` for Docker
|
||||||
|
- Cache handlers for multi-instance ISR
|
||||||
|
- What works vs needs extra setup
|
||||||
|
|
||||||
|
## Debug Tricks
|
||||||
|
|
||||||
|
See [debug-tricks.md](./debug-tricks.md) for:
|
||||||
|
|
||||||
|
- MCP endpoint for AI-assisted debugging
|
||||||
|
- Rebuild specific routes with `--debug-build-paths`
|
||||||
84
.agents/skills/next-best-practices/async-patterns.md
Normal file
84
.agents/skills/next-best-practices/async-patterns.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# Async Patterns
|
||||||
|
|
||||||
|
In Next.js 15+, `params`, `searchParams`, `cookies()`, and `headers()` are asynchronous.
|
||||||
|
|
||||||
|
## Async Params and SearchParams
|
||||||
|
|
||||||
|
Always type them as `Promise<...>` and await them.
|
||||||
|
|
||||||
|
### Pages and Layouts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
type Props = { params: Promise<{ slug: string }> };
|
||||||
|
|
||||||
|
export default async function Page({ params }: Props) {
|
||||||
|
const { slug } = await params;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Route Handlers
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### SearchParams
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
type Props = {
|
||||||
|
params: Promise<{ slug: string }>;
|
||||||
|
searchParams: Promise<{ query?: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function Page({ params, searchParams }: Props) {
|
||||||
|
const { slug } = await params;
|
||||||
|
const { query } = await searchParams;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Synchronous Components
|
||||||
|
|
||||||
|
Use `React.use()` for non-async components:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { use } from 'react';
|
||||||
|
|
||||||
|
type Props = { params: Promise<{ slug: string }> };
|
||||||
|
|
||||||
|
export default function Page({ params }: Props) {
|
||||||
|
const { slug } = use(params);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### generateMetadata
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
type Props = { params: Promise<{ slug: string }> };
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
|
const { slug } = await params;
|
||||||
|
return { title: slug };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Async Cookies and Headers
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { cookies, headers } from 'next/headers';
|
||||||
|
|
||||||
|
export default async function Page() {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const headersList = await headers();
|
||||||
|
|
||||||
|
const theme = cookieStore.get('theme');
|
||||||
|
const userAgent = headersList.get('user-agent');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration Codemod
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @next/codemod@latest next-async-request-api .
|
||||||
|
```
|
||||||
182
.agents/skills/next-best-practices/bundling.md
Normal file
182
.agents/skills/next-best-practices/bundling.md
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
# Bundling
|
||||||
|
|
||||||
|
Fix common bundling issues with third-party packages.
|
||||||
|
|
||||||
|
## Server-Incompatible Packages
|
||||||
|
|
||||||
|
Some packages use browser APIs (`window`, `document`, `localStorage`) and fail in Server Components.
|
||||||
|
|
||||||
|
### Error Signs
|
||||||
|
|
||||||
|
```
|
||||||
|
ReferenceError: window is not defined
|
||||||
|
ReferenceError: document is not defined
|
||||||
|
ReferenceError: localStorage is not defined
|
||||||
|
Module not found: Can't resolve 'fs'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution 1: Mark as Client-Only
|
||||||
|
|
||||||
|
If the package is only needed on client:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Fails - package uses window
|
||||||
|
import SomeChart from 'some-chart-library';
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <SomeChart />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Use dynamic import with ssr: false
|
||||||
|
import dynamic from 'next/dynamic';
|
||||||
|
|
||||||
|
const SomeChart = dynamic(() => import('some-chart-library'), {
|
||||||
|
ssr: false
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <SomeChart />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution 2: Externalize from Server Bundle
|
||||||
|
|
||||||
|
For packages that should run on server but have bundling issues:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
serverExternalPackages: ['problematic-package']
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Use this for:
|
||||||
|
|
||||||
|
- Packages with native bindings (sharp, bcrypt)
|
||||||
|
- Packages that don't bundle well (some ORMs)
|
||||||
|
- Packages with circular dependencies
|
||||||
|
|
||||||
|
### Solution 3: Client Component Wrapper
|
||||||
|
|
||||||
|
Wrap the entire usage in a client component:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ChartWrapper.tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { Chart } from 'chart-library';
|
||||||
|
|
||||||
|
export function ChartWrapper(props) {
|
||||||
|
return <Chart {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// app/page.tsx (server component)
|
||||||
|
import { ChartWrapper } from '@/components/ChartWrapper';
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <ChartWrapper data={data} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## CSS Imports
|
||||||
|
|
||||||
|
Import CSS files instead of using `<link>` tags. Next.js handles bundling and optimization.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Manual link tag
|
||||||
|
<link rel='stylesheet' href='/styles.css' />;
|
||||||
|
|
||||||
|
// Good: Import CSS
|
||||||
|
import './styles.css';
|
||||||
|
|
||||||
|
// Good: CSS Modules
|
||||||
|
import styles from './Button.module.css';
|
||||||
|
```
|
||||||
|
|
||||||
|
## Polyfills
|
||||||
|
|
||||||
|
Next.js includes common polyfills automatically. Don't load redundant ones from polyfill.io or similar CDNs.
|
||||||
|
|
||||||
|
Already included: `Array.from`, `Object.assign`, `Promise`, `fetch`, `Map`, `Set`, `Symbol`, `URLSearchParams`, and 50+ others.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Redundant polyfills
|
||||||
|
<script src='https://polyfill.io/v3/polyfill.min.js?features=fetch,Promise,Array.from' />
|
||||||
|
|
||||||
|
// Good: Next.js includes these automatically
|
||||||
|
```
|
||||||
|
|
||||||
|
## ESM/CommonJS Issues
|
||||||
|
|
||||||
|
### Error Signs
|
||||||
|
|
||||||
|
```
|
||||||
|
SyntaxError: Cannot use import statement outside a module
|
||||||
|
Error: require() of ES Module
|
||||||
|
Module not found: ESM packages need to be imported
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution: Transpile Package
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
transpilePackages: ['some-esm-package', 'another-package']
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Problematic Packages
|
||||||
|
|
||||||
|
| Package | Issue | Solution |
|
||||||
|
| --------------- | --------------- | --------------------------------------------------------------- |
|
||||||
|
| `sharp` | Native bindings | `serverExternalPackages: ['sharp']` |
|
||||||
|
| `bcrypt` | Native bindings | `serverExternalPackages: ['bcrypt']` or use `bcryptjs` |
|
||||||
|
| `canvas` | Native bindings | `serverExternalPackages: ['canvas']` |
|
||||||
|
| `recharts` | Uses window | `dynamic(() => import('recharts'), { ssr: false })` |
|
||||||
|
| `react-quill` | Uses document | `dynamic(() => import('react-quill'), { ssr: false })` |
|
||||||
|
| `mapbox-gl` | Uses window | `dynamic(() => import('mapbox-gl'), { ssr: false })` |
|
||||||
|
| `monaco-editor` | Uses window | `dynamic(() => import('@monaco-editor/react'), { ssr: false })` |
|
||||||
|
| `lottie-web` | Uses document | `dynamic(() => import('lottie-react'), { ssr: false })` |
|
||||||
|
|
||||||
|
## Bundle Analysis
|
||||||
|
|
||||||
|
Analyze bundle size with the built-in analyzer (Next.js 16.1+):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
next experimental-analyze
|
||||||
|
```
|
||||||
|
|
||||||
|
This opens an interactive UI to:
|
||||||
|
|
||||||
|
- Filter by route, environment (client/server), and type
|
||||||
|
- Inspect module sizes and import chains
|
||||||
|
- View treemap visualization
|
||||||
|
|
||||||
|
Save output for comparison:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
next experimental-analyze --output
|
||||||
|
# Output saved to .next/diagnostics/analyze
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/guides/package-bundling
|
||||||
|
|
||||||
|
## Migrating from Webpack to Turbopack
|
||||||
|
|
||||||
|
Turbopack is the default bundler in Next.js 15+. If you have custom webpack config, migrate to Turbopack-compatible alternatives:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
// Good: Works with Turbopack
|
||||||
|
serverExternalPackages: ['package'],
|
||||||
|
transpilePackages: ['package'],
|
||||||
|
|
||||||
|
// Bad: Webpack-only - migrate away from this
|
||||||
|
webpack: (config) => {
|
||||||
|
// custom webpack config
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/building-your-application/upgrading/from-webpack-to-turbopack
|
||||||
300
.agents/skills/next-best-practices/data-patterns.md
Normal file
300
.agents/skills/next-best-practices/data-patterns.md
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
# Data Patterns
|
||||||
|
|
||||||
|
Choose the right data fetching pattern for each use case.
|
||||||
|
|
||||||
|
## Decision Tree
|
||||||
|
|
||||||
|
```
|
||||||
|
Need to fetch data?
|
||||||
|
├── From a Server Component?
|
||||||
|
│ └── Use: Fetch directly (no API needed)
|
||||||
|
│
|
||||||
|
├── From a Client Component?
|
||||||
|
│ ├── Is it a mutation (POST/PUT/DELETE)?
|
||||||
|
│ │ └── Use: Server Action
|
||||||
|
│ └── Is it a read (GET)?
|
||||||
|
│ └── Use: Route Handler OR pass from Server Component
|
||||||
|
│
|
||||||
|
├── Need external API access (webhooks, third parties)?
|
||||||
|
│ └── Use: Route Handler
|
||||||
|
│
|
||||||
|
└── Need REST API for mobile app / external clients?
|
||||||
|
└── Use: Route Handler
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pattern 1: Server Components (Preferred for Reads)
|
||||||
|
|
||||||
|
Fetch data directly in Server Components - no API layer needed.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/users/page.tsx
|
||||||
|
async function UsersPage() {
|
||||||
|
// Direct database access - no API round-trip
|
||||||
|
const users = await db.user.findMany();
|
||||||
|
|
||||||
|
// Or fetch from external API
|
||||||
|
const posts = await fetch('https://api.example.com/posts').then((r) => r.json());
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul>
|
||||||
|
{users.map((user) => (
|
||||||
|
<li key={user.id}>{user.name}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefits**:
|
||||||
|
|
||||||
|
- No API to maintain
|
||||||
|
- No client-server waterfall
|
||||||
|
- Secrets stay on server
|
||||||
|
- Direct database access
|
||||||
|
|
||||||
|
## Pattern 2: Server Actions (Preferred for Mutations)
|
||||||
|
|
||||||
|
Server Actions are the recommended way to handle mutations.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/actions.ts
|
||||||
|
'use server';
|
||||||
|
|
||||||
|
import { revalidatePath } from 'next/cache';
|
||||||
|
|
||||||
|
export async function createPost(formData: FormData) {
|
||||||
|
const title = formData.get('title') as string;
|
||||||
|
|
||||||
|
await db.post.create({ data: { title } });
|
||||||
|
|
||||||
|
revalidatePath('/posts');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePost(id: string) {
|
||||||
|
await db.post.delete({ where: { id } });
|
||||||
|
|
||||||
|
revalidateTag('posts');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/posts/new/page.tsx
|
||||||
|
import { createPost } from '@/app/actions';
|
||||||
|
|
||||||
|
export default function NewPost() {
|
||||||
|
return (
|
||||||
|
<form action={createPost}>
|
||||||
|
<input name='title' required />
|
||||||
|
<button type='submit'>Create</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Benefits**:
|
||||||
|
|
||||||
|
- End-to-end type safety
|
||||||
|
- Progressive enhancement (works without JS)
|
||||||
|
- Automatic request handling
|
||||||
|
- Integrated with React transitions
|
||||||
|
|
||||||
|
**Constraints**:
|
||||||
|
|
||||||
|
- POST only (no GET caching semantics)
|
||||||
|
- Internal use only (no external access)
|
||||||
|
- Cannot return non-serializable data
|
||||||
|
|
||||||
|
## Pattern 3: Route Handlers (APIs)
|
||||||
|
|
||||||
|
Use Route Handlers when you need a REST API.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/api/posts/route.ts
|
||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
// GET is cacheable
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const posts = await db.post.findMany();
|
||||||
|
return NextResponse.json(posts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST for mutations
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
const body = await request.json();
|
||||||
|
const post = await db.post.create({ data: body });
|
||||||
|
return NextResponse.json(post, { status: 201 });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**When to use**:
|
||||||
|
|
||||||
|
- External API access (mobile apps, third parties)
|
||||||
|
- Webhooks from external services
|
||||||
|
- GET endpoints that need HTTP caching
|
||||||
|
- OpenAPI/Swagger documentation needed
|
||||||
|
|
||||||
|
**When NOT to use**:
|
||||||
|
|
||||||
|
- Internal data fetching (use Server Components)
|
||||||
|
- Mutations from your UI (use Server Actions)
|
||||||
|
|
||||||
|
## Avoiding Data Waterfalls
|
||||||
|
|
||||||
|
### Problem: Sequential Fetches
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Sequential waterfalls
|
||||||
|
async function Dashboard() {
|
||||||
|
const user = await getUser(); // Wait...
|
||||||
|
const posts = await getPosts(); // Then wait...
|
||||||
|
const comments = await getComments(); // Then wait...
|
||||||
|
|
||||||
|
return <div>...</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution 1: Parallel Fetching with Promise.all
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Parallel fetching
|
||||||
|
async function Dashboard() {
|
||||||
|
const [user, posts, comments] = await Promise.all([getUser(), getPosts(), getComments()]);
|
||||||
|
|
||||||
|
return <div>...</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution 2: Streaming with Suspense
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Show content progressively
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
|
async function Dashboard() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Suspense fallback={<UserSkeleton />}>
|
||||||
|
<UserSection />
|
||||||
|
</Suspense>
|
||||||
|
<Suspense fallback={<PostsSkeleton />}>
|
||||||
|
<PostsSection />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function UserSection() {
|
||||||
|
const user = await getUser(); // Fetches independently
|
||||||
|
return <div>{user.name}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function PostsSection() {
|
||||||
|
const posts = await getPosts(); // Fetches independently
|
||||||
|
return <PostList posts={posts} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Solution 3: Preload Pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// lib/data.ts
|
||||||
|
import { cache } from 'react';
|
||||||
|
|
||||||
|
export const getUser = cache(async (id: string) => {
|
||||||
|
return db.user.findUnique({ where: { id } });
|
||||||
|
});
|
||||||
|
|
||||||
|
export const preloadUser = (id: string) => {
|
||||||
|
void getUser(id); // Fire and forget
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/user/[id]/page.tsx
|
||||||
|
import { getUser, preloadUser } from '@/lib/data';
|
||||||
|
|
||||||
|
export default async function UserPage({ params }) {
|
||||||
|
const { id } = await params;
|
||||||
|
|
||||||
|
// Start fetching early
|
||||||
|
preloadUser(id);
|
||||||
|
|
||||||
|
// Do other work...
|
||||||
|
|
||||||
|
// Data likely ready by now
|
||||||
|
const user = await getUser(id);
|
||||||
|
return <div>{user.name}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Client Component Data Fetching
|
||||||
|
|
||||||
|
When Client Components need data:
|
||||||
|
|
||||||
|
### Option 1: Pass from Server Component (Preferred)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Server Component
|
||||||
|
async function Page() {
|
||||||
|
const data = await fetchData();
|
||||||
|
return <ClientComponent initialData={data} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client Component
|
||||||
|
('use client');
|
||||||
|
function ClientComponent({ initialData }) {
|
||||||
|
const [data, setData] = useState(initialData);
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Fetch on Mount (When Necessary)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
function ClientComponent() {
|
||||||
|
const [data, setData] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/data')
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then(setData);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!data) return <Loading />;
|
||||||
|
return <div>{data.value}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 3: Server Action for Reads (Works But Not Ideal)
|
||||||
|
|
||||||
|
Server Actions can be called from Client Components for reads, but this is not their intended purpose:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
import { getData } from './actions';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
function ClientComponent() {
|
||||||
|
const [data, setData] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getData().then(setData);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <div>{data?.value}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: Server Actions always use POST, so no HTTP caching. Prefer Route Handlers for cacheable reads.
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
| Pattern | Use Case | HTTP Method | Caching |
|
||||||
|
| ---------------------- | --------------------------- | ----------- | -------------------- |
|
||||||
|
| Server Component fetch | Internal reads | Any | Full Next.js caching |
|
||||||
|
| Server Action | Mutations, form submissions | POST only | No |
|
||||||
|
| Route Handler | External APIs, webhooks | Any | GET can be cached |
|
||||||
|
| Client fetch to API | Client-side reads | Any | HTTP cache headers |
|
||||||
122
.agents/skills/next-best-practices/debug-tricks.md
Normal file
122
.agents/skills/next-best-practices/debug-tricks.md
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
# Debug Tricks
|
||||||
|
|
||||||
|
Tricks to speed up debugging Next.js applications.
|
||||||
|
|
||||||
|
## MCP Endpoint (Dev Server)
|
||||||
|
|
||||||
|
Next.js exposes a `/_next/mcp` endpoint in development for AI-assisted debugging via MCP (Model Context Protocol).
|
||||||
|
|
||||||
|
- **Next.js 16+**: Enabled by default, use `next-devtools-mcp`
|
||||||
|
- **Next.js < 16**: Requires `experimental.mcpServer: true` in next.config.js
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/guides/mcp
|
||||||
|
|
||||||
|
**Important**: Find the actual port of the running Next.js dev server (check terminal output or `package.json` scripts). Don't assume port 3000.
|
||||||
|
|
||||||
|
### Request Format
|
||||||
|
|
||||||
|
The endpoint uses JSON-RPC 2.0 over HTTP POST:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:<port>/_next/mcp \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Accept: application/json, text/event-stream" \
|
||||||
|
-d '{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": "1",
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {
|
||||||
|
"name": "<tool-name>",
|
||||||
|
"arguments": {}
|
||||||
|
}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Available Tools
|
||||||
|
|
||||||
|
#### `get_errors`
|
||||||
|
|
||||||
|
Get current errors from dev server (build errors, runtime errors with source-mapped stacks):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_errors", "arguments": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `get_routes`
|
||||||
|
|
||||||
|
Discover all routes by scanning filesystem:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_routes", "arguments": {} }
|
||||||
|
// Optional: { "name": "get_routes", "arguments": { "routerType": "app" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns: `{ "appRouter": ["/", "/api/users/[id]", ...], "pagesRouter": [...] }`
|
||||||
|
|
||||||
|
#### `get_project_metadata`
|
||||||
|
|
||||||
|
Get project path and dev server URL:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_project_metadata", "arguments": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns: `{ "projectPath": "/path/to/project", "devServerUrl": "http://localhost:3000" }`
|
||||||
|
|
||||||
|
#### `get_page_metadata`
|
||||||
|
|
||||||
|
Get runtime metadata about current page render (requires active browser session):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_page_metadata", "arguments": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns segment trie data showing layouts, boundaries, and page components.
|
||||||
|
|
||||||
|
#### `get_logs`
|
||||||
|
|
||||||
|
Get path to Next.js development log file:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_logs", "arguments": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns path to `<distDir>/logs/next-development.log`
|
||||||
|
|
||||||
|
#### `get_server_action_by_id`
|
||||||
|
|
||||||
|
Locate a Server Action by ID:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "name": "get_server_action_by_id", "arguments": { "actionId": "<action-id>" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example: Get Errors
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:<port>/_next/mcp \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Accept: application/json, text/event-stream" \
|
||||||
|
-d '{"jsonrpc":"2.0","id":"1","method":"tools/call","params":{"name":"get_errors","arguments":{}}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rebuild Specific Routes (Next.js 16+)
|
||||||
|
|
||||||
|
Use `--debug-build-paths` to rebuild only specific routes instead of the entire app:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Rebuild a specific route
|
||||||
|
next build --debug-build-paths "/dashboard"
|
||||||
|
|
||||||
|
# Rebuild routes matching a glob
|
||||||
|
next build --debug-build-paths "/api/*"
|
||||||
|
|
||||||
|
# Dynamic routes
|
||||||
|
next build --debug-build-paths "/blog/[slug]"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use this to:
|
||||||
|
|
||||||
|
- Quickly verify a build fix without full rebuild
|
||||||
|
- Debug static generation issues for specific pages
|
||||||
|
- Iterate faster on build errors
|
||||||
74
.agents/skills/next-best-practices/directives.md
Normal file
74
.agents/skills/next-best-practices/directives.md
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
# Directives
|
||||||
|
|
||||||
|
## React Directives
|
||||||
|
|
||||||
|
These are React directives, not Next.js specific.
|
||||||
|
|
||||||
|
### `'use client'`
|
||||||
|
|
||||||
|
Marks a component as a Client Component. Required for:
|
||||||
|
|
||||||
|
- React hooks (`useState`, `useEffect`, etc.)
|
||||||
|
- Event handlers (`onClick`, `onChange`)
|
||||||
|
- Browser APIs (`window`, `localStorage`)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
export function Counter() {
|
||||||
|
const [count, setCount] = useState(0);
|
||||||
|
return <button onClick={() => setCount(count + 1)}>{count}</button>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: https://react.dev/reference/rsc/use-client
|
||||||
|
|
||||||
|
### `'use server'`
|
||||||
|
|
||||||
|
Marks a function as a Server Action. Can be passed to Client Components.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use server';
|
||||||
|
|
||||||
|
export async function submitForm(formData: FormData) {
|
||||||
|
// Runs on server
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or inline within a Server Component:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default function Page() {
|
||||||
|
async function submit() {
|
||||||
|
'use server';
|
||||||
|
// Runs on server
|
||||||
|
}
|
||||||
|
return <form action={submit}>...</form>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference: https://react.dev/reference/rsc/use-server
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Next.js Directive
|
||||||
|
|
||||||
|
### `'use cache'`
|
||||||
|
|
||||||
|
Marks a function or component for caching. Part of Next.js Cache Components.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use cache';
|
||||||
|
|
||||||
|
export async function getCachedData() {
|
||||||
|
return await fetchData();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Requires `cacheComponents: true` in `next.config.ts`.
|
||||||
|
|
||||||
|
For detailed usage including cache profiles, `cacheLife()`, `cacheTag()`, and `updateTag()`, see the `next-cache-components` skill.
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/api-reference/directives/use-cache
|
||||||
228
.agents/skills/next-best-practices/error-handling.md
Normal file
228
.agents/skills/next-best-practices/error-handling.md
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
# Error Handling
|
||||||
|
|
||||||
|
Handle errors gracefully in Next.js applications.
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/getting-started/error-handling
|
||||||
|
|
||||||
|
## Error Boundaries
|
||||||
|
|
||||||
|
### `error.tsx`
|
||||||
|
|
||||||
|
Catches errors in a route segment and its children:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
export default function Error({
|
||||||
|
error,
|
||||||
|
reset
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string };
|
||||||
|
reset: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h2>Something went wrong!</h2>
|
||||||
|
<button onClick={() => reset()}>Try again</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important:** `error.tsx` must be a Client Component.
|
||||||
|
|
||||||
|
### `global-error.tsx`
|
||||||
|
|
||||||
|
Catches errors in root layout:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
export default function GlobalError({
|
||||||
|
error,
|
||||||
|
reset
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string };
|
||||||
|
reset: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<h2>Something went wrong!</h2>
|
||||||
|
<button onClick={() => reset()}>Try again</button>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important:** Must include `<html>` and `<body>` tags.
|
||||||
|
|
||||||
|
## Server Actions: Navigation API Gotcha
|
||||||
|
|
||||||
|
**Do NOT wrap navigation APIs in try-catch.** They throw special errors that Next.js handles internally.
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/api-reference/functions/redirect#behavior
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use server'
|
||||||
|
|
||||||
|
import { redirect } from 'next/navigation'
|
||||||
|
import { notFound } from 'next/navigation'
|
||||||
|
|
||||||
|
// Bad: try-catch catches the navigation "error"
|
||||||
|
async function createPost(formData: FormData) {
|
||||||
|
try {
|
||||||
|
const post = await db.post.create({ ... })
|
||||||
|
redirect(`/posts/${post.id}`) // This throws!
|
||||||
|
} catch (error) {
|
||||||
|
// redirect() throw is caught here - navigation fails!
|
||||||
|
return { error: 'Failed to create post' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Call navigation APIs outside try-catch
|
||||||
|
async function createPost(formData: FormData) {
|
||||||
|
let post
|
||||||
|
try {
|
||||||
|
post = await db.post.create({ ... })
|
||||||
|
} catch (error) {
|
||||||
|
return { error: 'Failed to create post' }
|
||||||
|
}
|
||||||
|
redirect(`/posts/${post.id}`) // Outside try-catch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Re-throw navigation errors
|
||||||
|
async function createPost(formData: FormData) {
|
||||||
|
try {
|
||||||
|
const post = await db.post.create({ ... })
|
||||||
|
redirect(`/posts/${post.id}`)
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message === 'NEXT_REDIRECT') {
|
||||||
|
throw error // Re-throw navigation errors
|
||||||
|
}
|
||||||
|
return { error: 'Failed to create post' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Same applies to:
|
||||||
|
|
||||||
|
- `redirect()` - 307 temporary redirect
|
||||||
|
- `permanentRedirect()` - 308 permanent redirect
|
||||||
|
- `notFound()` - 404 not found
|
||||||
|
- `forbidden()` - 403 forbidden
|
||||||
|
- `unauthorized()` - 401 unauthorized
|
||||||
|
|
||||||
|
Use `unstable_rethrow()` to re-throw these errors in catch blocks:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { unstable_rethrow } from 'next/navigation';
|
||||||
|
|
||||||
|
async function action() {
|
||||||
|
try {
|
||||||
|
// ...
|
||||||
|
redirect('/success');
|
||||||
|
} catch (error) {
|
||||||
|
unstable_rethrow(error); // Re-throws Next.js internal errors
|
||||||
|
return { error: 'Something went wrong' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Redirects
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { redirect, permanentRedirect } from 'next/navigation';
|
||||||
|
|
||||||
|
// 307 Temporary - use for most cases
|
||||||
|
redirect('/new-path');
|
||||||
|
|
||||||
|
// 308 Permanent - use for URL migrations (cached by browsers)
|
||||||
|
permanentRedirect('/new-url');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Auth Errors
|
||||||
|
|
||||||
|
Trigger auth-related error pages:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { forbidden, unauthorized } from 'next/navigation';
|
||||||
|
|
||||||
|
async function Page() {
|
||||||
|
const session = await getSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
unauthorized(); // Renders unauthorized.tsx (401)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!session.hasAccess) {
|
||||||
|
forbidden(); // Renders forbidden.tsx (403)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Dashboard />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Create corresponding error pages:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/forbidden.tsx
|
||||||
|
export default function Forbidden() {
|
||||||
|
return <div>You don't have access to this resource</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// app/unauthorized.tsx
|
||||||
|
export default function Unauthorized() {
|
||||||
|
return <div>Please log in to continue</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Not Found
|
||||||
|
|
||||||
|
### `not-found.tsx`
|
||||||
|
|
||||||
|
Custom 404 page for a route segment:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export default function NotFound() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h2>Not Found</h2>
|
||||||
|
<p>Could not find the requested resource</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Triggering Not Found
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
|
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const post = await getPost(id);
|
||||||
|
|
||||||
|
if (!post) {
|
||||||
|
notFound(); // Renders closest not-found.tsx
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div>{post.title}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Hierarchy
|
||||||
|
|
||||||
|
Errors bubble up to the nearest error boundary:
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── error.tsx # Catches errors from all children
|
||||||
|
├── blog/
|
||||||
|
│ ├── error.tsx # Catches errors in /blog/*
|
||||||
|
│ └── [slug]/
|
||||||
|
│ ├── error.tsx # Catches errors in /blog/[slug]
|
||||||
|
│ └── page.tsx
|
||||||
|
└── layout.tsx # Errors here go to global-error.tsx
|
||||||
|
```
|
||||||
141
.agents/skills/next-best-practices/file-conventions.md
Normal file
141
.agents/skills/next-best-practices/file-conventions.md
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
# File Conventions
|
||||||
|
|
||||||
|
Next.js App Router uses file-based routing with special file conventions.
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/getting-started/project-structure
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── layout.tsx # Root layout (required)
|
||||||
|
├── page.tsx # Home page (/)
|
||||||
|
├── loading.tsx # Loading UI
|
||||||
|
├── error.tsx # Error UI
|
||||||
|
├── not-found.tsx # 404 UI
|
||||||
|
├── global-error.tsx # Global error UI
|
||||||
|
├── route.ts # API endpoint
|
||||||
|
├── template.tsx # Re-rendered layout
|
||||||
|
├── default.tsx # Parallel route fallback
|
||||||
|
├── blog/
|
||||||
|
│ ├── page.tsx # /blog
|
||||||
|
│ └── [slug]/
|
||||||
|
│ └── page.tsx # /blog/:slug
|
||||||
|
└── (group)/ # Route group (no URL impact)
|
||||||
|
└── page.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
## Special Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
| --------------- | ---------------------------------------- |
|
||||||
|
| `page.tsx` | UI for a route segment |
|
||||||
|
| `layout.tsx` | Shared UI for segment and children |
|
||||||
|
| `loading.tsx` | Loading UI (Suspense boundary) |
|
||||||
|
| `error.tsx` | Error UI (Error boundary) |
|
||||||
|
| `not-found.tsx` | 404 UI |
|
||||||
|
| `route.ts` | API endpoint |
|
||||||
|
| `template.tsx` | Like layout but re-renders on navigation |
|
||||||
|
| `default.tsx` | Fallback for parallel routes |
|
||||||
|
|
||||||
|
## Route Segments
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── blog/ # Static segment: /blog
|
||||||
|
├── [slug]/ # Dynamic segment: /:slug
|
||||||
|
├── [...slug]/ # Catch-all: /a/b/c
|
||||||
|
├── [[...slug]]/ # Optional catch-all: / or /a/b/c
|
||||||
|
└── (marketing)/ # Route group (ignored in URL)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Parallel Routes
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── @analytics/
|
||||||
|
│ └── page.tsx
|
||||||
|
├── @sidebar/
|
||||||
|
│ └── page.tsx
|
||||||
|
└── layout.tsx # Receives { analytics, sidebar } as props
|
||||||
|
```
|
||||||
|
|
||||||
|
## Intercepting Routes
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── feed/
|
||||||
|
│ └── page.tsx
|
||||||
|
├── @modal/
|
||||||
|
│ └── (.)photo/[id]/ # Intercepts /photo/[id] from /feed
|
||||||
|
│ └── page.tsx
|
||||||
|
└── photo/[id]/
|
||||||
|
└── page.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Conventions:
|
||||||
|
|
||||||
|
- `(.)` - same level
|
||||||
|
- `(..)` - one level up
|
||||||
|
- `(..)(..)` - two levels up
|
||||||
|
- `(...)` - from root
|
||||||
|
|
||||||
|
## Private Folders
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── _components/ # Private folder (not a route)
|
||||||
|
│ └── Button.tsx
|
||||||
|
└── page.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Prefix with `_` to exclude from routing.
|
||||||
|
|
||||||
|
## Middleware / Proxy
|
||||||
|
|
||||||
|
### Next.js 14-15: `middleware.ts`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// middleware.ts (root of project)
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import type { NextRequest } from 'next/server';
|
||||||
|
|
||||||
|
export function middleware(request: NextRequest) {
|
||||||
|
// Auth, redirects, rewrites, etc.
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/dashboard/:path*', '/api/:path*']
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Next.js 16+: `proxy.ts`
|
||||||
|
|
||||||
|
Renamed for clarity - same capabilities, different names:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// proxy.ts (root of project)
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import type { NextRequest } from 'next/server';
|
||||||
|
|
||||||
|
export function proxy(request: NextRequest) {
|
||||||
|
// Same logic as middleware
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const proxyConfig = {
|
||||||
|
matcher: ['/dashboard/:path*', '/api/:path*']
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
| Version | File | Export | Config |
|
||||||
|
| ------- | --------------- | -------------- | ------------- |
|
||||||
|
| v14-15 | `middleware.ts` | `middleware()` | `config` |
|
||||||
|
| v16+ | `proxy.ts` | `proxy()` | `proxyConfig` |
|
||||||
|
|
||||||
|
**Migration**: Run `npx @next/codemod@latest upgrade` to auto-rename.
|
||||||
|
|
||||||
|
## File Conventions Reference
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/api-reference/file-conventions
|
||||||
246
.agents/skills/next-best-practices/font.md
Normal file
246
.agents/skills/next-best-practices/font.md
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
# Font Optimization
|
||||||
|
|
||||||
|
Use `next/font` for automatic font optimization with zero layout shift.
|
||||||
|
|
||||||
|
## Google Fonts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/layout.tsx
|
||||||
|
import { Inter } from 'next/font/google';
|
||||||
|
|
||||||
|
const inter = Inter({ subsets: ['latin'] });
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<html lang='en' className={inter.className}>
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multiple Fonts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Inter, Roboto_Mono } from 'next/font/google';
|
||||||
|
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
variable: '--font-inter'
|
||||||
|
});
|
||||||
|
|
||||||
|
const robotoMono = Roboto_Mono({
|
||||||
|
subsets: ['latin'],
|
||||||
|
variable: '--font-roboto-mono'
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<html lang='en' className={`${inter.variable} ${robotoMono.variable}`}>
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use in CSS:
|
||||||
|
|
||||||
|
```css
|
||||||
|
body {
|
||||||
|
font-family: var(--font-inter);
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
font-family: var(--font-roboto-mono);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Font Weights and Styles
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Single weight
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
weight: '400'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Multiple weights
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
weight: ['400', '500', '700']
|
||||||
|
});
|
||||||
|
|
||||||
|
// Variable font (recommended) - includes all weights
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin']
|
||||||
|
// No weight needed - variable fonts support all weights
|
||||||
|
});
|
||||||
|
|
||||||
|
// With italic
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
style: ['normal', 'italic']
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Local Fonts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import localFont from 'next/font/local';
|
||||||
|
|
||||||
|
const myFont = localFont({
|
||||||
|
src: './fonts/MyFont.woff2'
|
||||||
|
});
|
||||||
|
|
||||||
|
// Multiple files for different weights
|
||||||
|
const myFont = localFont({
|
||||||
|
src: [
|
||||||
|
{
|
||||||
|
path: './fonts/MyFont-Regular.woff2',
|
||||||
|
weight: '400',
|
||||||
|
style: 'normal'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: './fonts/MyFont-Bold.woff2',
|
||||||
|
weight: '700',
|
||||||
|
style: 'normal'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
// Variable font
|
||||||
|
const myFont = localFont({
|
||||||
|
src: './fonts/MyFont-Variable.woff2',
|
||||||
|
variable: '--font-my-font'
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tailwind CSS Integration
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/layout.tsx
|
||||||
|
import { Inter } from 'next/font/google';
|
||||||
|
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
variable: '--font-inter'
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function RootLayout({ children }) {
|
||||||
|
return (
|
||||||
|
<html lang='en' className={inter.variable}>
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
// tailwind.config.js
|
||||||
|
module.exports = {
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['var(--font-inter)']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Preloading Subsets
|
||||||
|
|
||||||
|
Only load needed character subsets:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Latin only (most common)
|
||||||
|
const inter = Inter({ subsets: ['latin'] });
|
||||||
|
|
||||||
|
// Multiple subsets
|
||||||
|
const inter = Inter({ subsets: ['latin', 'latin-ext', 'cyrillic'] });
|
||||||
|
```
|
||||||
|
|
||||||
|
## Display Strategy
|
||||||
|
|
||||||
|
Control font loading behavior:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const inter = Inter({
|
||||||
|
subsets: ['latin'],
|
||||||
|
display: 'swap' // Default - shows fallback, swaps when loaded
|
||||||
|
});
|
||||||
|
|
||||||
|
// Options:
|
||||||
|
// 'auto' - browser decides
|
||||||
|
// 'block' - short block period, then swap
|
||||||
|
// 'swap' - immediate fallback, swap when ready (recommended)
|
||||||
|
// 'fallback' - short block, short swap, then fallback
|
||||||
|
// 'optional' - short block, no swap (use if font is optional)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Don't Use Manual Font Links
|
||||||
|
|
||||||
|
Always use `next/font` instead of `<link>` tags for Google Fonts.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Manual link tag (blocks rendering, no optimization)
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter" rel="stylesheet" />
|
||||||
|
|
||||||
|
// Bad: Missing display and preconnect
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter" rel="stylesheet" />
|
||||||
|
|
||||||
|
// Good: Use next/font (self-hosted, zero layout shift)
|
||||||
|
import { Inter } from 'next/font/google'
|
||||||
|
|
||||||
|
const inter = Inter({ subsets: ['latin'] })
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Mistakes
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Importing font in every component
|
||||||
|
// components/Button.tsx
|
||||||
|
import { Inter } from 'next/font/google'
|
||||||
|
const inter = Inter({ subsets: ['latin'] }) // Creates new instance each time!
|
||||||
|
|
||||||
|
// Good: Import once in layout, use CSS variable
|
||||||
|
// app/layout.tsx
|
||||||
|
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
|
||||||
|
|
||||||
|
// Bad: Using @import in CSS (blocks rendering)
|
||||||
|
/* globals.css */
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Inter');
|
||||||
|
|
||||||
|
// Good: Use next/font (self-hosted, no network request)
|
||||||
|
import { Inter } from 'next/font/google'
|
||||||
|
|
||||||
|
// Bad: Loading all weights when only using a few
|
||||||
|
const inter = Inter({ subsets: ['latin'] }) // Loads all weights
|
||||||
|
|
||||||
|
// Good: Specify only needed weights (for non-variable fonts)
|
||||||
|
const inter = Inter({ subsets: ['latin'], weight: ['400', '700'] })
|
||||||
|
|
||||||
|
// Bad: Missing subset - loads all characters
|
||||||
|
const inter = Inter({})
|
||||||
|
|
||||||
|
// Good: Always specify subset
|
||||||
|
const inter = Inter({ subsets: ['latin'] })
|
||||||
|
```
|
||||||
|
|
||||||
|
## Font in Specific Components
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// For component-specific fonts, export from a shared file
|
||||||
|
// lib/fonts.ts
|
||||||
|
import { Inter, Playfair_Display } from 'next/font/google';
|
||||||
|
|
||||||
|
export const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
|
||||||
|
export const playfair = Playfair_Display({ subsets: ['latin'], variable: '--font-playfair' });
|
||||||
|
|
||||||
|
// components/Heading.tsx
|
||||||
|
import { playfair } from '@/lib/fonts';
|
||||||
|
|
||||||
|
export function Heading({ children }) {
|
||||||
|
return <h1 className={playfair.className}>{children}</h1>;
|
||||||
|
}
|
||||||
|
```
|
||||||
108
.agents/skills/next-best-practices/functions.md
Normal file
108
.agents/skills/next-best-practices/functions.md
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
# Functions
|
||||||
|
|
||||||
|
Next.js function APIs.
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/api-reference/functions
|
||||||
|
|
||||||
|
## Navigation Hooks (Client)
|
||||||
|
|
||||||
|
| Hook | Purpose | Reference |
|
||||||
|
| --------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
|
||||||
|
| `useRouter` | Programmatic navigation (`push`, `replace`, `back`, `refresh`) | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-router) |
|
||||||
|
| `usePathname` | Get current pathname | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-pathname) |
|
||||||
|
| `useSearchParams` | Read URL search parameters | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-search-params) |
|
||||||
|
| `useParams` | Access dynamic route parameters | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-params) |
|
||||||
|
| `useSelectedLayoutSegment` | Active child segment (one level) | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment) |
|
||||||
|
| `useSelectedLayoutSegments` | All active segments below layout | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments) |
|
||||||
|
| `useLinkStatus` | Check link prefetch status | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-link-status) |
|
||||||
|
| `useReportWebVitals` | Report Core Web Vitals metrics | [Docs](https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals) |
|
||||||
|
|
||||||
|
## Server Functions
|
||||||
|
|
||||||
|
| Function | Purpose | Reference |
|
||||||
|
| ------------ | -------------------------------------------- | ---------------------------------------------------------------------- |
|
||||||
|
| `cookies` | Read/write cookies | [Docs](https://nextjs.org/docs/app/api-reference/functions/cookies) |
|
||||||
|
| `headers` | Read request headers | [Docs](https://nextjs.org/docs/app/api-reference/functions/headers) |
|
||||||
|
| `draftMode` | Enable preview of unpublished CMS content | [Docs](https://nextjs.org/docs/app/api-reference/functions/draft-mode) |
|
||||||
|
| `after` | Run code after response finishes streaming | [Docs](https://nextjs.org/docs/app/api-reference/functions/after) |
|
||||||
|
| `connection` | Wait for connection before dynamic rendering | [Docs](https://nextjs.org/docs/app/api-reference/functions/connection) |
|
||||||
|
| `userAgent` | Parse User-Agent header | [Docs](https://nextjs.org/docs/app/api-reference/functions/userAgent) |
|
||||||
|
|
||||||
|
## Generate Functions
|
||||||
|
|
||||||
|
| Function | Purpose | Reference |
|
||||||
|
| ----------------------- | --------------------------------------- | ----------------------------------------------------------------------------------- |
|
||||||
|
| `generateStaticParams` | Pre-render dynamic routes at build time | [Docs](https://nextjs.org/docs/app/api-reference/functions/generate-static-params) |
|
||||||
|
| `generateMetadata` | Dynamic metadata | [Docs](https://nextjs.org/docs/app/api-reference/functions/generate-metadata) |
|
||||||
|
| `generateViewport` | Dynamic viewport config | [Docs](https://nextjs.org/docs/app/api-reference/functions/generate-viewport) |
|
||||||
|
| `generateSitemaps` | Multiple sitemaps for large sites | [Docs](https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps) |
|
||||||
|
| `generateImageMetadata` | Multiple OG images per route | [Docs](https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata) |
|
||||||
|
|
||||||
|
## Request/Response
|
||||||
|
|
||||||
|
| Function | Purpose | Reference |
|
||||||
|
| --------------- | ------------------------------ | -------------------------------------------------------------------------- |
|
||||||
|
| `NextRequest` | Extended Request with helpers | [Docs](https://nextjs.org/docs/app/api-reference/functions/next-request) |
|
||||||
|
| `NextResponse` | Extended Response with helpers | [Docs](https://nextjs.org/docs/app/api-reference/functions/next-response) |
|
||||||
|
| `ImageResponse` | Generate OG images | [Docs](https://nextjs.org/docs/app/api-reference/functions/image-response) |
|
||||||
|
|
||||||
|
## Common Examples
|
||||||
|
|
||||||
|
### Navigation
|
||||||
|
|
||||||
|
Use `next/link` for internal navigation instead of `<a>` tags.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Plain anchor tag
|
||||||
|
<a href='/about'>About</a>;
|
||||||
|
|
||||||
|
// Good: Next.js Link
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
<Link href='/about'>About</Link>;
|
||||||
|
```
|
||||||
|
|
||||||
|
Active link styling:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { usePathname } from 'next/navigation';
|
||||||
|
|
||||||
|
export function NavLink({ href, children }) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link href={href} className={pathname === href ? 'active' : ''}>
|
||||||
|
{children}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Static Generation
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/blog/[slug]/page.tsx
|
||||||
|
export async function generateStaticParams() {
|
||||||
|
const posts = await getPosts();
|
||||||
|
return posts.map((post) => ({ slug: post.slug }));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### After Response
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { after } from 'next/server';
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const data = await processRequest(request);
|
||||||
|
|
||||||
|
after(async () => {
|
||||||
|
await logAnalytics(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
return Response.json({ success: true });
|
||||||
|
}
|
||||||
|
```
|
||||||
86
.agents/skills/next-best-practices/hydration-error.md
Normal file
86
.agents/skills/next-best-practices/hydration-error.md
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
# Hydration Errors
|
||||||
|
|
||||||
|
Diagnose and fix React hydration mismatch errors.
|
||||||
|
|
||||||
|
## Error Signs
|
||||||
|
|
||||||
|
- "Hydration failed because the initial UI does not match"
|
||||||
|
- "Text content does not match server-rendered HTML"
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
|
||||||
|
In development, click the hydration error to see the server/client diff.
|
||||||
|
|
||||||
|
## Common Causes and Fixes
|
||||||
|
|
||||||
|
### Browser-only APIs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Causes mismatch - window doesn't exist on server
|
||||||
|
<div>{window.innerWidth}</div>;
|
||||||
|
|
||||||
|
// Good: Use client component with mounted check
|
||||||
|
('use client');
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
|
export function ClientOnly({ children }: { children: React.ReactNode }) {
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
useEffect(() => setMounted(true), []);
|
||||||
|
return mounted ? children : null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Date/Time Rendering
|
||||||
|
|
||||||
|
Server and client may be in different timezones:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Causes mismatch
|
||||||
|
<span>{new Date().toLocaleString()}</span>;
|
||||||
|
|
||||||
|
// Good: Render on client only
|
||||||
|
('use client');
|
||||||
|
const [time, setTime] = useState<string>();
|
||||||
|
useEffect(() => setTime(new Date().toLocaleString()), []);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Random Values or IDs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Random values differ between server and client
|
||||||
|
<div id={Math.random().toString()}>
|
||||||
|
|
||||||
|
// Good: Use useId hook
|
||||||
|
import { useId } from 'react'
|
||||||
|
|
||||||
|
function Input() {
|
||||||
|
const id = useId()
|
||||||
|
return <input id={id} />
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Invalid HTML Nesting
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Invalid - div inside p
|
||||||
|
<p><div>Content</div></p>
|
||||||
|
|
||||||
|
// Bad: Invalid - p inside p
|
||||||
|
<p><p>Nested</p></p>
|
||||||
|
|
||||||
|
// Good: Valid nesting
|
||||||
|
<div><p>Content</p></div>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Third-party Scripts
|
||||||
|
|
||||||
|
Scripts that modify DOM during hydration.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Use next/script with afterInteractive
|
||||||
|
import Script from 'next/script';
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <Script src='https://example.com/script.js' strategy='afterInteractive' />;
|
||||||
|
}
|
||||||
|
```
|
||||||
173
.agents/skills/next-best-practices/image.md
Normal file
173
.agents/skills/next-best-practices/image.md
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
# Image Optimization
|
||||||
|
|
||||||
|
Use `next/image` for automatic image optimization.
|
||||||
|
|
||||||
|
## Always Use next/image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Avoid native img
|
||||||
|
<img src='/hero.png' alt='Hero' />;
|
||||||
|
|
||||||
|
// Good: Use next/image
|
||||||
|
import Image from 'next/image';
|
||||||
|
<Image src='/hero.png' alt='Hero' width={800} height={400} />;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Required Props
|
||||||
|
|
||||||
|
Images need explicit dimensions to prevent layout shift:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Local images - dimensions inferred automatically
|
||||||
|
import heroImage from './hero.png'
|
||||||
|
<Image src={heroImage} alt="Hero" />
|
||||||
|
|
||||||
|
// Remote images - must specify width/height
|
||||||
|
<Image src="https://example.com/image.jpg" alt="Hero" width={800} height={400} />
|
||||||
|
|
||||||
|
// Or use fill for parent-relative sizing
|
||||||
|
<div style={{ position: 'relative', width: '100%', height: 400 }}>
|
||||||
|
<Image src="/hero.png" alt="Hero" fill style={{ objectFit: 'cover' }} />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Remote Images Configuration
|
||||||
|
|
||||||
|
Remote domains must be configured in `next.config.js`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
images: {
|
||||||
|
remotePatterns: [
|
||||||
|
{
|
||||||
|
protocol: 'https',
|
||||||
|
hostname: 'example.com',
|
||||||
|
pathname: '/images/**'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
protocol: 'https',
|
||||||
|
hostname: '*.cdn.com' // Wildcard subdomain
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Responsive Images
|
||||||
|
|
||||||
|
Use `sizes` to tell the browser which size to download:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Full-width hero
|
||||||
|
<Image
|
||||||
|
src="/hero.png"
|
||||||
|
alt="Hero"
|
||||||
|
fill
|
||||||
|
sizes="100vw"
|
||||||
|
/>
|
||||||
|
|
||||||
|
// Responsive grid (3 columns on desktop, 1 on mobile)
|
||||||
|
<Image
|
||||||
|
src="/card.png"
|
||||||
|
alt="Card"
|
||||||
|
fill
|
||||||
|
sizes="(max-width: 768px) 100vw, 33vw"
|
||||||
|
/>
|
||||||
|
|
||||||
|
// Fixed sidebar image
|
||||||
|
<Image
|
||||||
|
src="/avatar.png"
|
||||||
|
alt="Avatar"
|
||||||
|
width={200}
|
||||||
|
height={200}
|
||||||
|
sizes="200px"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Blur Placeholder
|
||||||
|
|
||||||
|
Prevent layout shift with placeholders:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Local images - automatic blur hash
|
||||||
|
import heroImage from './hero.png'
|
||||||
|
<Image src={heroImage} alt="Hero" placeholder="blur" />
|
||||||
|
|
||||||
|
// Remote images - provide blurDataURL
|
||||||
|
<Image
|
||||||
|
src="https://example.com/image.jpg"
|
||||||
|
alt="Hero"
|
||||||
|
width={800}
|
||||||
|
height={400}
|
||||||
|
placeholder="blur"
|
||||||
|
blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRg..."
|
||||||
|
/>
|
||||||
|
|
||||||
|
// Or use color placeholder
|
||||||
|
<Image
|
||||||
|
src="https://example.com/image.jpg"
|
||||||
|
alt="Hero"
|
||||||
|
width={800}
|
||||||
|
height={400}
|
||||||
|
placeholder="empty"
|
||||||
|
style={{ backgroundColor: '#e0e0e0' }}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Priority Loading
|
||||||
|
|
||||||
|
Use `priority` for above-the-fold images (LCP):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Hero image - loads immediately
|
||||||
|
<Image src="/hero.png" alt="Hero" fill priority />
|
||||||
|
|
||||||
|
// Below-fold images - lazy loaded by default (no priority needed)
|
||||||
|
<Image src="/card.png" alt="Card" width={400} height={300} />
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Mistakes
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Missing sizes with fill - downloads largest image
|
||||||
|
<Image src="/hero.png" alt="Hero" fill />
|
||||||
|
|
||||||
|
// Good: Add sizes for proper responsive behavior
|
||||||
|
<Image src="/hero.png" alt="Hero" fill sizes="100vw" />
|
||||||
|
|
||||||
|
// Bad: Using width/height for aspect ratio only
|
||||||
|
<Image src="/hero.png" alt="Hero" width={16} height={9} />
|
||||||
|
|
||||||
|
// Good: Use actual display dimensions or fill with sizes
|
||||||
|
<Image src="/hero.png" alt="Hero" fill sizes="100vw" style={{ objectFit: 'cover' }} />
|
||||||
|
|
||||||
|
// Bad: Remote image without config
|
||||||
|
<Image src="https://untrusted.com/image.jpg" alt="Image" width={400} height={300} />
|
||||||
|
// Error: Invalid src prop, hostname not configured
|
||||||
|
|
||||||
|
// Good: Add hostname to next.config.js remotePatterns
|
||||||
|
```
|
||||||
|
|
||||||
|
## Static Export
|
||||||
|
|
||||||
|
When using `output: 'export'`, use `unoptimized` or custom loader:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Option 1: Disable optimization
|
||||||
|
<Image src='/hero.png' alt='Hero' width={800} height={400} unoptimized />;
|
||||||
|
|
||||||
|
// Option 2: Global config
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
output: 'export',
|
||||||
|
images: { unoptimized: true }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Option 3: Custom loader (Cloudinary, Imgix, etc.)
|
||||||
|
const cloudinaryLoader = ({ src, width, quality }) => {
|
||||||
|
return `https://res.cloudinary.com/demo/image/upload/w_${width},q_${quality || 75}/${src}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
<Image loader={cloudinaryLoader} src='sample.jpg' alt='Sample' width={800} height={400} />;
|
||||||
|
```
|
||||||
292
.agents/skills/next-best-practices/metadata.md
Normal file
292
.agents/skills/next-best-practices/metadata.md
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
# Metadata
|
||||||
|
|
||||||
|
Add SEO metadata to Next.js pages using the Metadata API.
|
||||||
|
|
||||||
|
## Important: Server Components Only
|
||||||
|
|
||||||
|
The `metadata` object and `generateMetadata` function are **only supported in Server Components**. They cannot be used in Client Components.
|
||||||
|
|
||||||
|
If the target page has `'use client'`:
|
||||||
|
|
||||||
|
1. Remove `'use client'` if possible, move client logic to child components
|
||||||
|
2. Or extract metadata to a parent Server Component layout
|
||||||
|
3. Or split the file: Server Component with metadata imports Client Components
|
||||||
|
|
||||||
|
## Static Metadata
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import type { Metadata } from 'next';
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'Page Title',
|
||||||
|
description: 'Page description for search engines'
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dynamic Metadata
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import type { Metadata } from 'next';
|
||||||
|
|
||||||
|
type Props = { params: Promise<{ slug: string }> };
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
|
const { slug } = await params;
|
||||||
|
const post = await getPost(slug);
|
||||||
|
return { title: post.title, description: post.description };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Avoid Duplicate Fetches
|
||||||
|
|
||||||
|
Use React `cache()` when the same data is needed for both metadata and page:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { cache } from 'react';
|
||||||
|
|
||||||
|
export const getPost = cache(async (slug: string) => {
|
||||||
|
return await db.posts.findFirst({ where: { slug } });
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Viewport
|
||||||
|
|
||||||
|
Separate from metadata for streaming support:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import type { Viewport } from 'next';
|
||||||
|
|
||||||
|
export const viewport: Viewport = {
|
||||||
|
width: 'device-width',
|
||||||
|
initialScale: 1,
|
||||||
|
themeColor: '#000000'
|
||||||
|
};
|
||||||
|
|
||||||
|
// Or dynamic
|
||||||
|
export function generateViewport({ params }): Viewport {
|
||||||
|
return { themeColor: getThemeColor(params) };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Title Templates
|
||||||
|
|
||||||
|
In root layout for consistent naming:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: { default: 'Site Name', template: '%s | Site Name' }
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Metadata File Conventions
|
||||||
|
|
||||||
|
Reference: https://nextjs.org/docs/app/getting-started/project-structure#metadata-file-conventions
|
||||||
|
|
||||||
|
Place these files in `app/` directory (or route segments):
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
| ------------------------------- | --------------------------------------------- |
|
||||||
|
| `favicon.ico` | Favicon |
|
||||||
|
| `icon.png` / `icon.svg` | App icon |
|
||||||
|
| `apple-icon.png` | Apple app icon |
|
||||||
|
| `opengraph-image.png` | OG image |
|
||||||
|
| `twitter-image.png` | Twitter card image |
|
||||||
|
| `sitemap.ts` / `sitemap.xml` | Sitemap (use `generateSitemaps` for multiple) |
|
||||||
|
| `robots.ts` / `robots.txt` | Robots directives |
|
||||||
|
| `manifest.ts` / `manifest.json` | Web app manifest |
|
||||||
|
|
||||||
|
## SEO Best Practice: Static Files Are Often Enough
|
||||||
|
|
||||||
|
For most sites, **static metadata files provide excellent SEO coverage**:
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── favicon.ico
|
||||||
|
├── opengraph-image.png # Works for both OG and Twitter
|
||||||
|
├── sitemap.ts
|
||||||
|
├── robots.ts
|
||||||
|
└── layout.tsx # With title/description metadata
|
||||||
|
```
|
||||||
|
|
||||||
|
**Tips:**
|
||||||
|
|
||||||
|
- A single `opengraph-image.png` covers both Open Graph and Twitter (Twitter falls back to OG)
|
||||||
|
- Static `title` and `description` in layout metadata is sufficient for most pages
|
||||||
|
- Only use dynamic `generateMetadata` when content varies per page
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# OG Image Generation
|
||||||
|
|
||||||
|
Generate dynamic Open Graph images using `next/og`.
|
||||||
|
|
||||||
|
## Important Rules
|
||||||
|
|
||||||
|
1. **Use `next/og`** - not `@vercel/og` (it's built into Next.js)
|
||||||
|
2. **No searchParams** - OG images can't access search params, use route params instead
|
||||||
|
3. **Avoid Edge runtime** - Use default Node.js runtime
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
|
||||||
|
// Bad
|
||||||
|
// import { ImageResponse } from '@vercel/og'
|
||||||
|
// export const runtime = 'edge'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic OG Image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/opengraph-image.tsx
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
|
||||||
|
export const alt = 'Site Name';
|
||||||
|
export const size = { width: 1200, height: 630 };
|
||||||
|
export const contentType = 'image/png';
|
||||||
|
|
||||||
|
export default function Image() {
|
||||||
|
return new ImageResponse(
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 128,
|
||||||
|
background: 'white',
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Hello World
|
||||||
|
</div>,
|
||||||
|
{ ...size }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dynamic OG Image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/blog/[slug]/opengraph-image.tsx
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
|
||||||
|
export const alt = 'Blog Post';
|
||||||
|
export const size = { width: 1200, height: 630 };
|
||||||
|
export const contentType = 'image/png';
|
||||||
|
|
||||||
|
type Props = { params: Promise<{ slug: string }> };
|
||||||
|
|
||||||
|
export default async function Image({ params }: Props) {
|
||||||
|
const { slug } = await params;
|
||||||
|
const post = await getPost(slug);
|
||||||
|
|
||||||
|
return new ImageResponse(
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 48,
|
||||||
|
background: 'linear-gradient(to bottom, #1a1a1a, #333)',
|
||||||
|
color: 'white',
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: 48
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontSize: 64, fontWeight: 'bold' }}>{post.title}</div>
|
||||||
|
<div style={{ marginTop: 24, opacity: 0.8 }}>{post.description}</div>
|
||||||
|
</div>,
|
||||||
|
{ ...size }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom Fonts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { readFile } from 'fs/promises';
|
||||||
|
|
||||||
|
export default async function Image() {
|
||||||
|
const fontPath = join(process.cwd(), 'assets/fonts/Inter-Bold.ttf');
|
||||||
|
const fontData = await readFile(fontPath);
|
||||||
|
|
||||||
|
return new ImageResponse(
|
||||||
|
<div style={{ fontFamily: 'Inter', fontSize: 64 }}>Custom Font Text</div>,
|
||||||
|
{
|
||||||
|
width: 1200,
|
||||||
|
height: 630,
|
||||||
|
fonts: [{ name: 'Inter', data: fontData, style: 'normal' }]
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## File Naming
|
||||||
|
|
||||||
|
- `opengraph-image.tsx` - Open Graph (Facebook, LinkedIn)
|
||||||
|
- `twitter-image.tsx` - Twitter/X cards (optional, falls back to OG)
|
||||||
|
|
||||||
|
## Styling Notes
|
||||||
|
|
||||||
|
ImageResponse uses Flexbox layout:
|
||||||
|
|
||||||
|
- Use `display: 'flex'`
|
||||||
|
- No CSS Grid support
|
||||||
|
- Styles must be inline objects
|
||||||
|
|
||||||
|
## Multiple OG Images
|
||||||
|
|
||||||
|
Use `generateImageMetadata` for multiple images per route:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/blog/[slug]/opengraph-image.tsx
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
|
||||||
|
export async function generateImageMetadata({ params }) {
|
||||||
|
const images = await getPostImages(params.slug);
|
||||||
|
return images.map((img, idx) => ({
|
||||||
|
id: idx,
|
||||||
|
alt: img.alt,
|
||||||
|
size: { width: 1200, height: 630 },
|
||||||
|
contentType: 'image/png'
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function Image({ params, id }) {
|
||||||
|
const images = await getPostImages(params.slug);
|
||||||
|
const image = images[id];
|
||||||
|
return new ImageResponse(/* ... */);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multiple Sitemaps
|
||||||
|
|
||||||
|
Use `generateSitemaps` for large sites:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/sitemap.ts
|
||||||
|
import type { MetadataRoute } from 'next';
|
||||||
|
|
||||||
|
export async function generateSitemaps() {
|
||||||
|
// Return array of sitemap IDs
|
||||||
|
return [{ id: 0 }, { id: 1 }, { id: 2 }];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function sitemap({ id }: { id: number }): Promise<MetadataRoute.Sitemap> {
|
||||||
|
const start = id * 50000;
|
||||||
|
const end = start + 50000;
|
||||||
|
const products = await getProducts(start, end);
|
||||||
|
|
||||||
|
return products.map((product) => ({
|
||||||
|
url: `https://example.com/product/${product.id}`,
|
||||||
|
lastModified: product.updatedAt
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Generates `/sitemap/0.xml`, `/sitemap/1.xml`, etc.
|
||||||
286
.agents/skills/next-best-practices/parallel-routes.md
Normal file
286
.agents/skills/next-best-practices/parallel-routes.md
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
# Parallel & Intercepting Routes
|
||||||
|
|
||||||
|
Parallel routes render multiple pages in the same layout. Intercepting routes show a different UI when navigating from within your app vs direct URL access. Together they enable modal patterns.
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── @modal/ # Parallel route slot
|
||||||
|
│ ├── default.tsx # Required! Returns null
|
||||||
|
│ ├── (.)photos/ # Intercepts /photos/*
|
||||||
|
│ │ └── [id]/
|
||||||
|
│ │ └── page.tsx # Modal content
|
||||||
|
│ └── [...]catchall/ # Optional: catch unmatched
|
||||||
|
│ └── page.tsx
|
||||||
|
├── photos/
|
||||||
|
│ └── [id]/
|
||||||
|
│ └── page.tsx # Full page (direct access)
|
||||||
|
├── layout.tsx # Renders both children and @modal
|
||||||
|
└── page.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 1: Root Layout with Slot
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/layout.tsx
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
modal
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
modal: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
{modal}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 2: Default File (Critical!)
|
||||||
|
|
||||||
|
**Every parallel route slot MUST have a `default.tsx`** to prevent 404s on hard navigation.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/@modal/default.tsx
|
||||||
|
export default function Default() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Without this file, refreshing any page will 404 because Next.js can't determine what to render in the `@modal` slot.
|
||||||
|
|
||||||
|
## Step 3: Intercepting Route (Modal)
|
||||||
|
|
||||||
|
The `(.)` prefix intercepts routes at the same level.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/@modal/(.)photos/[id]/page.tsx
|
||||||
|
import { Modal } from '@/components/modal';
|
||||||
|
|
||||||
|
export default async function PhotoModal({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const photo = await getPhoto(id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal>
|
||||||
|
<img src={photo.url} alt={photo.title} />
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 4: Full Page (Direct Access)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/photos/[id]/page.tsx
|
||||||
|
export default async function PhotoPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const photo = await getPhoto(id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='full-page'>
|
||||||
|
<img src={photo.url} alt={photo.title} />
|
||||||
|
<h1>{photo.title}</h1>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Step 5: Modal Component with Correct Closing
|
||||||
|
|
||||||
|
**Critical: Use `router.back()` to close modals, NOT `router.push()` or `<Link>`.**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/modal.tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { useCallback, useEffect, useRef } from 'react';
|
||||||
|
|
||||||
|
export function Modal({ children }: { children: React.ReactNode }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const overlayRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Close on escape key
|
||||||
|
useEffect(() => {
|
||||||
|
function onKeyDown(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
router.back(); // Correct
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKeyDown);
|
||||||
|
return () => document.removeEventListener('keydown', onKeyDown);
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
// Close on overlay click
|
||||||
|
const handleOverlayClick = useCallback(
|
||||||
|
(e: React.MouseEvent) => {
|
||||||
|
if (e.target === overlayRef.current) {
|
||||||
|
router.back(); // Correct
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[router]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={overlayRef}
|
||||||
|
onClick={handleOverlayClick}
|
||||||
|
className='fixed inset-0 bg-black/50 flex items-center justify-center z-50'
|
||||||
|
>
|
||||||
|
<div className='bg-white rounded-lg p-6 max-w-2xl w-full mx-4'>
|
||||||
|
<button
|
||||||
|
onClick={() => router.back()} // Correct!
|
||||||
|
className='absolute top-4 right-4'
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Why NOT `router.push('/')` or `<Link href="/">`?
|
||||||
|
|
||||||
|
Using `push` or `Link` to "close" a modal:
|
||||||
|
|
||||||
|
1. Adds a new history entry (back button shows modal again)
|
||||||
|
2. Doesn't properly clear the intercepted route
|
||||||
|
3. Can cause the modal to flash or persist unexpectedly
|
||||||
|
|
||||||
|
`router.back()` correctly:
|
||||||
|
|
||||||
|
1. Removes the intercepted route from history
|
||||||
|
2. Returns to the previous page
|
||||||
|
3. Properly unmounts the modal
|
||||||
|
|
||||||
|
## Route Matcher Reference
|
||||||
|
|
||||||
|
Matchers match **route segments**, not filesystem paths:
|
||||||
|
|
||||||
|
| Matcher | Matches | Example |
|
||||||
|
| ---------- | ------------- | --------------------------------------------------------------------- |
|
||||||
|
| `(.)` | Same level | `@modal/(.)photos` intercepts `/photos` |
|
||||||
|
| `(..)` | One level up | `@modal/(..)settings` from `/dashboard/@modal` intercepts `/settings` |
|
||||||
|
| `(..)(..)` | Two levels up | Rarely used |
|
||||||
|
| `(...)` | From root | `@modal/(...)photos` intercepts `/photos` from anywhere |
|
||||||
|
|
||||||
|
**Common mistake**: Thinking `(..)` means "parent folder" - it means "parent route segment".
|
||||||
|
|
||||||
|
## Handling Hard Navigation
|
||||||
|
|
||||||
|
When users directly visit `/photos/123` (bookmark, refresh, shared link):
|
||||||
|
|
||||||
|
- The intercepting route is bypassed
|
||||||
|
- The full `photos/[id]/page.tsx` renders
|
||||||
|
- Modal doesn't appear (expected behavior)
|
||||||
|
|
||||||
|
If you want the modal to appear on direct access too, you need additional logic:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/photos/[id]/page.tsx
|
||||||
|
import { Modal } from '@/components/modal';
|
||||||
|
|
||||||
|
export default async function PhotoPage({ params }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const photo = await getPhoto(id);
|
||||||
|
|
||||||
|
// Option: Render as modal on direct access too
|
||||||
|
return (
|
||||||
|
<Modal>
|
||||||
|
<img src={photo.url} alt={photo.title} />
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Gotchas
|
||||||
|
|
||||||
|
### 1. Missing `default.tsx` → 404 on Refresh
|
||||||
|
|
||||||
|
Every `@slot` folder needs a `default.tsx` that returns `null` (or appropriate content).
|
||||||
|
|
||||||
|
### 2. Modal Persists After Navigation
|
||||||
|
|
||||||
|
You're using `router.push()` instead of `router.back()`.
|
||||||
|
|
||||||
|
### 3. Nested Parallel Routes Need Defaults Too
|
||||||
|
|
||||||
|
If you have `@modal` inside a route group, each level needs its own `default.tsx`:
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── (marketing)/
|
||||||
|
│ ├── @modal/
|
||||||
|
│ │ └── default.tsx # Needed!
|
||||||
|
│ └── layout.tsx
|
||||||
|
└── layout.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Intercepted Route Shows Wrong Content
|
||||||
|
|
||||||
|
Check your matcher:
|
||||||
|
|
||||||
|
- `(.)photos` intercepts `/photos` from the same route level
|
||||||
|
- If your `@modal` is in `app/dashboard/@modal`, use `(.)photos` to intercept `/dashboard/photos`, not `/photos`
|
||||||
|
|
||||||
|
### 5. TypeScript Errors with `params`
|
||||||
|
|
||||||
|
In Next.js 15+, `params` is a Promise:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Correct
|
||||||
|
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Complete Example: Photo Gallery Modal
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── @modal/
|
||||||
|
│ ├── default.tsx
|
||||||
|
│ └── (.)photos/
|
||||||
|
│ └── [id]/
|
||||||
|
│ └── page.tsx
|
||||||
|
├── photos/
|
||||||
|
│ ├── page.tsx # Gallery grid
|
||||||
|
│ └── [id]/
|
||||||
|
│ └── page.tsx # Full photo page
|
||||||
|
├── layout.tsx
|
||||||
|
└── page.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Links in the gallery:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/photos/page.tsx
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
export default async function Gallery() {
|
||||||
|
const photos = await getPhotos();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='grid grid-cols-3 gap-4'>
|
||||||
|
{photos.map((photo) => (
|
||||||
|
<Link key={photo.id} href={`/photos/${photo.id}`}>
|
||||||
|
<img src={photo.thumbnail} alt={photo.title} />
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Clicking a photo → Modal opens (intercepted)
|
||||||
|
Direct URL → Full page renders
|
||||||
|
Refresh while modal open → Full page renders
|
||||||
143
.agents/skills/next-best-practices/route-handlers.md
Normal file
143
.agents/skills/next-best-practices/route-handlers.md
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
# Route Handlers
|
||||||
|
|
||||||
|
Create API endpoints with `route.ts` files.
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/api/users/route.ts
|
||||||
|
export async function GET() {
|
||||||
|
const users = await getUsers();
|
||||||
|
return Response.json(users);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json();
|
||||||
|
const user = await createUser(body);
|
||||||
|
return Response.json(user, { status: 201 });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Supported Methods
|
||||||
|
|
||||||
|
`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`
|
||||||
|
|
||||||
|
## GET Handler Conflicts with page.tsx
|
||||||
|
|
||||||
|
**A `route.ts` and `page.tsx` cannot coexist in the same folder.**
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── api/
|
||||||
|
│ └── users/
|
||||||
|
│ └── route.ts # /api/users
|
||||||
|
└── users/
|
||||||
|
├── page.tsx # /users (page)
|
||||||
|
└── route.ts # Warning: Conflicts with page.tsx!
|
||||||
|
```
|
||||||
|
|
||||||
|
If you need both a page and an API at the same path, use different paths:
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── users/
|
||||||
|
│ └── page.tsx # /users (page)
|
||||||
|
└── api/
|
||||||
|
└── users/
|
||||||
|
└── route.ts # /api/users (API)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Behavior
|
||||||
|
|
||||||
|
Route handlers run in a **Server Component-like environment**:
|
||||||
|
|
||||||
|
- Yes: Can use `async/await`
|
||||||
|
- Yes: Can access `cookies()`, `headers()`
|
||||||
|
- Yes: Can use Node.js APIs
|
||||||
|
- No: Cannot use React hooks
|
||||||
|
- No: Cannot use React DOM APIs
|
||||||
|
- No: Cannot use browser APIs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: This won't work - no React DOM in route handlers
|
||||||
|
import { renderToString } from 'react-dom/server';
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const html = renderToString(<Component />); // Error!
|
||||||
|
return new Response(html);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dynamic Route Handlers
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/api/users/[id]/route.ts
|
||||||
|
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const user = await getUser(id);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return Response.json({ error: 'Not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(user);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Request Helpers
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
// URL and search params
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const query = searchParams.get('q');
|
||||||
|
|
||||||
|
// Headers
|
||||||
|
const authHeader = request.headers.get('authorization');
|
||||||
|
|
||||||
|
// Cookies (Next.js helper)
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const token = cookieStore.get('token');
|
||||||
|
|
||||||
|
return Response.json({ query, token });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Response Helpers
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// JSON response
|
||||||
|
return Response.json({ data });
|
||||||
|
|
||||||
|
// With status
|
||||||
|
return Response.json({ error: 'Not found' }, { status: 404 });
|
||||||
|
|
||||||
|
// With headers
|
||||||
|
return Response.json(data, {
|
||||||
|
headers: {
|
||||||
|
'Cache-Control': 'max-age=3600'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Redirect
|
||||||
|
return Response.redirect(new URL('/login', request.url));
|
||||||
|
|
||||||
|
// Stream
|
||||||
|
return new Response(stream, {
|
||||||
|
headers: { 'Content-Type': 'text/event-stream' }
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## When to Use Route Handlers vs Server Actions
|
||||||
|
|
||||||
|
| Use Case | Route Handlers | Server Actions |
|
||||||
|
| ------------------------ | -------------- | -------------- |
|
||||||
|
| Form submissions | No | Yes |
|
||||||
|
| Data mutations from UI | No | Yes |
|
||||||
|
| Third-party webhooks | Yes | No |
|
||||||
|
| External API consumption | Yes | No |
|
||||||
|
| Public REST API | Yes | No |
|
||||||
|
| File uploads | Both work | Both work |
|
||||||
|
|
||||||
|
**Prefer Server Actions** for mutations triggered from your UI.
|
||||||
|
**Use Route Handlers** for external integrations and public APIs.
|
||||||
160
.agents/skills/next-best-practices/rsc-boundaries.md
Normal file
160
.agents/skills/next-best-practices/rsc-boundaries.md
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
# RSC Boundaries
|
||||||
|
|
||||||
|
Detect and prevent invalid patterns when crossing Server/Client component boundaries.
|
||||||
|
|
||||||
|
## Detection Rules
|
||||||
|
|
||||||
|
### 1. Async Client Components Are Invalid
|
||||||
|
|
||||||
|
Client components **cannot** be async functions. Only Server Components can be async.
|
||||||
|
|
||||||
|
**Detect:** File has `'use client'` AND component is `async function` or returns `Promise`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: async client component
|
||||||
|
'use client';
|
||||||
|
export default async function UserProfile() {
|
||||||
|
const user = await getUser(); // Cannot await in client component
|
||||||
|
return <div>{user.name}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Remove async, fetch data in parent server component
|
||||||
|
// page.tsx (server component - no 'use client')
|
||||||
|
export default async function Page() {
|
||||||
|
const user = await getUser();
|
||||||
|
return <UserProfile user={user} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserProfile.tsx (client component)
|
||||||
|
('use client');
|
||||||
|
export function UserProfile({ user }: { user: User }) {
|
||||||
|
return <div>{user.name}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: async arrow function client component
|
||||||
|
'use client';
|
||||||
|
const Dashboard = async () => {
|
||||||
|
const data = await fetchDashboard();
|
||||||
|
return <div>{data}</div>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Good: Fetch in server component, pass data down
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Non-Serializable Props to Client Components
|
||||||
|
|
||||||
|
Props passed from Server → Client must be JSON-serializable.
|
||||||
|
|
||||||
|
**Detect:** Server component passes these to a client component:
|
||||||
|
|
||||||
|
- Functions (except Server Actions with `'use server'`)
|
||||||
|
- `Date` objects
|
||||||
|
- `Map`, `Set`, `WeakMap`, `WeakSet`
|
||||||
|
- Class instances
|
||||||
|
- `Symbol` (unless globally registered)
|
||||||
|
- Circular references
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Function prop
|
||||||
|
// page.tsx (server)
|
||||||
|
export default function Page() {
|
||||||
|
const handleClick = () => console.log('clicked');
|
||||||
|
return <ClientButton onClick={handleClick} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Define function inside client component
|
||||||
|
// ClientButton.tsx
|
||||||
|
('use client');
|
||||||
|
export function ClientButton() {
|
||||||
|
const handleClick = () => console.log('clicked');
|
||||||
|
return <button onClick={handleClick}>Click</button>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Date object (silently becomes string, then crashes)
|
||||||
|
// page.tsx (server)
|
||||||
|
export default async function Page() {
|
||||||
|
const post = await getPost();
|
||||||
|
return <PostCard createdAt={post.createdAt} />; // Date object
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostCard.tsx (client) - will crash on .getFullYear()
|
||||||
|
('use client');
|
||||||
|
export function PostCard({ createdAt }: { createdAt: Date }) {
|
||||||
|
return <span>{createdAt.getFullYear()}</span>; // Runtime error!
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good: Serialize to string on server
|
||||||
|
// page.tsx (server)
|
||||||
|
export default async function Page() {
|
||||||
|
const post = await getPost();
|
||||||
|
return <PostCard createdAt={post.createdAt.toISOString()} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostCard.tsx (client)
|
||||||
|
('use client');
|
||||||
|
export function PostCard({ createdAt }: { createdAt: string }) {
|
||||||
|
const date = new Date(createdAt);
|
||||||
|
return <span>{date.getFullYear()}</span>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Class instance
|
||||||
|
const user = new UserModel(data)
|
||||||
|
<ClientProfile user={user} /> // Methods will be stripped
|
||||||
|
|
||||||
|
// Good: Pass plain object
|
||||||
|
const user = await getUser()
|
||||||
|
<ClientProfile user={{ id: user.id, name: user.name }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Map/Set
|
||||||
|
<ClientComponent items={new Map([['a', 1]])} />
|
||||||
|
|
||||||
|
// Good: Convert to array/object
|
||||||
|
<ClientComponent items={Object.fromEntries(map)} />
|
||||||
|
<ClientComponent items={Array.from(set)} />
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Server Actions Are the Exception
|
||||||
|
|
||||||
|
Functions marked with `'use server'` CAN be passed to client components.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Valid: Server Action can be passed
|
||||||
|
// actions.ts
|
||||||
|
'use server';
|
||||||
|
export async function submitForm(formData: FormData) {
|
||||||
|
// server-side logic
|
||||||
|
}
|
||||||
|
|
||||||
|
// page.tsx (server)
|
||||||
|
import { submitForm } from './actions';
|
||||||
|
export default function Page() {
|
||||||
|
return <ClientForm onSubmit={submitForm} />; // OK!
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientForm.tsx (client)
|
||||||
|
('use client');
|
||||||
|
export function ClientForm({ onSubmit }: { onSubmit: (data: FormData) => Promise<void> }) {
|
||||||
|
return <form action={onSubmit}>...</form>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
| Pattern | Valid? | Fix |
|
||||||
|
| --------------------------------- | ------ | ------------------------------------- |
|
||||||
|
| `'use client'` + `async function` | No | Fetch in server parent, pass data |
|
||||||
|
| Pass `() => {}` to client | No | Define in client or use server action |
|
||||||
|
| Pass `new Date()` to client | No | Use `.toISOString()` |
|
||||||
|
| Pass `new Map()` to client | No | Convert to object/array |
|
||||||
|
| Pass class instance to client | No | Pass plain object |
|
||||||
|
| Pass server action to client | Yes | - |
|
||||||
|
| Pass `string/number/boolean` | Yes | - |
|
||||||
|
| Pass plain object/array | Yes | - |
|
||||||
40
.agents/skills/next-best-practices/runtime-selection.md
Normal file
40
.agents/skills/next-best-practices/runtime-selection.md
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# Runtime Selection
|
||||||
|
|
||||||
|
## Use Node.js Runtime by Default
|
||||||
|
|
||||||
|
Use the default Node.js runtime for new routes and pages. Only use Edge runtime if the project already uses it or there's a specific requirement.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Default - no runtime config needed (uses Node.js)
|
||||||
|
export default function Page() { ... }
|
||||||
|
|
||||||
|
// Caution: Only if already used in project or specifically required
|
||||||
|
export const runtime = 'edge'
|
||||||
|
```
|
||||||
|
|
||||||
|
## When to Use Each
|
||||||
|
|
||||||
|
### Node.js Runtime (Default)
|
||||||
|
|
||||||
|
- Full Node.js API support
|
||||||
|
- File system access (`fs`)
|
||||||
|
- Full `crypto` support
|
||||||
|
- Database connections
|
||||||
|
- Most npm packages work
|
||||||
|
|
||||||
|
### Edge Runtime
|
||||||
|
|
||||||
|
- Only for specific edge-location latency requirements
|
||||||
|
- Limited API (no `fs`, limited `crypto`)
|
||||||
|
- Smaller cold start
|
||||||
|
- Geographic distribution needs
|
||||||
|
|
||||||
|
## Detection
|
||||||
|
|
||||||
|
**Before adding `runtime = 'edge'`**, check:
|
||||||
|
|
||||||
|
1. Does the project already use Edge runtime?
|
||||||
|
2. Is there a specific latency requirement?
|
||||||
|
3. Are all dependencies Edge-compatible?
|
||||||
|
|
||||||
|
If unsure, use Node.js runtime.
|
||||||
137
.agents/skills/next-best-practices/scripts.md
Normal file
137
.agents/skills/next-best-practices/scripts.md
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
# Scripts
|
||||||
|
|
||||||
|
Loading third-party scripts in Next.js.
|
||||||
|
|
||||||
|
## Use next/script
|
||||||
|
|
||||||
|
Always use `next/script` instead of native `<script>` tags for better performance.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Native script tag
|
||||||
|
<script src='https://example.com/script.js'></script>;
|
||||||
|
|
||||||
|
// Good: Next.js Script component
|
||||||
|
import Script from 'next/script';
|
||||||
|
|
||||||
|
<Script src='https://example.com/script.js' />;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Inline Scripts Need ID
|
||||||
|
|
||||||
|
Inline scripts require an `id` attribute for Next.js to track them.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Missing id
|
||||||
|
<Script dangerouslySetInnerHTML={{ __html: 'console.log("hi")' }} />
|
||||||
|
|
||||||
|
// Good: Has id
|
||||||
|
<Script id="my-script" dangerouslySetInnerHTML={{ __html: 'console.log("hi")' }} />
|
||||||
|
|
||||||
|
// Good: Inline with id
|
||||||
|
<Script id="show-banner">
|
||||||
|
{`document.getElementById('banner').classList.remove('hidden')`}
|
||||||
|
</Script>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Don't Put Script in Head
|
||||||
|
|
||||||
|
`next/script` should not be placed inside `next/head`. It handles its own positioning.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Script inside Head
|
||||||
|
import Head from 'next/head'
|
||||||
|
import Script from 'next/script'
|
||||||
|
|
||||||
|
<Head>
|
||||||
|
<Script src="/analytics.js" />
|
||||||
|
</Head>
|
||||||
|
|
||||||
|
// Good: Script outside Head
|
||||||
|
<Head>
|
||||||
|
<title>Page</title>
|
||||||
|
</Head>
|
||||||
|
<Script src="/analytics.js" />
|
||||||
|
```
|
||||||
|
|
||||||
|
## Loading Strategies
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// afterInteractive (default) - Load after page is interactive
|
||||||
|
<Script src="/analytics.js" strategy="afterInteractive" />
|
||||||
|
|
||||||
|
// lazyOnload - Load during idle time
|
||||||
|
<Script src="/widget.js" strategy="lazyOnload" />
|
||||||
|
|
||||||
|
// beforeInteractive - Load before page is interactive (use sparingly)
|
||||||
|
// Only works in app/layout.tsx or pages/_document.js
|
||||||
|
<Script src="/critical.js" strategy="beforeInteractive" />
|
||||||
|
|
||||||
|
// worker - Load in web worker (experimental)
|
||||||
|
<Script src="/heavy.js" strategy="worker" />
|
||||||
|
```
|
||||||
|
|
||||||
|
## Google Analytics
|
||||||
|
|
||||||
|
Use `@next/third-parties` instead of inline GA scripts.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Inline GA script
|
||||||
|
<Script src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX" />
|
||||||
|
<Script id="ga-init">
|
||||||
|
{`window.dataLayer = window.dataLayer || [];
|
||||||
|
function gtag(){dataLayer.push(arguments);}
|
||||||
|
gtag('js', new Date());
|
||||||
|
gtag('config', 'G-XXXXX');`}
|
||||||
|
</Script>
|
||||||
|
|
||||||
|
// Good: Next.js component
|
||||||
|
import { GoogleAnalytics } from '@next/third-parties/google'
|
||||||
|
|
||||||
|
export default function Layout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<body>{children}</body>
|
||||||
|
<GoogleAnalytics gaId="G-XXXXX" />
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Google Tag Manager
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { GoogleTagManager } from '@next/third-parties/google';
|
||||||
|
|
||||||
|
export default function Layout({ children }) {
|
||||||
|
return (
|
||||||
|
<html>
|
||||||
|
<GoogleTagManager gtmId='GTM-XXXXX' />
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Other Third-Party Scripts
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// YouTube embed
|
||||||
|
import { YouTubeEmbed } from '@next/third-parties/google';
|
||||||
|
|
||||||
|
<YouTubeEmbed videoid='dQw4w9WgXcQ' />;
|
||||||
|
|
||||||
|
// Google Maps
|
||||||
|
import { GoogleMapsEmbed } from '@next/third-parties/google';
|
||||||
|
|
||||||
|
<GoogleMapsEmbed apiKey='YOUR_API_KEY' mode='place' q='Brooklyn+Bridge,New+York,NY' />;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
| Pattern | Issue | Fix |
|
||||||
|
| --------------------------------------------- | -------------------------- | ------------------------- |
|
||||||
|
| `<script src="...">` | No optimization | Use `next/script` |
|
||||||
|
| `<Script>` without id | Can't track inline scripts | Add `id` attribute |
|
||||||
|
| `<Script>` inside `<Head>` | Wrong placement | Move outside Head |
|
||||||
|
| Inline GA/GTM scripts | No optimization | Use `@next/third-parties` |
|
||||||
|
| `strategy="beforeInteractive"` outside layout | Won't work | Only use in root layout |
|
||||||
375
.agents/skills/next-best-practices/self-hosting.md
Normal file
375
.agents/skills/next-best-practices/self-hosting.md
Normal file
@@ -0,0 +1,375 @@
|
|||||||
|
# Self-Hosting Next.js
|
||||||
|
|
||||||
|
Deploy Next.js outside of Vercel with confidence.
|
||||||
|
|
||||||
|
## Quick Start: Standalone Output
|
||||||
|
|
||||||
|
For Docker or any containerized deployment, use standalone output:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
output: 'standalone'
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates a minimal `standalone` folder with only production dependencies:
|
||||||
|
|
||||||
|
```
|
||||||
|
.next/
|
||||||
|
├── standalone/
|
||||||
|
│ ├── server.js # Entry point
|
||||||
|
│ ├── node_modules/ # Only production deps
|
||||||
|
│ └── .next/ # Build output
|
||||||
|
└── static/ # Must be copied separately
|
||||||
|
```
|
||||||
|
|
||||||
|
## Docker Deployment
|
||||||
|
|
||||||
|
### Dockerfile
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM node:20-alpine AS base
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
FROM base AS deps
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json* ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Build
|
||||||
|
FROM base AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production
|
||||||
|
FROM base AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Create non-root user
|
||||||
|
RUN addgroup --system --gid 1001 nodejs
|
||||||
|
RUN adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
|
# Copy standalone output
|
||||||
|
COPY --from=builder /app/.next/standalone ./
|
||||||
|
COPY --from=builder /app/.next/static ./.next/static
|
||||||
|
COPY --from=builder /app/public ./public
|
||||||
|
|
||||||
|
USER nextjs
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV HOSTNAME="0.0.0.0"
|
||||||
|
|
||||||
|
CMD ["node", "server.js"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Compose
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
web:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- '3000:3000'
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ['CMD', 'wget', '-q', '--spider', 'http://localhost:3000/api/health']
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
```
|
||||||
|
|
||||||
|
## PM2 Deployment
|
||||||
|
|
||||||
|
For traditional server deployments:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// ecosystem.config.js
|
||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'nextjs',
|
||||||
|
script: '.next/standalone/server.js',
|
||||||
|
instances: 'max',
|
||||||
|
exec_mode: 'cluster',
|
||||||
|
env: {
|
||||||
|
NODE_ENV: 'production',
|
||||||
|
PORT: 3000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
pm2 start ecosystem.config.js
|
||||||
|
```
|
||||||
|
|
||||||
|
## ISR and Cache Handlers
|
||||||
|
|
||||||
|
### The Problem
|
||||||
|
|
||||||
|
ISR (Incremental Static Regeneration) uses filesystem caching by default. This **breaks with multiple instances**:
|
||||||
|
|
||||||
|
- Instance A regenerates page → saves to its local disk
|
||||||
|
- Instance B serves stale page → doesn't see Instance A's cache
|
||||||
|
- Load balancer sends users to random instances → inconsistent content
|
||||||
|
|
||||||
|
### Solution: Custom Cache Handler
|
||||||
|
|
||||||
|
Next.js 14+ supports custom cache handlers for shared storage:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
cacheHandler: require.resolve('./cache-handler.js'),
|
||||||
|
cacheMaxMemorySize: 0 // Disable in-memory cache
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Redis Cache Handler Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
// cache-handler.js
|
||||||
|
const Redis = require('ioredis');
|
||||||
|
|
||||||
|
const redis = new Redis(process.env.REDIS_URL);
|
||||||
|
const CACHE_PREFIX = 'nextjs:';
|
||||||
|
|
||||||
|
module.exports = class CacheHandler {
|
||||||
|
constructor(options) {
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(key) {
|
||||||
|
const data = await redis.get(CACHE_PREFIX + key);
|
||||||
|
if (!data) return null;
|
||||||
|
|
||||||
|
const parsed = JSON.parse(data);
|
||||||
|
return {
|
||||||
|
value: parsed.value,
|
||||||
|
lastModified: parsed.lastModified
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async set(key, data, ctx) {
|
||||||
|
const cacheData = {
|
||||||
|
value: data,
|
||||||
|
lastModified: Date.now()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Set TTL based on revalidate option
|
||||||
|
if (ctx?.revalidate) {
|
||||||
|
await redis.setex(CACHE_PREFIX + key, ctx.revalidate, JSON.stringify(cacheData));
|
||||||
|
} else {
|
||||||
|
await redis.set(CACHE_PREFIX + key, JSON.stringify(cacheData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async revalidateTag(tags) {
|
||||||
|
// Implement tag-based invalidation
|
||||||
|
// This requires tracking which keys have which tags
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### S3 Cache Handler Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
// cache-handler.js
|
||||||
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
||||||
|
|
||||||
|
const s3 = new S3Client({ region: process.env.AWS_REGION });
|
||||||
|
const BUCKET = process.env.CACHE_BUCKET;
|
||||||
|
|
||||||
|
module.exports = class CacheHandler {
|
||||||
|
async get(key) {
|
||||||
|
try {
|
||||||
|
const response = await s3.send(
|
||||||
|
new GetObjectCommand({
|
||||||
|
Bucket: BUCKET,
|
||||||
|
Key: `cache/${key}`
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const body = await response.Body.transformToString();
|
||||||
|
return JSON.parse(body);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.name === 'NoSuchKey') return null;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async set(key, data, ctx) {
|
||||||
|
await s3.send(
|
||||||
|
new PutObjectCommand({
|
||||||
|
Bucket: BUCKET,
|
||||||
|
Key: `cache/${key}`,
|
||||||
|
Body: JSON.stringify({
|
||||||
|
value: data,
|
||||||
|
lastModified: Date.now()
|
||||||
|
}),
|
||||||
|
ContentType: 'application/json'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## What Works vs What Needs Setup
|
||||||
|
|
||||||
|
| Feature | Single Instance | Multi-Instance | Notes |
|
||||||
|
| -------------------- | --------------- | ------------------- | --------------------------- |
|
||||||
|
| SSR | Yes | Yes | No special setup |
|
||||||
|
| SSG | Yes | Yes | Built at deploy time |
|
||||||
|
| ISR | Yes | Needs cache handler | Filesystem cache breaks |
|
||||||
|
| Image Optimization | Yes | Yes | CPU-intensive, consider CDN |
|
||||||
|
| Middleware | Yes | Yes | Runs on Node.js |
|
||||||
|
| Edge Runtime | Limited | Limited | Some features Node-only |
|
||||||
|
| `revalidatePath/Tag` | Yes | Needs cache handler | Must share cache |
|
||||||
|
| `next/font` | Yes | Yes | Fonts bundled at build |
|
||||||
|
| Draft Mode | Yes | Yes | Cookie-based |
|
||||||
|
|
||||||
|
## Image Optimization
|
||||||
|
|
||||||
|
Next.js Image Optimization works out of the box but is CPU-intensive.
|
||||||
|
|
||||||
|
### Option 1: Built-in (Simple)
|
||||||
|
|
||||||
|
Works automatically, but consider:
|
||||||
|
|
||||||
|
- Set `deviceSizes` and `imageSizes` in config to limit variants
|
||||||
|
- Use `minimumCacheTTL` to reduce regeneration
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
images: {
|
||||||
|
minimumCacheTTL: 60 * 60 * 24, // 24 hours
|
||||||
|
deviceSizes: [640, 750, 1080, 1920] // Limit sizes
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: External Loader (Recommended for Scale)
|
||||||
|
|
||||||
|
Offload to Cloudinary, Imgix, or similar:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// next.config.js
|
||||||
|
module.exports = {
|
||||||
|
images: {
|
||||||
|
loader: 'custom',
|
||||||
|
loaderFile: './lib/image-loader.js'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
// lib/image-loader.js
|
||||||
|
export default function cloudinaryLoader({ src, width, quality }) {
|
||||||
|
const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`];
|
||||||
|
return `https://res.cloudinary.com/demo/image/upload/${params.join(',')}${src}`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
### Build-time vs Runtime
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Available at build time only (baked into bundle)
|
||||||
|
NEXT_PUBLIC_API_URL=https://api.example.com
|
||||||
|
|
||||||
|
// Available at runtime (server-side only)
|
||||||
|
DATABASE_URL=postgresql://...
|
||||||
|
API_SECRET=...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Runtime Configuration
|
||||||
|
|
||||||
|
For truly dynamic config, don't use `NEXT_PUBLIC_*`. Instead:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/api/config/route.ts
|
||||||
|
export async function GET() {
|
||||||
|
return Response.json({
|
||||||
|
apiUrl: process.env.API_URL,
|
||||||
|
features: process.env.FEATURES?.split(',')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## OpenNext: Serverless Without Vercel
|
||||||
|
|
||||||
|
[OpenNext](https://open-next.js.org/) adapts Next.js for AWS Lambda, Cloudflare Workers, etc.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx create-sst@latest
|
||||||
|
# or
|
||||||
|
npx @opennextjs/aws build
|
||||||
|
```
|
||||||
|
|
||||||
|
Supports:
|
||||||
|
|
||||||
|
- AWS Lambda + CloudFront
|
||||||
|
- Cloudflare Workers
|
||||||
|
- Netlify Functions
|
||||||
|
- Deno Deploy
|
||||||
|
|
||||||
|
## Health Check Endpoint
|
||||||
|
|
||||||
|
Always include a health check for load balancers:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// app/api/health/route.ts
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
// Optional: check database connection
|
||||||
|
// await db.$queryRaw`SELECT 1`;
|
||||||
|
|
||||||
|
return Response.json({ status: 'healthy' }, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ status: 'unhealthy' }, { status: 503 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pre-Deployment Checklist
|
||||||
|
|
||||||
|
1. **Build locally first**: `npm run build` - catch errors before deploy
|
||||||
|
2. **Test standalone output**: `node .next/standalone/server.js`
|
||||||
|
3. **Set `output: 'standalone'`** for Docker
|
||||||
|
4. **Configure cache handler** for multi-instance ISR
|
||||||
|
5. **Set `HOSTNAME="0.0.0.0"`** for containers
|
||||||
|
6. **Copy `public/` and `.next/static/`** - not included in standalone
|
||||||
|
7. **Add health check endpoint**
|
||||||
|
8. **Test ISR revalidation** after deployment
|
||||||
|
9. **Monitor memory usage** - Node.js defaults may need tuning
|
||||||
|
|
||||||
|
## Testing Cache Handler
|
||||||
|
|
||||||
|
**Critical**: Test your cache handler on every Next.js upgrade:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start multiple instances
|
||||||
|
PORT=3001 node .next/standalone/server.js &
|
||||||
|
PORT=3002 node .next/standalone/server.js &
|
||||||
|
|
||||||
|
# Trigger ISR revalidation
|
||||||
|
curl http://localhost:3001/api/revalidate?path=/posts
|
||||||
|
|
||||||
|
# Verify both instances see the update
|
||||||
|
curl http://localhost:3001/posts
|
||||||
|
curl http://localhost:3002/posts
|
||||||
|
# Should return identical content
|
||||||
|
```
|
||||||
67
.agents/skills/next-best-practices/suspense-boundaries.md
Normal file
67
.agents/skills/next-best-practices/suspense-boundaries.md
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
# Suspense Boundaries
|
||||||
|
|
||||||
|
Client hooks that cause CSR bailout without Suspense boundaries.
|
||||||
|
|
||||||
|
## useSearchParams
|
||||||
|
|
||||||
|
Always requires Suspense boundary in static routes. Without it, the entire page becomes client-side rendered.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Bad: Entire page becomes CSR
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
|
export default function SearchBar() {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
return <div>Query: {searchParams.get('q')}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Wrap in Suspense
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
import SearchBar from './search-bar';
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<div>Loading...</div>}>
|
||||||
|
<SearchBar />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## usePathname
|
||||||
|
|
||||||
|
Requires Suspense boundary when route has dynamic parameters.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// In dynamic route [slug]
|
||||||
|
// Bad: No Suspense
|
||||||
|
'use client';
|
||||||
|
import { usePathname } from 'next/navigation';
|
||||||
|
|
||||||
|
export function Breadcrumb() {
|
||||||
|
const pathname = usePathname();
|
||||||
|
return <nav>{pathname}</nav>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good: Wrap in Suspense
|
||||||
|
<Suspense fallback={<BreadcrumbSkeleton />}>
|
||||||
|
<Breadcrumb />
|
||||||
|
</Suspense>
|
||||||
|
```
|
||||||
|
|
||||||
|
If you use `generateStaticParams`, Suspense is optional.
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
| Hook | Suspense Required |
|
||||||
|
| ------------------- | -------------------- |
|
||||||
|
| `useSearchParams()` | Yes |
|
||||||
|
| `usePathname()` | Yes (dynamic routes) |
|
||||||
|
| `useParams()` | No |
|
||||||
|
| `useRouter()` | No |
|
||||||
242
.agents/skills/shadcn/SKILL.md
Normal file
242
.agents/skills/shadcn/SKILL.md
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
---
|
||||||
|
name: shadcn
|
||||||
|
description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
|
||||||
|
user-invocable: false
|
||||||
|
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
|
||||||
|
---
|
||||||
|
|
||||||
|
# shadcn/ui
|
||||||
|
|
||||||
|
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||||
|
|
||||||
|
## Current Project Context
|
||||||
|
|
||||||
|
```json
|
||||||
|
!`npx shadcn@latest info --json`
|
||||||
|
```
|
||||||
|
|
||||||
|
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
|
||||||
|
2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
|
||||||
|
3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
|
||||||
|
4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
|
||||||
|
|
||||||
|
## Critical Rules
|
||||||
|
|
||||||
|
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
|
||||||
|
|
||||||
|
### Styling & Tailwind → [styling.md](./rules/styling.md)
|
||||||
|
|
||||||
|
- **`className` for layout, not styling.** Never override component colors or typography.
|
||||||
|
- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
|
||||||
|
- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
|
||||||
|
- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||||
|
- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
|
||||||
|
- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
|
||||||
|
- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
|
||||||
|
|
||||||
|
### Forms & Inputs → [forms.md](./rules/forms.md)
|
||||||
|
|
||||||
|
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
|
||||||
|
- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
|
||||||
|
- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
|
||||||
|
- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
|
||||||
|
- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
|
||||||
|
- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
|
||||||
|
|
||||||
|
### Component Structure → [composition.md](./rules/composition.md)
|
||||||
|
|
||||||
|
- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.
|
||||||
|
- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
|
||||||
|
- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||||
|
- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
|
||||||
|
- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
|
||||||
|
- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
|
||||||
|
- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
|
||||||
|
|
||||||
|
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
|
||||||
|
|
||||||
|
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
|
||||||
|
- **Callouts use `Alert`.** Don't build custom styled divs.
|
||||||
|
- **Empty states use `Empty`.** Don't build custom empty state markup.
|
||||||
|
- **Toast via `sonner`.** Use `toast()` from `sonner`.
|
||||||
|
- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
|
||||||
|
- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
|
||||||
|
- **Use `Badge`** instead of custom styled spans.
|
||||||
|
|
||||||
|
### Icons → [icons.md](./rules/icons.md)
|
||||||
|
|
||||||
|
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
|
||||||
|
- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
|
||||||
|
- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
|
||||||
|
|
||||||
|
### CLI
|
||||||
|
|
||||||
|
- **Never decode or fetch preset codes manually.** Pass them directly to `npx shadcn@latest init --preset <code>`.
|
||||||
|
|
||||||
|
## Key Patterns
|
||||||
|
|
||||||
|
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Form layout: FieldGroup + Field, not div + Label.
|
||||||
|
<FieldGroup>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" />
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
|
||||||
|
// Validation: data-invalid on Field, aria-invalid on the control.
|
||||||
|
<Field data-invalid>
|
||||||
|
<FieldLabel>Email</FieldLabel>
|
||||||
|
<Input aria-invalid />
|
||||||
|
<FieldDescription>Invalid email.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
// Icons in buttons: data-icon, no sizing classes.
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
// Spacing: gap-*, not space-y-*.
|
||||||
|
<div className="flex flex-col gap-4"> // correct
|
||||||
|
<div className="space-y-4"> // wrong
|
||||||
|
|
||||||
|
// Equal dimensions: size-*, not w-* h-*.
|
||||||
|
<Avatar className="size-10"> // correct
|
||||||
|
<Avatar className="w-10 h-10"> // wrong
|
||||||
|
|
||||||
|
// Status colors: Badge variants or semantic tokens, not raw colors.
|
||||||
|
<Badge variant="secondary">+20.1%</Badge> // correct
|
||||||
|
<span className="text-emerald-600">+20.1%</span> // wrong
|
||||||
|
```
|
||||||
|
|
||||||
|
## Component Selection
|
||||||
|
|
||||||
|
| Need | Use |
|
||||||
|
| -------------------------- | --------------------------------------------------------------------------------------------------- |
|
||||||
|
| Button/action | `Button` with appropriate variant |
|
||||||
|
| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
|
||||||
|
| Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` |
|
||||||
|
| Data display | `Table`, `Card`, `Badge`, `Avatar` |
|
||||||
|
| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
|
||||||
|
| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
|
||||||
|
| Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` |
|
||||||
|
| Command palette | `Command` inside `Dialog` |
|
||||||
|
| Charts | `Chart` (wraps Recharts) |
|
||||||
|
| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
|
||||||
|
| Empty states | `Empty` |
|
||||||
|
| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
|
||||||
|
| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
|
||||||
|
|
||||||
|
## Key Fields
|
||||||
|
|
||||||
|
The injected project context contains these key fields:
|
||||||
|
|
||||||
|
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
|
||||||
|
- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
|
||||||
|
- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
|
||||||
|
- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
|
||||||
|
- **`style`** → component visual treatment (e.g. `nova`, `vega`).
|
||||||
|
- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
|
||||||
|
- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
|
||||||
|
- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
|
||||||
|
- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
|
||||||
|
- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
|
||||||
|
|
||||||
|
See [cli.md — `info` command](./cli.md) for the full field reference.
|
||||||
|
|
||||||
|
## Component Docs, Examples, and Usage
|
||||||
|
|
||||||
|
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest docs button dialog select
|
||||||
|
```
|
||||||
|
|
||||||
|
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
|
||||||
|
2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
|
||||||
|
3. **Find components** — `npx shadcn@latest search`.
|
||||||
|
4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
|
||||||
|
5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
|
||||||
|
6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
|
||||||
|
7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
|
||||||
|
8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
|
||||||
|
9. **Switching presets** — Ask the user first: **reinstall**, **merge**, or **skip**?
|
||||||
|
- **Reinstall**: `npx shadcn@latest init --preset <code> --force --reinstall`. Overwrites all components.
|
||||||
|
- **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
|
||||||
|
- **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
|
||||||
|
- **Important**: Always run preset commands inside the user's project directory. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||||
|
|
||||||
|
## Updating Components
|
||||||
|
|
||||||
|
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
|
||||||
|
|
||||||
|
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
|
||||||
|
2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
|
||||||
|
3. Decide per file based on the diff:
|
||||||
|
- No local changes → safe to overwrite.
|
||||||
|
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
|
||||||
|
- User says "just update everything" → use `--overwrite`, but confirm first.
|
||||||
|
4. **Never use `--overwrite` without the user's explicit approval.**
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create a new project.
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova
|
||||||
|
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
|
||||||
|
|
||||||
|
# Create a monorepo project.
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova --monorepo
|
||||||
|
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
|
||||||
|
|
||||||
|
# Initialize existing project.
|
||||||
|
npx shadcn@latest init --preset base-nova
|
||||||
|
npx shadcn@latest init --defaults # shortcut: --template=next --preset=base-nova
|
||||||
|
|
||||||
|
# Add components.
|
||||||
|
npx shadcn@latest add button card dialog
|
||||||
|
npx shadcn@latest add @magicui/shimmer-button
|
||||||
|
npx shadcn@latest add --all
|
||||||
|
|
||||||
|
# Preview changes before adding/updating.
|
||||||
|
npx shadcn@latest add button --dry-run
|
||||||
|
npx shadcn@latest add button --diff button.tsx
|
||||||
|
npx shadcn@latest add @acme/form --view button.tsx
|
||||||
|
|
||||||
|
# Search registries.
|
||||||
|
npx shadcn@latest search @shadcn -q "sidebar"
|
||||||
|
npx shadcn@latest search @tailark -q "stats"
|
||||||
|
|
||||||
|
# Get component docs and example URLs.
|
||||||
|
npx shadcn@latest docs button dialog select
|
||||||
|
|
||||||
|
# View registry item details (for items not yet installed).
|
||||||
|
npx shadcn@latest view @shadcn/button
|
||||||
|
```
|
||||||
|
|
||||||
|
**Named presets:** `base-nova`, `radix-nova`
|
||||||
|
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
|
||||||
|
**Preset codes:** Base62 strings starting with `a` (e.g. `a2r6bw`), from [ui.shadcn.com](https://ui.shadcn.com).
|
||||||
|
|
||||||
|
## Detailed References
|
||||||
|
|
||||||
|
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
|
||||||
|
- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
|
||||||
|
- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
|
||||||
|
- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
|
||||||
|
- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
|
||||||
|
- [cli.md](./cli.md) — Commands, flags, presets, templates
|
||||||
|
- [customization.md](./customization.md) — Theming, CSS variables, extending components
|
||||||
5
.agents/skills/shadcn/agents/openai.yml
Normal file
5
.agents/skills/shadcn/agents/openai.yml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
interface:
|
||||||
|
display_name: 'shadcn/ui'
|
||||||
|
short_description: 'Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI.'
|
||||||
|
icon_small: './assets/shadcn-small.png'
|
||||||
|
icon_large: './assets/shadcn.png'
|
||||||
BIN
.agents/skills/shadcn/assets/shadcn-small.png
Normal file
BIN
.agents/skills/shadcn/assets/shadcn-small.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
BIN
.agents/skills/shadcn/assets/shadcn.png
Normal file
BIN
.agents/skills/shadcn/assets/shadcn.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
257
.agents/skills/shadcn/cli.md
Normal file
257
.agents/skills/shadcn/cli.md
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
# shadcn CLI Reference
|
||||||
|
|
||||||
|
Configuration is read from `components.json`.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
|
||||||
|
|
||||||
|
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Commands: init, add (dry-run, smart merge), search, view, docs, info, build
|
||||||
|
- Templates: next, vite, start, react-router, astro
|
||||||
|
- Presets: named, code, URL formats and fields
|
||||||
|
- Switching presets
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### `init` — Initialize or create a project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest init [components...] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ----------------------- | ----- | --------------------------------------------------------- | ------- |
|
||||||
|
| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
|
||||||
|
| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
|
||||||
|
| `--yes` | `-y` | Skip confirmation prompt | `true` |
|
||||||
|
| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
|
||||||
|
| `--force` | `-f` | Force overwrite existing configuration | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
| `--name <name>` | `-n` | Name for new project | — |
|
||||||
|
| `--silent` | `-s` | Mute output | `false` |
|
||||||
|
| `--rtl` | | Enable RTL support | — |
|
||||||
|
| `--reinstall` | | Re-install existing UI components | `false` |
|
||||||
|
| `--monorepo` | | Scaffold a monorepo project | — |
|
||||||
|
| `--no-monorepo` | | Skip the monorepo prompt | — |
|
||||||
|
|
||||||
|
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
|
||||||
|
|
||||||
|
### `add` — Add components
|
||||||
|
|
||||||
|
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add [components...] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`), URLs, or local paths.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
|
||||||
|
| `--yes` | `-y` | Skip confirmation prompt | `false` |
|
||||||
|
| `--overwrite` | `-o` | Overwrite existing files | `false` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
| `--all` | `-a` | Add all available components | `false` |
|
||||||
|
| `--path <path>` | `-p` | Target path for the component | — |
|
||||||
|
| `--silent` | `-s` | Mute output | `false` |
|
||||||
|
| `--dry-run` | | Preview all changes without writing files | `false` |
|
||||||
|
| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||||
|
| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
|
||||||
|
|
||||||
|
#### Dry-Run Mode
|
||||||
|
|
||||||
|
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Preview all changes.
|
||||||
|
npx shadcn@latest add button --dry-run
|
||||||
|
|
||||||
|
# Show diffs for all files (top 5).
|
||||||
|
npx shadcn@latest add button --diff
|
||||||
|
|
||||||
|
# Show the diff for a specific file.
|
||||||
|
npx shadcn@latest add button --diff button.tsx
|
||||||
|
|
||||||
|
# Show contents for all files (top 5).
|
||||||
|
npx shadcn@latest add button --view
|
||||||
|
|
||||||
|
# Show the full content of a specific file.
|
||||||
|
npx shadcn@latest add button --view button.tsx
|
||||||
|
|
||||||
|
# Works with URLs too.
|
||||||
|
npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
|
||||||
|
|
||||||
|
# CSS diffs.
|
||||||
|
npx shadcn@latest add button --diff globals.css
|
||||||
|
```
|
||||||
|
|
||||||
|
**When to use dry-run:**
|
||||||
|
|
||||||
|
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
|
||||||
|
- Before overwriting existing components — use `--diff` to preview the changes first.
|
||||||
|
- When the user wants to inspect component source code without installing — use `--view`.
|
||||||
|
- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
|
||||||
|
- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
|
||||||
|
|
||||||
|
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
|
||||||
|
|
||||||
|
#### Smart Merge from Upstream
|
||||||
|
|
||||||
|
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
|
||||||
|
|
||||||
|
### `search` — Search registries
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest search <registries...> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`. Without `-q`, lists all items.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ------------------- | ----- | ---------------------- | ------- |
|
||||||
|
| `--query <query>` | `-q` | Search query | — |
|
||||||
|
| `--limit <number>` | `-l` | Max items per registry | `100` |
|
||||||
|
| `--offset <number>` | `-o` | Items to skip | `0` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
### `view` — View item details
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest view <items...> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Displays item info including file contents. Example: `npx shadcn@latest view @shadcn/button`.
|
||||||
|
|
||||||
|
### `docs` — Get component documentation URLs
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest docs <components...> [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
|
||||||
|
|
||||||
|
Example output for `npx shadcn@latest docs input button`:
|
||||||
|
|
||||||
|
```
|
||||||
|
base radix
|
||||||
|
|
||||||
|
input
|
||||||
|
docs https://ui.shadcn.com/docs/components/radix/input
|
||||||
|
examples https://raw.githubusercontent.com/.../examples/input-example.tsx
|
||||||
|
|
||||||
|
button
|
||||||
|
docs https://ui.shadcn.com/docs/components/radix/button
|
||||||
|
examples https://raw.githubusercontent.com/.../examples/button-example.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
|
||||||
|
|
||||||
|
### `diff` — Check for updates
|
||||||
|
|
||||||
|
Do not use this command. Use `npx shadcn@latest add --diff` instead.
|
||||||
|
|
||||||
|
### `info` — Project information
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest info [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ------------- | ----- | ----------------- | ------- |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
**Project Info fields:**
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
| -------------------- | --------- | ------------------------------------------------------------------ |
|
||||||
|
| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
|
||||||
|
| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
|
||||||
|
| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
|
||||||
|
| `isRSC` | `boolean` | Whether React Server Components are enabled |
|
||||||
|
| `isTsx` | `boolean` | Whether the project uses TypeScript |
|
||||||
|
| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
|
||||||
|
| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
|
||||||
|
| `tailwindCssFile` | `string` | Path to the global CSS file |
|
||||||
|
| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
|
||||||
|
| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
|
||||||
|
|
||||||
|
**Components.json fields:**
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
|
||||||
|
| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
|
||||||
|
| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
|
||||||
|
| `rsc` | `boolean` | RSC flag from config |
|
||||||
|
| `tsx` | `boolean` | TypeScript flag |
|
||||||
|
| `tailwind.config` | `string` | Tailwind config path |
|
||||||
|
| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
|
||||||
|
| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
|
||||||
|
| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
|
||||||
|
| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
|
||||||
|
| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
|
||||||
|
| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
|
||||||
|
| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
|
||||||
|
| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
|
||||||
|
| `registries` | `object` | Configured custom registries |
|
||||||
|
|
||||||
|
**Links fields:**
|
||||||
|
|
||||||
|
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
|
||||||
|
|
||||||
|
### `build` — Build a custom registry
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest build [registry] [options]
|
||||||
|
```
|
||||||
|
|
||||||
|
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
|
||||||
|
|
||||||
|
| Flag | Short | Description | Default |
|
||||||
|
| ----------------- | ----- | ----------------- | ------------ |
|
||||||
|
| `--output <path>` | `-o` | Output directory | `./public/r` |
|
||||||
|
| `--cwd <cwd>` | `-c` | Working directory | current |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Templates
|
||||||
|
|
||||||
|
| Value | Framework | Monorepo support |
|
||||||
|
| -------------- | -------------- | ---------------- |
|
||||||
|
| `next` | Next.js | Yes |
|
||||||
|
| `vite` | Vite | Yes |
|
||||||
|
| `start` | TanStack Start | Yes |
|
||||||
|
| `react-router` | React Router | Yes |
|
||||||
|
| `astro` | Astro | Yes |
|
||||||
|
| `laravel` | Laravel | No |
|
||||||
|
|
||||||
|
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Presets
|
||||||
|
|
||||||
|
Three ways to specify a preset via `--preset`:
|
||||||
|
|
||||||
|
1. **Named:** `--preset base-nova` or `--preset radix-nova`
|
||||||
|
2. **Code:** `--preset a2r6bw` (base62 string, starts with lowercase `a`)
|
||||||
|
3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
|
||||||
|
|
||||||
|
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
|
||||||
|
|
||||||
|
## Switching Presets
|
||||||
|
|
||||||
|
Ask the user first: **reinstall**, **merge**, or **skip** existing components?
|
||||||
|
|
||||||
|
- **Re-install** → `npx shadcn@latest init --preset <code> --force --reinstall`. Overwrites all component files with the new preset styles. Use when the user hasn't customized components.
|
||||||
|
- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
|
||||||
|
- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
|
||||||
|
|
||||||
|
Always run preset commands inside the user's project directory. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
|
||||||
203
.agents/skills/shadcn/customization.md
Normal file
203
.agents/skills/shadcn/customization.md
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
# Customization & Theming
|
||||||
|
|
||||||
|
Components reference semantic CSS variable tokens. Change the variables to change every component.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- How it works (CSS variables → Tailwind utilities → components)
|
||||||
|
- Color variables and OKLCH format
|
||||||
|
- Dark mode setup
|
||||||
|
- Changing the theme (presets, CSS variables)
|
||||||
|
- Adding custom colors (Tailwind v3 and v4)
|
||||||
|
- Border radius
|
||||||
|
- Customizing components (variants, className, wrappers)
|
||||||
|
- Checking for updates
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
|
||||||
|
2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
|
||||||
|
3. Components use these utilities — changing a variable changes all components that reference it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Color Variables
|
||||||
|
|
||||||
|
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
|
||||||
|
|
||||||
|
| Variable | Purpose |
|
||||||
|
| -------------------------------------------- | -------------------------------- |
|
||||||
|
| `--background` / `--foreground` | Page background and default text |
|
||||||
|
| `--card` / `--card-foreground` | Card surfaces |
|
||||||
|
| `--primary` / `--primary-foreground` | Primary buttons and actions |
|
||||||
|
| `--secondary` / `--secondary-foreground` | Secondary actions |
|
||||||
|
| `--muted` / `--muted-foreground` | Muted/disabled states |
|
||||||
|
| `--accent` / `--accent-foreground` | Hover and accent states |
|
||||||
|
| `--destructive` / `--destructive-foreground` | Error and destructive actions |
|
||||||
|
| `--border` | Default border color |
|
||||||
|
| `--input` | Form input borders |
|
||||||
|
| `--ring` | Focus ring color |
|
||||||
|
| `--chart-1` through `--chart-5` | Chart/data visualization |
|
||||||
|
| `--sidebar-*` | Sidebar-specific colors |
|
||||||
|
| `--surface` / `--surface-foreground` | Secondary surface |
|
||||||
|
|
||||||
|
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dark Mode
|
||||||
|
|
||||||
|
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ThemeProvider } from 'next-themes';
|
||||||
|
|
||||||
|
<ThemeProvider attribute='class' defaultTheme='system' enableSystem>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Changing the Theme
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Apply a preset code from ui.shadcn.com.
|
||||||
|
npx shadcn@latest init --preset a2r6bw --force
|
||||||
|
|
||||||
|
# Switch to a named preset.
|
||||||
|
npx shadcn@latest init --preset radix-nova --force
|
||||||
|
npx shadcn@latest init --reinstall # update existing components to match
|
||||||
|
|
||||||
|
# Use a custom theme URL.
|
||||||
|
npx shadcn@latest init --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..." --force
|
||||||
|
```
|
||||||
|
|
||||||
|
Or edit CSS variables directly in `globals.css`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding Custom Colors
|
||||||
|
|
||||||
|
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* 1. Define in the global CSS file. */
|
||||||
|
:root {
|
||||||
|
--warning: oklch(0.84 0.16 84);
|
||||||
|
--warning-foreground: oklch(0.28 0.07 46);
|
||||||
|
}
|
||||||
|
.dark {
|
||||||
|
--warning: oklch(0.41 0.11 46);
|
||||||
|
--warning-foreground: oklch(0.99 0.02 95);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* 2a. Register with Tailwind v4 (@theme inline). */
|
||||||
|
@theme inline {
|
||||||
|
--color-warning: var(--warning);
|
||||||
|
--color-warning-foreground: var(--warning-foreground);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// 2b. Register with Tailwind v3 (tailwind.config.js).
|
||||||
|
module.exports = {
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
warning: 'oklch(var(--warning) / <alpha-value>)',
|
||||||
|
'warning-foreground': 'oklch(var(--warning-foreground) / <alpha-value>)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// 3. Use in components.
|
||||||
|
<div className='bg-warning text-warning-foreground'>Warning</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Border Radius
|
||||||
|
|
||||||
|
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Customizing Components
|
||||||
|
|
||||||
|
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
|
||||||
|
|
||||||
|
Prefer these approaches in order:
|
||||||
|
|
||||||
|
### 1. Built-in variants
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button variant='outline' size='sm'>
|
||||||
|
Click
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Tailwind classes via `className`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className='max-w-md mx-auto'>...</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Add a new variant
|
||||||
|
|
||||||
|
Edit the component source to add a variant via `cva`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ui/button.tsx
|
||||||
|
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Wrapper components
|
||||||
|
|
||||||
|
Compose shadcn/ui primitives into higher-level components:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
export function ConfirmDialog({ title, description, onConfirm, children }) {
|
||||||
|
return (
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Checking for Updates
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add button --diff
|
||||||
|
```
|
||||||
|
|
||||||
|
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx shadcn@latest add button --dry-run # see all affected files
|
||||||
|
npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
|
||||||
47
.agents/skills/shadcn/evals/evals.json
Normal file
47
.agents/skills/shadcn/evals/evals.json
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"skill_name": "shadcn",
|
||||||
|
"evals": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
|
||||||
|
"expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses FieldGroup and Field components for form layout instead of raw div with space-y",
|
||||||
|
"Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
|
||||||
|
"Uses data-invalid on Field and aria-invalid on the input control for validation states",
|
||||||
|
"Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
|
||||||
|
"Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
|
||||||
|
"No manual dark: color overrides"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
|
||||||
|
"expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Includes DialogTitle for accessibility (visible or with sr-only class)",
|
||||||
|
"Avatar component includes AvatarFallback",
|
||||||
|
"Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
|
||||||
|
"No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
|
||||||
|
"Uses tabler icons (@tabler/icons-react) instead of lucide-react",
|
||||||
|
"Uses asChild for custom triggers (radix preset)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
|
||||||
|
"expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
|
||||||
|
"files": [],
|
||||||
|
"expectations": [
|
||||||
|
"Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
|
||||||
|
"Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
|
||||||
|
"Uses Badge component for percentage change instead of custom styled spans",
|
||||||
|
"Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
|
||||||
|
"Uses gap-* instead of space-y-* or space-x-* for spacing",
|
||||||
|
"Uses size-* when width and height are equal instead of separate w-* h-*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
94
.agents/skills/shadcn/mcp.md
Normal file
94
.agents/skills/shadcn/mcp.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
# shadcn MCP Server
|
||||||
|
|
||||||
|
The CLI includes an MCP server that lets AI assistants search, browse, view, and install components from registries.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
shadcn mcp # start the MCP server (stdio)
|
||||||
|
shadcn mcp init # write config for your editor
|
||||||
|
```
|
||||||
|
|
||||||
|
Editor config files:
|
||||||
|
|
||||||
|
| Editor | Config file |
|
||||||
|
| ----------- | ------------------------------- |
|
||||||
|
| Claude Code | `.mcp.json` |
|
||||||
|
| Cursor | `.cursor/mcp.json` |
|
||||||
|
| VS Code | `.vscode/mcp.json` |
|
||||||
|
| OpenCode | `opencode.json` |
|
||||||
|
| Codex | `~/.codex/config.toml` (manual) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
|
||||||
|
|
||||||
|
### `shadcn:get_project_registries`
|
||||||
|
|
||||||
|
Returns registry names from `components.json`. Errors if no `components.json` exists.
|
||||||
|
|
||||||
|
**Input:** none
|
||||||
|
|
||||||
|
### `shadcn:list_items_in_registries`
|
||||||
|
|
||||||
|
Lists all items from one or more registries.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[]), `limit` (number, optional), `offset` (number, optional)
|
||||||
|
|
||||||
|
### `shadcn:search_items_in_registries`
|
||||||
|
|
||||||
|
Fuzzy search across registries.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[]), `query` (string), `limit` (number, optional), `offset` (number, optional)
|
||||||
|
|
||||||
|
### `shadcn:view_items_in_registries`
|
||||||
|
|
||||||
|
View item details including full file contents.
|
||||||
|
|
||||||
|
**Input:** `items` (string[]) — e.g. `["@shadcn/button", "@shadcn/card"]`
|
||||||
|
|
||||||
|
### `shadcn:get_item_examples_from_registries`
|
||||||
|
|
||||||
|
Find usage examples and demos with source code.
|
||||||
|
|
||||||
|
**Input:** `registries` (string[]), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
|
||||||
|
|
||||||
|
### `shadcn:get_add_command_for_items`
|
||||||
|
|
||||||
|
Returns the CLI install command.
|
||||||
|
|
||||||
|
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
|
||||||
|
|
||||||
|
### `shadcn:get_audit_checklist`
|
||||||
|
|
||||||
|
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
|
||||||
|
|
||||||
|
**Input:** none
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuring Registries
|
||||||
|
|
||||||
|
Registries are set in `components.json`. The `@shadcn` registry is always built-in.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"registries": {
|
||||||
|
"@acme": "https://acme.com/r/{name}.json",
|
||||||
|
"@private": {
|
||||||
|
"url": "https://private.com/r/{name}.json",
|
||||||
|
"headers": { "Authorization": "Bearer ${MY_TOKEN}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Names must start with `@`.
|
||||||
|
- URLs must contain `{name}`.
|
||||||
|
- `${VAR}` references are resolved from environment variables.
|
||||||
|
|
||||||
|
Community registry index: `https://ui.shadcn.com/r/registries.json`
|
||||||
308
.agents/skills/shadcn/rules/base-vs-radix.md
Normal file
308
.agents/skills/shadcn/rules/base-vs-radix.md
Normal file
@@ -0,0 +1,308 @@
|
|||||||
|
# Base vs Radix
|
||||||
|
|
||||||
|
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Composition: asChild vs render
|
||||||
|
- Button / trigger as non-button element
|
||||||
|
- Select (items prop, placeholder, positioning, multiple, object values)
|
||||||
|
- ToggleGroup (type vs multiple)
|
||||||
|
- Slider (scalar vs array)
|
||||||
|
- Accordion (type and defaultValue)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Composition: asChild (radix) vs render (base)
|
||||||
|
|
||||||
|
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger>
|
||||||
|
<div>
|
||||||
|
<Button>Open</Button>
|
||||||
|
</div>
|
||||||
|
</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button>Open</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogTrigger render={<Button />}>Open</DialogTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Button / trigger as non-button element (base only)
|
||||||
|
|
||||||
|
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
|
||||||
|
|
||||||
|
**Incorrect (base):** missing `nativeButton={false}`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button render={<a href='/docs' />}>Read the docs</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button render={<a href='/docs' />} nativeButton={false}>
|
||||||
|
Read the docs
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button asChild>
|
||||||
|
<a href='/docs'>Read the docs</a>
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Same for triggers whose `render` is not a `Button`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
|
||||||
|
Pick date
|
||||||
|
</PopoverTrigger>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Select
|
||||||
|
|
||||||
|
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder='Select a fruit' />
|
||||||
|
</SelectTrigger>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const items = [
|
||||||
|
{ label: "Select a fruit", value: null },
|
||||||
|
{ label: "Apple", value: "apple" },
|
||||||
|
{ label: "Banana", value: "banana" },
|
||||||
|
]
|
||||||
|
|
||||||
|
<Select items={items}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
{items.map((item) => (
|
||||||
|
<SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder='Select a fruit' />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem value='apple'>Apple</SelectItem>
|
||||||
|
<SelectItem value='banana'>Banana</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
|
||||||
|
|
||||||
|
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
<SelectContent alignItemWithTrigger={false} side="bottom">
|
||||||
|
|
||||||
|
// radix.
|
||||||
|
<SelectContent position="popper">
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Select — multiple selection and object values (base only)
|
||||||
|
|
||||||
|
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
|
||||||
|
|
||||||
|
**Correct (base — multiple selection):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select items={items} multiple defaultValue={[]}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue>
|
||||||
|
{(value: string[]) => (value.length === 0 ? 'Select fruits' : `${value.length} selected`)}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
...
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base — object values):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue>{(value) => value.name}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
...
|
||||||
|
</Select>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ToggleGroup
|
||||||
|
|
||||||
|
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<ToggleGroup type='single' defaultValue='daily'>
|
||||||
|
<ToggleGroupItem value='daily'>Daily</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Single (no prop needed), defaultValue is always an array.
|
||||||
|
<ToggleGroup defaultValue={["daily"]} spacing={2}>
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
|
||||||
|
// Multi-selection.
|
||||||
|
<ToggleGroup multiple>
|
||||||
|
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Single, defaultValue is a string.
|
||||||
|
<ToggleGroup type="single" defaultValue="daily" spacing={2}>
|
||||||
|
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
|
||||||
|
// Multi-selection.
|
||||||
|
<ToggleGroup type="multiple">
|
||||||
|
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Controlled single value:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base — wrap/unwrap arrays.
|
||||||
|
const [value, setValue] = React.useState("normal")
|
||||||
|
<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
|
||||||
|
|
||||||
|
// radix — plain string.
|
||||||
|
const [value, setValue] = React.useState("normal")
|
||||||
|
<ToggleGroup type="single" value={value} onValueChange={setValue}>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Slider
|
||||||
|
|
||||||
|
Base accepts a plain number for a single thumb. Radix always requires an array.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={[50]} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={50} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Slider defaultValue={[50]} max={100} step={1} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// base.
|
||||||
|
const [value, setValue] = React.useState([0.3, 0.7])
|
||||||
|
<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
|
||||||
|
|
||||||
|
// radix.
|
||||||
|
const [value, setValue] = React.useState([0.3, 0.7])
|
||||||
|
<Slider value={value} onValueChange={setValue} />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Accordion
|
||||||
|
|
||||||
|
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
|
||||||
|
|
||||||
|
**Incorrect (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion type='single' collapsible defaultValue='item-1'>
|
||||||
|
<AccordionItem value='item-1'>...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (base):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion defaultValue={["item-1"]}>
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
|
// Multi-select.
|
||||||
|
<Accordion multiple defaultValue={["item-1", "item-2"]}>
|
||||||
|
<AccordionItem value="item-1">...</AccordionItem>
|
||||||
|
<AccordionItem value="item-2">...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct (radix):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Accordion type='single' collapsible defaultValue='item-1'>
|
||||||
|
<AccordionItem value='item-1'>...</AccordionItem>
|
||||||
|
</Accordion>
|
||||||
|
```
|
||||||
197
.agents/skills/shadcn/rules/composition.md
Normal file
197
.agents/skills/shadcn/rules/composition.md
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
# Component Composition
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Items always inside their Group component
|
||||||
|
- Callouts use Alert
|
||||||
|
- Empty states use Empty component
|
||||||
|
- Toast notifications use sonner
|
||||||
|
- Choosing between overlay components
|
||||||
|
- Dialog, Sheet, and Drawer always need a Title
|
||||||
|
- Card structure
|
||||||
|
- Button has no isPending or isLoading prop
|
||||||
|
- TabsTrigger must be inside TabsList
|
||||||
|
- Avatar always needs AvatarFallback
|
||||||
|
- Use Separator instead of raw hr or border divs
|
||||||
|
- Use Skeleton for loading placeholders
|
||||||
|
- Use Badge instead of custom styled spans
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Items always inside their Group component
|
||||||
|
|
||||||
|
Never render items directly inside the content container.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value='apple'>Apple</SelectItem>
|
||||||
|
<SelectItem value='banana'>Banana</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem value='apple'>Apple</SelectItem>
|
||||||
|
<SelectItem value='banana'>Banana</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies to all group-based components:
|
||||||
|
|
||||||
|
| Item | Group |
|
||||||
|
| ---------------------------------------------------------- | ------------------- |
|
||||||
|
| `SelectItem`, `SelectLabel` | `SelectGroup` |
|
||||||
|
| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
|
||||||
|
| `MenubarItem` | `MenubarGroup` |
|
||||||
|
| `ContextMenuItem` | `ContextMenuGroup` |
|
||||||
|
| `CommandItem` | `CommandGroup` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Callouts use Alert
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Alert>
|
||||||
|
<AlertTitle>Warning</AlertTitle>
|
||||||
|
<AlertDescription>Something needs attention.</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Empty states use Empty component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Empty>
|
||||||
|
<EmptyHeader>
|
||||||
|
<EmptyMedia variant='icon'>
|
||||||
|
<FolderIcon />
|
||||||
|
</EmptyMedia>
|
||||||
|
<EmptyTitle>No projects yet</EmptyTitle>
|
||||||
|
<EmptyDescription>Get started by creating a new project.</EmptyDescription>
|
||||||
|
</EmptyHeader>
|
||||||
|
<EmptyContent>
|
||||||
|
<Button>Create Project</Button>
|
||||||
|
</EmptyContent>
|
||||||
|
</Empty>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Toast notifications use sonner
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
toast.success('Changes saved.');
|
||||||
|
toast.error('Something went wrong.');
|
||||||
|
toast('File deleted.', {
|
||||||
|
action: { label: 'Undo', onClick: () => undoDelete() }
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Choosing between overlay components
|
||||||
|
|
||||||
|
| Use case | Component |
|
||||||
|
| ---------------------------------- | ------------- |
|
||||||
|
| Focused task that requires input | `Dialog` |
|
||||||
|
| Destructive action confirmation | `AlertDialog` |
|
||||||
|
| Side panel with details or filters | `Sheet` |
|
||||||
|
| Mobile-first bottom panel | `Drawer` |
|
||||||
|
| Quick info on hover | `HoverCard` |
|
||||||
|
| Small contextual content on click | `Popover` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dialog, Sheet, and Drawer always need a Title
|
||||||
|
|
||||||
|
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Edit Profile</DialogTitle>
|
||||||
|
<DialogDescription>Update your profile.</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
...
|
||||||
|
</DialogContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Card structure
|
||||||
|
|
||||||
|
Use full composition — don't dump everything into `CardContent`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Team Members</CardTitle>
|
||||||
|
<CardDescription>Manage your team.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>...</CardContent>
|
||||||
|
<CardFooter>
|
||||||
|
<Button>Invite</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Button has no isPending or isLoading prop
|
||||||
|
|
||||||
|
Compose with `Spinner` + `data-icon` + `disabled`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button disabled>
|
||||||
|
<Spinner data-icon='inline-start' />
|
||||||
|
Saving...
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TabsTrigger must be inside TabsList
|
||||||
|
|
||||||
|
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Tabs defaultValue='account'>
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value='account'>Account</TabsTrigger>
|
||||||
|
<TabsTrigger value='password'>Password</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value='account'>...</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avatar always needs AvatarFallback
|
||||||
|
|
||||||
|
Always include `AvatarFallback` for when the image fails to load:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src='/avatar.png' alt='User' />
|
||||||
|
<AvatarFallback>JD</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use existing components instead of custom markup
|
||||||
|
|
||||||
|
| Instead of | Use |
|
||||||
|
| -------------------------------------------------- | ------------------------------------ |
|
||||||
|
| `<hr>` or `<div className="border-t">` | `<Separator />` |
|
||||||
|
| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
|
||||||
|
| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
|
||||||
194
.agents/skills/shadcn/rules/forms.md
Normal file
194
.agents/skills/shadcn/rules/forms.md
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
# Forms & Inputs
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Forms use FieldGroup + Field
|
||||||
|
- InputGroup requires InputGroupInput/InputGroupTextarea
|
||||||
|
- Buttons inside inputs use InputGroup + InputGroupAddon
|
||||||
|
- Option sets (2–7 choices) use ToggleGroup
|
||||||
|
- FieldSet + FieldLegend for grouping related fields
|
||||||
|
- Field validation and disabled states
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Forms use FieldGroup + Field
|
||||||
|
|
||||||
|
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FieldGroup>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor='email'>Email</FieldLabel>
|
||||||
|
<Input id='email' type='email' />
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor='password'>Password</FieldLabel>
|
||||||
|
<Input id='password' type='password' />
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
|
||||||
|
|
||||||
|
**Choosing form controls:**
|
||||||
|
|
||||||
|
- Simple text input → `Input`
|
||||||
|
- Dropdown with predefined options → `Select`
|
||||||
|
- Searchable dropdown → `Combobox`
|
||||||
|
- Native HTML select (no JS) → `native-select`
|
||||||
|
- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
|
||||||
|
- Single choice from few options → `RadioGroup`
|
||||||
|
- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`
|
||||||
|
- OTP/verification code → `InputOTP`
|
||||||
|
- Multi-line text → `Textarea`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## InputGroup requires InputGroupInput/InputGroupTextarea
|
||||||
|
|
||||||
|
Never use raw `Input` or `Textarea` inside an `InputGroup`.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<InputGroup>
|
||||||
|
<Input placeholder='Search...' />
|
||||||
|
</InputGroup>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { InputGroup, InputGroupInput } from '@/components/ui/input-group';
|
||||||
|
|
||||||
|
<InputGroup>
|
||||||
|
<InputGroupInput placeholder='Search...' />
|
||||||
|
</InputGroup>;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Buttons inside inputs use InputGroup + InputGroupAddon
|
||||||
|
|
||||||
|
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className='relative'>
|
||||||
|
<Input placeholder='Search...' className='pr-10' />
|
||||||
|
<Button className='absolute right-0 top-0' size='icon'>
|
||||||
|
<SearchIcon />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { InputGroup, InputGroupInput, InputGroupAddon } from '@/components/ui/input-group';
|
||||||
|
|
||||||
|
<InputGroup>
|
||||||
|
<InputGroupInput placeholder='Search...' />
|
||||||
|
<InputGroupAddon>
|
||||||
|
<Button size='icon'>
|
||||||
|
<SearchIcon data-icon='inline-start' />
|
||||||
|
</Button>
|
||||||
|
</InputGroupAddon>
|
||||||
|
</InputGroup>;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Option sets (2–7 choices) use ToggleGroup
|
||||||
|
|
||||||
|
Don't manually loop `Button` components with active state.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const [selected, setSelected] = useState("daily")
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{["daily", "weekly", "monthly"].map((option) => (
|
||||||
|
<Button
|
||||||
|
key={option}
|
||||||
|
variant={selected === option ? "default" : "outline"}
|
||||||
|
onClick={() => setSelected(option)}
|
||||||
|
>
|
||||||
|
{option}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||||
|
|
||||||
|
<ToggleGroup spacing={2}>
|
||||||
|
<ToggleGroupItem value='daily'>Daily</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value='weekly'>Weekly</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value='monthly'>Monthly</ToggleGroupItem>
|
||||||
|
</ToggleGroup>;
|
||||||
|
```
|
||||||
|
|
||||||
|
Combine with `Field` for labelled toggle groups:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Field orientation='horizontal'>
|
||||||
|
<FieldTitle id='theme-label'>Theme</FieldTitle>
|
||||||
|
<ToggleGroup aria-labelledby='theme-label' spacing={2}>
|
||||||
|
<ToggleGroupItem value='light'>Light</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value='dark'>Dark</ToggleGroupItem>
|
||||||
|
<ToggleGroupItem value='system'>System</ToggleGroupItem>
|
||||||
|
</ToggleGroup>
|
||||||
|
</Field>
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## FieldSet + FieldLegend for grouping related fields
|
||||||
|
|
||||||
|
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<FieldSet>
|
||||||
|
<FieldLegend variant='label'>Preferences</FieldLegend>
|
||||||
|
<FieldDescription>Select all that apply.</FieldDescription>
|
||||||
|
<FieldGroup className='gap-3'>
|
||||||
|
<Field orientation='horizontal'>
|
||||||
|
<Checkbox id='dark' />
|
||||||
|
<FieldLabel htmlFor='dark' className='font-normal'>
|
||||||
|
Dark mode
|
||||||
|
</FieldLabel>
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
</FieldSet>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Field validation and disabled states
|
||||||
|
|
||||||
|
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Invalid.
|
||||||
|
<Field data-invalid>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" aria-invalid />
|
||||||
|
<FieldDescription>Invalid email address.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
// Disabled.
|
||||||
|
<Field data-disabled>
|
||||||
|
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||||
|
<Input id="email" disabled />
|
||||||
|
</Field>
|
||||||
|
```
|
||||||
|
|
||||||
|
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
|
||||||
101
.agents/skills/shadcn/rules/icons.md
Normal file
101
.agents/skills/shadcn/rules/icons.md
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
# Icons
|
||||||
|
|
||||||
|
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Icons in Button use data-icon attribute
|
||||||
|
|
||||||
|
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon className='mr-2 size-4' />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start"/>
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button>
|
||||||
|
Next
|
||||||
|
<ArrowRightIcon data-icon="inline-end"/>
|
||||||
|
</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No sizing classes on icons inside components
|
||||||
|
|
||||||
|
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon className="size-4" data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<SettingsIcon className="mr-2 size-4" />
|
||||||
|
Settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button>
|
||||||
|
<SearchIcon data-icon="inline-start" />
|
||||||
|
Search
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<SettingsIcon />
|
||||||
|
Settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pass icons as component objects, not string keys
|
||||||
|
|
||||||
|
Use `icon={CheckIcon}`, not a string key to a lookup map.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const iconMap = {
|
||||||
|
check: CheckIcon,
|
||||||
|
alert: AlertIcon
|
||||||
|
};
|
||||||
|
|
||||||
|
function StatusBadge({ icon }: { icon: string }) {
|
||||||
|
const Icon = iconMap[icon];
|
||||||
|
return <Icon />;
|
||||||
|
}
|
||||||
|
|
||||||
|
<StatusBadge icon='check' />;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
|
||||||
|
import { CheckIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
|
||||||
|
return <Icon />;
|
||||||
|
}
|
||||||
|
|
||||||
|
<StatusBadge icon={CheckIcon} />;
|
||||||
|
```
|
||||||
161
.agents/skills/shadcn/rules/styling.md
Normal file
161
.agents/skills/shadcn/rules/styling.md
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
# Styling & Customization
|
||||||
|
|
||||||
|
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- Semantic colors
|
||||||
|
- Built-in variants first
|
||||||
|
- className for layout only
|
||||||
|
- No space-x-_ / space-y-_
|
||||||
|
- Prefer size-_ over w-_ h-\* when equal
|
||||||
|
- Prefer truncate shorthand
|
||||||
|
- No manual dark: color overrides
|
||||||
|
- Use cn() for conditional classes
|
||||||
|
- No manual z-index on overlay components
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Semantic colors
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className='bg-blue-500 text-white'>
|
||||||
|
<p className='text-gray-600'>Secondary text</p>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className='bg-primary text-primary-foreground'>
|
||||||
|
<p className='text-muted-foreground'>Secondary text</p>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No raw color values for status/state indicators
|
||||||
|
|
||||||
|
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<span className="text-emerald-600">+20.1%</span>
|
||||||
|
<span className="text-green-500">Active</span>
|
||||||
|
<span className="text-red-600">-3.2%</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Badge variant="secondary">+20.1%</Badge>
|
||||||
|
<Badge>Active</Badge>
|
||||||
|
<span className="text-destructive">-3.2%</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Built-in variants first
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button className='border border-input bg-transparent hover:bg-accent'>Click me</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Button variant='outline'>Click me</Button>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## className for layout only
|
||||||
|
|
||||||
|
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className='bg-blue-100 text-blue-900 font-bold'>
|
||||||
|
<CardContent>Dashboard</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Card className='max-w-md mx-auto'>
|
||||||
|
<CardContent>Dashboard</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
To customize a component's appearance, prefer these approaches in order:
|
||||||
|
|
||||||
|
1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.
|
||||||
|
2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.
|
||||||
|
3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No space-x-_ / space-y-_
|
||||||
|
|
||||||
|
Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className='flex flex-col gap-4'>
|
||||||
|
<Input />
|
||||||
|
<Input />
|
||||||
|
<Button>Submit</Button>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prefer size-_ over w-_ h-\* when equal
|
||||||
|
|
||||||
|
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prefer truncate shorthand
|
||||||
|
|
||||||
|
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No manual dark: color overrides
|
||||||
|
|
||||||
|
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use cn() for conditional classes
|
||||||
|
|
||||||
|
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
|
||||||
|
|
||||||
|
**Incorrect:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## No manual z-index on overlay components
|
||||||
|
|
||||||
|
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
|
||||||
202
.agents/skills/skill-creator/LICENSE.txt
Normal file
202
.agents/skills/skill-creator/LICENSE.txt
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
510
.agents/skills/skill-creator/SKILL.md
Normal file
510
.agents/skills/skill-creator/SKILL.md
Normal file
@@ -0,0 +1,510 @@
|
|||||||
|
---
|
||||||
|
name: skill-creator
|
||||||
|
description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Skill Creator
|
||||||
|
|
||||||
|
A skill for creating new skills and iteratively improving them.
|
||||||
|
|
||||||
|
At a high level, the process of creating a skill goes like this:
|
||||||
|
|
||||||
|
- Decide what you want the skill to do and roughly how it should do it
|
||||||
|
- Write a draft of the skill
|
||||||
|
- Create a few test prompts and run claude-with-access-to-the-skill on them
|
||||||
|
- Help the user evaluate the results both qualitatively and quantitatively
|
||||||
|
- While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)
|
||||||
|
- Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics
|
||||||
|
- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)
|
||||||
|
- Repeat until you're satisfied
|
||||||
|
- Expand the test set and try again at larger scale
|
||||||
|
|
||||||
|
Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.
|
||||||
|
|
||||||
|
On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.
|
||||||
|
|
||||||
|
Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead.
|
||||||
|
|
||||||
|
Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.
|
||||||
|
|
||||||
|
Cool? Cool.
|
||||||
|
|
||||||
|
## Communicating with the user
|
||||||
|
|
||||||
|
The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate.
|
||||||
|
|
||||||
|
So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:
|
||||||
|
|
||||||
|
- "evaluation" and "benchmark" are borderline, but OK
|
||||||
|
- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them
|
||||||
|
|
||||||
|
It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Creating a skill
|
||||||
|
|
||||||
|
### Capture Intent
|
||||||
|
|
||||||
|
Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.
|
||||||
|
|
||||||
|
1. What should this skill enable Claude to do?
|
||||||
|
2. When should this skill trigger? (what user phrases/contexts)
|
||||||
|
3. What's the expected output format?
|
||||||
|
4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.
|
||||||
|
|
||||||
|
### Interview and Research
|
||||||
|
|
||||||
|
Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.
|
||||||
|
|
||||||
|
Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.
|
||||||
|
|
||||||
|
### Write the SKILL.md
|
||||||
|
|
||||||
|
Based on the user interview, fill in these components:
|
||||||
|
|
||||||
|
- **name**: Skill identifier
|
||||||
|
- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'"
|
||||||
|
- **compatibility**: Required tools, dependencies (optional, rarely needed)
|
||||||
|
- **the rest of the skill :)**
|
||||||
|
|
||||||
|
### Skill Writing Guide
|
||||||
|
|
||||||
|
#### Anatomy of a Skill
|
||||||
|
|
||||||
|
```
|
||||||
|
skill-name/
|
||||||
|
├── SKILL.md (required)
|
||||||
|
│ ├── YAML frontmatter (name, description required)
|
||||||
|
│ └── Markdown instructions
|
||||||
|
└── Bundled Resources (optional)
|
||||||
|
├── scripts/ - Executable code for deterministic/repetitive tasks
|
||||||
|
├── references/ - Docs loaded into context as needed
|
||||||
|
└── assets/ - Files used in output (templates, icons, fonts)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Progressive Disclosure
|
||||||
|
|
||||||
|
Skills use a three-level loading system:
|
||||||
|
|
||||||
|
1. **Metadata** (name + description) - Always in context (~100 words)
|
||||||
|
2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)
|
||||||
|
3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)
|
||||||
|
|
||||||
|
These word counts are approximate and you can feel free to go longer if needed.
|
||||||
|
|
||||||
|
**Key patterns:**
|
||||||
|
|
||||||
|
- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.
|
||||||
|
- Reference files clearly from SKILL.md with guidance on when to read them
|
||||||
|
- For large reference files (>300 lines), include a table of contents
|
||||||
|
|
||||||
|
**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:
|
||||||
|
|
||||||
|
```
|
||||||
|
cloud-deploy/
|
||||||
|
├── SKILL.md (workflow + selection)
|
||||||
|
└── references/
|
||||||
|
├── aws.md
|
||||||
|
├── gcp.md
|
||||||
|
└── azure.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Claude reads only the relevant reference file.
|
||||||
|
|
||||||
|
#### Principle of Lack of Surprise
|
||||||
|
|
||||||
|
This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though.
|
||||||
|
|
||||||
|
#### Writing Patterns
|
||||||
|
|
||||||
|
Prefer using the imperative form in instructions.
|
||||||
|
|
||||||
|
**Defining output formats** - You can do it like this:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Report structure
|
||||||
|
|
||||||
|
ALWAYS use this exact template:
|
||||||
|
|
||||||
|
# [Title]
|
||||||
|
|
||||||
|
## Executive summary
|
||||||
|
|
||||||
|
## Key findings
|
||||||
|
|
||||||
|
## Recommendations
|
||||||
|
```
|
||||||
|
|
||||||
|
**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little):
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Commit message format
|
||||||
|
|
||||||
|
**Example 1:**
|
||||||
|
Input: Added user authentication with JWT tokens
|
||||||
|
Output: feat(auth): implement JWT-based authentication
|
||||||
|
```
|
||||||
|
|
||||||
|
### Writing Style
|
||||||
|
|
||||||
|
Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.
|
||||||
|
|
||||||
|
### Test Cases
|
||||||
|
|
||||||
|
After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them.
|
||||||
|
|
||||||
|
Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"skill_name": "example-skill",
|
||||||
|
"evals": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"prompt": "User's task prompt",
|
||||||
|
"expected_output": "Description of expected result",
|
||||||
|
"files": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).
|
||||||
|
|
||||||
|
## Running and evaluating test cases
|
||||||
|
|
||||||
|
This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.
|
||||||
|
|
||||||
|
Put results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.
|
||||||
|
|
||||||
|
### Step 1: Spawn all runs (with-skill AND baseline) in the same turn
|
||||||
|
|
||||||
|
For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.
|
||||||
|
|
||||||
|
**With-skill run:**
|
||||||
|
|
||||||
|
```
|
||||||
|
Execute this task:
|
||||||
|
- Skill path: <path-to-skill>
|
||||||
|
- Task: <eval prompt>
|
||||||
|
- Input files: <eval files if any, or "none">
|
||||||
|
- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/
|
||||||
|
- Outputs to save: <what the user cares about — e.g., "the .docx file", "the final CSV">
|
||||||
|
```
|
||||||
|
|
||||||
|
**Baseline run** (same prompt, but the baseline depends on context):
|
||||||
|
|
||||||
|
- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.
|
||||||
|
- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.
|
||||||
|
|
||||||
|
Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"eval_id": 0,
|
||||||
|
"eval_name": "descriptive-name-here",
|
||||||
|
"prompt": "The user's task prompt",
|
||||||
|
"assertions": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2: While runs are in progress, draft assertions
|
||||||
|
|
||||||
|
Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.
|
||||||
|
|
||||||
|
Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.
|
||||||
|
|
||||||
|
Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.
|
||||||
|
|
||||||
|
### Step 3: As runs complete, capture timing data
|
||||||
|
|
||||||
|
When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"total_tokens": 84852,
|
||||||
|
"duration_ms": 23332,
|
||||||
|
"total_duration_seconds": 23.3
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.
|
||||||
|
|
||||||
|
### Step 4: Grade, aggregate, and launch the viewer
|
||||||
|
|
||||||
|
Once all runs are done:
|
||||||
|
|
||||||
|
1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.
|
||||||
|
|
||||||
|
2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>
|
||||||
|
```
|
||||||
|
|
||||||
|
This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.
|
||||||
|
Put each with_skill version before its baseline counterpart.
|
||||||
|
|
||||||
|
3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.
|
||||||
|
|
||||||
|
4. **Launch the viewer** with both qualitative outputs and quantitative data:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
nohup python <skill-creator-path>/eval-viewer/generate_review.py \
|
||||||
|
<workspace>/iteration-N \
|
||||||
|
--skill-name "my-skill" \
|
||||||
|
--benchmark <workspace>/iteration-N/benchmark.json \
|
||||||
|
> /dev/null 2>&1 &
|
||||||
|
VIEWER_PID=$!
|
||||||
|
```
|
||||||
|
|
||||||
|
For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.
|
||||||
|
|
||||||
|
**Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.
|
||||||
|
|
||||||
|
Note: please use generate_review.py to create the viewer; there's no need to write custom HTML.
|
||||||
|
|
||||||
|
5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know."
|
||||||
|
|
||||||
|
### What the user sees in the viewer
|
||||||
|
|
||||||
|
The "Outputs" tab shows one test case at a time:
|
||||||
|
|
||||||
|
- **Prompt**: the task that was given
|
||||||
|
- **Output**: the files the skill produced, rendered inline where possible
|
||||||
|
- **Previous Output** (iteration 2+): collapsed section showing last iteration's output
|
||||||
|
- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail
|
||||||
|
- **Feedback**: a textbox that auto-saves as they type
|
||||||
|
- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox
|
||||||
|
|
||||||
|
The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.
|
||||||
|
|
||||||
|
Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`.
|
||||||
|
|
||||||
|
### Step 5: Read the feedback
|
||||||
|
|
||||||
|
When the user tells you they're done, read `feedback.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"reviews": [
|
||||||
|
{
|
||||||
|
"run_id": "eval-0-with_skill",
|
||||||
|
"feedback": "the chart is missing axis labels",
|
||||||
|
"timestamp": "..."
|
||||||
|
},
|
||||||
|
{ "run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..." },
|
||||||
|
{ "run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..." }
|
||||||
|
],
|
||||||
|
"status": "complete"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.
|
||||||
|
|
||||||
|
Kill the viewer server when you're done with it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kill $VIEWER_PID 2>/dev/null
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Improving the skill
|
||||||
|
|
||||||
|
This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.
|
||||||
|
|
||||||
|
### How to think about improvements
|
||||||
|
|
||||||
|
1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.
|
||||||
|
|
||||||
|
2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.
|
||||||
|
|
||||||
|
3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are _smart_. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.
|
||||||
|
|
||||||
|
4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.
|
||||||
|
|
||||||
|
This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.
|
||||||
|
|
||||||
|
### The iteration loop
|
||||||
|
|
||||||
|
After improving the skill:
|
||||||
|
|
||||||
|
1. Apply your improvements to the skill
|
||||||
|
2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.
|
||||||
|
3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration
|
||||||
|
4. Wait for the user to review and tell you they're done
|
||||||
|
5. Read the new feedback, improve again, repeat
|
||||||
|
|
||||||
|
Keep going until:
|
||||||
|
|
||||||
|
- The user says they're happy
|
||||||
|
- The feedback is all empty (everything looks good)
|
||||||
|
- You're not making meaningful progress
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Advanced: Blind comparison
|
||||||
|
|
||||||
|
For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.
|
||||||
|
|
||||||
|
This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Description Optimization
|
||||||
|
|
||||||
|
The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.
|
||||||
|
|
||||||
|
### Step 1: Generate trigger eval queries
|
||||||
|
|
||||||
|
Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{ "query": "the user prompt", "should_trigger": true },
|
||||||
|
{ "query": "another prompt", "should_trigger": false }
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
The queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).
|
||||||
|
|
||||||
|
Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"`
|
||||||
|
|
||||||
|
Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"`
|
||||||
|
|
||||||
|
For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.
|
||||||
|
|
||||||
|
For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.
|
||||||
|
|
||||||
|
The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.
|
||||||
|
|
||||||
|
### Step 2: Review with user
|
||||||
|
|
||||||
|
Present the eval set to the user for review using the HTML template:
|
||||||
|
|
||||||
|
1. Read the template from `assets/eval_review.html`
|
||||||
|
2. Replace the placeholders:
|
||||||
|
- `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)
|
||||||
|
- `__SKILL_NAME_PLACEHOLDER__` → the skill's name
|
||||||
|
- `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description
|
||||||
|
3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`
|
||||||
|
4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set"
|
||||||
|
5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)
|
||||||
|
|
||||||
|
This step matters — bad eval queries lead to bad descriptions.
|
||||||
|
|
||||||
|
### Step 3: Run the optimization loop
|
||||||
|
|
||||||
|
Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically."
|
||||||
|
|
||||||
|
Save the eval set to the workspace, then run in the background:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m scripts.run_loop \
|
||||||
|
--eval-set <path-to-trigger-eval.json> \
|
||||||
|
--skill-path <path-to-skill> \
|
||||||
|
--model <model-id-powering-this-session> \
|
||||||
|
--max-iterations 5 \
|
||||||
|
--verbose
|
||||||
|
```
|
||||||
|
|
||||||
|
Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.
|
||||||
|
|
||||||
|
While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.
|
||||||
|
|
||||||
|
This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.
|
||||||
|
|
||||||
|
### How skill triggering works
|
||||||
|
|
||||||
|
Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.
|
||||||
|
|
||||||
|
This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality.
|
||||||
|
|
||||||
|
### Step 4: Apply the result
|
||||||
|
|
||||||
|
Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Package and Present (only if `present_files` tool is available)
|
||||||
|
|
||||||
|
Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m scripts.package_skill <path/to/skill-folder>
|
||||||
|
```
|
||||||
|
|
||||||
|
After packaging, direct the user to the resulting `.skill` file path so they can install it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Claude.ai-specific instructions
|
||||||
|
|
||||||
|
In Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt:
|
||||||
|
|
||||||
|
**Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested.
|
||||||
|
|
||||||
|
**Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?"
|
||||||
|
|
||||||
|
**Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user.
|
||||||
|
|
||||||
|
**The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one.
|
||||||
|
|
||||||
|
**Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai.
|
||||||
|
|
||||||
|
**Blind comparison**: Requires subagents. Skip it.
|
||||||
|
|
||||||
|
**Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file.
|
||||||
|
|
||||||
|
**Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case:
|
||||||
|
|
||||||
|
- **Preserve the original name.** Note the skill's directory name and `name` frontmatter field -- use them unchanged. E.g., if the installed skill is `research-helper`, output `research-helper.skill` (not `research-helper-v2`).
|
||||||
|
- **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to `/tmp/skill-name/`, edit there, and package from the copy.
|
||||||
|
- **If packaging manually, stage in `/tmp/` first**, then copy to the output directory -- direct writes may fail due to permissions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cowork-Specific Instructions
|
||||||
|
|
||||||
|
If you're in Cowork, the main things to know are:
|
||||||
|
|
||||||
|
- You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.)
|
||||||
|
- You don't have a browser or display, so when generating the eval viewer, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser.
|
||||||
|
- For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER _BEFORE_ evaluating inputs yourself. You want to get them in front of the human ASAP!
|
||||||
|
- Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first).
|
||||||
|
- Packaging works — `package_skill.py` just needs Python and a filesystem.
|
||||||
|
- Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape.
|
||||||
|
- **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. Follow the update guidance in the claude.ai section above.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reference files
|
||||||
|
|
||||||
|
The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.
|
||||||
|
|
||||||
|
- `agents/grader.md` — How to evaluate assertions against outputs
|
||||||
|
- `agents/comparator.md` — How to do blind A/B comparison between two outputs
|
||||||
|
- `agents/analyzer.md` — How to analyze why one version beat another
|
||||||
|
|
||||||
|
The references/ directory has additional documentation:
|
||||||
|
|
||||||
|
- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Repeating one more time the core loop here for emphasis:
|
||||||
|
|
||||||
|
- Figure out what the skill is about
|
||||||
|
- Draft or edit the skill
|
||||||
|
- Run claude-with-access-to-the-skill on test prompts
|
||||||
|
- With the user, evaluate the outputs:
|
||||||
|
- Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them
|
||||||
|
- Run quantitative evals
|
||||||
|
- Repeat until you and the user are satisfied
|
||||||
|
- Package the final skill and return it to the user.
|
||||||
|
|
||||||
|
Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens.
|
||||||
|
|
||||||
|
Good luck!
|
||||||
283
.agents/skills/skill-creator/agents/analyzer.md
Normal file
283
.agents/skills/skill-creator/agents/analyzer.md
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
# Post-hoc Analyzer Agent
|
||||||
|
|
||||||
|
Analyze blind comparison results to understand WHY the winner won and generate improvement suggestions.
|
||||||
|
|
||||||
|
## Role
|
||||||
|
|
||||||
|
After the blind comparator determines a winner, the Post-hoc Analyzer "unblids" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved?
|
||||||
|
|
||||||
|
## Inputs
|
||||||
|
|
||||||
|
You receive these parameters in your prompt:
|
||||||
|
|
||||||
|
- **winner**: "A" or "B" (from blind comparison)
|
||||||
|
- **winner_skill_path**: Path to the skill that produced the winning output
|
||||||
|
- **winner_transcript_path**: Path to the execution transcript for the winner
|
||||||
|
- **loser_skill_path**: Path to the skill that produced the losing output
|
||||||
|
- **loser_transcript_path**: Path to the execution transcript for the loser
|
||||||
|
- **comparison_result_path**: Path to the blind comparator's output JSON
|
||||||
|
- **output_path**: Where to save the analysis results
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
### Step 1: Read Comparison Result
|
||||||
|
|
||||||
|
1. Read the blind comparator's output at comparison_result_path
|
||||||
|
2. Note the winning side (A or B), the reasoning, and any scores
|
||||||
|
3. Understand what the comparator valued in the winning output
|
||||||
|
|
||||||
|
### Step 2: Read Both Skills
|
||||||
|
|
||||||
|
1. Read the winner skill's SKILL.md and key referenced files
|
||||||
|
2. Read the loser skill's SKILL.md and key referenced files
|
||||||
|
3. Identify structural differences:
|
||||||
|
- Instructions clarity and specificity
|
||||||
|
- Script/tool usage patterns
|
||||||
|
- Example coverage
|
||||||
|
- Edge case handling
|
||||||
|
|
||||||
|
### Step 3: Read Both Transcripts
|
||||||
|
|
||||||
|
1. Read the winner's transcript
|
||||||
|
2. Read the loser's transcript
|
||||||
|
3. Compare execution patterns:
|
||||||
|
- How closely did each follow their skill's instructions?
|
||||||
|
- What tools were used differently?
|
||||||
|
- Where did the loser diverge from optimal behavior?
|
||||||
|
- Did either encounter errors or make recovery attempts?
|
||||||
|
|
||||||
|
### Step 4: Analyze Instruction Following
|
||||||
|
|
||||||
|
For each transcript, evaluate:
|
||||||
|
|
||||||
|
- Did the agent follow the skill's explicit instructions?
|
||||||
|
- Did the agent use the skill's provided tools/scripts?
|
||||||
|
- Were there missed opportunities to leverage skill content?
|
||||||
|
- Did the agent add unnecessary steps not in the skill?
|
||||||
|
|
||||||
|
Score instruction following 1-10 and note specific issues.
|
||||||
|
|
||||||
|
### Step 5: Identify Winner Strengths
|
||||||
|
|
||||||
|
Determine what made the winner better:
|
||||||
|
|
||||||
|
- Clearer instructions that led to better behavior?
|
||||||
|
- Better scripts/tools that produced better output?
|
||||||
|
- More comprehensive examples that guided edge cases?
|
||||||
|
- Better error handling guidance?
|
||||||
|
|
||||||
|
Be specific. Quote from skills/transcripts where relevant.
|
||||||
|
|
||||||
|
### Step 6: Identify Loser Weaknesses
|
||||||
|
|
||||||
|
Determine what held the loser back:
|
||||||
|
|
||||||
|
- Ambiguous instructions that led to suboptimal choices?
|
||||||
|
- Missing tools/scripts that forced workarounds?
|
||||||
|
- Gaps in edge case coverage?
|
||||||
|
- Poor error handling that caused failures?
|
||||||
|
|
||||||
|
### Step 7: Generate Improvement Suggestions
|
||||||
|
|
||||||
|
Based on the analysis, produce actionable suggestions for improving the loser skill:
|
||||||
|
|
||||||
|
- Specific instruction changes to make
|
||||||
|
- Tools/scripts to add or modify
|
||||||
|
- Examples to include
|
||||||
|
- Edge cases to address
|
||||||
|
|
||||||
|
Prioritize by impact. Focus on changes that would have changed the outcome.
|
||||||
|
|
||||||
|
### Step 8: Write Analysis Results
|
||||||
|
|
||||||
|
Save structured analysis to `{output_path}`.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Write a JSON file with this structure:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"comparison_summary": {
|
||||||
|
"winner": "A",
|
||||||
|
"winner_skill": "path/to/winner/skill",
|
||||||
|
"loser_skill": "path/to/loser/skill",
|
||||||
|
"comparator_reasoning": "Brief summary of why comparator chose winner"
|
||||||
|
},
|
||||||
|
"winner_strengths": [
|
||||||
|
"Clear step-by-step instructions for handling multi-page documents",
|
||||||
|
"Included validation script that caught formatting errors",
|
||||||
|
"Explicit guidance on fallback behavior when OCR fails"
|
||||||
|
],
|
||||||
|
"loser_weaknesses": [
|
||||||
|
"Vague instruction 'process the document appropriately' led to inconsistent behavior",
|
||||||
|
"No script for validation, agent had to improvise and made errors",
|
||||||
|
"No guidance on OCR failure, agent gave up instead of trying alternatives"
|
||||||
|
],
|
||||||
|
"instruction_following": {
|
||||||
|
"winner": {
|
||||||
|
"score": 9,
|
||||||
|
"issues": ["Minor: skipped optional logging step"]
|
||||||
|
},
|
||||||
|
"loser": {
|
||||||
|
"score": 6,
|
||||||
|
"issues": [
|
||||||
|
"Did not use the skill's formatting template",
|
||||||
|
"Invented own approach instead of following step 3",
|
||||||
|
"Missed the 'always validate output' instruction"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"improvement_suggestions": [
|
||||||
|
{
|
||||||
|
"priority": "high",
|
||||||
|
"category": "instructions",
|
||||||
|
"suggestion": "Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template",
|
||||||
|
"expected_impact": "Would eliminate ambiguity that caused inconsistent behavior"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"priority": "high",
|
||||||
|
"category": "tools",
|
||||||
|
"suggestion": "Add validate_output.py script similar to winner skill's validation approach",
|
||||||
|
"expected_impact": "Would catch formatting errors before final output"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"priority": "medium",
|
||||||
|
"category": "error_handling",
|
||||||
|
"suggestion": "Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'",
|
||||||
|
"expected_impact": "Would prevent early failure on difficult documents"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"transcript_insights": {
|
||||||
|
"winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output",
|
||||||
|
"loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guidelines
|
||||||
|
|
||||||
|
- **Be specific**: Quote from skills and transcripts, don't just say "instructions were unclear"
|
||||||
|
- **Be actionable**: Suggestions should be concrete changes, not vague advice
|
||||||
|
- **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent
|
||||||
|
- **Prioritize by impact**: Which changes would most likely have changed the outcome?
|
||||||
|
- **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental?
|
||||||
|
- **Stay objective**: Analyze what happened, don't editorialize
|
||||||
|
- **Think about generalization**: Would this improvement help on other evals too?
|
||||||
|
|
||||||
|
## Categories for Suggestions
|
||||||
|
|
||||||
|
Use these categories to organize improvement suggestions:
|
||||||
|
|
||||||
|
| Category | Description |
|
||||||
|
| ---------------- | ---------------------------------------------- |
|
||||||
|
| `instructions` | Changes to the skill's prose instructions |
|
||||||
|
| `tools` | Scripts, templates, or utilities to add/modify |
|
||||||
|
| `examples` | Example inputs/outputs to include |
|
||||||
|
| `error_handling` | Guidance for handling failures |
|
||||||
|
| `structure` | Reorganization of skill content |
|
||||||
|
| `references` | External docs or resources to add |
|
||||||
|
|
||||||
|
## Priority Levels
|
||||||
|
|
||||||
|
- **high**: Would likely change the outcome of this comparison
|
||||||
|
- **medium**: Would improve quality but may not change win/loss
|
||||||
|
- **low**: Nice to have, marginal improvement
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Analyzing Benchmark Results
|
||||||
|
|
||||||
|
When analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements.
|
||||||
|
|
||||||
|
## Role
|
||||||
|
|
||||||
|
Review all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone.
|
||||||
|
|
||||||
|
## Inputs
|
||||||
|
|
||||||
|
You receive these parameters in your prompt:
|
||||||
|
|
||||||
|
- **benchmark_data_path**: Path to the in-progress benchmark.json with all run results
|
||||||
|
- **skill_path**: Path to the skill being benchmarked
|
||||||
|
- **output_path**: Where to save the notes (as JSON array of strings)
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
### Step 1: Read Benchmark Data
|
||||||
|
|
||||||
|
1. Read the benchmark.json containing all run results
|
||||||
|
2. Note the configurations tested (with_skill, without_skill)
|
||||||
|
3. Understand the run_summary aggregates already calculated
|
||||||
|
|
||||||
|
### Step 2: Analyze Per-Assertion Patterns
|
||||||
|
|
||||||
|
For each expectation across all runs:
|
||||||
|
|
||||||
|
- Does it **always pass** in both configurations? (may not differentiate skill value)
|
||||||
|
- Does it **always fail** in both configurations? (may be broken or beyond capability)
|
||||||
|
- Does it **always pass with skill but fail without**? (skill clearly adds value here)
|
||||||
|
- Does it **always fail with skill but pass without**? (skill may be hurting)
|
||||||
|
- Is it **highly variable**? (flaky expectation or non-deterministic behavior)
|
||||||
|
|
||||||
|
### Step 3: Analyze Cross-Eval Patterns
|
||||||
|
|
||||||
|
Look for patterns across evals:
|
||||||
|
|
||||||
|
- Are certain eval types consistently harder/easier?
|
||||||
|
- Do some evals show high variance while others are stable?
|
||||||
|
- Are there surprising results that contradict expectations?
|
||||||
|
|
||||||
|
### Step 4: Analyze Metrics Patterns
|
||||||
|
|
||||||
|
Look at time_seconds, tokens, tool_calls:
|
||||||
|
|
||||||
|
- Does the skill significantly increase execution time?
|
||||||
|
- Is there high variance in resource usage?
|
||||||
|
- Are there outlier runs that skew the aggregates?
|
||||||
|
|
||||||
|
### Step 5: Generate Notes
|
||||||
|
|
||||||
|
Write freeform observations as a list of strings. Each note should:
|
||||||
|
|
||||||
|
- State a specific observation
|
||||||
|
- Be grounded in the data (not speculation)
|
||||||
|
- Help the user understand something the aggregate metrics don't show
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value"
|
||||||
|
- "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky"
|
||||||
|
- "Without-skill runs consistently fail on table extraction expectations (0% pass rate)"
|
||||||
|
- "Skill adds 13s average execution time but improves pass rate by 50%"
|
||||||
|
- "Token usage is 80% higher with skill, primarily due to script output parsing"
|
||||||
|
- "All 3 without-skill runs for eval 1 produced empty output"
|
||||||
|
|
||||||
|
### Step 6: Write Notes
|
||||||
|
|
||||||
|
Save notes to `{output_path}` as a JSON array of strings:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
"Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value",
|
||||||
|
"Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure",
|
||||||
|
"Without-skill runs consistently fail on table extraction expectations",
|
||||||
|
"Skill adds 13s average execution time but improves pass rate by 50%"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Guidelines
|
||||||
|
|
||||||
|
**DO:**
|
||||||
|
|
||||||
|
- Report what you observe in the data
|
||||||
|
- Be specific about which evals, expectations, or runs you're referring to
|
||||||
|
- Note patterns that aggregate metrics would hide
|
||||||
|
- Provide context that helps interpret the numbers
|
||||||
|
|
||||||
|
**DO NOT:**
|
||||||
|
|
||||||
|
- Suggest improvements to the skill (that's for the improvement step, not benchmarking)
|
||||||
|
- Make subjective quality judgments ("the output was good/bad")
|
||||||
|
- Speculate about causes without evidence
|
||||||
|
- Repeat information already in the run_summary aggregates
|
||||||
203
.agents/skills/skill-creator/agents/comparator.md
Normal file
203
.agents/skills/skill-creator/agents/comparator.md
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
# Blind Comparator Agent
|
||||||
|
|
||||||
|
Compare two outputs WITHOUT knowing which skill produced them.
|
||||||
|
|
||||||
|
## Role
|
||||||
|
|
||||||
|
The Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach.
|
||||||
|
|
||||||
|
Your judgment is based purely on output quality and task completion.
|
||||||
|
|
||||||
|
## Inputs
|
||||||
|
|
||||||
|
You receive these parameters in your prompt:
|
||||||
|
|
||||||
|
- **output_a_path**: Path to the first output file or directory
|
||||||
|
- **output_b_path**: Path to the second output file or directory
|
||||||
|
- **eval_prompt**: The original task/prompt that was executed
|
||||||
|
- **expectations**: List of expectations to check (optional - may be empty)
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
### Step 1: Read Both Outputs
|
||||||
|
|
||||||
|
1. Examine output A (file or directory)
|
||||||
|
2. Examine output B (file or directory)
|
||||||
|
3. Note the type, structure, and content of each
|
||||||
|
4. If outputs are directories, examine all relevant files inside
|
||||||
|
|
||||||
|
### Step 2: Understand the Task
|
||||||
|
|
||||||
|
1. Read the eval_prompt carefully
|
||||||
|
2. Identify what the task requires:
|
||||||
|
- What should be produced?
|
||||||
|
- What qualities matter (accuracy, completeness, format)?
|
||||||
|
- What would distinguish a good output from a poor one?
|
||||||
|
|
||||||
|
### Step 3: Generate Evaluation Rubric
|
||||||
|
|
||||||
|
Based on the task, generate a rubric with two dimensions:
|
||||||
|
|
||||||
|
**Content Rubric** (what the output contains):
|
||||||
|
| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
|
||||||
|
|-----------|----------|----------------|---------------|
|
||||||
|
| Correctness | Major errors | Minor errors | Fully correct |
|
||||||
|
| Completeness | Missing key elements | Mostly complete | All elements present |
|
||||||
|
| Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout |
|
||||||
|
|
||||||
|
**Structure Rubric** (how the output is organized):
|
||||||
|
| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) |
|
||||||
|
|-----------|----------|----------------|---------------|
|
||||||
|
| Organization | Disorganized | Reasonably organized | Clear, logical structure |
|
||||||
|
| Formatting | Inconsistent/broken | Mostly consistent | Professional, polished |
|
||||||
|
| Usability | Difficult to use | Usable with effort | Easy to use |
|
||||||
|
|
||||||
|
Adapt criteria to the specific task. For example:
|
||||||
|
|
||||||
|
- PDF form → "Field alignment", "Text readability", "Data placement"
|
||||||
|
- Document → "Section structure", "Heading hierarchy", "Paragraph flow"
|
||||||
|
- Data output → "Schema correctness", "Data types", "Completeness"
|
||||||
|
|
||||||
|
### Step 4: Evaluate Each Output Against the Rubric
|
||||||
|
|
||||||
|
For each output (A and B):
|
||||||
|
|
||||||
|
1. **Score each criterion** on the rubric (1-5 scale)
|
||||||
|
2. **Calculate dimension totals**: Content score, Structure score
|
||||||
|
3. **Calculate overall score**: Average of dimension scores, scaled to 1-10
|
||||||
|
|
||||||
|
### Step 5: Check Assertions (if provided)
|
||||||
|
|
||||||
|
If expectations are provided:
|
||||||
|
|
||||||
|
1. Check each expectation against output A
|
||||||
|
2. Check each expectation against output B
|
||||||
|
3. Count pass rates for each output
|
||||||
|
4. Use expectation scores as secondary evidence (not the primary decision factor)
|
||||||
|
|
||||||
|
### Step 6: Determine the Winner
|
||||||
|
|
||||||
|
Compare A and B based on (in priority order):
|
||||||
|
|
||||||
|
1. **Primary**: Overall rubric score (content + structure)
|
||||||
|
2. **Secondary**: Assertion pass rates (if applicable)
|
||||||
|
3. **Tiebreaker**: If truly equal, declare a TIE
|
||||||
|
|
||||||
|
Be decisive - ties should be rare. One output is usually better, even if marginally.
|
||||||
|
|
||||||
|
### Step 7: Write Comparison Results
|
||||||
|
|
||||||
|
Save results to a JSON file at the path specified (or `comparison.json` if not specified).
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Write a JSON file with this structure:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"winner": "A",
|
||||||
|
"reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.",
|
||||||
|
"rubric": {
|
||||||
|
"A": {
|
||||||
|
"content": {
|
||||||
|
"correctness": 5,
|
||||||
|
"completeness": 5,
|
||||||
|
"accuracy": 4
|
||||||
|
},
|
||||||
|
"structure": {
|
||||||
|
"organization": 4,
|
||||||
|
"formatting": 5,
|
||||||
|
"usability": 4
|
||||||
|
},
|
||||||
|
"content_score": 4.7,
|
||||||
|
"structure_score": 4.3,
|
||||||
|
"overall_score": 9.0
|
||||||
|
},
|
||||||
|
"B": {
|
||||||
|
"content": {
|
||||||
|
"correctness": 3,
|
||||||
|
"completeness": 2,
|
||||||
|
"accuracy": 3
|
||||||
|
},
|
||||||
|
"structure": {
|
||||||
|
"organization": 3,
|
||||||
|
"formatting": 2,
|
||||||
|
"usability": 3
|
||||||
|
},
|
||||||
|
"content_score": 2.7,
|
||||||
|
"structure_score": 2.7,
|
||||||
|
"overall_score": 5.4
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"output_quality": {
|
||||||
|
"A": {
|
||||||
|
"score": 9,
|
||||||
|
"strengths": ["Complete solution", "Well-formatted", "All fields present"],
|
||||||
|
"weaknesses": ["Minor style inconsistency in header"]
|
||||||
|
},
|
||||||
|
"B": {
|
||||||
|
"score": 5,
|
||||||
|
"strengths": ["Readable output", "Correct basic structure"],
|
||||||
|
"weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"expectation_results": {
|
||||||
|
"A": {
|
||||||
|
"passed": 4,
|
||||||
|
"total": 5,
|
||||||
|
"pass_rate": 0.8,
|
||||||
|
"details": [
|
||||||
|
{ "text": "Output includes name", "passed": true },
|
||||||
|
{ "text": "Output includes date", "passed": true },
|
||||||
|
{ "text": "Format is PDF", "passed": true },
|
||||||
|
{ "text": "Contains signature", "passed": false },
|
||||||
|
{ "text": "Readable text", "passed": true }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"B": {
|
||||||
|
"passed": 3,
|
||||||
|
"total": 5,
|
||||||
|
"pass_rate": 0.6,
|
||||||
|
"details": [
|
||||||
|
{ "text": "Output includes name", "passed": true },
|
||||||
|
{ "text": "Output includes date", "passed": false },
|
||||||
|
{ "text": "Format is PDF", "passed": true },
|
||||||
|
{ "text": "Contains signature", "passed": false },
|
||||||
|
{ "text": "Readable text", "passed": true }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If no expectations were provided, omit the `expectation_results` field entirely.
|
||||||
|
|
||||||
|
## Field Descriptions
|
||||||
|
|
||||||
|
- **winner**: "A", "B", or "TIE"
|
||||||
|
- **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie)
|
||||||
|
- **rubric**: Structured rubric evaluation for each output
|
||||||
|
- **content**: Scores for content criteria (correctness, completeness, accuracy)
|
||||||
|
- **structure**: Scores for structure criteria (organization, formatting, usability)
|
||||||
|
- **content_score**: Average of content criteria (1-5)
|
||||||
|
- **structure_score**: Average of structure criteria (1-5)
|
||||||
|
- **overall_score**: Combined score scaled to 1-10
|
||||||
|
- **output_quality**: Summary quality assessment
|
||||||
|
- **score**: 1-10 rating (should match rubric overall_score)
|
||||||
|
- **strengths**: List of positive aspects
|
||||||
|
- **weaknesses**: List of issues or shortcomings
|
||||||
|
- **expectation_results**: (Only if expectations provided)
|
||||||
|
- **passed**: Number of expectations that passed
|
||||||
|
- **total**: Total number of expectations
|
||||||
|
- **pass_rate**: Fraction passed (0.0 to 1.0)
|
||||||
|
- **details**: Individual expectation results
|
||||||
|
|
||||||
|
## Guidelines
|
||||||
|
|
||||||
|
- **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality.
|
||||||
|
- **Be specific**: Cite specific examples when explaining strengths and weaknesses.
|
||||||
|
- **Be decisive**: Choose a winner unless outputs are genuinely equivalent.
|
||||||
|
- **Output quality first**: Assertion scores are secondary to overall task completion.
|
||||||
|
- **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness.
|
||||||
|
- **Explain your reasoning**: The reasoning field should make it clear why you chose the winner.
|
||||||
|
- **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better.
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user