Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat: add 5 skills — d1-drizzle-schema, hono-api-scaffolder, shadcn-ui, github-release, gemini-peer-review
Jezf71ec2d0b5a0
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex fde3af8c..22420dc8 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -6,13 +6,13 @@},"metadata": {"description": "Workflow skills for Claude Code - each produces tangible output",- "version": "6.0.0",- "updated": "2026-02-17"+ "version": "8.0.0",+ "updated": "2026-02-18"},"plugins": [{"name": "all",- "description": "All 17 workflow skills: Cloudflare, web design, SEO, Google integrations, Tailwind, favicons, icons, colour palettes, ElevenLabs, MCP, memory management, capabilities reference, writing style.",+ "description": "All 22 workflow skills: Cloudflare, Hono APIs, D1/Drizzle, web design, SEO, Google integrations, Tailwind, shadcn/ui, favicons, icons, colour palettes, ElevenLabs, MCP, memory management, GitHub releases, Gemini peer review, capabilities reference, writing style.","source": "./","skills": ["./skills/skill-creator",@@ -31,7 +31,12 @@"./skills/memory-manager","./skills/google-apps-script","./skills/claude-capabilities",- "./skills/aussie-business-english"+ "./skills/aussie-business-english",+ "./skills/d1-drizzle-schema",+ "./skills/hono-api-scaffolder",+ "./skills/shadcn-ui",+ "./skills/github-release",+ "./skills/gemini-peer-review"]},{@@ -48,19 +53,22 @@},{"name": "cloudflare",- "description": "Cloudflare Workers: scaffold from scratch or clone vite-flare-starter.",+ "description": "Cloudflare Workers: scaffold projects, Hono API routes, D1/Drizzle schemas.","source": "./","skills": ["./skills/cloudflare-worker-builder",- "./skills/vite-flare-starter"+ "./skills/vite-flare-starter",+ "./skills/hono-api-scaffolder",+ "./skills/d1-drizzle-schema"]},{"name": "frontend",- "description": "Set up Tailwind v4 + shadcn/ui with dark mode theming.",+ "description": "Tailwind v4 theming + shadcn/ui component installation, customisation, and recipes.","source": "./","skills": [- "./skills/tailwind-theme-builder"+ "./skills/tailwind-theme-builder",+ "./skills/shadcn-ui"]},{@@ -100,12 +108,14 @@},{"name": "development",- "description": "Skill creation, CLAUDE.md memory management, and Claude capabilities reference.",+ "description": "Skill creation, CLAUDE.md memory management, GitHub releases, Gemini peer review, and Claude capabilities reference.","source": "./","skills": ["./skills/skill-creator","./skills/memory-manager",- "./skills/claude-capabilities"+ "./skills/claude-capabilities",+ "./skills/github-release",+ "./skills/gemini-peer-review"]},{diff --git a/CLAUDE.md b/CLAUDE.mdindex cc41635d..907758a9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,11 +15,14 @@ Production workflow skills for Claude Code CLI. Each skill guides Claude through```claude-skills/-├── skills/ # All skills (17)+├── skills/ # All skills (22)│ ├── skill-creator/ # Foundation: create new skills (Anthropic official)│ ├── cloudflare-worker-builder/ # Scaffold Cloudflare Worker projects│ ├── vite-flare-starter/ # Full-stack Cloudflare app from starter template+│ ├── hono-api-scaffolder/ # Scaffold Hono API routes, middleware, endpoint docs+│ ├── d1-drizzle-schema/ # Drizzle ORM schemas for Cloudflare D1│ ├── tailwind-theme-builder/ # Set up Tailwind v4 + shadcn/ui themes+│ ├── shadcn-ui/ # shadcn/ui component installation, recipes, customisation│ ├── color-palette/ # Generate colour palettes from brand hex│ ├── favicon-gen/ # Generate favicon packages│ ├── icon-set-generator/ # Generate custom SVG icon sets@@ -31,6 +34,8 @@ claude-skills/│ ├── elevenlabs-agents/ # Build ElevenLabs voice agents│ ├── mcp-builder/ # Build MCP servers with FastMCP│ ├── memory-manager/ # Audit and restructure CLAUDE.md hierarchy+│ ├── github-release/ # Sanitize and publish GitHub releases+│ ├── gemini-peer-review/ # Second opinion from Gemini on code/architecture│ ├── claude-capabilities/ # Current Claude AI & Code capabilities reference│ └── aussie-business-english/ # Australian business English writing style├── CLAUDE.md # This filediff --git a/README.md b/README.mdindex 78e5eb99..aafd643d 100644--- a/README.md+++ b/README.md@@ -25,6 +25,11 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t| **[memory-manager](skills/memory-manager)** | Optimised CLAUDE.md memory hierarchy || **[claude-capabilities](skills/claude-capabilities)** | Current Claude AI & Code capabilities reference || **[aussie-business-english](skills/aussie-business-english)** | Australian business English writing style |+| **[d1-drizzle-schema](skills/d1-drizzle-schema)** | Drizzle ORM schemas for Cloudflare D1 |+| **[hono-api-scaffolder](skills/hono-api-scaffolder)** | Hono API routes, middleware, endpoint documentation |+| **[shadcn-ui](skills/shadcn-ui)** | shadcn/ui components with installation, customisation, recipes |+| **[github-release](skills/github-release)** | Sanitized, tagged GitHub releases with safety checks |+| **[gemini-peer-review](skills/gemini-peer-review)** | Second opinion from Gemini on code, architecture, security |## Install@@ -44,7 +49,7 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t/plugin install ai@jezweb-skills # ElevenLabs agents/plugin install mcp@jezweb-skills # MCP servers/plugin install writing@jezweb-skills # Australian business English-/plugin install development@jezweb-skills # skill-creator + memory-manager + capabilities ref+/plugin install development@jezweb-skills # skill-creator, memory-manager, releases, Gemini review```## Create Your Own@@ -61,6 +66,17 @@ Follows the [Agent Skills spec](https://agentskills.io/specification).See [CLAUDE.md](CLAUDE.md) for development details.+## History++This repo started as a collection of 105 skills — many were informational reference guides (CSS patterns, API docs, framework cheatsheets). With Claude Opus 4.6's expanded training data and built-in capabilities, those reference skills became redundant. Claude already knows the material.++**v2** keeps only skills that produce tangible output: files, projects, configurations, deployments. The count dropped from 105 to 22, but each one earns its place.++The full v1 collection is preserved:+- **Tag `v1-final`** — all 105 skills at the point of transition+- **Branch `archive/low-priority-skills`** — 13 previously archived skills+- **Full git history** — `git log v1-final` to browse+## LicenseMITdiff --git a/skills/d1-drizzle-schema/SKILL.md b/skills/d1-drizzle-schema/SKILL.mdnew file mode 100644index 00000000..51c84b7c--- /dev/null+++ b/skills/d1-drizzle-schema/SKILL.md@@ -0,0 +1,152 @@+---+name: d1-drizzle-schema+description: "Generate Drizzle ORM schemas for Cloudflare D1 databases with correct D1-specific patterns. Produces schema files, migration commands, type exports, and DATABASE_SCHEMA.md documentation. Handles D1 quirks: foreign keys always enforced, no native BOOLEAN/DATETIME types, 100 bound parameter limit, JSON stored as TEXT. Use when creating a new database, adding tables, or scaffolding a D1 data layer."+compatibility: claude-code-only+---++# D1 Drizzle Schema++Generate correct Drizzle ORM schemas for Cloudflare D1. D1 is SQLite-based but has important differences that cause subtle bugs if you use standard SQLite patterns. This skill produces schemas that work correctly with D1's constraints.++## Critical D1 Differences++| Feature | Standard SQLite | D1 |+|---------|-----------------|-----|+| Foreign keys | OFF by default | **Always ON** (cannot disable) |+| Boolean type | No | No — use `integer({ mode: 'boolean' })` |+| Datetime type | No | No — use `integer({ mode: 'timestamp' })` |+| Max bound params | ~999 | **100** (affects bulk inserts) |+| JSON support | Extension | **Always available** (json_extract, ->, ->>) |+| Concurrency | Multi-writer | **Single-threaded** (one query at a time) |++## Workflow++### Step 1: Describe the Data Model++Gather requirements: what tables, what relationships, what needs indexing. If working from an existing description, infer the schema directly.++### Step 2: Generate Drizzle Schema++Create schema files using D1-correct column patterns:++```typescript+import { sqliteTable, text, integer, real, index, uniqueIndex } from 'drizzle-orm/sqlite-core'++export const users = sqliteTable('users', {+ // UUID primary key (preferred for D1)+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),++ // Text fields+ name: text('name').notNull(),+ email: text('email').notNull(),++ // Enum (stored as TEXT, validated at schema level)+ role: text('role', { enum: ['admin', 'editor', 'viewer'] }).notNull().default('viewer'),++ // Boolean (D1 has no BOOL — stored as INTEGER 0/1)+ emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),++ // Timestamp (D1 has no DATETIME — stored as unix seconds)+ createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),+ updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),++ // Typed JSON (stored as TEXT, Drizzle auto-serialises)+ preferences: text('preferences', { mode: 'json' }).$type<UserPreferences>(),++ // Foreign key (always enforced in D1)+ organisationId: text('organisation_id').references(() => organisations.id, { onDelete: 'cascade' }),+}, (table) => ({+ emailIdx: uniqueIndex('users_email_idx').on(table.email),+ orgIdx: index('users_org_idx').on(table.organisationId),+}))+```++See [references/column-patterns.md](references/column-patterns.md) for the full type reference.++### Step 3: Add Relations++Drizzle relations are query builder helpers (separate from FK constraints):++```typescript+import { relations } from 'drizzle-orm'++export const usersRelations = relations(users, ({ one, many }) => ({+ organisation: one(organisations, {+ fields: [users.organisationId],+ references: [organisations.id],+ }),+ posts: many(posts),+}))+```++### Step 4: Export Types++```typescript+export type User = typeof users.$inferSelect+export type NewUser = typeof users.$inferInsert+```++### Step 5: Set Up Drizzle Config++Copy [assets/drizzle-config-template.ts](assets/drizzle-config-template.ts) to `drizzle.config.ts` and update the schema path.++### Step 6: Add Migration Scripts++Add to `package.json`:+```json+{+ "db:generate": "drizzle-kit generate",+ "db:migrate:local": "wrangler d1 migrations apply DB --local",+ "db:migrate:remote": "wrangler d1 migrations apply DB --remote"+}+```++**Always run on BOTH local AND remote before testing.**++### Step 7: Generate DATABASE_SCHEMA.md++Document the schema for future sessions:+- Tables with columns, types, and constraints+- Relationships and foreign keys+- Indexes and their purpose+- Migration workflow++## Bulk Insert Pattern++D1 limits bound parameters to 100. Calculate batch size:++```typescript+const BATCH_SIZE = Math.floor(100 / COLUMNS_PER_ROW)+for (let i = 0; i < rows.length; i += BATCH_SIZE) {+ await db.insert(table).values(rows.slice(i, i + BATCH_SIZE))+}+```++## D1 Runtime Usage++```typescript+import { drizzle } from 'drizzle-orm/d1'+import * as schema from './schema'++// In Worker fetch handler:+const db = drizzle(env.DB, { schema })++// Query patterns+const all = await db.select().from(schema.users).all() // Array<User>+const one = await db.select().from(schema.users).where(eq(schema.users.id, id)).get() // User | undefined+const count = await db.select({ count: sql`count(*)` }).from(schema.users).get()+```++## Reference Files++| When | Read |+|------|------|+| D1 vs SQLite, JSON queries, limits | [references/d1-specifics.md](references/d1-specifics.md) |+| Column type patterns for Drizzle + D1 | [references/column-patterns.md](references/column-patterns.md) |++## Assets++| File | Purpose |+|------|---------|+| [assets/drizzle-config-template.ts](assets/drizzle-config-template.ts) | Starter drizzle.config.ts for D1 |+| [assets/schema-template.ts](assets/schema-template.ts) | Example schema with all common D1 patterns |diff --git a/skills/d1-drizzle-schema/assets/drizzle-config-template.ts b/skills/d1-drizzle-schema/assets/drizzle-config-template.tsnew file mode 100644index 00000000..9f9b296e--- /dev/null+++ b/skills/d1-drizzle-schema/assets/drizzle-config-template.ts@@ -0,0 +1,15 @@+import { defineConfig } from 'drizzle-kit'++export default defineConfig({+ schema: './src/server/db/schema.ts',+ out: './drizzle',+ dialect: 'sqlite',+ driver: 'd1-http',+ dbCredentials: {+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,+ databaseId: process.env.CLOUDFLARE_D1_DATABASE_ID!,+ token: process.env.CLOUDFLARE_API_TOKEN!,+ },+ verbose: true,+ strict: true,+})diff --git a/skills/d1-drizzle-schema/assets/schema-template.ts b/skills/d1-drizzle-schema/assets/schema-template.tsnew file mode 100644index 00000000..c39f6e26--- /dev/null+++ b/skills/d1-drizzle-schema/assets/schema-template.ts@@ -0,0 +1,58 @@+/**+ * D1 Drizzle Schema Template+ *+ * Demonstrates all common D1 column patterns:+ * - UUID primary key, text with enums, boolean as integer,+ * timestamp as integer, typed JSON, foreign keys, indexes+ */+import { sqliteTable, text, integer, real, index, uniqueIndex } from 'drizzle-orm/sqlite-core'+import { relations } from 'drizzle-orm'++// --- Users ---++export const users = sqliteTable('users', {+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),+ name: text('name').notNull(),+ email: text('email').notNull(),+ role: text('role', { enum: ['admin', 'editor', 'viewer'] }).notNull().default('viewer'),+ emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),+ preferences: text('preferences', { mode: 'json' }).$type<Record<string, unknown>>(),+ createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),+ updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),+}, (table) => ({+ emailIdx: uniqueIndex('users_email_idx').on(table.email),+}))++export const usersRelations = relations(users, ({ many }) => ({+ posts: many(posts),+}))++// --- Posts ---++export const posts = sqliteTable('posts', {+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),+ title: text('title').notNull(),+ content: text('content'),+ status: text('status', { enum: ['draft', 'published', 'archived'] }).notNull().default('draft'),+ authorId: text('author_id').notNull().references(() => users.id, { onDelete: 'cascade' }),+ metadata: text('metadata', { mode: 'json' }).$type<Record<string, unknown>>(),+ publishedAt: integer('published_at', { mode: 'timestamp' }),+ createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),+}, (table) => ({+ authorIdx: index('posts_author_idx').on(table.authorId),+ statusIdx: index('posts_status_idx').on(table.status),+}))++export const postsRelations = relations(posts, ({ one }) => ({+ author: one(users, {+ fields: [posts.authorId],+ references: [users.id],+ }),+}))++// --- Type Exports ---++export type User = typeof users.$inferSelect+export type NewUser = typeof users.$inferInsert+export type Post = typeof posts.$inferSelect+export type NewPost = typeof posts.$inferInsertdiff --git a/skills/d1-drizzle-schema/references/column-patterns.md b/skills/d1-drizzle-schema/references/column-patterns.mdnew file mode 100644index 00000000..0f612489--- /dev/null+++ b/skills/d1-drizzle-schema/references/column-patterns.md@@ -0,0 +1,210 @@+# Column Patterns++Complete reference for every Drizzle ORM column type used with Cloudflare D1. All patterns verified against real D1 projects.++## Imports++```typescript+import { sqliteTable, text, integer, real, blob, index, uniqueIndex } from 'drizzle-orm/sqlite-core'+import { relations, sql } from 'drizzle-orm'+```++## Primary Keys++### Text UUID (preferred)++```typescript+id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),+```++Generates UUIDs at insert time. Works in Workers runtime (crypto.randomUUID is available).++### Integer Autoincrement++```typescript+id: integer('id').primaryKey({ autoIncrement: true }),+```++Use when you need sequential IDs or when the table is insert-heavy and UUID overhead matters.++## Text++### Plain text++```typescript+name: text('name').notNull(),+description: text('description'), // nullable+```++### Text with enum++```typescript+role: text('role', { enum: ['admin', 'editor', 'viewer'] }).notNull().default('viewer'),+status: text('status', { enum: ['draft', 'published', 'archived'] }).notNull().default('draft'),+```++Stored as TEXT in D1. Drizzle validates at the TypeScript level — no database-level constraint.++## Boolean++D1 has no native BOOLEAN. Use INTEGER with `mode: 'boolean'`:++```typescript+emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),+enabled: integer('enabled', { mode: 'boolean' }).notNull().default(true),+```++Stored as 0/1 in D1. Drizzle auto-converts to/from `boolean` in TypeScript.++## Timestamps++D1 has no native DATETIME. Use INTEGER with `mode: 'timestamp'`:++```typescript+// Stores as unix epoch seconds, returns as Date object+createdAt: integer('created_at', { mode: 'timestamp' })+ .notNull()+ .$defaultFn(() => new Date()),++updatedAt: integer('updated_at', { mode: 'timestamp' })+ .notNull()+ .$defaultFn(() => new Date()),+```++### Manual unix timestamps (when you don't want Date objects)++```typescript+timestamp: integer('timestamp').notNull().$defaultFn(() => Math.floor(Date.now() / 1000)),+```++## Numbers++### Integer++```typescript+count: integer('count').notNull().default(0),+sortOrder: integer('sort_order'),+```++### Real (float/decimal)++```typescript+price: real('price').notNull(),+latitude: real('latitude'),+longitude: real('longitude'),+```++## JSON++Store as TEXT with `mode: 'json'`. Drizzle handles JSON.stringify/parse automatically.++### Typed JSON (recommended)++```typescript+preferences: text('preferences', { mode: 'json' })+ .$type<{ theme: string; notifications: boolean }>()+ .$defaultFn(() => ({ theme: 'default', notifications: true })),++metadata: text('metadata', { mode: 'json' })+ .$type<Record<string, unknown>>(),++changes: text('changes', { mode: 'json' })+ .$type<Record<string, { old: unknown; new: unknown }>>(),+```++### Untyped JSON (when schema varies)++```typescript+rawData: text('raw_data'), // manual JSON.stringify/parse+```++Use `{ mode: 'json' }` unless you need to query JSON fields in raw SQL — in that case, use plain `text()` and handle serialisation yourself.++## Foreign Keys++Foreign keys are **always enforced in D1** (cannot disable with PRAGMA).++```typescript+// Inline reference+userId: text('user_id')+ .notNull()+ .references(() => users.id, { onDelete: 'cascade' }),++// With set null+categoryId: text('category_id')+ .references(() => categories.id, { onDelete: 'set null' }),++// Self-referencing+parentId: text('parent_id')+ .references((): AnySQLiteColumn => categories.id),+```++**Cascade options**: `cascade`, `set null`, `restrict`, `no action` (default).++**Migration ordering**: When creating tables with circular FKs, use `PRAGMA defer_foreign_keys = on` at the start of the migration.++## Indexes++Defined in the table function callback (second argument to `sqliteTable`):++```typescript+export const posts = sqliteTable('posts', {+ id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),+ title: text('title').notNull(),+ authorId: text('author_id').notNull().references(() => users.id),+ status: text('status', { enum: ['draft', 'published'] }).notNull(),+ publishedAt: integer('published_at', { mode: 'timestamp' }),+}, (table) => ({+ // Single column index+ authorIdx: index('posts_author_idx').on(table.authorId),++ // Unique index+ slugIdx: uniqueIndex('posts_slug_idx').on(table.slug),++ // Composite index+ statusDateIdx: index('posts_status_date_idx').on(table.status, table.publishedAt),+}))+```++**Naming convention**: `{table}_{column(s)}_{idx|uniq}`.++## Relations++Drizzle relations are query builder helpers — not database-level constraints. Define alongside FKs.++### One-to-many++```typescript+export const usersRelations = relations(users, ({ many }) => ({+ posts: many(posts),+}))++export const postsRelations = relations(posts, ({ one }) => ({+ author: one(users, {+ fields: [posts.authorId],+ references: [users.id],+ }),+}))+```++### Many-to-many (via junction table)++```typescript+export const postTags = sqliteTable('post_tags', {+ postId: text('post_id').notNull().references(() => posts.id, { onDelete: 'cascade' }),+ tagId: text('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }),+}, (table) => ({+ pk: uniqueIndex('post_tags_pk').on(table.postId, table.tagId),+}))+```++## Type Exports++Always export inferred types for every table:++```typescript+export type User = typeof users.$inferSelect+export type NewUser = typeof users.$inferInsert+export type Post = typeof posts.$inferSelect+export type NewPost = typeof posts.$inferInsert+```diff --git a/skills/d1-drizzle-schema/references/d1-specifics.md b/skills/d1-drizzle-schema/references/d1-specifics.mdnew file mode 100644index 00000000..75be7ac1--- /dev/null+++ b/skills/d1-drizzle-schema/references/d1-specifics.md@@ -0,0 +1,141 @@+# D1 Specifics++Reference for Cloudflare D1 behaviour that differs from standard SQLite. Load this when troubleshooting D1 issues or when you need to write raw SQL against D1.++## D1 vs Standard SQLite++| Feature | Standard SQLite | D1 |+|---------|-----------------|-----|+| Foreign keys default | OFF | **ON (always enforced)** |+| `PRAGMA foreign_keys` | Can toggle freely | **Blocked** — always on |+| `PRAGMA defer_foreign_keys` | Available | Available (for migration ordering) |+| Other PRAGMAs | Full access | Restricted (table_list, table_info, table_xinfo only) |+| Bound parameters per query | ~999 | **100** |+| Max database size | Filesystem | 10 GB (paid) / 500 MB (free) |+| Max columns per table | Unlimited | **100** |+| Max string/BLOB size | Unlimited | **2 MB** |+| Max SQL statement length | Unlimited | **100 KB** |+| Max queries per Worker invocation | N/A | 1000 (paid) / 50 (free) |+| Max concurrent D1 connections | N/A | **6 per Worker** |+| Max query duration | N/A | **30 seconds** |+| Concurrency model | Multi-writer | **Single-threaded** (Durable Object) |+| BigInt support | Yes | **No** (JS 52-bit limit) |+| Virtual tables (FTS5) | Yes | Yes, but **blocks `wrangler d1 export`** |++## JSON in D1++JSON functions are always available (no extension loading needed).++### Storage++JSON is stored as `TEXT` columns. Drizzle handles serialisation with `{ mode: 'json' }`.++### Extraction Functions++| Function | Returns | Example |+|----------|---------|---------|+| `json_extract(col, '$.path')` | SQL type matching JSON type | `json_extract(data, '$.name')` → `"Alice"` |+| `col -> '$.path'` | JSON representation | `data -> '$.score'` → `42` (as JSON) |+| `col ->> '$.path'` | SQL TEXT | `data ->> '$.score'` → `"42"` (as TEXT) |+| `json_each(value)` | Rows (top-level array) | Expand array into rows |+| `json_tree(value)` | Rows (full nested) | Expand entire structure |++### Type Coercion++| JSON type | D1 type |+|-----------|---------|+| `null` | `NULL` |+| number (integer) | `INTEGER` |+| number (decimal) | `REAL` |+| boolean | `INTEGER` (1 = true, 0 = false) |+| string | `TEXT` |+| object/array | `TEXT` |++### Generated Columns from JSON++D1 supports generated columns — extract JSON fields as indexable columns:++```sql+CREATE TABLE sensor_data (+ raw_data TEXT,+ location AS (json_extract(raw_data, '$.location')) STORED+);+CREATE INDEX idx_location ON sensor_data(location);+```++### JSON Gotcha++`json_extract()` throws `malformed JSON` (error 9015) if the column contains non-JSON text. Guard with `json_valid()`:++```sql+SELECT * FROM events+WHERE json_valid(metadata) AND json_extract(metadata, '$.country') = 'AU'+```++## Query Result Formats++### `.all<T>()` — Array of row objects++```typescript+const { results, success, meta } = await env.DB+ .prepare("SELECT * FROM users WHERE role = ?")+ .bind("admin")+ .all<UserRow>()+// results: UserRow[]+// meta: { duration, rows_read, rows_written, last_row_id, changes, size_after }+```++### `.first()` — Single row or null++```typescript+const row = await env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(id).first()+// row: Record<string, unknown> | null++// With column name — returns scalar:+const count = await env.DB.prepare("SELECT COUNT(*) as count FROM users").first('count')+// count: number | null+```++### `.run()` — Execute mutation (no rows returned)++```typescript+const result = await env.DB+ .prepare("INSERT INTO users (id, name) VALUES (?, ?)")+ .bind(id, name)+ .run()+// result: { success, meta: { changes, last_row_id, ... } }+```++### `.raw()` — Array of arrays (no column names)++```typescript+const rows = await env.DB.prepare("SELECT id, name FROM users").raw()+// rows: [["abc", "Alice"], ["def", "Bob"]]++// With column names:+const rows = await env.DB.prepare("SELECT id, name FROM users").raw({ columnNames: true })+// rows: [["id", "name"], ["abc", "Alice"], ["def", "Bob"]]+```++### `.batch()` — Multiple statements in one transaction++```typescript+const [r1, r2] = await env.DB.batch([+ env.DB.prepare("INSERT INTO users VALUES (?, ?)").bind(id1, name1),+ env.DB.prepare("INSERT INTO users VALUES (?, ?)").bind(id2, name2),+])+// Returns: D1Result[] — one per statement, all in single transaction+```++## Batch Insert Calculation++D1's 100 parameter limit means: `max_rows_per_insert = Math.floor(100 / columns_per_row)`++| Columns | Max rows per INSERT |+|---------|-------------------|+| 5 | 20 |+| 10 | 10 |+| 15 | 6 |+| 20 | 5 |++Symptoms of hitting the limit: silent failure, partial data, or cryptic "Failed to insert" error.diff --git a/skills/gemini-peer-review/SKILL.md b/skills/gemini-peer-review/SKILL.mdnew file mode 100644index 00000000..48c4adca--- /dev/null+++ b/skills/gemini-peer-review/SKILL.md@@ -0,0 +1,102 @@+---+name: gemini-peer-review+description: "Get a second opinion from Gemini on code, architecture, debugging, or security. Uses gemini-coach CLI with AI-to-AI prompting for clear, actionable analysis. Trigger with 'ask gemini', 'gemini review', 'second opinion', 'peer review', or 'consult gemini'."+compatibility: claude-code-only+---++# Gemini Peer Review++Consult Gemini as a coding peer for a second opinion on code quality, architecture decisions, debugging, or security reviews.++## Prerequisites++- `gemini-coach` CLI installed (wraps Gemini CLI with AI-to-AI prompting)+- Gemini CLI authenticated (`gemini` to test)++## Modes++### Code Review++```bash+gemini-coach review src/auth.ts src/api.ts+```++Review specific files for bugs, logic errors, security vulnerabilities, performance issues, and best practice violations.++### Architecture Advice++```bash+gemini-coach architect "Should I use D1 or KV for session storage?" .+```++Get feedback on design decisions with trade-off analysis. Passing `.` includes project context.++### Debugging Help++```bash+gemini-coach debug src/problematic-file.ts+```++Analyse errors when stuck after 2+ failed fix attempts. Gemini sees the code fresh without your debugging context bias.++### Security Scan++```bash+gemini-coach security-scan ./src/api/+```++Scan code for security vulnerabilities (injection, auth bypass, data exposure).++### Quick Question++```bash+gemini-coach quick "Best way to handle WebSockets in Workers?"+```++Fast question without file context.++### Project Review++```bash+gemini-coach project-review "Analyse architecture and suggest improvements" /path/to/project+```++Full project analysis using Gemini's 1M token context.++## When to Use++**Good use cases**:+- Before committing major changes (final review)+- When stuck debugging after multiple attempts+- Architecture decisions with multiple valid options+- Security-sensitive code review+- "What am I missing?" moments++**Avoid using for**:+- Simple syntax checks (Claude handles these faster)+- Every single edit (too slow, unnecessary)+- Questions with obvious answers++## Model Selection++`gemini-coach` automatically selects the right model:++| Mode | Model | Typical Time |+|------|-------|-------------|+| review, debug, quick | gemini-2.5-flash | 5-15s |+| architect, security-scan | gemini-2.5-pro | 15-30s |++Override: `GEMINI_MODEL=gemini-2.5-pro gemini-coach review ...`++## Synthesizing Results++After receiving Gemini's analysis:+1. Present Gemini's findings to the user+2. Add your own perspective — agree/disagree with specific points+3. Let the user decide which recommendations to implement++## Reference Files++| When | Read |+|------|------|+| AI-to-AI prompt templates, model details | [references/prompt-templates.md](references/prompt-templates.md) |diff --git a/skills/gemini-peer-review/references/prompt-templates.md b/skills/gemini-peer-review/references/prompt-templates.mdnew file mode 100644index 00000000..25182894--- /dev/null+++ b/skills/gemini-peer-review/references/prompt-templates.md@@ -0,0 +1,71 @@+# Prompt Templates++## AI-to-AI Prompting Format++Always use this format when constructing prompts for Gemini. It prevents role confusion — Gemini knows it's advising Claude Code, not talking to the human.++```+[Claude Code consulting Gemini for peer review]++Task: [Specific task description]++Provide direct analysis with file:line references. I will synthesize your findings with mine before presenting to the developer.+```++## Per-Mode Templates++### Code Review++```+[Claude Code consulting Gemini for peer review]++Task: Code review — check for bugs, logic errors, security vulnerabilities (SQL injection, XSS, etc.), performance issues, best practice violations, type safety problems, and missing error handling.++[If reference docs available:]+Check against these official docs:+- [URL]++Provide direct analysis with file:line references. I will synthesize your findings with mine before presenting to the developer.+```++### Architecture Advice++```+[Claude Code consulting Gemini for peer review]++Task: Architecture advice — [description of the decision or problem]++Analyse for: architectural anti-patterns, scalability concerns, maintainability issues, better alternatives, potential technical debt.++Provide specific, actionable recommendations and rationale. I will synthesize your findings with mine before presenting to the developer.+```++### Debugging Help++```+[Claude Code consulting Gemini for peer review]++Task: Debug analysis — identify root cause (not just symptoms), explain why it's happening, suggest specific fix with code example, and how to prevent in future.++Error: [error message/description]+What was tried: [previous attempts if any]++Provide direct analysis with file:line references. I will synthesize your findings with mine before presenting to the developer.+```++### Security Scan++```+[Claude Code consulting Gemini for peer review]++Task: Security audit — check for injection vulnerabilities, authentication/authorisation issues, data exposure, insecure defaults, missing input validation, CORS misconfiguration, and credential handling.++Provide direct analysis with file:line references and severity ratings. I will synthesize your findings with mine before presenting to the developer.+```++## Flash vs Pro++- **Flash** (default): Faster (~5-15s), good for code reviews, debugging, most tasks. Safer with directory scanning.+- **Pro**: Better reasoning (~15-30s), preferred for complex architecture decisions and security reviews. May try to use tools aggressively when scanning directories.++Both models have similar quality on straightforward tasks. Pro's advantage shows on complex reasoning where trade-off analysis matters.diff --git a/skills/github-release/SKILL.md b/skills/github-release/SKILL.mdnew file mode 100644index 00000000..94a010af--- /dev/null+++ b/skills/github-release/SKILL.md@@ -0,0 +1,152 @@+---+name: github-release+description: "Prepare and publish GitHub releases. Sanitizes code for public release (secrets scan, personal artifacts, LICENSE/README validation), creates version tags, and publishes via gh CLI. Trigger with 'release', 'publish', 'open source', 'prepare for release', 'create release', or 'github release'."+compatibility: claude-code-only+---++# GitHub Release++Sanitize and release projects to GitHub. Two-phase workflow: safety checks first, then tag and publish.++## Prerequisites++- `gh` CLI installed and authenticated (`gh auth status`)+- `gitleaks` installed for secrets scanning (`brew install gitleaks` or download from GitHub)+- Git repository with a remote configured++## Workflow++### Phase 1: Sanitize++Run these checks before any public release. Stop on blockers.++#### 1. Scan for Secrets (BLOCKER)++```bash+gitleaks detect --no-git --source=. --verbose+```++If secrets found: **STOP**. Remove secrets, move to environment variables. Check git history with `git log -S "secret_value"` — if in history, use BFG Repo-Cleaner.++If gitleaks not installed, do manual checks:++```bash+# Check for .env files+find . -name ".env*" -not -path "*/node_modules/*"++# Check config files for hardcoded secrets+grep -ri "api_key\|token\|secret\|password" wrangler.toml wrangler.jsonc .dev.vars 2>/dev/null+```++#### 2. Remove Personal Artifacts++Check for and remove session/planning files that shouldn't be published:++- `SESSION.md` — session state+- `planning/`, `screenshots/` — working directories+- `test-*.ts`, `test-*.js` — local test files++Either delete them or add to `.gitignore`.++#### 3. Validate LICENSE++```bash+ls LICENSE LICENSE.md LICENSE.txt 2>/dev/null+```++If missing: create one. MIT is the default for Jez's projects. For private repos, use the proprietary license (see `~/.claude/rules/git-workflow.md`).++#### 4. Validate README++Check README exists and has basic sections:++```bash+grep -i "## Install\|## Usage\|## License" README.md+```++If missing sections, add them before release.++#### 5. Check .gitignore++Verify essential patterns are present:++```bash+grep -E "node_modules|\.env|dist/|\.dev\.vars" .gitignore+```++#### 6. Build Test (non-blocking)++```bash+npm run build 2>&1+```++#### 7. Dependency Audit (non-blocking)++```bash+npm audit --audit-level=high+```++#### 8. Create Sanitization Commit++If any changes were made during sanitization:++```bash+git add -A+git commit -m "chore: prepare for release"+```++### Phase 2: Release++#### 1. Determine Version++Check `package.json` for current version, or ask the user. Ensure version starts with `v` prefix.++#### 2. Check Tag Doesn't Exist++```bash+git tag -l "v[version]"+```++If it exists, ask user whether to delete and recreate or use a different version.++#### 3. Show What's Being Released++```bash+LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")+if [ -z "$LAST_TAG" ]; then+ git log --oneline --no-merges HEAD | head -20+else+ git log --oneline --no-merges ${LAST_TAG}..HEAD+fi+```++#### 4. Create Tag and Push++```bash+git tag -a v[version] -m "Release v[version]"+git push origin $(git branch --show-current)+git push origin --tags+```++#### 5. Create GitHub Release++```bash+gh release create v[version] \+ --title "Release v[version]" \+ --notes "[auto-generated from commits]"+```++For pre-releases add `--prerelease`. For drafts add `--draft`.++#### 6. Report++Show the user:+- Release URL+- Next steps (npm publish if applicable, announcements)++## Reference Files++| When | Read |+|------|------|+| Detailed safety checks | [references/safety-checklist.md](references/safety-checklist.md) |+| Release mechanics | [references/release-workflow.md](references/release-workflow.md) |diff --git a/skills/github-release/references/release-workflow.md b/skills/github-release/references/release-workflow.mdnew file mode 100644index 00000000..bf179026--- /dev/null+++ b/skills/github-release/references/release-workflow.md@@ -0,0 +1,90 @@+# Release Workflow++Detailed reference for the tag-push-release mechanics.++## Version Detection++Check `package.json` first:++```bash+node -p "require('./package.json').version" 2>/dev/null+```++If no package.json, ask user for version. Always prefix with `v` (e.g., `v1.0.0`).++## Monorepo Tags++In monorepos, use scoped tags:++```bash+# Single repo+git tag -a v1.0.0 -m "Release v1.0.0"++# Monorepo+git tag -a mypackage-v1.0.0 -m "Release mypackage v1.0.0"+```++## Tag Conflicts++If tag already exists locally:++```bash+# Delete local tag+git tag -d v1.0.0++# If also on remote (dangerous — confirm with user)+git push origin :refs/tags/v1.0.0+```++## Push Sequence++Always push branch first, then tags:++```bash+BRANCH=$(git branch --show-current)+git push origin ${BRANCH}+git push origin --tags+```++If push fails:+- Set upstream: `git push -u origin ${BRANCH}`+- Check auth: `gh auth status`+- Verify remote: `git remote -v`++## Release Notes++Generate from commits since last tag:++```bash+LAST_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")++if [ -z "$LAST_TAG" ]; then+ git log --oneline --no-merges HEAD+else+ git log --oneline --no-merges ${LAST_TAG}..HEAD+fi+```++Format as markdown bullet list under `## What's New`.++## gh release create++```bash+# Standard release+gh release create v1.0.0 --title "Release v1.0.0" --notes "## What's New+- Feature A+- Bug fix B"++# Pre-release (beta/rc)+gh release create v1.0.0-beta.1 --title "v1.0.0 Beta 1" --notes "..." --prerelease++# Draft (not published)+gh release create v1.0.0 --title "Release v1.0.0" --notes "..." --draft+```++## Post-Release++Depending on project type:+- **npm package**: `npm publish`+- **Announce**: Social media, relevant communities+- **Update docs**: Ensure README references latest versiondiff --git a/skills/github-release/references/safety-checklist.md b/skills/github-release/references/safety-checklist.mdnew file mode 100644index 00000000..ce704bcb--- /dev/null+++ b/skills/github-release/references/safety-checklist.md@@ -0,0 +1,48 @@+# Safety Checklist++Pre-release safety checks for public repositories.++## Blockers (must pass)++| Check | How | Fail action |+|-------|-----|-------------|+| No secrets in files | `gitleaks detect --no-git --source=.` | Remove secrets, check git history |+| No secrets in git history | `git log -S "sk_" -S "ghp_" -S "PRIVATE KEY"` | BFG Repo-Cleaner |+| LICENSE exists | `ls LICENSE*` | Create MIT or proprietary |+| Remote URL is correct | `git remote -v` | Fix with `git remote set-url` |++## Warnings (should fix)++| Check | How | Recommendation |+|-------|-----|----------------|+| README has Install/Usage/License | `grep -i "## Install\|## Usage" README.md` | Add missing sections |+| .gitignore has essentials | `grep "node_modules\|\.env" .gitignore` | Add missing patterns |+| No personal artifacts | `ls SESSION.md planning/ screenshots/ 2>/dev/null` | Delete or .gitignore |+| Build succeeds | `npm run build` | Fix before release |+| No critical vulnerabilities | `npm audit --audit-level=high` | `npm audit fix` |+| No large files (>1MB) | `find . -size +1M -not -path "*/node_modules/*" -not -path "*/.git/*"` | Git LFS or external storage |++## Common Secret Patterns++| Pattern | Example |+|---------|---------|+| API keys | `sk_live_...`, `ghp_...`, `AKIA...` |+| Tokens | `Bearer eyJ...`, `xoxb-...` |+| Private keys | `-----BEGIN PRIVATE KEY-----` |+| Passwords | `password = "..."`, `DB_PASSWORD=...` |+| Cloudflare | `account_id` in committed wrangler files with real IDs |++## Package.json Fields++For npm packages, verify these fields before publish:++```json+{+ "name": "@scope/package",+ "version": "1.0.0",+ "description": "Clear description",+ "license": "MIT",+ "repository": { "type": "git", "url": "https://github.com/..." },+ "keywords": ["relevant", "terms"]+}+```diff --git a/skills/hono-api-scaffolder/SKILL.md b/skills/hono-api-scaffolder/SKILL.mdnew file mode 100644index 00000000..71434efb--- /dev/null+++ b/skills/hono-api-scaffolder/SKILL.md@@ -0,0 +1,208 @@+---+name: hono-api-scaffolder+description: "Scaffold Hono API routes for Cloudflare Workers. Produces route files, middleware, typed bindings, Zod validation, error handling, and API_ENDPOINTS.md documentation. Use after a project is set up with cloudflare-worker-builder or vite-flare-starter, when you need to add API routes, create endpoints, or generate API documentation."+compatibility: claude-code-only+---++# Hono API Scaffolder++Add structured API routes to an existing Cloudflare Workers project. This skill runs AFTER the project shell exists (via cloudflare-worker-builder or vite-flare-starter) and produces route files, middleware, and endpoint documentation.++## Workflow++### Step 1: Gather Endpoints++Determine what the API needs. Either ask the user or infer from the project description. Group endpoints by resource:++```+Users: GET /api/users, GET /api/users/:id, POST /api/users, PUT /api/users/:id, DELETE /api/users/:id+Posts: GET /api/posts, GET /api/posts/:id, POST /api/posts, PUT /api/posts/:id+Auth: POST /api/auth/login, POST /api/auth/logout, GET /api/auth/me+```++### Step 2: Create Route Files++One file per resource group. Use the template from [assets/route-template.ts](assets/route-template.ts):++```typescript+// src/routes/users.ts+import { Hono } from 'hono'+import { zValidator } from '@hono/zod-validator'+import { z } from 'zod'+import type { Env } from '../types'++const app = new Hono<{ Bindings: Env }>()++// GET /api/users+app.get('/', async (c) => {+ const db = c.env.DB+ const { results } = await db.prepare('SELECT * FROM users').all()+ return c.json({ users: results })+})++// GET /api/users/:id+app.get('/:id', async (c) => {+ const id = c.req.param('id')+ const user = await db.prepare('SELECT * FROM users WHERE id = ?').bind(id).first()+ if (!user) return c.json({ error: 'Not found' }, 404)+ return c.json({ user })+})++// POST /api/users+const createUserSchema = z.object({+ name: z.string().min(1),+ email: z.string().email(),+})++app.post('/', zValidator('json', createUserSchema), async (c) => {+ const body = c.req.valid('json')+ // ... insert logic+ return c.json({ user }, 201)+})++export default app+```++### Step 3: Add Middleware++Based on project needs, add from [assets/middleware-template.ts](assets/middleware-template.ts):++**Auth middleware** — protect routes requiring authentication:+```typescript+import { createMiddleware } from 'hono/factory'+import type { Env } from '../types'++export const requireAuth = createMiddleware<{ Bindings: Env }>(async (c, next) => {+ const token = c.req.header('Authorization')?.replace('Bearer ', '')+ if (!token) return c.json({ error: 'Unauthorized' }, 401)+ // Validate token...+ await next()+})+```++**CORS** — use Hono's built-in:+```typescript+import { cors } from 'hono/cors'+app.use('/api/*', cors({ origin: ['https://example.com'] }))+```++### Step 4: Wire Routes++Mount all route groups in the main entry point:++```typescript+// src/index.ts+import { Hono } from 'hono'+import type { Env } from './types'+import users from './routes/users'+import posts from './routes/posts'+import auth from './routes/auth'+import { errorHandler } from './middleware/error-handler'++const app = new Hono<{ Bindings: Env }>()++// Global error handler+app.onError(errorHandler)++// Mount routes+app.route('/api/users', users)+app.route('/api/posts', posts)+app.route('/api/auth', auth)++// Health check+app.get('/api/health', (c) => c.json({ status: 'ok' }))++export default app+```++### Step 5: Create Types++```typescript+// src/types.ts+export interface Env {+ DB: D1Database+ KV: KVNamespace // if needed+ R2: R2Bucket // if needed+ API_SECRET: string // secrets+}+```++### Step 6: Generate API_ENDPOINTS.md++Document all endpoints. See [references/endpoint-docs-template.md](references/endpoint-docs-template.md) for the format:++```markdown+## POST /api/users+Create a new user.+- **Auth**: Required (Bearer token)+- **Body**: `{ name: string, email: string }`+- **Response 201**: `{ user: User }`+- **Response 400**: `{ error: string, details: ZodError }`+```++## Key Patterns++### Zod Validation++Always validate request bodies with `@hono/zod-validator`:++```typescript+import { zValidator } from '@hono/zod-validator'+app.post('/', zValidator('json', schema), async (c) => {+ const body = c.req.valid('json') // fully typed+})+```++Install: `pnpm add @hono/zod-validator zod`++### Error Handling++Use the standard error handler from [assets/error-handler.ts](assets/error-handler.ts):++```typescript+export const errorHandler = (err: Error, c: Context) => {+ console.error(err)+ return c.json({ error: err.message }, 500)+}+```++**API routes must return JSON errors, not redirects.** `fetch()` follows redirects silently, then the client tries to parse HTML as JSON.++### RPC Type Safety++For end-to-end type safety between Worker and client:++```typescript+// Worker: export the app type+export type AppType = typeof app++// Client: use hc (Hono Client)+import { hc } from 'hono/client'+import type { AppType } from '../worker/src/index'++const client = hc<AppType>('https://api.example.com')+const res = await client.api.users.$get() // fully typed+```++### Route Groups vs Single File++| Project size | Structure |+|-------------|-----------|+| < 10 endpoints | Single `index.ts` with all routes |+| 10-30 endpoints | Route files per resource (`routes/users.ts`) |+| 30+ endpoints | Route files + shared middleware + typed context |++## Reference Files++| When | Read |+|------|------|+| Hono patterns, middleware, RPC | [references/hono-patterns.md](references/hono-patterns.md) |+| API_ENDPOINTS.md format | [references/endpoint-docs-template.md](references/endpoint-docs-template.md) |++## Assets++| File | Purpose |+|------|---------|+| [assets/route-template.ts](assets/route-template.ts) | Starter route file with CRUD + Zod |+| [assets/middleware-template.ts](assets/middleware-template.ts) | Auth middleware template |+| [assets/error-handler.ts](assets/error-handler.ts) | Standard JSON error handler |diff --git a/skills/hono-api-scaffolder/assets/error-handler.ts b/skills/hono-api-scaffolder/assets/error-handler.tsnew file mode 100644index 00000000..bf12d1a8--- /dev/null+++ b/skills/hono-api-scaffolder/assets/error-handler.ts@@ -0,0 +1,17 @@+/**+ * Standard Error Handler+ *+ * Returns JSON errors for all routes.+ * API routes must return JSON, never HTML redirects.+ */+import type { Context } from 'hono'+import { HTTPException } from 'hono/http-exception'++export const errorHandler = (err: Error, c: Context) => {+ if (err instanceof HTTPException) {+ return c.json({ error: err.message }, err.status)+ }++ console.error('Unhandled error:', err)+ return c.json({ error: 'Internal server error' }, 500)+}diff --git a/skills/hono-api-scaffolder/assets/middleware-template.ts b/skills/hono-api-scaffolder/assets/middleware-template.tsnew file mode 100644index 00000000..f03a5269--- /dev/null+++ b/skills/hono-api-scaffolder/assets/middleware-template.ts@@ -0,0 +1,30 @@+/**+ * Auth Middleware Template+ *+ * Validates Bearer token and sets userId/role in context.+ * Customise the token validation logic for your auth system.+ */+import { createMiddleware } from 'hono/factory'+import type { Env } from '../types'++type AuthVariables = {+ userId: string+ role: string+}++export const requireAuth = createMiddleware<{+ Bindings: Env+ Variables: AuthVariables+}>(async (c, next) => {+ const token = c.req.header('Authorization')?.replace('Bearer ', '')+ if (!token) {+ return c.json({ error: 'Unauthorized' }, 401)+ }++ // TODO: Validate token (JWT, session lookup, API key check, etc.)+ // const decoded = await verifyToken(token, c.env.JWT_SECRET)+ // c.set('userId', decoded.sub)+ // c.set('role', decoded.role)++ await next()+})diff --git a/skills/hono-api-scaffolder/assets/route-template.ts b/skills/hono-api-scaffolder/assets/route-template.tsnew file mode 100644index 00000000..37fee8f7--- /dev/null+++ b/skills/hono-api-scaffolder/assets/route-template.ts@@ -0,0 +1,59 @@+/**+ * Route Template — [Resource Name]+ *+ * Copy this file to src/routes/[resource].ts and customise.+ * Includes: list, get, create, update, delete with Zod validation.+ */+import { Hono } from 'hono'+import { zValidator } from '@hono/zod-validator'+import { z } from 'zod'+import type { Env } from '../types'++const app = new Hono<{ Bindings: Env }>()++const createSchema = z.object({+ name: z.string().min(1).max(100),+ // Add fields here+})++const updateSchema = createSchema.partial()++// GET /api/[resource]+app.get('/', async (c) => {+ const db = c.env.DB+ const { results } = await db.prepare('SELECT * FROM [table] ORDER BY created_at DESC').all()+ return c.json({ items: results })+})++// GET /api/[resource]/:id+app.get('/:id', async (c) => {+ const id = c.req.param('id')+ const item = await c.env.DB.prepare('SELECT * FROM [table] WHERE id = ?').bind(id).first()+ if (!item) return c.json({ error: 'Not found' }, 404)+ return c.json({ item })+})++// POST /api/[resource]+app.post('/', zValidator('json', createSchema), async (c) => {+ const body = c.req.valid('json')+ const id = crypto.randomUUID()+ await c.env.DB.prepare('INSERT INTO [table] (id, name) VALUES (?, ?)').bind(id, body.name).run()+ return c.json({ item: { id, ...body } }, 201)+})++// PUT /api/[resource]/:id+app.put('/:id', zValidator('json', updateSchema), async (c) => {+ const id = c.req.param('id')+ const body = c.req.valid('json')+ // ... update logic+ return c.json({ item: { id, ...body } })+})++// DELETE /api/[resource]/:id+app.delete('/:id', async (c) => {+ const id = c.req.param('id')+ await c.env.DB.prepare('DELETE FROM [table] WHERE id = ?').bind(id).run()+ return c.body(null, 204)+})++export default appdiff --git a/skills/hono-api-scaffolder/references/endpoint-docs-template.md b/skills/hono-api-scaffolder/references/endpoint-docs-template.mdnew file mode 100644index 00000000..6d9dbe06--- /dev/null+++ b/skills/hono-api-scaffolder/references/endpoint-docs-template.md@@ -0,0 +1,106 @@+# API Endpoints Documentation Template++Use this format when generating API_ENDPOINTS.md for a project.++## Template++```markdown+# API Endpoints++Base URL: `https://[project].workers.dev` (production) | `http://localhost:5173` (dev)++## Authentication++[Describe auth method: Bearer token, session cookie, API key, none]++## Endpoints++### [Resource Name]++#### GET /api/[resource]++List all [resources].++- **Auth**: [Required/None]+- **Query params**:+ - `page` (number, default: 1)+ - `limit` (number, default: 20, max: 100)+ - `search` (string, optional)+- **Response 200**:+ ```json+ {+ "[resources]": [...],+ "total": 42,+ "page": 1,+ "limit": 20+ }+ ```++#### GET /api/[resource]/:id++Get a single [resource] by ID.++- **Auth**: [Required/None]+- **Response 200**: `{ "[resource]": { ... } }`+- **Response 404**: `{ "error": "Not found" }`++#### POST /api/[resource]++Create a new [resource].++- **Auth**: Required+- **Body**:+ ```json+ {+ "name": "string (required)",+ "email": "string (required, email format)"+ }+ ```+- **Response 201**: `{ "[resource]": { ... } }`+- **Response 400**: `{ "error": "Validation failed", "details": { ... } }`++#### PUT /api/[resource]/:id++Update an existing [resource].++- **Auth**: Required+- **Body**: Same as POST (all fields optional)+- **Response 200**: `{ "[resource]": { ... } }`+- **Response 404**: `{ "error": "Not found" }`++#### DELETE /api/[resource]/:id++Delete a [resource].++- **Auth**: Required+- **Response 204**: (no body)+- **Response 404**: `{ "error": "Not found" }`++## Error Format++All errors return JSON:++```json+{+ "error": "Human-readable error message",+ "details": {} // optional, present for validation errors+}+```++| Status | Meaning |+|--------|---------|+| 400 | Bad request / validation error |+| 401 | Not authenticated |+| 403 | Not authorised |+| 404 | Resource not found |+| 500 | Internal server error |+```++## Guidelines++- Document every endpoint, including auth requirements+- Show example request bodies with field types and constraints+- Show example response shapes (JSON)+- Include all possible error responses+- List query parameters with defaults and limits+- Keep descriptions to one line per endpointdiff --git a/skills/hono-api-scaffolder/references/hono-patterns.md b/skills/hono-api-scaffolder/references/hono-patterns.mdnew file mode 100644index 00000000..5735401f--- /dev/null+++ b/skills/hono-api-scaffolder/references/hono-patterns.md@@ -0,0 +1,209 @@+# Hono Patterns++Advanced patterns for Hono on Cloudflare Workers. Load this when building complex APIs or troubleshooting route issues.++## Route Priority++Hono matches routes in registration order. Place specific routes before generic ones:++```typescript+// Correct order+app.get('/api/users/me', getMeHandler) // specific first+app.get('/api/users/:id', getUserHandler) // param route second+app.get('/api/users', listUsersHandler) // list last+```++## Middleware Chains++Middleware runs in order of `app.use()` registration:++```typescript+app.use('*', logger()) // all routes+app.use('/api/*', cors()) // all API routes+app.use('/api/admin/*', requireAuth) // admin routes only+```++### Per-Route Middleware++```typescript+app.get('/api/secret', requireAuth, async (c) => {+ // runs after auth middleware+})+```++### Typed Context with Variables++```typescript+// Set in middleware+export const authMiddleware = createMiddleware<{+ Bindings: Env+ Variables: { userId: string; role: string }+}>(async (c, next) => {+ c.set('userId', decoded.sub)+ c.set('role', decoded.role)+ await next()+})++// Read in handler+app.get('/api/me', authMiddleware, (c) => {+ const userId = c.get('userId') // typed string+})+```++## Request Handling++### Path Parameters++```typescript+app.get('/api/posts/:id', (c) => {+ const id = c.req.param('id') // string+})++// Multiple params+app.get('/api/orgs/:orgId/users/:userId', (c) => {+ const { orgId, userId } = c.req.param()+})+```++### Query Parameters++```typescript+app.get('/api/users', (c) => {+ const page = parseInt(c.req.query('page') || '1')+ const limit = parseInt(c.req.query('limit') || '20')+ const search = c.req.query('search')+})+```++### Headers++```typescript+const token = c.req.header('Authorization')?.replace('Bearer ', '')+const contentType = c.req.header('Content-Type')+```++## Response Patterns++### JSON (most common)++```typescript+return c.json({ users }, 200)+return c.json({ error: 'Not found' }, 404)+return c.json({ user }, 201) // created+```++### Empty responses++```typescript+return c.body(null, 204) // no content (DELETE success)+return new Response(null, { status: 204 })+```++### Redirects++```typescript+return c.redirect('/login', 302)+```++### Streaming++```typescript+return c.stream(async (stream) => {+ await stream.write('chunk 1')+ await stream.write('chunk 2')+})+```++## Error Handling++### Global error handler++```typescript+app.onError((err, c) => {+ if (err instanceof HTTPException) {+ return c.json({ error: err.message }, err.status)+ }+ console.error(err)+ return c.json({ error: 'Internal server error' }, 500)+})+```++### HTTPException++```typescript+import { HTTPException } from 'hono/http-exception'++throw new HTTPException(403, { message: 'Forbidden' })+```++### Not Found handler++```typescript+app.notFound((c) => c.json({ error: 'Not found' }, 404))+```++## Zod Validation Patterns++### Body validation++```typescript+const schema = z.object({+ name: z.string().min(1).max(100),+ email: z.string().email(),+ role: z.enum(['admin', 'editor', 'viewer']).optional(),+})++app.post('/', zValidator('json', schema), async (c) => {+ const body = c.req.valid('json')+})+```++### Query validation++```typescript+const querySchema = z.object({+ page: z.coerce.number().min(1).default(1),+ limit: z.coerce.number().min(1).max(100).default(20),+ search: z.string().optional(),+})++app.get('/', zValidator('query', querySchema), async (c) => {+ const { page, limit, search } = c.req.valid('query')+})+```++### Custom error response++```typescript+app.post('/',+ zValidator('json', schema, (result, c) => {+ if (!result.success) {+ return c.json({ error: 'Validation failed', details: result.error.flatten() }, 400)+ }+ }),+ handler,+)+```++## RPC (Remote Procedure Call)++End-to-end type safety between Worker and client without code generation:++```typescript+// Worker: chain routes for type inference+const routes = app+ .get('/api/users', async (c) => c.json({ users: [] }))+ .post('/api/users', zValidator('json', schema), async (c) => c.json({ user: {} }, 201))++export type AppType = typeof routes++// Client:+import { hc } from 'hono/client'+import type { AppType } from './worker'++const client = hc<AppType>('https://api.example.com')+const res = await client.api.users.$get()+const data = await res.json() // typed: { users: User[] }+```++**Key**: The route chain must be assigned to a variable for type inference to work. Don't use `app.route()` for RPC — mount routes directly on the app.diff --git a/skills/shadcn-ui/SKILL.md b/skills/shadcn-ui/SKILL.mdnew file mode 100644index 00000000..4ac84cd3--- /dev/null+++ b/skills/shadcn-ui/SKILL.md@@ -0,0 +1,181 @@+---+name: shadcn-ui+description: "Install and configure shadcn/ui components for React projects. Guides component selection, installation order, dependency management, customisation with semantic tokens, and common UI recipes (forms, data tables, navigation, modals). Use after tailwind-theme-builder has set up the theme infrastructure, when adding components, building forms, creating data tables, or setting up navigation."+---++# shadcn/ui Components++Add shadcn/ui components to a themed React project. This skill runs AFTER `tailwind-theme-builder` has set up CSS variables, ThemeProvider, and dark mode. It handles component installation, customisation, and combining components into working patterns.++**Prerequisite**: Theme infrastructure must exist (CSS variables, components.json, cn() utility). Use `tailwind-theme-builder` first if not set up.++## Installation Order++Install components in dependency order. Foundation components first, then feature components:++### Foundation (install first)++```bash+pnpm dlx shadcn@latest add button+pnpm dlx shadcn@latest add input label+pnpm dlx shadcn@latest add card+```++### Feature Components (install as needed)++```bash+# Forms+pnpm dlx shadcn@latest add form # needs: react-hook-form, zod, @hookform/resolvers+pnpm dlx shadcn@latest add textarea select checkbox switch++# Feedback+pnpm dlx shadcn@latest add toast # needs: sonner+pnpm dlx shadcn@latest add alert badge++# Overlay+pnpm dlx shadcn@latest add dialog sheet popover dropdown-menu++# Data Display+pnpm dlx shadcn@latest add table # for data tables, also: @tanstack/react-table+pnpm dlx shadcn@latest add tabs separator avatar++# Navigation+pnpm dlx shadcn@latest add navigation-menu command+```++### External Dependencies++| Component | Requires |+|-----------|----------|+| Form | `react-hook-form`, `zod`, `@hookform/resolvers` |+| Toast | `sonner` |+| Data Table | `@tanstack/react-table` |+| Command | `cmdk` |+| Date Picker | `date-fns` (optional) |++Install external deps separately: `pnpm add react-hook-form zod @hookform/resolvers`++## Known Gotchas++These are documented corrections that prevent common bugs:++### Radix Select — No Empty Strings++```tsx+// Don't use empty string values+<SelectItem value="">All</SelectItem> // BREAKS++// Use sentinel value+<SelectItem value="__any__">All</SelectItem> // WORKS+const actual = value === "__any__" ? "" : value+```++### React Hook Form — Null Values++```tsx+// Don't spread {...field} — it passes null which Input rejects+<Input+ value={field.value ?? ''}+ onChange={field.onChange}+ onBlur={field.onBlur}+ name={field.name}+ ref={field.ref}+/>+```++### Lucide Icons — Tree-Shaking++```tsx+// Don't use dynamic import — icons get tree-shaken in production+import * as LucideIcons from 'lucide-react'+const Icon = LucideIcons[iconName] // BREAKS in prod++// Use explicit map+import { Home, Users, Settings, type LucideIcon } from 'lucide-react'+const ICON_MAP: Record<string, LucideIcon> = { Home, Users, Settings }+const Icon = ICON_MAP[iconName]+```++### Dialog Width Override++```tsx+// Default sm:max-w-lg won't be overridden by max-w-6xl+<DialogContent className="max-w-6xl"> // DOESN'T WORK++// Use same breakpoint prefix+<DialogContent className="sm:max-w-6xl"> // WORKS+```++## Customising Components++shadcn components use semantic CSS tokens from your theme. To customise:++### Variant extension++Add custom variants by editing the component file in `src/components/ui/`:++```tsx+// button.tsx — add a "brand" variant+const buttonVariants = cva("...", {+ variants: {+ variant: {+ default: "bg-primary text-primary-foreground",+ brand: "bg-brand text-brand-foreground hover:bg-brand/90",+ // ... existing variants+ },+ },+})+```++### Colour overrides++Use semantic tokens from your theme — never raw Tailwind colours:++```tsx+// Don't use raw colours+<Button className="bg-blue-500"> // WRONG++// Use semantic tokens+<Button className="bg-primary"> // RIGHT+<Card className="bg-card text-card-foreground"> // RIGHT+```++## Workflow++### Step 1: Assess Needs++Determine what UI patterns the project needs:++| Need | Components |+|------|-----------|+| Forms with validation | Form, Input, Label, Select, Textarea, Button, Toast |+| Data display with sorting | Table, Badge, Pagination |+| Admin CRUD interface | Dialog, Form, Table, Button, Toast |+| Marketing/landing page | Card, Button, Badge, Separator |+| Settings/preferences | Tabs, Form, Switch, Select, Toast |+| Navigation | NavigationMenu (desktop), Sheet (mobile), ModeToggle |++### Step 2: Install Components++Install foundation first, then feature components for the identified needs. Use the commands above.++### Step 3: Build Recipes++Combine components into working patterns. See [references/recipes.md](references/recipes.md) for complete working examples:++- **Contact Form** — Form + Input + Textarea + Button + Toast+- **Data Table** — Table + Column sorting + Pagination + Search+- **Modal CRUD** — Dialog + Form + Button+- **Navigation** — Sheet + NavigationMenu + ModeToggle+- **Settings Page** — Tabs + Form + Switch + Select + Toast++### Step 4: Customise++Apply project-specific colours and variants using semantic tokens from the theme.++## Reference Files++| When | Read |+|------|------|+| Choosing components, install commands, props | [references/component-catalogue.md](references/component-catalogue.md) |+| Building complete UI patterns | [references/recipes.md](references/recipes.md) |diff --git a/skills/shadcn-ui/references/component-catalogue.md b/skills/shadcn-ui/references/component-catalogue.mdnew file mode 100644index 00000000..2eea1dac--- /dev/null+++ b/skills/shadcn-ui/references/component-catalogue.md@@ -0,0 +1,252 @@+# Component Catalogue++The ~15 most-used shadcn/ui components with install commands, key props, and gotchas. Not exhaustive — see [shadcn/ui docs](https://ui.shadcn.com) for the full list.++## Button++```bash+pnpm dlx shadcn@latest add button+```++**Variants**: `default`, `destructive`, `outline`, `secondary`, `ghost`, `link`+**Sizes**: `default`, `sm`, `lg`, `icon`++```tsx+<Button variant="outline" size="sm" onClick={handleClick}>Save</Button>+<Button variant="ghost" size="icon"><Trash className="h-4 w-4" /></Button>+<Button disabled={isPending}>{isPending ? 'Saving...' : 'Save'}</Button>+```++## Input + Label++```bash+pnpm dlx shadcn@latest add input label+```++```tsx+<div className="space-y-2">+ <Label htmlFor="email">Email</Label>+ <Input id="email" type="email" placeholder="[email protected]" />+</div>+```++**Note**: When using with react-hook-form, don't spread `{...field}` — pass props individually to avoid null value issues.++## Card++```bash+pnpm dlx shadcn@latest add card+```++```tsx+<Card>+ <CardHeader>+ <CardTitle>Title</CardTitle>+ <CardDescription>Description</CardDescription>+ </CardHeader>+ <CardContent>Body</CardContent>+ <CardFooter>Footer</CardFooter>+</Card>+```++## Form++```bash+pnpm dlx shadcn@latest add form+pnpm add react-hook-form zod @hookform/resolvers+```++Wraps react-hook-form with shadcn styling. See [recipes.md](recipes.md) for complete form examples.++**Key exports**: `Form`, `FormField`, `FormItem`, `FormLabel`, `FormControl`, `FormMessage`++## Dialog++```bash+pnpm dlx shadcn@latest add dialog+```++```tsx+<Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild><Button>Open</Button></DialogTrigger>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Title</DialogTitle>+ <DialogDescription>Description</DialogDescription>+ </DialogHeader>+ {/* content */}+ <DialogFooter>+ <Button onClick={() => setOpen(false)}>Close</Button>+ </DialogFooter>+ </DialogContent>+</Dialog>+```++**Gotcha**: Override width with `sm:max-w-*` (must match breakpoint prefix).++## Sheet++```bash+pnpm dlx shadcn@latest add sheet+```++Side panel — commonly used for mobile navigation.++```tsx+<Sheet>+ <SheetTrigger asChild><Button variant="ghost" size="icon"><Menu /></Button></SheetTrigger>+ <SheetContent side="left">+ <SheetHeader><SheetTitle>Navigation</SheetTitle></SheetHeader>+ {/* nav links */}+ </SheetContent>+</Sheet>+```++**Sides**: `left`, `right`, `top`, `bottom`++## Table++```bash+pnpm dlx shadcn@latest add table+```++Static table. For sortable/filterable data tables, also install `@tanstack/react-table`. See [recipes.md](recipes.md) for the data table pattern.++```tsx+<Table>+ <TableHeader>+ <TableRow><TableHead>Name</TableHead><TableHead>Email</TableHead></TableRow>+ </TableHeader>+ <TableBody>+ {users.map(u => (+ <TableRow key={u.id}>+ <TableCell>{u.name}</TableCell>+ <TableCell>{u.email}</TableCell>+ </TableRow>+ ))}+ </TableBody>+</Table>+```++## Select++```bash+pnpm dlx shadcn@latest add select+```++```tsx+<Select value={value} onValueChange={setValue}>+ <SelectTrigger><SelectValue placeholder="Choose..." /></SelectTrigger>+ <SelectContent>+ <SelectItem value="option1">Option 1</SelectItem>+ <SelectItem value="option2">Option 2</SelectItem>+ </SelectContent>+</Select>+```++**Gotcha**: No empty string values. Use `"__any__"` sentinel for "All" options.++## Toast (Sonner)++```bash+pnpm dlx shadcn@latest add toast+pnpm add sonner+```++Add `<Toaster />` to your root layout, then:++```tsx+import { toast } from 'sonner'++toast.success('Saved successfully')+toast.error('Something went wrong')+toast.promise(saveData(), {+ loading: 'Saving...',+ success: 'Saved!',+ error: 'Failed to save',+})+```++## Tabs++```bash+pnpm dlx shadcn@latest add tabs+```++```tsx+<Tabs defaultValue="general">+ <TabsList>+ <TabsTrigger value="general">General</TabsTrigger>+ <TabsTrigger value="security">Security</TabsTrigger>+ </TabsList>+ <TabsContent value="general">General settings...</TabsContent>+ <TabsContent value="security">Security settings...</TabsContent>+</Tabs>+```++## Dropdown Menu++```bash+pnpm dlx shadcn@latest add dropdown-menu+```++```tsx+<DropdownMenu>+ <DropdownMenuTrigger asChild><Button variant="ghost" size="icon"><MoreHorizontal /></Button></DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={handleEdit}>Edit</DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="text-destructive" onClick={handleDelete}>Delete</DropdownMenuItem>+ </DropdownMenuContent>+</DropdownMenu>+```++## Badge++```bash+pnpm dlx shadcn@latest add badge+```++**Variants**: `default`, `secondary`, `outline`, `destructive`++```tsx+<Badge variant="secondary">Draft</Badge>+<Badge variant="destructive">Overdue</Badge>+```++## Switch++```bash+pnpm dlx shadcn@latest add switch+```++```tsx+<div className="flex items-center gap-2">+ <Switch id="notifications" checked={enabled} onCheckedChange={setEnabled} />+ <Label htmlFor="notifications">Enable notifications</Label>+</div>+```++## Separator++```bash+pnpm dlx shadcn@latest add separator+```++```tsx+<Separator /> {/* horizontal */}+<Separator orientation="vertical" className="h-6" /> {/* vertical */}+```++## Avatar++```bash+pnpm dlx shadcn@latest add avatar+```++```tsx+<Avatar>+ <AvatarImage src={user.avatar} alt={user.name} />+ <AvatarFallback>{user.name[0]}</AvatarFallback>+</Avatar>+```diff --git a/skills/shadcn-ui/references/recipes.md b/skills/shadcn-ui/references/recipes.mdnew file mode 100644index 00000000..53151dbf--- /dev/null+++ b/skills/shadcn-ui/references/recipes.md@@ -0,0 +1,342 @@+# Component Recipes++Complete working examples combining shadcn/ui components into common UI patterns.++## Contact Form++Components: Form + Input + Textarea + Button + Toast++```tsx+import { useForm } from 'react-hook-form'+import { zodResolver } from '@hookform/resolvers/zod'+import { z } from 'zod'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Textarea } from '@/components/ui/textarea'+import {+ Form, FormField, FormItem, FormLabel, FormControl, FormMessage,+} from '@/components/ui/form'++const schema = z.object({+ name: z.string().min(1, 'Name is required'),+ email: z.string().email('Invalid email'),+ message: z.string().min(10, 'Message must be at least 10 characters'),+})++export function ContactForm() {+ const form = useForm<z.infer<typeof schema>>({+ resolver: zodResolver(schema),+ defaultValues: { name: '', email: '', message: '' },+ })++ async function onSubmit(values: z.infer<typeof schema>) {+ try {+ await fetch('/api/contact', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(values),+ })+ toast.success('Message sent!')+ form.reset()+ } catch {+ toast.error('Failed to send message')+ }+ }++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">+ <FormField control={form.control} name="name" render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl><Input value={field.value ?? ''} onChange={field.onChange} onBlur={field.onBlur} name={field.name} ref={field.ref} /></FormControl>+ <FormMessage />+ </FormItem>+ )} />+ <FormField control={form.control} name="email" render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <FormControl><Input type="email" value={field.value ?? ''} onChange={field.onChange} onBlur={field.onBlur} name={field.name} ref={field.ref} /></FormControl>+ <FormMessage />+ </FormItem>+ )} />+ <FormField control={form.control} name="message" render={({ field }) => (+ <FormItem>+ <FormLabel>Message</FormLabel>+ <FormControl><Textarea value={field.value ?? ''} onChange={field.onChange} onBlur={field.onBlur} name={field.name} ref={field.ref} /></FormControl>+ <FormMessage />+ </FormItem>+ )} />+ <Button type="submit" disabled={form.formState.isSubmitting}>+ {form.formState.isSubmitting ? 'Sending...' : 'Send'}+ </Button>+ </form>+ </Form>+ )+}+```++## Data Table++Components: Table + @tanstack/react-table + Input (search) + Button (pagination)++```tsx+import { useState } from 'react'+import {+ useReactTable, getCoreRowModel, getSortedRowModel,+ getFilteredRowModel, getPaginationRowModel,+ flexRender, type ColumnDef, type SortingState,+} from '@tanstack/react-table'+import { ArrowUpDown } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'++interface DataTableProps<T> {+ columns: ColumnDef<T>[]+ data: T[]+}++export function DataTable<T>({ columns, data }: DataTableProps<T>) {+ const [sorting, setSorting] = useState<SortingState>([])+ const [globalFilter, setGlobalFilter] = useState('')++ const table = useReactTable({+ data, columns,+ state: { sorting, globalFilter },+ onSortingChange: setSorting,+ onGlobalFilterChange: setGlobalFilter,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ })++ return (+ <div className="space-y-4">+ <Input placeholder="Search..." value={globalFilter} onChange={(e) => setGlobalFilter(e.target.value)} className="max-w-sm" />+ <Table>+ <TableHeader>+ {table.getHeaderGroups().map(hg => (+ <TableRow key={hg.id}>+ {hg.headers.map(h => (+ <TableHead key={h.id}>+ {h.isPlaceholder ? null : (+ <Button variant="ghost" onClick={h.column.getToggleSortingHandler()}>+ {flexRender(h.column.columnDef.header, h.getContext())}+ <ArrowUpDown className="ml-2 h-4 w-4" />+ </Button>+ )}+ </TableHead>+ ))}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody>+ {table.getRowModel().rows.map(row => (+ <TableRow key={row.id}>+ {row.getVisibleCells().map(cell => (+ <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>+ ))}+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <div className="flex items-center justify-between">+ <span className="text-sm text-muted-foreground">+ {table.getFilteredRowModel().rows.length} result(s)+ </span>+ <div className="flex gap-2">+ <Button variant="outline" size="sm" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()}>Previous</Button>+ <Button variant="outline" size="sm" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()}>Next</Button>+ </div>+ </div>+ </div>+ )+}+```++## Modal CRUD++Components: Dialog + Form + Button (create/edit in a modal)++```tsx+import { useState } from 'react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'++interface Item { id: string; name: string; email: string }++export function CrudModal({ item, open, onOpenChange, onSave }: {+ item?: Item // undefined = create, defined = edit+ open: boolean+ onOpenChange: (open: boolean) => void+ onSave: (data: Omit<Item, 'id'>) => Promise<void>+}) {+ const [name, setName] = useState(item?.name ?? '')+ const [email, setEmail] = useState(item?.email ?? '')+ const [saving, setSaving] = useState(false)++ async function handleSave() {+ setSaving(true)+ try {+ await onSave({ name, email })+ toast.success(item ? 'Updated!' : 'Created!')+ onOpenChange(false)+ } catch {+ toast.error('Failed to save')+ } finally {+ setSaving(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{item ? 'Edit' : 'Create'} Item</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="name">Name</Label>+ <Input id="name" value={name} onChange={(e) => setName(e.target.value)} />+ </div>+ <div className="space-y-2">+ <Label htmlFor="email">Email</Label>+ <Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button onClick={handleSave} disabled={saving}>{saving ? 'Saving...' : 'Save'}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}+```++## Responsive Navigation++Components: NavigationMenu (desktop) + Sheet (mobile) + ModeToggle++```tsx+import { useState } from 'react'+import { Menu } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet'+import { ModeToggle } from '@/components/mode-toggle'++const navLinks = [+ { label: 'Home', href: '/' },+ { label: 'About', href: '/about' },+ { label: 'Contact', href: '/contact' },+]++export function Navigation() {+ return (+ <header className="border-b">+ <div className="container flex h-14 items-center justify-between">+ <span className="font-bold">Logo</span>++ {/* Desktop nav */}+ <nav className="hidden md:flex items-center gap-6">+ {navLinks.map(link => (+ <a key={link.href} href={link.href} className="text-sm text-muted-foreground hover:text-foreground transition-colors">+ {link.label}+ </a>+ ))}+ <ModeToggle />+ </nav>++ {/* Mobile nav */}+ <div className="flex md:hidden items-center gap-2">+ <ModeToggle />+ <Sheet>+ <SheetTrigger asChild>+ <Button variant="ghost" size="icon"><Menu className="h-5 w-5" /></Button>+ </SheetTrigger>+ <SheetContent side="right">+ <SheetHeader><SheetTitle>Menu</SheetTitle></SheetHeader>+ <nav className="flex flex-col gap-4 mt-4">+ {navLinks.map(link => (+ <a key={link.href} href={link.href} className="text-lg">{link.label}</a>+ ))}+ </nav>+ </SheetContent>+ </Sheet>+ </div>+ </div>+ </header>+ )+}+```++## Settings Page++Components: Tabs + Form + Switch + Select + Toast++```tsx+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Switch } from '@/components/ui/switch'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'+import { Separator } from '@/components/ui/separator'++export function SettingsPage() {+ return (+ <div className="max-w-2xl space-y-6">+ <h1 className="text-2xl font-bold">Settings</h1>+ <Tabs defaultValue="general">+ <TabsList>+ <TabsTrigger value="general">General</TabsTrigger>+ <TabsTrigger value="notifications">Notifications</TabsTrigger>+ </TabsList>++ <TabsContent value="general" className="space-y-6 mt-4">+ <div className="space-y-2">+ <Label htmlFor="name">Display Name</Label>+ <Input id="name" defaultValue="Jez" />+ </div>+ <div className="space-y-2">+ <Label htmlFor="timezone">Timezone</Label>+ <Select defaultValue="australia-sydney">+ <SelectTrigger><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="australia-sydney">Australia/Sydney</SelectItem>+ <SelectItem value="utc">UTC</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <Separator />+ <Button onClick={() => toast.success('Settings saved')}>Save</Button>+ </TabsContent>++ <TabsContent value="notifications" className="space-y-4 mt-4">+ <div className="flex items-center justify-between">+ <div>+ <Label>Email notifications</Label>+ <p className="text-sm text-muted-foreground">Receive email updates</p>+ </div>+ <Switch defaultChecked />+ </div>+ <div className="flex items-center justify-between">+ <div>+ <Label>Marketing emails</Label>+ <p className="text-sm text-muted-foreground">Receive promotional content</p>+ </div>+ <Switch />+ </div>+ </TabsContent>+ </Tabs>+ </div>+ )+}+```